Join workers on drop — Mesa atexit race killed exiting processes
Browse files at this commit9276137148c863fe7db33b14ac8518aea8273333Parent: 9fa0211- fix
- join workers on drop — Mesa atexit race killed exiting processes
3 changed files +152 -20
- crates/engine/examples/drop_cost.rs +28 -0
- crates/engine/src/decode.rs +79 -3
- crates/engine/src/playback.rs +45 -17
crates/engine/examples/drop_cost.rsadded+28 -0
| @@ -0,0 +1,28 @@ | |||
| 1 | +//! Scratch: how long a PlaybackSession takes to drop now that it joins its | ||
| 2 | +//! decode worker. Worst case is what a UI scrub pays per abandoned session. | ||
| 3 | +use std::time::Instant; | ||
| 4 | + | ||
| 5 | +fn main() { | ||
| 6 | + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/test_av.mp4"); | ||
| 7 | + let mut worst = 0f64; | ||
| 8 | + for i in 0..20 { | ||
| 9 | + let session = engine::PlaybackSession::open(path).expect("open"); | ||
| 10 | + let t = Instant::now(); | ||
| 11 | + drop(session); | ||
| 12 | + let ms = t.elapsed().as_secs_f64() * 1000.0; | ||
| 13 | + worst = worst.max(ms); | ||
| 14 | + eprintln!("run {i}: drop {ms:.1} ms"); | ||
| 15 | + } | ||
| 16 | + eprintln!("worst drop: {worst:.1} ms"); | ||
| 17 | + | ||
| 18 | + // The scrub path: every seek now joins the worker it replaces. | ||
| 19 | + let mut session = engine::PlaybackSession::open(path).expect("open"); | ||
| 20 | + let mut worst_seek = 0f64; | ||
| 21 | + for i in 0..20 { | ||
| 22 | + let t = Instant::now(); | ||
| 23 | + session.seek(f64::from(i) * 0.2); | ||
| 24 | + let ms = t.elapsed().as_secs_f64() * 1000.0; | ||
| 25 | + worst_seek = worst_seek.max(ms); | ||
| 26 | + } | ||
| 27 | + eprintln!("worst seek: {worst_seek:.1} ms"); | ||
| 28 | +} | ||
crates/engine/src/decode.rsmodified+79 -3
| @@ -23,6 +23,44 @@ pub struct Frame { | |||
| 23 | pub bgra: Vec<u8>, | 23 | pub bgra: Vec<u8>, |
| 24 | } | 24 | } |
| 25 | 25 | ||
| 26 | +/// A running decode worker: the flag that stops it, and the handle to wait on. | ||
| 27 | +/// | ||
| 28 | +/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` | ||
| 29 | +/// outlives the process otherwise, and Mesa's `atexit` handlers free the state | ||
| 30 | +/// it is still reading -- a SIGSEGV at exit, long after the last test passed. | ||
| 31 | +pub(crate) struct Worker { | ||
| 32 | + cancel: Arc<AtomicBool>, | ||
| 33 | + /// `None` once detached, and for a range with nothing to decode: either way | ||
| 34 | + /// there is no thread left to wait for. | ||
| 35 | + handle: Option<thread::JoinHandle<()>>, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +impl Worker { | ||
| 39 | + /// Stops the worker at its next check without waiting. Callers that replace | ||
| 40 | + /// a worker should do this first and drop the receiver second: a worker | ||
| 41 | + /// parked in `send` only wakes on the disconnect, so the join below would | ||
| 42 | + /// otherwise wait for a consumer that is never coming. | ||
| 43 | + pub(crate) fn cancel(&self) { | ||
| 44 | + self.cancel.store(true, Ordering::Release); | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /// Lets the worker run on unwatched -- what the public API does, since it | ||
| 48 | + /// hands out the flag alone. | ||
| 49 | + fn detach(mut self) -> Arc<AtomicBool> { | ||
| 50 | + self.handle = None; | ||
| 51 | + Arc::clone(&self.cancel) | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +impl Drop for Worker { | ||
| 56 | + fn drop(&mut self) { | ||
| 57 | + if let Some(handle) = self.handle.take() { | ||
| 58 | + self.cancel(); | ||
| 59 | + let _ = handle.join(); | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 26 | pub struct DecodeSession; | 64 | pub struct DecodeSession; |
| 27 | 65 | ||
| 28 | impl DecodeSession { | 66 | impl DecodeSession { |
| @@ -57,6 +95,18 @@ impl DecodeSession { | |||
| 57 | start_frame: u32, | 95 | start_frame: u32, |
| 58 | end_frame: u32, | 96 | end_frame: u32, |
| 59 | ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> { | 97 | ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> { |
| 98 | + let (meta, rx, worker) = Self::open_worker(path, start_frame, end_frame)?; | ||
| 99 | + Ok((meta, rx, worker.detach())) | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + /// As [`DecodeSession::open_range`], but the caller gets the whole | ||
| 103 | + /// [`Worker`] and can therefore *wait* for it. In-process only: a caller | ||
| 104 | + /// that outlives its workers has to be able to join them at exit. | ||
| 105 | + pub(crate) fn open_worker( | ||
| 106 | + path: impl AsRef<Path>, | ||
| 107 | + start_frame: u32, | ||
| 108 | + end_frame: u32, | ||
| 109 | + ) -> crate::Result<(VideoMeta, Receiver<Frame>, Worker)> { | ||
| 60 | let path = path.as_ref().to_path_buf(); | 110 | let path = path.as_ref().to_path_buf(); |
| 61 | let (meta, demuxer) = Demuxer::open(&path)?; | 111 | let (meta, demuxer) = Demuxer::open(&path)?; |
| 62 | let end_frame = end_frame.min(meta.frame_count); | 112 | let end_frame = end_frame.min(meta.frame_count); |
| @@ -67,15 +117,34 @@ impl DecodeSession { | |||
| 67 | if end_frame <= start_frame { | 117 | if end_frame <= start_frame { |
| 68 | // Nothing to decode: dropping `tx` here closes the channel cleanly, | 118 | // Nothing to decode: dropping `tx` here closes the channel cleanly, |
| 69 | // so the caller sees an immediate end of stream rather than an error. | 119 | // so the caller sees an immediate end of stream rather than an error. |
| 70 | - return Ok((meta, rx, cancel)); | 120 | + return Ok(( |
| 121 | + meta, | ||
| 122 | + rx, | ||
| 123 | + Worker { | ||
| 124 | + cancel, | ||
| 125 | + handle: None, | ||
| 126 | + }, | ||
| 127 | + )); | ||
| 71 | } | 128 | } |
| 72 | let worker_cancel = Arc::clone(&cancel); | 129 | let worker_cancel = Arc::clone(&cancel); |
| 73 | - thread::Builder::new() | 130 | + let handle = thread::Builder::new() |
| 74 | .name("decode".into()) | 131 | .name("decode".into()) |
| 75 | .spawn(move || { | 132 | .spawn(move || { |
| 133 | + // Cancelled before this thread was even scheduled -- do not | ||
| 134 | + // enter VA-API initialisation at all, because that is the one | ||
| 135 | + // stretch a cancel cannot interrupt (~65-90 ms of driver setup | ||
| 136 | + // that would then have to be torn down again). | ||
| 137 | + if worker_cancel.load(Ordering::Relaxed) { | ||
| 138 | + return; | ||
| 139 | + } | ||
| 76 | // The plugin has to be opened on the thread that uses it: its | 140 | // The plugin has to be opened on the thread that uses it: its |
| 77 | // VA-API state is not `Send`-safe across a later hand-off. | 141 | // VA-API state is not `Send`-safe across a later hand-off. |
| 78 | if let Some(hw) = open_hw(&path, start_frame) { | 142 | if let Some(hw) = open_hw(&path, start_frame) { |
| 143 | + // Cancelled *during* init: close the session (dropping `hw` | ||
| 144 | + // does it) and leave without decoding anything. | ||
| 145 | + if worker_cancel.load(Ordering::Relaxed) { | ||
| 146 | + return; | ||
| 147 | + } | ||
| 79 | eprintln!("decode backend: hardware (VA-API plugin)"); | 148 | eprintln!("decode backend: hardware (VA-API plugin)"); |
| 80 | if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) { | 149 | if run_hw(hw, &tx, start_frame, end_frame, &worker_cancel) { |
| 81 | return; | 150 | return; |
| @@ -87,7 +156,14 @@ impl DecodeSession { | |||
| 87 | eprintln!("decode backend: software (rusty_h264)"); | 156 | eprintln!("decode backend: software (rusty_h264)"); |
| 88 | run(demuxer, tx, start_frame, end_frame, &worker_cancel) | 157 | run(demuxer, tx, start_frame, end_frame, &worker_cancel) |
| 89 | })?; | 158 | })?; |
| 90 | - Ok((meta, rx, cancel)) | 159 | + Ok(( |
| 160 | + meta, | ||
| 161 | + rx, | ||
| 162 | + Worker { | ||
| 163 | + cancel, | ||
| 164 | + handle: Some(handle), | ||
| 165 | + }, | ||
| 166 | + )) | ||
| 91 | } | 167 | } |
| 92 | } | 168 | } |
| 93 | 169 | ||
crates/engine/src/playback.rsmodified+45 -17
| @@ -21,7 +21,7 @@ use std::time::Duration; | |||
| 21 | use crate::ao::AoSession; | 21 | use crate::ao::AoSession; |
| 22 | use crate::audio::{AudioChunk, AudioSession}; | 22 | use crate::audio::{AudioChunk, AudioSession}; |
| 23 | use crate::clock::{ClockSource, PlaybackClock}; | 23 | use crate::clock::{ClockSource, PlaybackClock}; |
| 24 | -use crate::decode::{DecodeSession, Frame}; | 24 | +use crate::decode::{DecodeSession, Frame, Worker}; |
| 25 | use crate::demux::{Demuxer, VideoMeta}; | 25 | use crate::demux::{Demuxer, VideoMeta}; |
| 26 | use crate::project::{Clip, Project}; | 26 | use crate::project::{Clip, Project}; |
| 27 | 27 | ||
| @@ -84,9 +84,10 @@ impl Audio { | |||
| 84 | pub struct PlaybackSession { | 84 | pub struct PlaybackSession { |
| 85 | meta: VideoMeta, | 85 | meta: VideoMeta, |
| 86 | frames: Receiver<Frame>, | 86 | frames: Receiver<Frame>, |
| 87 | - /// Stops the current decode worker, so an abandoned one cannot outlive a | 87 | + /// The current decode worker. Replacing or dropping this field cancels and |
| 88 | - /// seek by more than one access unit. | 88 | + /// joins the previous one, so no abandoned worker outlives the session -- |
| 89 | - cancel: Arc<AtomicBool>, | 89 | + /// which is what keeps a worker out of the driver's teardown at exit. |
| 90 | + worker: Worker, | ||
| 90 | clock: PlaybackClock, | 91 | clock: PlaybackClock, |
| 91 | audio: Option<Audio>, | 92 | audio: Option<Audio>, |
| 92 | /// The edit list. Everything a caller says in seconds is a *timeline* | 93 | /// The edit list. Everything a caller says in seconds is a *timeline* |
| @@ -107,22 +108,22 @@ impl PlaybackSession { | |||
| 107 | /// a file we cannot hear is still a file we can watch. | 108 | /// a file we cannot hear is still a file we can watch. |
| 108 | pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> { | 109 | pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> { |
| 109 | let path = path.as_ref().to_path_buf(); | 110 | let path = path.as_ref().to_path_buf(); |
| 110 | - // `open_at(_, 0)` rather than `open` purely for the cancel handle: the | 111 | + // `open_worker` rather than `open` purely for the worker handle: the |
| 111 | // field has to exist from the start for the first seek to use it. | 112 | // field has to exist from the start for the first seek to use it. |
| 112 | - let (meta, frames, cancel) = DecodeSession::open_at(&path, 0)?; | 113 | + let (meta, frames, worker) = DecodeSession::open_worker(&path, 0, u32::MAX)?; |
| 113 | let audio = open_audio(&path); | 114 | let audio = open_audio(&path); |
| 114 | let source = match audio { | 115 | let source = match audio { |
| 115 | Some(_) => ClockSource::Audio, | 116 | Some(_) => ClockSource::Audio, |
| 116 | None => ClockSource::Wall, | 117 | None => ClockSource::Wall, |
| 117 | }; | 118 | }; |
| 118 | // One clip covering the file, so timeline == source until the first | 119 | // One clip covering the file, so timeline == source until the first |
| 119 | - // edit -- and `open_at(_, 0)` is exactly that clip's range. | 120 | + // edit -- and the range opened above is exactly that clip's. |
| 120 | let project = Project::single(&path, meta.frame_count); | 121 | let project = Project::single(&path, meta.frame_count); |
| 121 | let range = project.clips()[0]; | 122 | let range = project.clips()[0]; |
| 122 | Ok(Self { | 123 | Ok(Self { |
| 123 | meta, | 124 | meta, |
| 124 | frames, | 125 | frames, |
| 125 | - cancel, | 126 | + worker, |
| 126 | clock: PlaybackClock::new(source), | 127 | clock: PlaybackClock::new(source), |
| 127 | audio, | 128 | audio, |
| 128 | project, | 129 | project, |
| @@ -152,7 +153,7 @@ impl PlaybackSession { | |||
| 152 | let first = doc.sources.first().ok_or("the project names no sources")?; | 153 | let first = doc.sources.first().ok_or("the project names no sources")?; |
| 153 | // Source 0 both scaffolds the session and defines the timeline, so it | 154 | // Source 0 both scaffolds the session and defines the timeline, so it |
| 154 | // is opened for playback rather than merely probed. | 155 | // is opened for playback rather than merely probed. |
| 155 | - let (meta, frames, cancel) = DecodeSession::open_at(first, 0) | 156 | + let (meta, frames, worker) = DecodeSession::open_worker(first, 0, u32::MAX) |
| 156 | .map_err(|e| format!("source {}: {e}", first.display()))?; | 157 | .map_err(|e| format!("source {}: {e}", first.display()))?; |
| 157 | let audio = open_audio(first); | 158 | let audio = open_audio(first); |
| 158 | let first_audio = AudioSession::probe(first)?; | 159 | let first_audio = AudioSession::probe(first)?; |
| @@ -184,7 +185,7 @@ impl PlaybackSession { | |||
| 184 | let mut session = Self { | 185 | let mut session = Self { |
| 185 | meta, | 186 | meta, |
| 186 | frames, | 187 | frames, |
| 187 | - cancel, | 188 | + worker, |
| 188 | clock: PlaybackClock::new(match audio { | 189 | clock: PlaybackClock::new(match audio { |
| 189 | Some(_) => ClockSource::Audio, | 190 | Some(_) => ClockSource::Audio, |
| 190 | None => ClockSource::Wall, | 191 | None => ClockSource::Wall, |
| @@ -270,10 +271,16 @@ impl PlaybackSession { | |||
| 270 | }; | 271 | }; |
| 271 | let clip = self.project.clips()[idx]; | 272 | let clip = self.project.clips()[idx]; |
| 272 | let out = clip.out_frame; | 273 | let out = clip.out_frame; |
| 273 | - match DecodeSession::open_range(&self.project.sources()[clip.source], source, out) { | 274 | + // We only get here on a disconnect, so the old worker has already |
| 274 | - Ok((_, frames, cancel)) => { | 275 | + // returned; cancel anyway, so the join below is unconditional in kind. |
| 276 | + self.worker.cancel(); | ||
| 277 | + match DecodeSession::open_worker(&self.project.sources()[clip.source], source, out) { | ||
| 278 | + Ok((_, frames, worker)) => { | ||
| 279 | + // Receiver first, worker second: the drop of the old receiver | ||
| 280 | + // is what would wake a worker parked in `send`, and only then | ||
| 281 | + // can the old worker's `Drop` join without waiting on us. | ||
| 275 | self.frames = frames; | 282 | self.frames = frames; |
| 276 | - self.cancel = cancel; | 283 | + self.worker = worker; |
| 277 | } | 284 | } |
| 278 | // Disappearing-file case, as in `seek`. The old receiver is still | 285 | // Disappearing-file case, as in `seek`. The old receiver is still |
| 279 | // disconnected, so the next pass moves on to the clip after this. | 286 | // disconnected, so the next pass moves on to the clip after this. |
| @@ -458,16 +465,24 @@ impl PlaybackSession { | |||
| 458 | // Cancel first, drop second: the old worker may be parked in `send` on | 465 | // Cancel first, drop second: the old worker may be parked in `send` on |
| 459 | // the bounded channel, where only the disconnect wakes it -- and it | 466 | // the bounded channel, where only the disconnect wakes it -- and it |
| 460 | // then finds the flag already set. | 467 | // then finds the flag already set. |
| 461 | - self.cancel.store(true, Ordering::Release); | 468 | + // |
| 469 | + // ponytail: replacing the worker below *joins* the outgoing one, so a | ||
| 470 | + // seek can cost one VA-API init (98 ms measured worst case, 1.6 ms | ||
| 471 | + // before this) and scrubbing is capped at ~10 seeks/s. If that shows in | ||
| 472 | + // the UI: park cancelled workers in a retire list instead, drop the | ||
| 473 | + // `is_finished` ones each seek and join whatever is left in `Drop` -- | ||
| 474 | + // same exit guarantee, no wait on the caller's thread. | ||
| 475 | + self.worker.cancel(); | ||
| 462 | // `target` is inside the timeline (never empty), so this always maps; | 476 | // `target` is inside the timeline (never empty), so this always maps; |
| 463 | // the range runs from there to the end of the clip it landed in. | 477 | // the range runs from there to the end of the clip it landed in. |
| 464 | if let Some((idx, source)) = self.project.map_timeline(target) { | 478 | if let Some((idx, source)) = self.project.map_timeline(target) { |
| 465 | let clip = self.project.clips()[idx]; | 479 | let clip = self.project.clips()[idx]; |
| 466 | let out = clip.out_frame; | 480 | let out = clip.out_frame; |
| 467 | - match DecodeSession::open_range(&self.project.sources()[clip.source], source, out) { | 481 | + match DecodeSession::open_worker(&self.project.sources()[clip.source], source, out) { |
| 468 | - Ok((_, frames, cancel)) => { | 482 | + Ok((_, frames, worker)) => { |
| 483 | + // Receiver first, worker second -- see `next_clip`. | ||
| 469 | self.frames = frames; | 484 | self.frames = frames; |
| 470 | - self.cancel = cancel; | 485 | + self.worker = worker; |
| 471 | } | 486 | } |
| 472 | // The file opened once already, so this is a disappearing-file | 487 | // The file opened once already, so this is a disappearing-file |
| 473 | // case: the timeline still moves, there are simply no more | 488 | // case: the timeline still moves, there are simply no more |
| @@ -562,6 +577,19 @@ impl PlaybackSession { | |||
| 562 | } | 577 | } |
| 563 | } | 578 | } |
| 564 | 579 | ||
| 580 | +impl Drop for PlaybackSession { | ||
| 581 | + /// The video worker cancels and joins itself when the `worker` field drops | ||
| 582 | + /// right after this; that is what a session must not exit without. This is | ||
| 583 | + /// the audio half: bumping the epoch retires the feeder at its next write, | ||
| 584 | + /// which drops the decode receiver with it. Neither is waited for -- no | ||
| 585 | + /// driver state is torn down on the audio side. | ||
| 586 | + fn drop(&mut self) { | ||
| 587 | + if let Some(audio) = &self.audio { | ||
| 588 | + audio.epoch.fetch_add(1, Ordering::Release); | ||
| 589 | + } | ||
| 590 | + } | ||
| 591 | +} | ||
| 592 | + | ||
| 565 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose | 593 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose |
| 566 | /// parameters are `timeline` and whose audio probes as `first`: same | 594 | /// parameters are `timeline` and whose audio probes as `first`: same |
| 567 | /// dimensions, same frame rate, same audio parameters or both silent -- one | 595 | /// dimensions, same frame rate, same audio parameters or both silent -- one |