diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index d0a382a..bdbca7b 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -76,6 +76,16 @@ pub(crate) enum Proxy { Native, /// Being made, in the background, while the film keeps playing. Making(engine::proxy::Job), + /// Stopped by hand ([`Player::cancel_proxy`]) and not yet gone: the worker + /// gives up at its next frame and deletes the half-written file itself, and + /// the job is held until it does. Kept as a state rather than dropped + /// because the encode may still *beat* the cancel -- a stand-in that is + /// already written is a file in the cache and is reported as one. + Cancelling(engine::proxy::Job), + /// Stopped, and the worker has gone. Not [`Self::Failed`]: nothing went + /// wrong, somebody asked for it -- and it stays in the map so no repaint + /// starts the encode that was just stopped over again. + Cancelled, /// There is one in the cache. What the switch actually plays. Ready, /// It could not be made: the film itself is what plays, and the row says @@ -93,6 +103,11 @@ impl Proxy { // Rounded down: a bar that says 100% while the encoder is still // writing is the one number a progress line must never show. Self::Making(job) => format!("proxy {}%", (job.progress() * 100.) as u32), + // Its own word while the worker is still winding down: "no proxy" + // the instant the × is clicked would be a claim about a file that + // is at that moment still being written. + Self::Cancelling(_) => "proxy stopping…".to_string(), + Self::Cancelled => "no proxy — stopped".to_string(), Self::Ready => "proxy".to_string(), Self::Failed => "no proxy".to_string(), } diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index a1d8ec1..1d92e2b 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -313,37 +313,87 @@ impl Player { /// Nothing waits for it: until a proxy is ready the film itself is what /// plays, switch or no switch ([`engine::PlaybackSession::picture_path`]), /// so a failure costs a line and no more. + /// + /// A stopped one settles here too ([`Player::cancel_proxy`]), which is what + /// makes the stop honest: the worker's own answer is what says the encode + /// is over and its half-written file gone -- and where the encode *beat* + /// the cancel, the answer is a finished stand-in and it is reported as one + /// rather than thrown away. pub(crate) fn poll_proxies(&mut self, cx: &mut Context) { - let done: Vec<(PathBuf, engine::Result)> = self + let done: Vec<(PathBuf, bool, engine::Result)> = self .proxies .iter() .filter_map(|(path, state)| match state { - Proxy::Making(job) => Some((path.clone(), job.outcome()?)), + Proxy::Making(job) => Some((path.clone(), false, job.outcome()?)), + Proxy::Cancelling(job) => Some((path.clone(), true, job.outcome()?)), _ => None, }) .collect(); - for (path, outcome) in done { - let text = match &outcome { - Ok(_) => format!( + for (path, stopped, outcome) in done { + let text = match (&outcome, stopped) { + (Ok(_), _) => format!( "PROXY READY for {} — Proxies on cuts on it", file_name(&path) ), - Err(e) => format!( + // Not a failure and not worded as one: the worker gave up + // because it was asked to, and it took its half-written file + // with it. + (Err(_), true) => format!( + "PROXY STOPPED for {} — nothing of it was kept, and the film itself is what \ + plays", + file_name(&path) + ), + (Err(e), false) => format!( "PROXY FAILED for {} — {e} — the film itself is what plays", file_name(&path) ), }; eprintln!("{text}"); self.notify_user(text.into()); - let state = match outcome { - Ok(_) => Proxy::Ready, - Err(_) => Proxy::Failed, + let state = match (outcome, stopped) { + (Ok(_), _) => Proxy::Ready, + (Err(_), true) => Proxy::Cancelled, + (Err(_), false) => Proxy::Failed, }; self.proxies.insert(path, state); cx.notify(); } } + /// The × on a library row while its stand-in is being made: the worker is + /// asked to give up at its next frame and delete the half-written file it + /// was writing ([`engine::proxy::Job::cancel`]), and the row says so until + /// it has. A whole feature film re-encoded is minutes of a machine the cut + /// is being made on, and there was no way to take it back. + /// + /// Nothing is deleted from here and nothing waits: the film itself is what + /// plays throughout ([`engine::PlaybackSession::picture_path`] stats the + /// cache and finds nothing), so a stop costs a line and no more. Asking + /// twice is asking once -- the second click finds a state that is not + /// [`Proxy::Making`] and answers nothing -- and a cancel that arrives after + /// the encode has already written its file settles as the *ready* stand-in + /// it is ([`Player::poll_proxies`]), never as a deletion of one in use. + pub(crate) fn cancel_proxy(&mut self, path: &std::path::Path, cx: &mut Context) { + // Taken out of its slot and put back one state on, rather than removed: + // a path that left this map is a path the next repaint starts an encode + // for all over again ([`Player::cache_media`]). + let Some(slot) = self.proxies.get_mut(path) else { + return; + }; + if !matches!(slot, Proxy::Making(_)) { + return; + } + let Proxy::Making(job) = std::mem::replace(slot, Proxy::Cancelled) else { + unreachable!("the slot was just read as one being made") + }; + job.cancel(); + *slot = Proxy::Cancelling(job); + let text = format!("STOPPING the stand-in for {}…", file_name(path)); + eprintln!("{text}"); + self.notify_user(text.into()); + cx.notify(); + } + /// What the Proxies button says after the state: how far the stand-ins /// have got, since "on" with nothing made yet and "on" with the whole /// library standing in are two different things to be looking at. Empty @@ -377,19 +427,26 @@ impl Player { /// Whether any stand-in is still being made -- what keeps the frame loop /// alive while one is, so its percentage moves on screen. + /// + /// One being stopped counts: its worker is still running until it reaches + /// the frame it gives up at, and the repaint that notices *that* is this + /// same loop -- without it a stopped row would sit on "stopping…" until + /// something else happened to repaint the window. pub(crate) fn making_proxies(&self) -> bool { self.proxies .values() - .any(|p| matches!(p, Proxy::Making(_))) + .any(|p| matches!(p, Proxy::Making(_) | Proxy::Cancelling(_))) } /// How many films are between "shall we?" and "done": the number the start /// of another is held against ([`PROXIES_AT_ONCE`]). A header being read - /// counts, because the answer may be an encode. + /// counts, because the answer may be an encode -- and so does one still + /// winding down from a stop, which is an encoder that has not let go of the + /// seat yet. pub(crate) fn in_flight_proxies(&self) -> usize { self.proxies .values() - .filter(|p| matches!(p, Proxy::Asked | Proxy::Making(_))) + .filter(|p| matches!(p, Proxy::Asked | Proxy::Making(_) | Proxy::Cancelling(_))) .count() } diff --git a/crates/app/src/ui/library.rs b/crates/app/src/ui/library.rs index 53a4ea6..f33ce9d 100644 --- a/crates/app/src/ui/library.rs +++ b/crates/app/src/ui/library.rs @@ -122,6 +122,18 @@ impl Player { .get(&row.path) .map_or_else(String::new, Proxy::detail), ); + // A stand-in being made is minutes of this machine, and the row + // that says how far it has got is where the way out of it belongs. + // Gone the moment the worker settles, like the percentage beside + // it: there is nothing left to stop. + let making = matches!(self.proxies.get(&row.path), Some(Proxy::Making(_))); + let stop_path = row.path.clone(); + let stop_tip: SharedString = format!( + "Stop making the stand-in for {} — nothing of it is kept, and the film itself is \ + what plays", + row.name + ) + .into(); let usable = row.unusable.is_none(); let (path, stream) = (row.path.clone(), row.stream); let dragged = (path.clone(), stream); @@ -219,6 +231,31 @@ impl Player { .child(under), ), ) + // The way out of the encode, on the row that shows it running. + // A `HIT_MIN` target and the subtitle row's ×, and it stops the + // click there: the row under it picks the file, and stopping an + // encode is not a way of choosing what to place. + .when(making, |d| { + d.child( + div() + .id(("proxy-stop", i)) + .flex_none() + .w(px(HIT_MIN)) + .h_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER()))) + .tooltip(move |_, cx| cx.new(|_| Tip(stop_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + cx.stop_propagation(); + this.cancel_proxy(&stop_path, cx); + })) + .child("×"), + ) + }) }) .collect(); div() diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 50f284d..5595f43 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -1029,6 +1029,112 @@ fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { assert_eq!(engine::proxy::cached(&source), None); } +/// The way out of a stand-in nobody wants to wait for -- a whole film through a +/// decoder and an encoder, started without being asked for, and until now with +/// nothing that could stop it. +/// +/// What a stop has to be worth trusting, all of it here: the worker really +/// gives up (it settles, so its encoder is closed and its thread is gone), the +/// half-written `.part` goes with it, and **nothing is left under the name a +/// finished stand-in would have** -- which is the invariant that keeps a cut +/// from being made on a truncated picture, since the cache is looked up by +/// existence alone ([`engine::proxy::cached`]). +/// +/// ...and the two edges: asking twice is asking once, and a stop that arrives +/// on a stand-in *already written* must not take that file away -- it is what +/// the switch is at that moment playing. +/// +/// Software seat, like every default test here ([`pin_software`]). +#[test] +fn a_stopped_proxy_leaves_neither_a_stand_in_nor_half_of_one() { + let _seat = pin_software(); + let source = asset("test_av.mp4"); + let out = engine::proxy::path_for(&source).expect("a cache directory"); + let part = part_path(&out); + // A stand-in left by an earlier run would make this a cache hit, and a + // cache hit is the one job with nothing to stop. + let _ = std::fs::remove_file(&out); + let _ = std::fs::remove_file(&part); + + let job = engine::proxy::generate(&source).expect("start the proxy"); + // Stopped with the encoder really running: a flag set before the worker has + // opened anything tests the flag and not the stop. + let opening = Instant::now(); + while job.encoder().is_none() && !job.is_finished() { + assert!( + opening.elapsed() < Duration::from_secs(120), + "the encoder never opened" + ); + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + !job.is_finished(), + "the fixture finished before it could be stopped: this test needs a film \ + the software seat takes a moment over" + ); + // Twice, because a second click on the × is a thing that happens. + job.cancel(); + job.cancel(); + let stopping = Instant::now(); + while !job.is_finished() { + assert!( + stopping.elapsed() < Duration::from_secs(120), + "the worker kept encoding after the stop: {:.0}% in", + job.progress() * 100. + ); + std::thread::sleep(Duration::from_millis(20)); + } + let refusal = job + .outcome() + .expect("a settled job has an outcome") + .err() + .expect("a stopped proxy is not a proxy"); + assert!( + refusal.to_string().contains("cancelled"), + "not the cancellation: {refusal}" + ); + assert!( + !out.exists(), + "a stopped proxy left {} behind, and the cache is looked up by existence", + out.display() + ); + assert!( + !part.exists(), + "a stopped proxy left the half-written {} behind", + part.display() + ); + assert_eq!( + engine::proxy::cached(&source), + None, + "the cache offers a stand-in that was never finished" + ); + // Past the end it is still idempotent, and the outcome is handed out once. + job.cancel(); + assert!(job.outcome().is_none(), "the outcome came out twice"); + assert!(!out.exists()); + + // The other edge, at no cost: a job for a film whose stand-in is already + // written is the cache-hit job, which is exactly what a stop racing the + // last instant of an encode settles into -- and cancelling it must leave + // the file alone, because that file is what the picture is coming off. + std::fs::write(&out, b"a stand-in that is already written").expect("seed the cache"); + let hit = engine::proxy::generate(&source).expect("ask again"); + assert!(hit.is_finished(), "a cached stand-in is done on the spot"); + hit.cancel(); + assert!( + out.is_file(), + "a stop deleted a finished stand-in the switch was playing" + ); + assert_eq!(engine::proxy::cached(&source), Some(out.clone())); + assert_eq!( + hit.outcome().expect("cached outcome").expect("cached path"), + out, + "the stop turned a finished stand-in into a failure" + ); + + std::fs::remove_file(&out).expect("clean the cache entry up"); +} + /// The same file on the **hardware** seat, asking the one question the software /// twin above cannot: is what the GPU wrote really every-frame-a-starting-point? ///