A refused project load cannot hang on its own decoder
Browse files at this commit771cd4a5cfa892580f150666532b75447dd696d2Parent: 5bc0cf5- fix
- a refused project load cannot hang on its own decoder
3 changed files +156 -33
- crates/engine/src/decode.rs +83 -17
- crates/engine/src/playback.rs +32 -16
- crates/engine/tests/saveload.rs +41 -0
crates/engine/src/decode.rsmodified+83 -17
| @@ -70,6 +70,21 @@ impl Drop for Worker { | ||
| 70 | 70 | } |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | +/// A running worker and the frames it is sending, handed out as one value | |
| 74 | +/// because they must be *dropped* as one, in this order: the receiver | |
| 75 | +/// disconnects first, which is the only thing that wakes a worker parked in a | |
| 76 | +/// full `send`, and the join inside [`Worker::drop`] runs second. | |
| 77 | +/// | |
| 78 | +/// Rust drops fields in declaration order, so this struct *is* that rule, and | |
| 79 | +/// it holds wherever the value goes: an early return out of a half-built | |
| 80 | +/// session, an unwind, a caller not written yet. Two separate locals do not | |
| 81 | +/// hold it -- they drop in reverse order of declaration, so the worker there | |
| 82 | +/// joins a thread nobody will ever drain, which is a hang and not a slow path. | |
| 83 | +pub(crate) struct FrameStream { | |
| 84 | + pub(crate) frames: Receiver<Frame>, | |
| 85 | + pub(crate) worker: Worker, | |
| 86 | +} | |
| 87 | + | |
| 73 | 88 | pub struct DecodeSession; |
| 74 | 89 | |
| 75 | 90 | impl DecodeSession { |
| @@ -104,8 +119,10 @@ impl DecodeSession { | ||
| 104 | 119 | start_frame: u32, |
| 105 | 120 | end_frame: u32, |
| 106 | 121 | ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> { |
| 107 | - let (meta, rx, worker) = Self::open_worker(path, start_frame, end_frame)?; | |
| 108 | - Ok((meta, rx, worker.detach())) | |
| 122 | + let (meta, stream) = Self::open_worker(path, start_frame, end_frame)?; | |
| 123 | + // The public API hands out the flag alone, so the worker is detached and | |
| 124 | + // the receiver goes to the caller: nothing here joins anything. | |
| 125 | + Ok((meta, stream.frames, stream.worker.detach())) | |
| 109 | 126 | } |
| 110 | 127 | |
| 111 | 128 | /// A worker that decodes nothing and emits `len` black frames, indexed from |
| @@ -113,17 +130,17 @@ impl DecodeSession { | ||
| 113 | 130 | /// channel as decoded frames, so a gap costs the caller no branch at all |
| 114 | 131 | /// beyond choosing this opener: same bounded channel, same backpressure, |
| 115 | 132 | /// same cancel, same retire path. |
| 116 | - pub(crate) fn open_black(width: u32, height: u32, len: u32) -> (Receiver<Frame>, Worker) { | |
| 133 | + pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream { | |
| 117 | 134 | let (tx, rx) = sync_channel(2); |
| 118 | 135 | let cancel = Arc::new(AtomicBool::new(false)); |
| 119 | 136 | if len == 0 { |
| 120 | - return ( | |
| 121 | - rx, | |
| 122 | - Worker { | |
| 137 | + return FrameStream { | |
| 138 | + frames: rx, | |
| 139 | + worker: Worker { | |
| 123 | 140 | cancel, |
| 124 | 141 | handle: None, |
| 125 | 142 | }, |
| 126 | - ); | |
| 143 | + }; | |
| 127 | 144 | } |
| 128 | 145 | let worker_cancel = Arc::clone(&cancel); |
| 129 | 146 | // One buffer, cloned per frame: opaque black is a constant, and the |
| @@ -148,7 +165,10 @@ impl DecodeSession { | ||
| 148 | 165 | } |
| 149 | 166 | }) |
| 150 | 167 | .ok(); |
| 151 | - (rx, Worker { cancel, handle }) | |
| 168 | + FrameStream { | |
| 169 | + frames: rx, | |
| 170 | + worker: Worker { cancel, handle }, | |
| 171 | + } | |
| 152 | 172 | } |
| 153 | 173 | |
| 154 | 174 | /// As [`DecodeSession::open_range`], but the caller gets the whole |
| @@ -158,7 +178,7 @@ impl DecodeSession { | ||
| 158 | 178 | path: impl AsRef<Path>, |
| 159 | 179 | start_frame: u32, |
| 160 | 180 | end_frame: u32, |
| 161 | - ) -> crate::Result<(VideoMeta, Receiver<Frame>, Worker)> { | |
| 181 | + ) -> crate::Result<(VideoMeta, FrameStream)> { | |
| 162 | 182 | let path = path.as_ref().to_path_buf(); |
| 163 | 183 | let (meta, demuxer) = Demuxer::open(&path)?; |
| 164 | 184 | let end_frame = end_frame.min(meta.frame_count); |
| @@ -171,10 +191,12 @@ impl DecodeSession { | ||
| 171 | 191 | // so the caller sees an immediate end of stream rather than an error. |
| 172 | 192 | return Ok(( |
| 173 | 193 | meta, |
| 174 | - rx, | |
| 175 | - Worker { | |
| 176 | - cancel, | |
| 177 | - handle: None, | |
| 194 | + FrameStream { | |
| 195 | + frames: rx, | |
| 196 | + worker: Worker { | |
| 197 | + cancel, | |
| 198 | + handle: None, | |
| 199 | + }, | |
| 178 | 200 | }, |
| 179 | 201 | )); |
| 180 | 202 | } |
| @@ -210,10 +232,12 @@ impl DecodeSession { | ||
| 210 | 232 | })?; |
| 211 | 233 | Ok(( |
| 212 | 234 | meta, |
| 213 | - rx, | |
| 214 | - Worker { | |
| 215 | - cancel, | |
| 216 | - handle: Some(handle), | |
| 235 | + FrameStream { | |
| 236 | + frames: rx, | |
| 237 | + worker: Worker { | |
| 238 | + cancel, | |
| 239 | + handle: Some(handle), | |
| 240 | + }, | |
| 217 | 241 | }, |
| 218 | 242 | )) |
| 219 | 243 | } |
| @@ -274,6 +298,48 @@ fn run_hw( | ||
| 274 | 298 | } |
| 275 | 299 | } |
| 276 | 300 | |
| 301 | +#[cfg(test)] | |
| 302 | +mod tests { | |
| 303 | + use super::*; | |
| 304 | + use std::sync::mpsc::RecvTimeoutError; | |
| 305 | + use std::time::Duration; | |
| 306 | + | |
| 307 | + fn asset(name: &str) -> PathBuf { | |
| 308 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | |
| 309 | + .join("../../assets") | |
| 310 | + .join(name) | |
| 311 | + } | |
| 312 | + | |
| 313 | + /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait. | |
| 314 | + /// The channel is bounded, so such a worker is parked in `send` within a | |
| 315 | + /// few frames, and the only thing that can wake it is its receiver going | |
| 316 | + /// away -- which is why the receiver is the first field and the join inside | |
| 317 | + /// `Worker::drop` is the second. Swap those two fields and this hangs. | |
| 318 | + /// | |
| 319 | + /// This is the whole basis of every teardown path in the engine, so it is | |
| 320 | + /// asserted rather than commented: the drop runs on a second thread and a | |
| 321 | + /// regression fails in ten seconds instead of hanging the suite forever. | |
| 322 | + #[test] | |
| 323 | + fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() { | |
| 324 | + let (_meta, stream) = | |
| 325 | + DecodeSession::open_worker(&asset("test_baseline.mp4"), 0, u32::MAX).expect("open"); | |
| 326 | + // Nothing is ever received: two frames fill the channel and the next | |
| 327 | + // send parks the decode thread, exactly as a refused project load does. | |
| 328 | + thread::sleep(Duration::from_millis(500)); | |
| 329 | + | |
| 330 | + let (done_tx, done_rx) = sync_channel(1); | |
| 331 | + thread::spawn(move || { | |
| 332 | + drop(stream); | |
| 333 | + let _ = done_tx.send(()); | |
| 334 | + }); | |
| 335 | + assert!( | |
| 336 | + done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout), | |
| 337 | + "dropping a parked stream deadlocked: it joined a decode thread \ | |
| 338 | + while still holding the receiver that thread is waiting on" | |
| 339 | + ); | |
| 340 | + } | |
| 341 | +} | |
| 342 | + | |
| 277 | 343 | fn run( |
| 278 | 344 | mut demuxer: Demuxer, |
| 279 | 345 | tx: SyncSender<Frame>, |
crates/engine/src/playback.rsmodified+32 -16
| @@ -122,7 +122,7 @@ impl PlaybackSession { | ||
| 122 | 122 | let path = path.as_ref().to_path_buf(); |
| 123 | 123 | // `open_worker` rather than `open` purely for the worker handle: the |
| 124 | 124 | // field has to exist from the start for the first seek to use it. |
| 125 | - let (meta, frames, worker) = DecodeSession::open_worker(&path, 0, u32::MAX)?; | |
| 125 | + let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?; | |
| 126 | 126 | let audio = open_audio(&path); |
| 127 | 127 | let source = match audio { |
| 128 | 128 | Some(_) => ClockSource::Audio, |
| @@ -134,8 +134,8 @@ impl PlaybackSession { | ||
| 134 | 134 | let span = project.span_at(Lane::Video, 0).expect("never empty"); |
| 135 | 135 | Ok(Self { |
| 136 | 136 | meta, |
| 137 | - frames, | |
| 138 | - worker, | |
| 137 | + frames: stream.frames, | |
| 138 | + worker: stream.worker, | |
| 139 | 139 | retired: Vec::new(), |
| 140 | 140 | clock: PlaybackClock::new(source), |
| 141 | 141 | audio, |
| @@ -162,13 +162,22 @@ impl PlaybackSession { | ||
| 162 | 162 | /// The undo history is not saved: `undo` is `false` on a fresh load. |
| 163 | 163 | pub fn open_project(path: &Path) -> crate::Result<Self> { |
| 164 | 164 | let doc = crate::edith::load(path)?; |
| 165 | - let first = doc.sources.first().ok_or("the project names no sources")?; | |
| 165 | + // Owned: the sources move into the `Project` below, and the device is | |
| 166 | + // opened after that (see the comment there). | |
| 167 | + let first = doc | |
| 168 | + .sources | |
| 169 | + .first() | |
| 170 | + .cloned() | |
| 171 | + .ok_or("the project names no sources")?; | |
| 166 | 172 | // Source 0 both scaffolds the session and defines the timeline, so it |
| 167 | 173 | // is opened for playback rather than merely probed. |
| 168 | - let (meta, frames, worker) = DecodeSession::open_worker(first, 0, u32::MAX) | |
| 174 | + // One value, not two locals: everything below this line can refuse, and | |
| 175 | + // locals drop in reverse declaration order -- a bare worker would join | |
| 176 | + // its decode thread while the receiver next to it was still holding | |
| 177 | + // that thread parked in `send`, which is a hang (see [`FrameStream`]). | |
| 178 | + let (meta, stream) = DecodeSession::open_worker(&first, 0, u32::MAX) | |
| 169 | 179 | .map_err(|e| format!("source {}: {e}", first.display()))?; |
| 170 | - let audio = open_audio(first); | |
| 171 | - let first_audio = AudioSession::probe(first)?; | |
| 180 | + let first_audio = AudioSession::probe(&first)?; | |
| 172 | 181 | |
| 173 | 182 | let mut counts = vec![meta.frame_count]; |
| 174 | 183 | for source in &doc.sources[1..] { |
| @@ -193,10 +202,16 @@ impl PlaybackSession { | ||
| 193 | 202 | let playhead = doc.playhead; |
| 194 | 203 | let project = Project::from_parts(doc.sources, doc.video, doc.audio)?; |
| 195 | 204 | let span = project.span_at(Lane::Video, 0).expect("never empty"); |
| 205 | + // Last, because it is the one thing here that cannot be taken back: the | |
| 206 | + // feeder thread outlives the `Audio` value (it holds its own clones) and | |
| 207 | + // only a session's `drop` retires it, so a refusal above this line would | |
| 208 | + // leave a PipeWire stream and a thread behind for a project that never | |
| 209 | + // opened. Nothing before it needs the device. | |
| 210 | + let audio = open_audio(&first); | |
| 196 | 211 | let mut session = Self { |
| 197 | 212 | meta, |
| 198 | - frames, | |
| 199 | - worker, | |
| 213 | + frames: stream.frames, | |
| 214 | + worker: stream.worker, | |
| 200 | 215 | retired: Vec::new(), |
| 201 | 216 | clock: PlaybackClock::new(match audio { |
| 202 | 217 | Some(_) => ClockSource::Audio, |
| @@ -318,7 +333,7 @@ impl PlaybackSession { | ||
| 318 | 333 | in_frame, |
| 319 | 334 | in_frame + span.len, |
| 320 | 335 | ) |
| 321 | - .map(|(_, frames, worker)| (frames, worker)) | |
| 336 | + .map(|(_, stream)| stream) | |
| 322 | 337 | .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)), |
| 323 | 338 | None => Ok(DecodeSession::open_black( |
| 324 | 339 | self.meta.width, |
| @@ -326,12 +341,13 @@ impl PlaybackSession { | ||
| 326 | 341 | span.len, |
| 327 | 342 | )), |
| 328 | 343 | }; |
| 329 | - if let Ok((frames, worker)) = opened { | |
| 330 | - // Receiver first, worker second: the drop of the old receiver is | |
| 331 | - // what wakes a worker parked in `send`, and only then can it return | |
| 332 | - // and be reaped by a later sweep. | |
| 333 | - self.frames = frames; | |
| 334 | - self.retire(worker); | |
| 344 | + if let Ok(stream) = opened { | |
| 345 | + // Receiver first, worker second: the drop of the *old* receiver is | |
| 346 | + // what wakes the outgoing worker if it is parked in `send`, and only | |
| 347 | + // then can it return and be reaped by a later sweep. Nothing here | |
| 348 | + // joins, so this ordering costs the seek nothing. | |
| 349 | + self.frames = stream.frames; | |
| 350 | + self.retire(stream.worker); | |
| 335 | 351 | } |
| 336 | 352 | self.span = span; |
| 337 | 353 | } |
crates/engine/tests/saveload.rsmodified+41 -0
| @@ -256,6 +256,47 @@ fn a_source_that_shrank_is_refused_by_clip() { | ||
| 256 | 256 | assert_eq!(whole.timeline_duration(), 5.0); |
| 257 | 257 | } |
| 258 | 258 | |
| 259 | +/// A refusal must *return*. Opening a project starts decoding source 0 before | |
| 260 | +/// it has validated anything, so by the time a later source is refused the | |
| 261 | +/// worker is several frames in -- and with a two-frame channel that nobody is | |
| 262 | +/// draining, it is parked in `send`. Tearing that down in the wrong order joins | |
| 263 | +/// a thread that is waiting for a receiver the same scope still holds, and the | |
| 264 | +/// app hangs on a bad project file instead of showing the error. | |
| 265 | +/// | |
| 266 | +/// The many sources are what make the park a certainty rather than a race: each | |
| 267 | +/// one is opened and probed before the clip check that refuses, which is far | |
| 268 | +/// longer than the few frames it takes to fill the channel. | |
| 269 | +#[test] | |
| 270 | +fn a_refused_project_does_not_hang_on_its_own_decoder() { | |
| 271 | + let dir = scratch("refusal_hang"); | |
| 272 | + copy_in(&dir, "test_av.mp4"); | |
| 273 | + let path = dir.join("refused.edith"); | |
| 274 | + let mut text = String::from("edith 1\nplayhead 0\n"); | |
| 275 | + for _ in 0..1024 { | |
| 276 | + text.push_str("source test_av.mp4\n"); | |
| 277 | + } | |
| 278 | + // Legal until the last line, which runs off the end of a 150-frame file. | |
| 279 | + text.push_str("clip 0 150 0\nclip 0 10000 0\n"); | |
| 280 | + std::fs::write(&path, &text).expect("write"); | |
| 281 | + | |
| 282 | + let (tx, rx) = std::sync::mpsc::sync_channel(1); | |
| 283 | + let probe = path.clone(); | |
| 284 | + std::thread::spawn(move || { | |
| 285 | + let err = PlaybackSession::open_project(&probe) | |
| 286 | + .err() | |
| 287 | + .map(|e| e.to_string()); | |
| 288 | + let _ = tx.send(err); | |
| 289 | + }); | |
| 290 | + match rx.recv_timeout(std::time::Duration::from_secs(60)) { | |
| 291 | + Ok(Some(err)) => assert!(err.contains("150"), "refused, but not by name: {err}"), | |
| 292 | + Ok(None) => panic!("a clip past the end of its file must not open"), | |
| 293 | + Err(_) => panic!( | |
| 294 | + "open_project hung on a refusal: its own decode worker is parked in \ | |
| 295 | + send and the teardown is waiting for it" | |
| 296 | + ), | |
| 297 | + } | |
| 298 | +} | |
| 299 | + | |
| 259 | 300 | #[test] |
| 260 | 301 | fn a_project_that_names_itself_is_refused() { |
| 261 | 302 | let dir = scratch("self_reference"); |