diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index 9d550b6..d0a382a 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -407,9 +407,21 @@ pub(crate) fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Opt // alone reads well: raw window rate spikes eightfold on either edge of a // stall, and the run average alone never notices a segment change. let overall = progress / elapsed; + // Never below zero, whatever the marks say. A bar that went *backwards* + // between two marks -- an export written again from the start after its + // hardware encoder died -- made this negative, which cancelled the run's + // own rate and left an answer that read "~0:00 left" over six minutes of + // software encoding. The bar is monotone at the source now + // (`engine::export`'s `fetch_max`), and a rate the other way is still not + // an estimate: a window that has gone nowhere leans on the whole run's + // rate, which is exactly what a stall does. let recent = marks .first() .filter(|&&(t, _)| elapsed - t >= ETA_SPAN) - .map_or(overall, |&(t, p)| (progress - p) / (elapsed - t)); - Some(2. * (1. - progress) / (recent + overall)) + .map_or(overall, |&(t, p)| ((progress - p) / (elapsed - t)).max(0.)); + // Both rates at once can only be zero where nothing has happened at all, + // which the guards above already answer with "estimating…" -- said in + // arithmetic as well, because the alternative is an infinite division + // printed as a clock. + Some(2. * (1. - progress) / (recent + overall)).filter(|left| left.is_finite()) } diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs index 00bbad8..efa4c23 100644 --- a/crates/app/src/tests/cards.rs +++ b/crates/app/src/tests/cards.rs @@ -1387,3 +1387,37 @@ fn the_export_estimate_rides_out_a_stall_and_converges() { assert_eq!(clock(114.), "1:54"); assert_eq!(clock(-1.), "0:00"); } + +/// The two shapes that made the countdown lie rather than guess: a bar that +/// went backwards, and a division that could reach infinity. The engine no +/// longer pulls its bar back (`export`'s `fetch_max`), which is why this asks +/// the estimator directly -- it is handed the marks a re-run used to leave. +#[test] +fn the_export_estimate_answers_a_bar_that_went_backwards_with_a_guess() { + // 93% at 400 s, then the hardware encoder dies and the mark stands while + // the software one writes the film again from the first frame. + let marks = vec![(392., 0.93), (396., 0.93), (400., 0.93)]; + let stalled = eta_secs(&marks, 400., 0.93).expect("a stall is still estimated"); + assert!(stalled > 0., "a running export has time left: {stalled}"); + // The old shape: the same marks against a bar that had been put back to + // zero. The rate cannot be negative, so what is left cannot be either -- + // and it is never the "~0:00 left" that read as an export about to finish. + let backwards = eta_secs(&marks, 400., 0.05).expect("a backward bar still estimates"); + assert!( + backwards >= stalled, + "a bar at 5% claimed less left than one at 93%: {backwards} vs {stalled}" + ); + assert!(backwards > 1., "the countdown read as good as finished"); + // Nothing it can be handed prints as an infinite clock. + for (marks, elapsed, progress) in [ + (vec![(0., 0.)], f32::MAX, f32::MIN_POSITIVE), + (vec![(0., f32::MAX)], 3., 0.5), + (Vec::new(), f32::MAX, 0.5), + ] { + let left = eta_secs(&marks, elapsed, progress); + assert!( + left.is_none_or(f32::is_finite), + "{left:?} would be printed as a clock" + ); + } +} diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 0586f42..d6726ef 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -380,7 +380,10 @@ struct Shared { /// backwards -- 5,458 backward steps over one film export before this rule /// was written down. A `store` is only correct where nothing else can be /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and - /// the audio-only export ([`run_audio`]) that has no second thread. + /// the audio-only export ([`run_audio`]) that has no second thread. The + /// rule outlives one attempt at the file: an export rerun in software + /// because the hardware seat died writes this same atomic, and the bar + /// holds where the dead seat left it rather than starting again. progress: AtomicU32, cancel: AtomicBool, finished: AtomicBool, @@ -513,7 +516,13 @@ pub fn start( { eprintln!("export video: {e}; writing it again in software"); let _ = std::fs::remove_file(&part); - worker.progress.store(0, Ordering::Relaxed); + // The bar is *not* put back to zero: the rerun writes + // it with `fetch_max` like everything else + // ([`Shared::progress`]), so it holds where the dead + // seat left it and moves again once the software + // encoder passes that mark. A person whose GPU has just + // died is the last one who should also watch the bar + // run backwards. let mut software = settings.clone(); software.seat = EncoderSeat::Software; run(&project, &meta, &part, &worker, &software) @@ -1619,7 +1628,7 @@ impl CopyPlan { done += 1; shared .progress - .store(picture_progress(done, total), Ordering::Relaxed); + .fetch_max(picture_progress(done, total), Ordering::Relaxed); } } // Everything up to here is still cancellable, exactly as the encoded @@ -2045,6 +2054,45 @@ fn window_fidelity( /// encodes and joins where the file it is writing needs the track. type AudioJob = thread::JoinHandle>>; +/// The pass while [`run`] holds it, joined however that function leaves -- +/// including through a `?`. +/// +/// A [`JoinHandle`](thread::JoinHandle) that is merely dropped *detaches* its +/// thread, and the one error that matters here is the hardware encoder's +/// process dying ([`crate::hwproc`]): the whole export is then written again by +/// [`start`], which starts an audio pass of its own. The abandoned one would go +/// on mixing and encoding the same sound beside it -- two passes of a feature +/// film's audio at once, on the machine that has just lost its GPU. Joined +/// instead, so an export has one audio pass at a time and none outlives it. +struct AudioPass(Option); + +impl AudioPass { + /// Whether the pass has landed, so the picture loop may collect it without + /// waiting. + fn is_finished(&self) -> bool { + self.0.as_ref().is_some_and(thread::JoinHandle::is_finished) + } + + /// Whether a pass is still to be collected -- which is what "the sound is + /// still being worked out" means on the encoder line. + fn running(&self) -> bool { + self.0.is_some() + } + + /// The handle, for the one caller that is about to join it itself. + fn take(&mut self) -> Option { + self.0.take() + } +} + +impl Drop for AudioPass { + fn drop(&mut self) { + if let Some(job) = self.0.take() { + let _ = job.join(); + } + } +} + /// The pass's answer, or the failure that is the export's failure. A panicked /// audio thread reads as an error rather than as silence: an export that wrote /// its picture and quietly no sound is the one outcome this must not have. @@ -2162,7 +2210,9 @@ fn run( }; // A Matroska file (and a copied one, whose muxer is the same) collects it // here; an mp4 leaves it running and collects it under the picture below. - let mut audio_job = Some(audio_job); + // Held in a guard from here on, so no way out of this function leaves the + // pass running behind it ([`AudioPass`]). + let mut audio_job = AudioPass(Some(audio_job)); // The condition is the *format*, and the copied-picture path below relies // on that covering it too: `plan` hands its packets straight to a Matroska // muxer, so it may only exist where this has already collected them -- @@ -2280,7 +2330,7 @@ fn run( // it replaced -- and the sound says whether it was copied or encoded, which // only `copy_audio` knows and, on the overlapped path, does not know yet. let seat = encoder.label(); - publish_seats(shared, seat, project, settings, sound, opus, audio_job.is_some()); + publish_seats(shared, seat, project, settings, sound, opus, audio_job.running()); // When the picture started, so the stage line below can say where under it // the sound landed -- the one number that says whether the two passes // really overlapped, in the same voice as `encode_audio`'s own timers. @@ -2391,10 +2441,7 @@ fn run( // encoded, and an overlapped pass that reported only at the end // would spend the whole encode first. Also where its measured // codec reaches the line on screen. - if audio_job - .as_ref() - .is_some_and(thread::JoinHandle::is_finished) - { + if audio_job.is_finished() { late = join_audio(audio_job.take().expect("just seen to be there"))?; sound = late.as_ref().map(|track| track.copied); opus = late diff --git a/crates/engine/src/hwproc.rs b/crates/engine/src/hwproc.rs index 3c1c2c9..cb593f9 100644 --- a/crates/engine/src/hwproc.rs +++ b/crates/engine/src/hwproc.rs @@ -13,8 +13,8 @@ //! handle on a child running `hw-encode-child`, which is the one process that //! `dlopen`s the plugin and therefore the only one a driver may kill. When it //! dies -- by `abort()`, by any signal, or by going quiet past -//! [`Remote::timeout`] -- the parent sees a closed socket or a timed-out read, -//! reaps the child, and reports an error carrying [`HW_LOST`]. The export then +//! [`Remote::deadline`] -- the parent sees a closed socket or a timed-out read, +//! reaps the child, and reports a [`Lost`]. The export then //! runs again on the software encoder ([`crate::export::start`]), or refuses in //! words where a person picked the GPU by name. //! @@ -36,17 +36,32 @@ use std::time::Duration; use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::hw::VhDma; -/// The words every "the child is gone" error carries, and the only thing -/// [`crate::export`] matches on to decide that the software encoder should have -/// another go at the file. A message, not an error kind, because -/// [`crate::Error`] is a boxed `dyn Error` and a caller two crates away reads -/// its text. +/// The words every "the child is gone" error carries, for the person reading +/// the log; what *decides* anything is [`Lost`], never this text. pub const HW_LOST: &str = "the hardware encoder process"; +/// The error a dead child carries. +/// +/// A type and not a phrase. [`is_lost`] is what commits a whole export to being +/// written again from the first frame ([`crate::export::start`]), and matching +/// on words handed that decision to any future error whose message happened to +/// mention the child -- a silent re-encode of a feature film, caused by a +/// wording. Nothing outside this module can make one. +#[derive(Debug)] +pub struct Lost(String); + +impl std::fmt::Display for Lost { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Lost {} + /// Whether an error is one: a driver that took its process down, rather than a /// picture this engine got wrong. pub fn is_lost(error: &crate::Error) -> bool { - error.to_string().contains(HW_LOST) + error.downcast_ref::().is_some() } /// The helper's file name; it is built into the same directory as the editor. @@ -407,8 +422,32 @@ pub struct Remote { /// Set the moment the child is known gone, so every later call refuses in /// the same words instead of blocking on a socket nobody holds. lost: Option, + /// The slowest call this child has answered, and how many it has answered + /// at all: what [`Remote::deadline`] measures its patience against. + slowest: Duration, + answered: u32, } +/// How many answered calls it takes before the wait stops being the configured +/// ceiling and becomes this encoder's own measure, how much slower than its +/// slowest answer a call may be before it is a wedge, and the least it is ever +/// given. +/// +/// The ceiling has to be generous -- an encoder opening on a 4K frame is not a +/// dead one -- and the export spends every second of it on a child that will +/// never answer again: the file is owed the software encoder and the wait is +/// pure delay before it starts. The window is what shrinks, not the ceiling. +/// Once a child has answered [`CALIBRATE`] calls, the machine has said how long +/// its own frames take, and eight times the slowest of them (never under +/// [`FLOOR`]) contains a wedge in two or three seconds rather than fifteen, +/// while a slow open still gets the whole ceiling and is never killed for +/// being slow. The editor is live throughout either way -- the wait is on the +/// export's own thread and the card goes on repainting -- so what this buys is +/// the delay, not the window. +const CALIBRATE: u32 = 8; +const SLACK: u32 = 8; +const FLOOR: Duration = Duration::from_secs(2); + impl Remote { /// How long the child may take over one call before it is treated as hung. /// A wedged ring does not always `abort()` -- it can simply stop -- and a @@ -421,6 +460,17 @@ impl Remote { Duration::from_millis(ms) } + /// How long the *next* call may take: the ceiling until this child has + /// shown what its frames cost, then its own slowest answer with room to + /// spare ([`CALIBRATE`]). + fn deadline(&self) -> Duration { + let ceiling = Self::timeout(); + match self.answered >= CALIBRATE { + true => ceiling.min((self.slowest * SLACK).max(FLOOR)), + false => ceiling, + } + } + /// Starts a child on this seat. `None` is the plugin's own "no" carried /// across the process boundary -- no driver, no entrypoint, a size refused /// -- and the caller takes the software encoder exactly as it always did. @@ -445,6 +495,8 @@ impl Remote { open, au: Vec::new(), lost: None, + slowest: Duration::ZERO, + answered: 0, }; // The child answers once its encoder is open: a byte, and with it the // descriptor of the staging buffer it made for this session's size. @@ -550,10 +602,18 @@ impl Remote { /// One request and its reply, which is every call above: the child is fed, /// then read, and anything that is not an answer is the child being gone. fn round_trip(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result> { + // Set per call, because what it may be is measured from the calls + // before it ([`deadline`]). + let _ = self.sock.set_read_timeout(Some(self.deadline())); + let started = std::time::Instant::now(); self.request(msg, fds)?; let mut au = std::mem::take(&mut self.au); let read = read_reply(&mut self.sock, &mut au); self.au = au; + if read.is_ok() { + self.slowest = self.slowest.max(started.elapsed()); + self.answered += 1; + } // Every "no access unit" leaves through a `return`, so the borrow of the // buffer below is the only one alive when it is taken. match read { @@ -569,7 +629,7 @@ impl Remote { fn request(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<()> { if let Some(gone) = &self.lost { - return Err(gone.clone().into()); + return Err(Lost(gone.clone()).into()); } match send_msg(&self.sock, msg, fds) { Ok(()) => Ok(()), @@ -591,10 +651,9 @@ impl Remote { Some(libc::SIGKILL) | None => format!("stopped answering ({why}) and was killed"), Some(signal) => format!("was killed by signal {signal}"), }; - let message = - format!("{HW_LOST} {how}; the driver took it down and not the editor"); + let message = format!("{HW_LOST} {how}; the driver took it down and not the editor"); self.lost = Some(message.clone()); - message.into() + Lost(message).into() } } diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 1622161..50f284d 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -1211,6 +1211,20 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { /// stays pinned to software: it is not what is under test and the fixture must /// decode the same way it does everywhere else in this file. fn injected(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T) -> T { + // Short, because one of these is waiting out a child that has stopped + // answering and the wait is the thing under test. + injected_with(abort, hang, Some("1500"), body) +} + +/// The same, with the wait left to the caller: `None` is what a person's own +/// editor runs with, which is the one setting none of the tests above ever +/// exercised. +fn injected_with( + abort: Option<&str>, + hang: Option<&str>, + timeout_ms: Option<&str>, + body: impl FnOnce() -> T, +) -> T { let _exclusive = SEAT.write().unwrap_or_else(|poisoned| poisoned.into_inner()); let restore = std::env::var_os("VE_SW_ENC"); unsafe { @@ -1218,9 +1232,10 @@ fn injected(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T std::env::remove_var("VE_SW_ENC"); std::env::set_var("VE_HW_TEST_FAKE", "1"); std::env::set_var("VE_HW_CHILD_BIN", env!("CARGO_BIN_EXE_hw-encode-child")); - // Short, because one of these is waiting out a child that has stopped - // answering and the wait is the thing under test. - std::env::set_var("VE_HW_TIMEOUT_MS", "1500"); + match timeout_ms { + Some(ms) => std::env::set_var("VE_HW_TIMEOUT_MS", ms), + None => std::env::remove_var("VE_HW_TIMEOUT_MS"), + } match abort { Some(at) => std::env::set_var("VE_HW_TEST_ABORT", at), None => std::env::remove_var("VE_HW_TEST_ABORT"), @@ -1298,6 +1313,164 @@ fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() { std::fs::remove_file(&out).unwrap(); } +/// ...and the bar over that same death only ever goes forwards. The rerun is a +/// whole second pass over the timeline, so the one thing a person must not see +/// is the progress they watched fill drop back to zero: it holds at the mark the +/// dead seat reached and moves on from there, ending exactly full. +#[test] +fn a_hardware_encoder_killed_mid_export_never_pulls_the_bar_backwards() { + let source = asset("test_baseline.mp4"); + let (project, meta) = short_edit(&source, 20); + let out = out_path("hw_child_abort_progress"); + + let seen = injected(Some("3"), None, || { + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + // Sampled far faster than the export writes, so the retry cannot slip + // through between two reads. + let started = Instant::now(); + let mut seen = vec![handle.progress()]; + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(180), + "export did not finish" + ); + let now = handle.progress(); + if now != *seen.last().unwrap() { + seen.push(now); + } + std::thread::sleep(Duration::from_millis(1)); + } + handle + .result() + .expect("a finished export has an outcome") + .expect("the export survived its encoder"); + seen.push(handle.progress()); + seen + }); + + assert!( + seen.windows(2).all(|pair| pair[1] >= pair[0]), + "the bar went backwards across the fallback: {seen:?}" + ); + assert_eq!( + seen.last().copied(), + Some(1.0), + "a finished export leaves a full bar: {seen:?}" + ); + std::fs::remove_file(&out).unwrap(); +} + +/// Threads of this very process that belong to an audio pass. Every worker the +/// pass starts inherits its name from the thread that spawned it (Linux `comm` +/// is inherited), so this is the pass *and its own workers* -- which is what +/// makes it a measure of how many passes are running: two at once is twice the +/// crowd of one. +fn audio_pass_threads() -> usize { + std::fs::read_dir("/proc/self/task") + .into_iter() + .flatten() + .flatten() + .filter(|thread| { + std::fs::read_to_string(thread.path().join("comm")) + .is_ok_and(|name| name.trim() == "export-audio") + }) + .count() +} + +/// The busiest that crowd ever gets while `export` writes this project. +fn busiest_audio_pass(project: Project, meta: engine::VideoMeta, out: &Path) -> usize { + let handle = engine::export::start(project, meta, out, &ExportSettings::default()); + let started = Instant::now(); + let mut most = 0; + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(180), + "export did not finish" + ); + most = most.max(audio_pass_threads()); + std::thread::sleep(Duration::from_millis(1)); + } + handle + .result() + .expect("a finished export has an outcome") + .expect("the export was written"); + most +} + +/// One audio pass at a time, across that same death. An mp4 runs the sound +/// beside the picture, and the picture's failure used to leave that thread +/// *detached*: the re-run started a second pass, and a machine that had just +/// lost its GPU mixed and encoded the same film's sound twice at once. Measured +/// against the same export with nothing dying under it -- the fallback may not +/// be a busier place than an ordinary export is. +#[test] +fn a_hardware_encoder_killed_mid_export_leaves_no_audio_pass_behind() { + // AC-3: an mp4 cannot carry it, so the pass is a real decode and encode + // rather than the packet copy an AAC source is over in a millisecond. + let source = asset("test_ac3.mp4"); + let out = out_path("hw_child_abort_audio"); + + let (project, meta) = short_edit(&source, 40); + let alone = { + let _seat = pin_software(); + busiest_audio_pass(project, meta, &out) + }; + std::fs::remove_file(&out).unwrap(); + + let (project, meta) = short_edit(&source, 40); + let across = injected(Some("3"), None, || busiest_audio_pass(project, meta, &out)); + + println!("audio pass threads: {alone} alone, {across} across the fallback"); + assert!( + across <= alone, + "the fallback ran {across} audio-pass threads where one pass runs {alone}" + ); + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); + assert_eq!(written.frame_count, 40, "every timeline frame was written"); + std::fs::remove_file(&out).unwrap(); +} + +/// What a *shipping* editor waits when its child stops answering. Every test +/// here pins `VE_HW_TIMEOUT_MS` at 1.5 s, so none of them ever ran the 15 s +/// default -- fifteen seconds an export spends on a child that will never +/// answer again, before the software encoder it is owed can even begin. +/// +/// The ceiling stays where it is, because an encoder opening on a 4K frame is +/// not a dead one. What changes is that a child which has answered its first +/// frames has *said* what its frames cost, and from then on the wait is that +/// measure and not the ceiling. +#[test] +fn a_wedged_child_is_waited_out_by_its_own_measure_not_the_ceiling() { + let (width, height) = (320u32, 240u32); + // No `VE_HW_TIMEOUT_MS` at all: the wait is the one a person's export gets. + injected_with(None, Some("10"), None, || { + let mut encoder = + HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened"); + let (y, u, v) = synthetic(0, width as usize, height as usize); + for frame in 0..10 { + assert!( + encoder.encode(&y, &u, &v, width, height, false).is_ok(), + "picture {frame} is before the wedge" + ); + } + let started = Instant::now(); + let wedged = encoder + .encode(&y, &u, &v, width, height, false) + .expect_err("a child that stops answering is not an encode"); + let waited = started.elapsed(); + println!("wedge at the shipping default: contained in {waited:.2?}"); + assert!(engine::hwproc::is_lost(&wedged), "{wedged}"); + assert!( + waited < Duration::from_secs(6), + "waited {waited:.2?} on a wedged child at the shipping default" + ); + // ...and never so little that a slow picture could be mistaken for a + // dead one: the floor holds even where every measured frame was + // instant, which the stand-in encoder's are. + assert!(waited >= Duration::from_secs(2), "waited only {waited:.2?}"); + }); +} + /// The same death at the *open*: the child never gets far enough to say yes, so /// there is no hardware seat at all and the software one takes the export from /// the first frame. A refusal, not a crash, and the file is whole.