diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 041b235db..f8c596189 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -554,7 +554,68 @@ impl Sources { /// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait /// for it (`None`: failed to open; not retried until `forget`), with the file's identity as /// opened. -type SourceSlot = Arc, ReadFile)>>; +type SourceSlot = Arc; + +#[derive(Default)] +struct Source { + opened: OnceLock<(Option, ReadFile)>, + #[cfg(not(target_arch = "wasm32"))] + dispatch: Mutex, +} + +#[cfg(not(target_arch = "wasm32"))] +type DecodeJob = Box; + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Dispatch { + active: bool, + pending: VecDeque, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Source { + fn enqueue(self: &Arc, workers: &'static rayon::ThreadPool, job: DecodeJob) { + let mut dispatch = lock(&self.dispatch); + if dispatch.active { + dispatch.pending.push_back(job); + return; + } + dispatch.active = true; + drop(dispatch); + self.start(workers, job); + } + + fn start(self: &Arc, workers: &'static rayon::ThreadPool, job: DecodeJob) { + let source = self.clone(); + workers.spawn_fifo(move || { + // Release on errors and unwinding too. Never hold the dispatch lock during a decode. + let _permit = DecodePermit { source, workers }; + job(); + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +struct DecodePermit { + source: SourceSlot, + workers: &'static rayon::ThreadPool, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for DecodePermit { + fn drop(&mut self) { + let mut dispatch = lock(&self.source.dispatch); + let next = dispatch.pending.pop_front(); + if next.is_none() { + dispatch.active = false; + } + drop(dispatch); + if let Some(job) = next { + self.source.start(self.workers, job); + } + } +} /// An opened movie/audio source, the turn its picture is shown with and the order its decoded /// audio channels arrive in. @@ -1198,7 +1259,11 @@ impl Inner { /// Each call notes the file as read (see [`crate::reads`]), with its identity as opened. fn opened(&self, path: &Arc) -> Option { let slot = lock(&self.sources).slot(path); - let (opened, file) = slot.get_or_init(|| self.open(path)); + self.opened_in(path, &slot) + } + + fn opened_in(&self, path: &Arc, slot: &SourceSlot) -> Option { + let (opened, file) = slot.opened.get_or_init(|| self.open(path)); reads::note(file.clone()); opened.clone() } @@ -1634,6 +1699,10 @@ impl Inner { /// (wasm32) or this is one of them. With the files the decode read (see [`crate::reads`]): /// collected on the thread that decodes, not noted anywhere (the caller notes them). fn run_decode(self: &Arc, loc: &Loc, footage: &Footage) -> (Result, ReadFiles) { + // A codec can yield to Rayon while holding its source's decoder mutex. Keep later + // roots for that source OUT of the work-stealing pool until this root finishes (#4074). + // Carry the slot too: forget/reopen must not pair an old permit with a new decoder. + let source = loc.media_t.map(|_| lock(&self.sources).slot(&loc.key.path)); #[cfg(not(target_arch = "wasm32"))] if let Some(threads) = decode_threads() && threads.current_thread_index().is_none() @@ -1642,14 +1711,20 @@ impl Inner { let (me, at, f) = (self.clone(), loc.clone(), footage.clone()); // The request's cancel flag and decoding hints go with it (#329). let hints = filmcraft_media::cancel::Context::current(); - threads.spawn(move || { + let slot = source.clone(); + let job = Box::new(move || { #[cfg(not(test))] - let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f))); + let decoded = reads::captured(|| hints.run(|| me.decode_source(&at, &f, slot.as_ref()))); // (the decodes counted on that thread are this thread's) #[cfg(test)] - let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f)))); + let decoded = crate::exr_channels::counting(|| reads::captured(|| hints.run(|| me.decode_source(&at, &f, slot.as_ref())))); let _ = tx.send(decoded); }); + if let Some(source) = &source { + source.enqueue(threads, job); + } else { + threads.spawn(job); + } // A plain block: this thread runs nothing else meanwhile. return match rx.recv() { #[cfg(not(test))] @@ -1668,11 +1743,14 @@ impl Inner { }; } let _decoding = Decoding::new(); - reads::captured(|| self.decode_source(loc, footage)) + reads::captured(|| self.decode_source(loc, footage, source.as_ref())) } /// Decode the picture `loc` names: a still whole, a movie frame at its size. - fn decode_source(&self, loc: &Loc, footage: &Footage) -> Result { + fn decode_source(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result { + if filmcraft_media::cancel::cancelled() { + return Err(MediaError::Cancelled); + } self.decodes.fetch_add(1, Ordering::Relaxed); #[cfg(test)] { @@ -1684,7 +1762,7 @@ impl Inner { } match loc.media_t { None => self.decode_still(loc, footage).map(|img| Pixels::F32(Arc::new(img))), - Some(_) => self.decode_media(loc, footage), + Some(_) => self.decode_media(loc, footage, source), } } @@ -1748,7 +1826,7 @@ impl Inner { } } - fn decode_media(&self, loc: &Loc, footage: &Footage) -> Result { + fn decode_media(&self, loc: &Loc, footage: &Footage, source: Option<&SourceSlot>) -> Result { let op = AlphaOp::of(footage, loc.float); let path = &loc.key.path; let f32 = |img| Pixels::F32(Arc::new(img)); @@ -1760,7 +1838,8 @@ impl Inner { Ok(f32(dynamic_to_image(frame, op))) } Some(mt) => { - let Opened { src, turn, .. } = self.opened(path).ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?; + let opened = source.map_or_else(|| self.opened(path), |slot| self.opened_in(path, slot)); + let Opened { src, turn, .. } = opened.ok_or_else(|| MediaError::Io(format!("{path}: cannot open")))?; // A movie shown turned a quarter (a phone held upright): the footage's size and // the render's are the turned picture's, the decoded frame's are the file's. let side = |(w, h): (u32, u32)| if crate::probe::swaps_sides(turn) { (h, w) } else { (w, h) }; @@ -2489,6 +2568,70 @@ mod tests { .collect() } + /// #4074: nested codec work may steal another root. A queued same-source root must not + /// re-enter its locked decoder, and an independent source must still make progress. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn movie_dispatch_does_not_reenter_a_locked_source() { + let workers: &'static _ = Box::leak(Box::new(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap())); + let codec = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap()); + let source = SourceSlot::default(); + let decoder = Arc::new(Mutex::new(())); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let first_decoder = decoder.clone(); + source.enqueue( + workers, + Box::new(move || { + let _decoder = lock(&first_decoder); + codec.install(move || { + entered_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + }), + ); + entered_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + source.enqueue( + workers, + Box::new(move || { + let _decoder = lock(&decoder); + done_tx.send(()).unwrap(); + }), + ); + let other = SourceSlot::default(); + let (other_tx, other_rx) = std::sync::mpsc::channel(); + other.enqueue(workers, Box::new(move || other_tx.send(()).unwrap())); + let independent = other_rx.recv_timeout(std::time::Duration::from_secs(2)); + // Always release the codec, including on regression failure. The timeout bounds a + // deadlock; no decode duration or throughput is being asserted. + release_tx.send(()).unwrap(); + assert!(independent.is_ok(), "another source must finish while this codec is parked"); + done_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn movie_dispatch_releases_queued_work_after_a_panic() { + let workers: &'static _ = Box::leak(Box::new(rayon::ThreadPoolBuilder::new().num_threads(1).panic_handler(|_| {}).build().unwrap())); + let source = SourceSlot::default(); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + source.enqueue( + workers, + Box::new(move || { + entered_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + panic!("a codec failed"); + }), + ); + entered_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + source.enqueue(workers, Box::new(move || done_tx.send(()).unwrap())); + release_tx.send(()).unwrap(); + done_rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap(); + } + /// #3269: requests for a frame being decoded wait for that decode and take its picture, also /// on rayon workers (the viewer's frame workers), which each decoded a private copy before. #[test]