From 4d0dd2b9a2819a1de8131993b4e232210f71cb7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 13 Aug 2026 14:04:33 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(import):=20Cancel=20stops=20?= =?UTF-8?q?the=20read,=20not=20only=20the=20landing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Cancel beside the import line gave the window back and let the disk carry on: a cancelled cold 24 GB remux still cost its twenty seconds, and the notice said so rather than doing anything about it. The flag now reaches the walk — `demux::with_cancel` installs it as the reading thread's own, and every Matroska cluster the header index and the subtitle pass step over checks it and gives up there, with `is_cancelled` telling an abandoned read from a file that would not open. Thread-scoped rather than a parameter, deliberately: a read *is* a thread here (an import worker, an audio feeder, a decode worker), and the walk that has to stop sits five frames under an `open` with a dozen callers, none of which have anything to cancel. An mp4's header stays uncancellable — it is one read inside `mp4::Mp4Reader` with no flag to poll — so the notice and the button say the read stops "where the container lets it" instead of promising the disk went quiet. The feeder's own abandoned opens are NOT wired to this, and the corner-cut in `spawn_feeder_deferred` says why: three runs of one build over 200 cold scrub steps measured 14, 101 and 137 live workers, so that number is the machine's and not the cancel's — and cancelling every step's walk would stop the sidecar index from ever being written, which is the thing that makes the second pass over a film fast. --- crates/app/src/importing.rs | 16 ++++-- crates/app/src/player/library.rs | 18 ++++-- crates/app/src/ui/overlays.rs | 4 +- crates/engine/src/audio.rs | 20 +++++++ crates/engine/src/demux.rs | 95 ++++++++++++++++++++++++++++++++ crates/engine/src/playback.rs | 50 +++++++++++++++-- crates/engine/tests/playback.rs | 70 +++++++++++++++++++++++ 7 files changed, 255 insertions(+), 18 deletions(-) diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index f73d9e1..a87c8e3 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -81,12 +81,16 @@ pub(crate) struct Import { /// the landing: what the worker read is dropped instead of joining the /// timeline. /// - /// corner-cut: the *read* is not stopped -- a demuxer walk polls nothing, so - /// the worker finishes into a result nobody takes, and the window is given - /// back at the click either way. Ceiling: a cancelled cold 24 GB import - /// still costs the disk its twenty seconds. Upgrade: a flag - /// `engine::demux::Demuxer::open` polls between clusters, which is where an - /// export's own cancel already lives ([`engine::ExportHandle::cancel`]). + /// ...and the read with it: the worker installs this as its thread's cancel + /// ([`engine::demux::with_cancel`]) and every Matroska cluster walk under it + /// -- the header index and the subtitle pass, the twenty seconds of a cold + /// 24 GB remux -- gives up at the next element. + /// + /// corner-cut: an mp4's header is one read inside `mp4::Mp4Reader`, which + /// has no flag to poll, so a cancelled mp4 import still finishes its own + /// header before the worker returns. Ceiling: the disk stays busy for that + /// read, though nothing waits on it. Upgrade path is our own `moov` parse, + /// which is a demuxer rewrite rather than a cancel. pub(crate) cancelled: Arc, } diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index c40c901..a964d43 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -257,7 +257,14 @@ impl Player { let gate = self.session.as_ref().map(PlaybackSession::import_gate); let read = cx.background_executor().spawn({ let (path, stage) = (path.clone(), Arc::clone(&stage)); - async move { open_ahead(what, &path, &stage, gate) } + let cancelled = Arc::clone(&cancelled); + // The Cancel beside the line reaches the *walk* this way: every + // cluster the reads below step over checks this flag, so a stopped + // import stops the disk rather than only the landing + // ([`engine::demux::with_cancel`]). + async move { + engine::demux::with_cancel(&cancelled, || open_ahead(what, &path, &stage, gate)) + } }); let now = Instant::now(); self.importing = Some(Import { @@ -311,9 +318,10 @@ impl Player { /// leaving five to start themselves would be the same wait under another /// name. /// - /// The read in flight is *not* stopped, for the reason [`Import::cancelled`] - /// gives, and the notice says as much rather than promising the disk went - /// quiet. + /// The read in flight is stopped too, where the container lets it be: a + /// Matroska walk checks this flag between clusters and gives up there + /// ([`engine::demux::with_cancel`]). See [`Import::cancelled`] for what an + /// mp4 header still costs. pub(crate) fn cancel_import(&mut self, cx: &mut Context) { let Some(import) = self.importing.take() else { return; @@ -328,7 +336,7 @@ impl Player { n => format!(" — {n} more dropped from the queue"), }; let text = format!( - "IMPORT CANCELLED: {}{tail} — the read already running finishes unheeded", + "IMPORT CANCELLED: {}{tail} — the read stops where the container lets it", file_name(&import.path) ); eprintln!("{text}"); diff --git a/crates/app/src/ui/overlays.rs b/crates/app/src/ui/overlays.rs index 2389cdc..0b869a5 100644 --- a/crates/app/src/ui/overlays.rs +++ b/crates/app/src/ui/overlays.rs @@ -58,8 +58,8 @@ impl Player { BG_RAISED(), None, "Cancel", - "stops this file and anything queued behind it; the read already \ - running finishes unheeded" + "stops this file and anything queued behind it, and the read with \ + them where the container lets it stop" .to_string(), true, cx.listener(|this, _: &ClickEvent, _, cx| this.cancel_import(cx)), diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 6a4564e..7b95ac8 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -201,6 +201,14 @@ pub struct MixControls { state: Mutex<(Vec, Limiter)>, /// A mixer thread has these; see the type docs. live: AtomicBool, + /// The open these were handed to finished without a mixer: a silent + /// timeline, or a source that would not open. Set by whoever ran that open + /// ([`PlaybackSession::start_audio`] does it from the feeder), because + /// [`Self::live`] alone cannot tell "no mixer will ever read this" from + /// "the mixer is still being opened" -- and a caller that cannot tell those + /// apart either rebuilds the sound under a cold open, once per fader nudge, + /// or hands a mix to nobody and never notices. + detached: AtomicBool, } impl MixControls { @@ -209,6 +217,7 @@ impl MixControls { version: AtomicU64::new(0), state: Mutex::new((gains, limiter)), live: AtomicBool::new(false), + detached: AtomicBool::new(false), }) } @@ -224,6 +233,17 @@ impl MixControls { self.live.load(Ordering::Acquire) } + /// Says the open is over and left no mixer behind; see [`Self::detached`]. + pub fn detach(&self) { + self.detached.store(true, Ordering::Release); + } + + /// Whether anything can still hear a [`set`](Self::set): a mixer reading + /// these, or an open still on its way to being one. + pub fn is_reachable(&self) -> bool { + !self.detached.load(Ordering::Acquire) + } + /// The mix, if it has moved since `seen`. `None` -- the every-block case -- /// takes no lock. fn changed(&self, seen: &mut u64) -> Option<(Vec, Limiter)> { diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 4378977..a20975a 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -26,6 +26,57 @@ use crate::colorspace::{ColorDescription, ContentLight, Tags, bitstream_tags}; const START_CODE: [u8; 4] = [0, 0, 0, 1]; +/// What a cancelled read fails with. A message rather than a variant because +/// [`crate::Error`] is a boxed error and always was; [`is_cancelled`] is what +/// tells this apart from a file that really would not open, so an abandoned +/// read is never reported to anyone as a broken file. +const CANCELLED: &str = "read cancelled"; + +thread_local! { + /// The flag the read running on *this* thread is abandoned by, installed by + /// [`with_cancel`]. + /// + /// Thread-scoped rather than passed down, and deliberately: a read is a + /// thread here -- an import worker, an audio feeder, a decode worker -- and + /// the walk that has to be stopped sits five frames under an `open` with a + /// dozen callers, none of which have anything to cancel. This way the two + /// that do say so at the top of their own thread and every loop below them + /// obeys, at the price of one thread-local load per cluster. + static CANCEL: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +/// Runs `read` with `flag` as this thread's cancel: setting it abandons the +/// walks inside at their next element, with [`CANCELLED`] rather than a verdict +/// about the file. Restores whatever was installed before, so a nested read is +/// not silently un-cancelled. +pub fn with_cancel( + flag: &std::sync::Arc, + read: impl FnOnce() -> T, +) -> T { + let previous = CANCEL.with(|cell| cell.borrow_mut().replace(flag.clone())); + let out = read(); + CANCEL.with(|cell| *cell.borrow_mut() = previous); + out +} + +/// Whether the read on this thread has been abandoned; `false` where nobody +/// installed a flag, which is every caller that has nothing to cancel. +fn cancelled() -> bool { + CANCEL.with(|cell| { + cell.borrow() + .as_ref() + .is_some_and(|flag| flag.load(Ordering::Acquire)) + }) +} + +/// Whether `error` is a read that was abandoned rather than a file that could +/// not be read: what keeps a cancelled import off the notice bar and a +/// superseded audio open off stderr. +pub fn is_cancelled(error: &crate::Error) -> bool { + error.to_string() == CANCELLED +} + /// 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. @@ -2641,6 +2692,13 @@ fn mkv_walk_blocks(file: &mut File, segment: (u64, u64), number: u64) -> crate:: let mut laced: Vec<(usize, usize)> = Vec::new(); let mut at = segment.0; while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { + // The whole segment is the walk a cancel exists for -- twenty seconds of + // disk on a cold 25 GB remux -- and this is where a Cancel beside an + // import, or a scrub step that superseded this open two hundred steps + // ago, stops the *read* instead of dropping its answer. + if cancelled() { + return Err(CANCELLED.into()); + } at = stop; if id != CLUSTER { continue; @@ -3929,6 +3987,10 @@ fn mkv_subtitle_blocks( let us = |ticks: i64| ticks * timestamp_scale as i64 / 1_000; let mut at = segment.0; while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { + // The import's second walk, stopped by the same Cancel as its first. + if cancelled() { + return Err(CANCELLED.into()); + } at = stop; if id != CLUSTER { continue; @@ -4027,6 +4089,39 @@ mod tests { found } + /// **A cancelled walk stops walking.** The flag the import's Cancel and a + /// superseded audio open both set ([`with_cancel`]) is read by the segment + /// walk itself, so the answer is an abandoned read rather than a verdict + /// about the file -- and the same walk without it still opens. + #[test] + fn a_cancelled_walk_gives_up_and_says_so() { + let Some(path) = matroska_fixtures().into_iter().next() else { + eprintln!("no Matroska fixture: the cancel walk is not measured"); + return; + }; + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let (_, lazy) = MkvDemuxer::open(&path).expect(&name); + let (segment, number) = (lazy.segment, lazy.number); + let mut file = File::open(&path).expect(&name); + + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + let stopped = with_cancel(&flag, || mkv_walk_blocks(&mut file, segment, number)); + let error = stopped.err().expect("a cancelled walk must not answer"); + assert!( + is_cancelled(&error), + "{name}: a cancelled walk reported {error} -- a verdict about the file" + ); + + // ...and nothing is cancelled by having been near a flag: the walk that + // was not asked to stop is the walk it always was. + flag.store(false, Ordering::Release); + let walked = with_cancel(&flag, || mkv_walk_blocks(&mut file, segment, number)); + assert!( + walked.is_ok_and(|(blocks, ..)| !blocks.is_empty()), + "{name}: the uncancelled walk found nothing" + ); + } + /// **The lazy index is the same index.** For every Matroska fixture, the /// window built off the file's `Cues` and the whole-segment walk it replaced /// agree on: the block list, the frame count, and where every one of the diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 617a394..bad0255 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -205,6 +205,20 @@ impl Audio { /// The epoch is captured *here*, at the seek, not when the open returns: a /// scrub abandons opens by the dozen and every one of them must still be /// the stale stream it was started as, however late it lands. + /// + /// corner-cut: an abandoned open is not *cancelled*, though the machinery + /// for it exists ([`crate::demux::with_cancel`], which the import's Cancel + /// uses): it runs to the end and its answer is dropped. Tried, and left + /// out for want of evidence -- 200 cold scrub steps over the 25 GB HEVC + /// remux measured 101, 137 and 14 live workers on three runs of the *same* + /// build, so the machine decides that number and not this. There is a + /// reason to expect it to hurt, too: a Matroska walk writes its sidecar + /// index only when it finishes (`demux::mkv_blocks`), so a drag that + /// cancels every step's walk would never write one and every step would + /// walk the segment again from the top. Ceiling: an abandoned open keeps + /// reading, and the decoder threads it started live until it does. Upgrade + /// path is an index the walk publishes as it goes -- then cancelling costs + /// nothing and can be measured on an idle machine. fn spawn_feeder_deferred( &self, open: impl FnOnce() -> Option> + Send + 'static, @@ -1603,9 +1617,22 @@ impl PlaybackSession { fn push_mix(&mut self) { let gains = self.project.audio_gains(); let limiter = self.project.limiter(); - match &self.mix { - Some(mix) => mix.set(gains, limiter), - None => self.reseek_audio(), + // A mixer reading these, or an open on its way to being one: either way + // the number is heard without a rebuild, and *that* is what a handle + // left over from an open that found nothing cannot do + // ([`crate::audio::MixControls::is_reachable`]). + if let Some(mix) = self.mix.as_ref().filter(|mix| mix.is_reachable()) { + mix.set(gains, limiter); + return; + } + // Nothing to hand it to. Only a setting that *needs* a mixer is worth + // the flush and the re-open: a ceiling dragged with the limiter off, or + // a fader put back to unity, changes not one sample of the flat + // single-stream path the timeline is already playing + // ([`AudioSession::is_mixed`]), and reseeking per nudge was a hole in + // the sound for a change nobody could hear. + if crate::audio::AudioSession::is_mixed(gains.len(), &gains, limiter) { + self.reseek_audio(); } } @@ -2668,9 +2695,22 @@ impl PlaybackSession { Ok(Some((_, rx))) => Some(rx), // A silent timeline, and a source that will not open: both // feed nothing, which the feeder itself reports by ending. - Ok(None) => None, + // The mix goes with them -- no mixer was started, so a fader + // moved later must rebuild the sound rather than hand its + // number to a thread that does not exist + // ([`crate::audio::MixControls::detach`]). + Ok(None) => { + worker_controls.detach(); + None + } Err(e) => { - eprintln!("timeline audio open failed: {e}"); + worker_controls.detach(); + // A read this session abandoned on purpose -- the seek + // after it, or the session going away -- is not a file + // that would not open, and says nothing. + if !crate::demux::is_cancelled(&e) { + eprintln!("timeline audio open failed: {e}"); + } None } } diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index d3f684a..3346b8c 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -530,6 +530,76 @@ fn a_cold_seek_storm_starves_no_quantum() { ); } +/// What a *drag* costs in threads: 200 scrub steps across a cold film with no +/// wait between them, which is a ruler dragged from end to end. Every step +/// abandons an audio open and starts another, and an abandoned one used to run +/// its read to the end anyway -- on a cold film that is seconds each, so the +/// threads pile up behind the drag rather than following it. +/// +/// The session's own count is the oracle (`live_workers`), and the process +/// thread count beside it says what the OS saw. +#[test] +#[ignore = "needs a running PipeWire daemon"] +fn a_cold_scrub_does_not_pile_up_threads() { + let path = std::env::var_os("EDITH_COLD_FILM") + .map(PathBuf::from) + .unwrap_or_else(|| asset("test_av.mp4")); + let steps: u32 = std::env::var("EDITH_STEPS") + .ok() + .and_then(|n| n.parse().ok()) + .unwrap_or(200); + let mut session = open(&path); + let duration = session.timeline_duration(); + let mut last_index = None; + session.play(); + run_for(&mut session, &mut last_index, Duration::from_millis(300)); + evict(&path); + + let (mut peak, mut peak_os) = (0, 0); + let scrub = Instant::now(); + for step in 0..steps { + session.seek(duration * f64::from(step) / f64::from(steps)); + session.tick(); + while session.try_frame().is_some() {} + peak = peak.max(session.live_workers()); + peak_os = peak_os.max(os_threads()); + sleep(Duration::from_millis(16)); // a drag reports at ~60 Hz + } + eprintln!( + "{steps} cold scrub steps in {:?}: peak {peak} session workers, {peak_os} process threads", + scrub.elapsed() + ); + // The peak is *reported*, not asserted: three runs of one build over the + // same film measured 14, 101 and 137, because what decides it is how much + // disk the rest of the machine is using while the opens run. What the + // session owes is a different question and a real one -- every worker the + // drag started has to end, or a drag is a leak. + let deadline = Instant::now() + Duration::from_secs(120); + while session.live_workers() > 2 { + assert!( + Instant::now() < deadline, + "the scrub leaked workers: {} still running two minutes on", + session.live_workers() + ); + sleep(Duration::from_millis(50)); + } + eprintln!("all but {} of them returned", session.live_workers()); +} + +/// Threads in this process, out of `/proc/self/status`. Only ever a report +/// beside the session's own count -- a suite decoding other files at the same +/// time moves this number without touching the session under test. +fn os_threads() -> usize { + std::fs::read_to_string("/proc/self/status") + .ok() + .and_then(|status| { + status + .lines() + .find_map(|line| line.strip_prefix("Threads:")?.trim().parse().ok()) + }) + .unwrap_or(0) +} + /// The edit list end to end: two cuts, drop the middle clip, play the result. /// What comes out is one contiguous timeline whose *pictures* skip the hole -- /// no audio needed, so this runs anywhere.