diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index 97b6748..7ace767 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -86,7 +86,13 @@ pub(crate) enum Proxy { /// own state because it is what makes "how many are in flight" a number: /// the answer comes back on a worker, and until it does this file may still /// turn into an encode. - Asked, + /// + /// Carries the flag [`engine::proxy::generate_if_wanted`] polls at the door + /// and around the header read: the same shape [`Self::Making`] carries a + /// cancellable [`engine::proxy::Job`] with, one step earlier -- there is no + /// `Job` yet to hold, so the raw flag is what a stop asked during this + /// state has to set. + Asked(std::sync::Arc), /// A file this machine cuts at speed as it is: no stand-in, and none /// wanted ([`engine::proxy::wanted`]). Native, diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 7994864..68f1a71 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -621,10 +621,15 @@ impl Player { /// film's stand-in has asked, and is told by the row how far it has got. pub(crate) fn start_proxy_for(&mut self, path: &std::path::Path, cx: &mut Context) { let path = path.to_path_buf(); - self.proxies.insert(path.clone(), Proxy::Asked); + // The same flag [`engine::proxy::generate_if_wanted`] polls at the door + // and around the header read: a click on the row while the header is + // still being walked ([`Player::toggle_proxy`]'s `Asked` arm) sets it, + // so the walk unwinds mid-read instead of running to completion. + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + self.proxies.insert(path.clone(), Proxy::Asked(cancel.clone())); let started = cx.background_executor().spawn({ let path = path.clone(); - async move { engine::proxy::generate_if_wanted(&path) } + async move { engine::proxy::generate_if_wanted(&path, &cancel) } }); cx.spawn(async move |this, cx| { let started = started.await; @@ -636,7 +641,7 @@ impl Player { // half of a click made during the ask is an encoder nothing in // the map can reach -- and it finishes minutes later and puts // back the stand-in somebody switched off. - let stopped = !matches!(this.proxies.get(&path), Some(Proxy::Asked)); + let stopped = !matches!(this.proxies.get(&path), Some(Proxy::Asked(_))); let state = match started { // Cancelled and *held*, exactly as a stop of a running one // is: the worker's own answer is what settles it, so an @@ -710,7 +715,11 @@ impl Player { Some(Proxy::Making(_)) => self.cancel_proxy(path, cx), // Already winding down: the second click on a stop is nothing. Some(Proxy::Cancelling(_)) => {} - Some(Proxy::Asked) => { + Some(Proxy::Asked(cancel)) => { + // Wakes the header read mid-walk ([`engine::proxy::started`]): + // without this the stop only ever landed once the read had + // already run to completion on its own (DEBT #91). + cancel.store(true, std::sync::atomic::Ordering::Release); engine::proxy::set_off(path, true); self.proxies.insert(path.to_path_buf(), Proxy::Cancelled); let text = format!("STOPPING the stand-in for {}…", file_name(path)); @@ -860,7 +869,7 @@ impl Player { pub(crate) fn in_flight_proxies(&self) -> usize { self.proxies .values() - .filter(|p| matches!(p, Proxy::Asked | Proxy::Making(_) | Proxy::Cancelling(_))) + .filter(|p| matches!(p, Proxy::Asked(_) | Proxy::Making(_) | Proxy::Cancelling(_))) .count() } diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs index 9202847..21a3b9f 100644 --- a/crates/app/src/tests/cards.rs +++ b/crates/app/src/tests/cards.rs @@ -2084,3 +2084,28 @@ fn darkroom_source_rows_keep_proxy_add_and_media_audio_text_paths() { ); } } + +/// DEBT #91: a click-to-stop while a stand-in's header is still being read +/// must reach the flag the read itself polls (`engine::proxy::started`), not +/// only relabel the row. Read off the source and not run, the way the row +/// above it is -- there is no `TestAppContext` in this binary to construct a +/// `Context` and call `toggle_proxy` on. On the state this fix +/// replaced, `start_proxy_for` handed the header read a flag nothing outside +/// it could reach and `Proxy::Asked` carried no field to store a stop into, +/// so `library.find("Proxy::Asked(cancel)")` below has nothing to find. +#[test] +fn toggle_proxy_wakes_the_asked_phase_it_stops() { + let library = src_text("player/library.rs"); + let start = &library[library.find("fn start_proxy_for(").expect("start_proxy_for")..]; + assert!( + start.contains("generate_if_wanted(&path, &cancel)"), + "start_proxy_for no longer hands the header read a cancel flag anyone can reach" + ); + let toggle = &library[library.find("fn toggle_proxy(").expect("toggle_proxy")..]; + let asked_arm = + &toggle[toggle.find("Proxy::Asked(cancel)").expect("the Asked arm's own flag")..]; + assert!( + asked_arm.contains("cancel.store(true"), + "a stop asked during Asked no longer sets the flag the header read polls" + ); +} diff --git a/crates/app/src/ui/dock_stance.rs b/crates/app/src/ui/dock_stance.rs index 45b7750..b982345 100644 --- a/crates/app/src/ui/dock_stance.rs +++ b/crates/app/src/ui/dock_stance.rs @@ -293,7 +293,7 @@ fn source_row( true, format!("Stopping the stand-in for {}…", row.name), ), - Some(Proxy::Asked) => ( + Some(Proxy::Asked(_)) => ( "○", false, None, diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 01dbe25..6581359 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -102,6 +102,14 @@ impl Seek for CancelableReader { } } +/// The same answer a walk gives up with on its own, for a caller that finds +/// its cancel already set before there is any walk to abandon -- a proxy's +/// header read finding its flag up the moment its seat is claimed, say. Kept +/// to one string so [`is_cancelled`] answers both the same way. +pub fn cancelled_read_error() -> crate::Error { + CANCELLED.into() +} + /// What the video track is coded with. Not a decoder choice by itself: only /// H.264 has a software decoder here, which is what [`Codec::needs_plugin`] /// says for the others. diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index b8b620f..f443d78 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -32,6 +32,8 @@ //! cancel a file export has ([`Job`]). use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; use std::time::UNIX_EPOCH; use crate::demux::{Codec, Demuxer, NoVideoTrack, VideoMeta}; @@ -439,7 +441,10 @@ impl Job { /// back through [`Job::outcome`], so a caller has two places to look and not /// twenty. pub fn generate(source: &Path) -> crate::Result { - Ok(started(source, |_| true)?.expect("nothing was filtered out")) + // Nothing here has anything to cancel a header read with -- a flag that is + // never set is the same as the read never checking one at all. + let uncancelled = Arc::new(AtomicBool::new(false)); + Ok(started(source, |_| true, &uncancelled)?.expect("nothing was filtered out")) } /// The same, for a file that is worth standing in for and nobody else @@ -461,7 +466,17 @@ pub fn generate(source: &Path) -> crate::Result { /// header says so -- so the demuxer's own [`NoVideoTrack`] answer is taken here /// as the same quiet `None`. A film that *has* a picture and will not open is a /// different thing and stays loud. -pub fn generate_if_wanted(source: &Path) -> crate::Result> { +/// +/// `cancel` is polled through the whole Asked phase, the same flag the caller +/// hands the [`Job`] once one exists: a click to stop this file's stand-in +/// while the header is still being read (a Matroska's is a cluster walk, not +/// a stat) used to have nothing to set, since there was no [`Job`] yet to +/// [`cancel`](Job::cancel) -- so the read ran to completion regardless, and a +/// stop landed only once an encoder was already open. Set before this is +/// called or at any point while it runs, it is read at the door and again +/// wrapped around the header read itself ([`crate::demux::with_cancel`]), so a +/// cancelled read unwinds at its next element instead of finishing. +pub fn generate_if_wanted(source: &Path, cancel: &Arc) -> crate::Result> { if crate::is_audio(source) || crate::is_image(source) { return Ok(None); } @@ -472,7 +487,7 @@ pub fn generate_if_wanted(source: &Path) -> crate::Result> { if is_off(source) { return Ok(None); } - match started(source, wanted) { + match started(source, wanted, cancel) { Err(e) if NoVideoTrack::is_it(&e) => Ok(None), other => other, } @@ -480,7 +495,18 @@ pub fn generate_if_wanted(source: &Path) -> crate::Result> { /// Both doors: the cache is looked at, the header is read once, and `only_if` /// decides off that header whether there is anything to do. -fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result> { +/// +/// `cancel` is checked the moment the seat is claimed and again around the +/// header read: a cancel that lands before either point is answered without +/// spending a read nobody wants the result of, with [`crate::demux::is_cancelled`] +/// true of the error -- and the seat this claimed is given back the same way +/// a cancelled encode's is, [`Claim`]'s own `Drop`, run on the early return +/// exactly as it is on the ordinary one. +fn started( + source: &Path, + only_if: fn(&VideoMeta) -> bool, + cancel: &Arc, +) -> crate::Result> { let out = path_for(source).ok_or("no cache directory to keep a proxy in")?; if out.is_file() { return Ok(Some(Job { @@ -493,10 +519,18 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result Arc { + Arc::new(AtomicBool::new(false)) + } + fn meta(width: u32, height: u32, codec: Codec) -> VideoMeta { VideoMeta { width, @@ -738,7 +778,7 @@ mod tests { for name in ["tone.wav", "song.mp3", "track.mka", "still.png", "shot.jpg"] { let file = dir.join(name); std::fs::write(&file, b"not a film, and never read").expect("write"); - let answer = generate_if_wanted(&file); + let answer = generate_if_wanted(&file, &uncancelled()); assert!( matches!(answer, Ok(None)), "{name} is not a film to stand in for: {:?}", @@ -758,7 +798,7 @@ mod tests { crate::demux::NoVideoTrack::is_it(&refusal), "not the no-picture answer: {refusal}" ); - let answer = generate_if_wanted(&silent_film); + let answer = generate_if_wanted(&silent_film, &uncancelled()); assert!( matches!(answer, Ok(None)), "an audio-only mp4 is not a film to stand in for: {:?}", @@ -873,7 +913,7 @@ mod tests { assert!(is_off(&file), "the mark is beside the cache entry"); // Which is what the sweep asks -- and it does not even read the header. assert!( - matches!(generate_if_wanted(&file), Ok(None)), + matches!(generate_if_wanted(&file, &uncancelled()), Ok(None)), "a switched-off film was started again" ); set_off(&file, false); @@ -891,6 +931,37 @@ mod tests { std::fs::remove_file(stale).expect("the old mark"); } + /// DEBT #91: a cancel already up when the Asked phase starts must answer + /// promptly and never touch the header at all -- before this, the flag + /// [`generate_if_wanted`] takes did not exist, so nothing here could be + /// cancelled before a [`Job`] existed to call [`Job::cancel`] on, and the + /// only way to see this pass on old code was to change the signature. + /// + /// The file is never a real film: the cancel is answered at the door, + /// before [`Demuxer::open`] is ever reached, which is what "promptly" + /// means here and what proves the header was never read. + #[test] + fn a_cancel_set_before_the_ask_stops_it_at_the_door() { + let dir = crate::scratch::Scratch::dir("proxy-cancel-at-door"); + let file = dir.join("a.mp4"); + std::fs::write(&file, b"not a real film, and never read").expect("write"); + let cancel = Arc::new(AtomicBool::new(true)); + + let answer = generate_if_wanted(&file, &cancel); + let err = answer.err().expect("a pre-cancelled ask must not hand back a job"); + assert!( + crate::demux::is_cancelled(&err), + "not the cancelled answer: {err}" + ); + assert_eq!(cached(&file), None, "no proxy was produced"); + + // Settled the same way a cancelled `Making` is: the seat this claimed + // is given back, so the very next ask -- uncancelled -- is free to take + // it rather than being told one is "already being made". + let out = path_for(&file).expect("a key"); + assert!(claim(&out).is_some(), "the door-cancel left the seat held"); + } + /// One encoder per film, in the engine and not only in the window that /// draws the switch: the seat is taken for as long as the job lives, and a /// second start for the same stand-in is refused rather than allowed to