forge
Explore
Log in

Don't you dare go Hollow

The decode thread says how it ended, and is waited for

Browse files at this commit

ba88e8f0b0e607bde15671ad034171e4aece3a56Ahmet Kaan GümüşParent: b728a45
  • fix
    • the decode thread says how it ended, and is waited for
Show full message
🐛 fix(export): the decode thread says how it ended, and is waited for

Two hazards the thread brought in, neither of which the serial decoder had.

A panicked decode thread dropped its sender saying nothing, and a shut channel
read as end of stream: the span ended "because the source ran out", the export
wrote what it had and reported success. A truncated file that says it finished
is the one outcome an export must never have, and before the decode moved onto
a thread the same panic took the whole export down. So the thread now states
every ending down the channel -- a picture, an error, or the `Ok(None)` that is
end of stream -- and a channel that shuts without one of them is the failure it
is. A source genuinely shorter than the clip that names it still ends its span
gracefully, and asking again after that stays end of stream rather than turning
into a disconnect.

And the thread was never joined. `decode::Worker` states why it must be: one
abandoned inside `vaInitialize` outlives the process, and Mesa's `atexit`
handlers free the state it is still reading -- a SIGSEGV at exit, long after
the export succeeded. The handle is kept and joined on drop, after the receiver
beside it, which is the field order `decode::FrameStream` is written in: the
disconnect is the only thing that wakes a decoder parked in a full send, so
joining first would wait for a consumer that is never coming.

Throughput is where it was (93.3 fps on a 1080p minute, hardware encode) and
the round-trips hold on both seats.
crates/engine/src/export.rsmodified+105 -12
@@ -3163,9 +3163,42 @@ enum ClipDecoder {
3163 3163
3164 /// The receiving half of a decode thread, plus the picture it last handed out3164 /// The receiving half of a decode thread, plus the picture it last handed out
3165 /// -- which is what lets `next` keep lending planes rather than moving them.3165 /// -- which is what lets `next` keep lending planes rather than moving them.
3166+///
3167+/// The first two fields are in this order on purpose, and it is the order
3168+/// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as
3169+/// they are declared, so the receiver disconnects *first* -- the only thing that
3170+/// wakes a decoder parked in a full `send` -- and the join inside
3171+/// [`DecodeThread::drop`] runs second. The other way round is a hang and not a
3172+/// slow path.
3166 struct Streamed {3173 struct Streamed {
3167- frames: Receiver<crate::Result<Yuv>>,3174+ frames: Receiver<crate::Result<Option<Yuv>>>,
3175+ /// Held only to be dropped: joining is all it does, and it must happen
3176+ /// after the receiver above (`_lib` in `crate::hw` is kept the same way).
3177+ _thread: DecodeThread,
3168 current: Option<Yuv>,3178 current: Option<Yuv>,
3179+ /// Whether the thread has said "no more pictures" in as many words. What
3180+ /// separates a stream that ended from a thread that vanished: after this,
3181+ /// the channel is disconnected because the decoder is *done*, and a further
3182+ /// ask is end of stream rather than a failure.
3183+ ended: bool,
3184+}
3185+
3186+/// A decode thread, joined when its span's decoder is dropped -- the rule
3187+/// [`crate::decode::Worker`] is written for: a thread abandoned mid
3188+/// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free
3189+/// the state it is still reading, which is a SIGSEGV at exit long after the
3190+/// export succeeded.
3191+struct DecodeThread(Option<thread::JoinHandle<()>>);
3192+
3193+impl Drop for DecodeThread {
3194+ fn drop(&mut self) {
3195+ if let Some(handle) = self.0.take() {
3196+ // The receiver is already gone (see `Streamed`'s field order), so a
3197+ // decoder blocked on `send` has been woken and this waits only for
3198+ // the thread to unwind its VA-API session.
3199+ let _ = handle.join();
3200+ }
3201+ }
3169 }3202 }
3170 3203
3171 /// One picture, owned, on its way from a decode thread to the encoder.3204 /// One picture, owned, on its way from a decode thread to the encoder.
@@ -3187,12 +3220,14 @@ impl ClipDecoder {
3187 }3220 }
3188 let path = path.to_path_buf();3221 let path = path.to_path_buf();
3189 let (tx, frames) = sync_channel(2);3222 let (tx, frames) = sync_channel(2);
3190- thread::Builder::new()3223+ let handle = thread::Builder::new()
3191 .name("export-decode".into())3224 .name("export-decode".into())
3192 .spawn(move || decode_stream(&path, start_frame, &tx))?;3225 .spawn(move || decode_stream(&path, start_frame, &tx))?;
3193 Ok(Self::Streamed(Streamed {3226 Ok(Self::Streamed(Streamed {
3194 frames,3227 frames,
3228+ _thread: DecodeThread(Some(handle)),
3195 current: None,3229 current: None,
3230+ ended: false,
3196 }))3231 }))
3197 }3232 }
3198 3233
@@ -3200,8 +3235,9 @@ impl ClipDecoder {
3200 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {3235 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
3201 match self {3236 match self {
3202 Self::Still(still) => Ok(Some(still.picture())),3237 Self::Still(still) => Ok(Some(still.picture())),
3238+ Self::Streamed(stream) if stream.ended => Ok(None),
3203 Self::Streamed(stream) => match stream.frames.recv() {3239 Self::Streamed(stream) => match stream.frames.recv() {
3204- Ok(Ok(frame)) => {3240+ Ok(Ok(Some(frame))) => {
3205 let frame = stream.current.insert(frame);3241 let frame = stream.current.insert(frame);
3206 Ok(Some((3242 Ok(Some((
3207 &frame.y,3243 &frame.y,
@@ -3211,13 +3247,21 @@ impl ClipDecoder {
3211 frame.height,3247 frame.height,
3212 )))3248 )))
3213 }3249 }
3250+ // The decoder said end of stream in as many words -- a source
3251+ // shorter than the clip that names it, which the span loop ends
3252+ // gracefully on.
3253+ Ok(Ok(None)) => {
3254+ stream.ended = true;
3255+ Ok(None)
3256+ }
3214 Ok(Err(e)) => Err(e),3257 Ok(Err(e)) => Err(e),
3215- // The thread closed the channel: end of stream, and the only3258+ // The channel went quiet without either: the thread panicked.
3216- // clean way it ends. Every failure came through as an `Err`3259+ // Read as end of stream that would truncate the export at this
3217- // above -- including the open's, which is why a file the3260+ // frame and *report success*, which is the one outcome an
3218- // plugin refuses still fails the export rather than looking3261+ // export must never have -- before the decode moved onto a
3219- // like a clip that ran out.3262+ // thread the same panic took the whole export down, and it
3220- Err(_) => Ok(None),3263+ // still does.
3264+ Err(_) => Err("the decoder stopped without a picture or a reason".into()),
3221 },3265 },
3222 }3266 }
3223 }3267 }
@@ -3230,7 +3274,12 @@ impl ClipDecoder {
3230 /// Unlike playback there is no mid-clip fallback to software: a hardware decode3274 /// Unlike playback there is no mid-clip fallback to software: a hardware decode
3231 /// that fails after the first picture fails the export, which then deletes the3275 /// that fails after the first picture fails the export, which then deletes the
3232 /// half-written file.3276 /// half-written file.
3233-fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Yuv>>) {3277+///
3278+/// Every way this returns says which way it was, down the channel: a picture, an
3279+/// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not
3280+/// one of them -- a silent close is a panicked thread, and the receiver treats
3281+/// it as the failure it is rather than as a source that ran out.
3282+fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Option<Yuv>>>) {
3234 let opened = match forced("VE_SW") {3283 let opened = match forced("VE_SW") {
3235 false => HwSession::open_at(path, start_frame).map(Pictures::Hw),3284 false => HwSession::open_at(path, start_frame).map(Pictures::Hw),
3236 true => None,3285 true => None,
@@ -3257,7 +3306,10 @@ fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Yu
3257 width,3306 width,
3258 height,3307 height,
3259 },3308 },
3260- Ok(None) => return,3309+ Ok(None) => {
3310+ let _ = tx.send(Ok(None));
3311+ return;
3312+ }
3261 Err(e) => {3313 Err(e) => {
3262 let _ = tx.send(Err(e));3314 let _ = tx.send(Err(e));
3263 return;3315 return;
@@ -3265,7 +3317,7 @@ fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Yu
3265 };3317 };
3266 // The consumer went away: the span ended early, or the export was3318 // The consumer went away: the span ended early, or the export was
3267 // cancelled. Either way there is nothing left to decode for.3319 // cancelled. Either way there is nothing left to decode for.
3268- if tx.send(Ok(frame)).is_err() {3320+ if tx.send(Ok(Some(frame))).is_err() {
3269 return;3321 return;
3270 }3322 }
3271 }3323 }
@@ -3355,6 +3407,47 @@ impl SwDecoder {
3355 mod tests {3407 mod tests {
3356 use super::*;3408 use super::*;
3357 3409
3410+ /// How a decode thread ended is never guessed from the channel being shut.
3411+ /// A source that genuinely ran out says so, and the span ends on it; a
3412+ /// thread that died without a word is a failure, because reading it as end
3413+ /// of stream would truncate the picture and *report the export finished*.
3414+ #[test]
3415+ fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() {
3416+ let streamed = |handle, frames| {
3417+ ClipDecoder::Streamed(Streamed {
3418+ frames,
3419+ _thread: DecodeThread(Some(handle)),
3420+ current: None,
3421+ ended: false,
3422+ })
3423+ };
3424+
3425+ let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
3426+ // Said its piece, then finished: the span walks on to its next clip.
3427+ let handle = thread::spawn(move || {
3428+ tx.send(Ok(None)).expect("the receiver is alive");
3429+ });
3430+ let mut ended = streamed(handle, frames);
3431+ assert!(ended.next().expect("a clean end is not an error").is_none());
3432+ // ...and asking again is the same answer and not a disconnect error.
3433+ assert!(ended.next().expect("still not an error").is_none());
3434+
3435+ let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
3436+ // Died holding the sender: the channel shuts with nothing said.
3437+ let handle = thread::spawn(move || {
3438+ let _tx = tx;
3439+ panic!("decoder died");
3440+ });
3441+ let mut died = streamed(handle, frames);
3442+ let e = died
3443+ .next()
3444+ .expect_err("a silent death must fail the export, not end the clip");
3445+ assert!(
3446+ e.to_string().contains("without a picture or a reason"),
3447+ "{e}"
3448+ );
3449+ }
3450+
3358 /// Three seconds of two tones, one per channel, interleaved: enough shape3451 /// Three seconds of two tones, one per channel, interleaved: enough shape
3359 /// that a correlation says something and enough length that the encoder3452 /// that a correlation says something and enough length that the encoder
3360 /// settles into a mode.3453 /// settles into a mode.