From 7652adab7d199d893f675eba15fb6d4567b1a422 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 05:55:51 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(decode):=20a=20seek=20into?= =?UTF-8?q?=20an=20open=20GOP=20is=20hardware's=20to=20finish?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Blu-ray remux codes its GOPs open: the I picture that opens one is stored ahead of the leading pictures that are *shown* before it, and those reference the GOP before. Restart decoding at that random access point -- which is what every seek, scrub and clip boundary does -- and the leading pictures have references nobody decoded, so the plugin failed its first frame, playback fell back to `rusty_h264`, and that decoder died on the file's I_PCM macroblocks. Seventeen of twenty scrub steps on a 5.27 GB AVC remux ended with no picture at all, and the three that survived cost 482 ms each in software. The pictures are not ours to show, so they are dropped and the decode walks on (bounded by `LEADING_LIMIT`, and only for a session that was positioned somewhere other than the file's own start). The refusal that the tolerance would otherwise swallow is kept at both ends: a stream read from frame 0 is still refused the moment its first picture will not decode, and the plugin probe now counts an immediate end of stream as a refusal rather than a pass -- a session that hands back no picture is the black-frame-and-instant-eof the probe exists to catch. The vendored H.264 decoder's own refusal goes with it: it failed a `frame_num` gap outright unless the stream declared gaps allowed, which is exactly the wrong reading here -- the gap is the editor's, made by starting in the middle of a film, and §8.2.5.2's non-existing frames are what stands in for it. The loop that builds them was already there, behind that flag. Twenty of twenty scrub steps on the remux now decode in hardware, 77 ms median against 482 ms; `seek_matches_linear_every_container` holds for every container, and `dump_frame seek` is what a picture reached by a seek can be compared with the same picture reached by decoding from the start. --- Cargo.toml | 7 +++- crates/engine-hw/src/lib.rs | 40 ++++++++++++++++++ crates/engine/examples/dump_frame.rs | 42 +++++++++++++++---- crates/engine/src/decode.rs | 8 +++- .../cros-codecs/src/decoder/stateless/h264.rs | 17 ++++---- 5 files changed, 98 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5f1f1d0..e336592 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,12 @@ edition = "2024" # cros-libva - fails to build against libva >= 1.23 headers # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; # and creates every decode context as 8-bit 4:2:0, which no HEVC -# Main 10 stream can decode into (its own TODO, its own answer) +# Main 10 stream can decode into (its own TODO, its own answer); +# and refuses an H.264 frame_num gap outright unless the stream +# declared one, which fails every seek into an open-GOP Blu-ray +# remux -- the gap is the *editor's*, made by restarting at a +# random access point, so the patch fills it with the §8.2.5.2 +# non-existing frames the loop right below it already builds # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 4c01862..db85183 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -104,6 +104,13 @@ type Av1Encoder = Av1StatelessEncoder< /// exists so a misbehaving driver returns an error instead of hanging the app. const STALL_LIMIT: u32 = 10_000; +/// How many undecodable access units a seek may drop before the session gives +/// up and calls the stream broken. An open GOP's leading pictures are a handful +/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one +/// we restarted in the middle of, so the error is real and the caller still +/// hears it. +const LEADING_LIMIT: u32 = 64; + struct Session { decoder: Decoder, /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, @@ -122,6 +129,11 @@ struct Session { flushed: bool, /// Pictures still to be decoded and thrown away to land on a seek target. skip: u32, + /// Access units dropped because they referenced pictures this session never + /// decoded -- see [`Session::pump`]. Counted rather than flagged so the + /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a + /// picture is handed out, which is where the window closes. + leading: u32, /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame, /// which is exactly why the pointers are only valid until the next call. out: Vec, @@ -260,6 +272,12 @@ impl Session { timestamp: 0, flushed: false, skip: 0, + // A stream read from its own beginning has no missing references + // and therefore no leading pictures to forgive: the window opens + // only for a session positioned somewhere else ([`Session::open_at`]), + // so a file whose first picture will not decode is still refused at + // the door rather than opening onto nothing. + leading: LEADING_LIMIT, out: Vec::new(), luma: 0, chroma: 0, @@ -277,6 +295,9 @@ impl Session { let target_frame = target_sample.saturating_sub(1); let first = session.demuxer.seek_to_sync_at_or_before(target_frame); session.skip = (i64::from(target_frame) - first).max(0) as u32; + if target_frame > 0 { + session.leading = 0; + } Some(session) } @@ -309,6 +330,9 @@ impl Session { continue; } self.emit(handle); + // Past the random access point's leading pictures: a decode + // error from here on is a real one again. + self.leading = LEADING_LIMIT; return Ok(true); } if self.flushed { @@ -332,6 +356,7 @@ impl Session { pool, pending, timestamp, + leading, .. } = self; match decoder @@ -353,6 +378,21 @@ impl Session { return Err("decoder stalled waiting for output buffers".into()); } } + // A picture that references pictures we never decoded, which is + // what an open GOP's leading pictures are after a seek: they + // display *before* the random access point we restarted at, so + // they are not ours to show and the stream is not broken. Drop + // the rest of the access unit (they are picture-aligned) and + // walk on -- failing here is what used to make a Blu-ray remux + // fall back to software on 17 seeks out of 20. + Err(e) if *leading < LEADING_LIMIT => { + if *leading == 0 { + eprintln!("engine_hw: skipping leading pictures after seek ({e})"); + } + *leading += 1; + pending.clear(); + *timestamp += 1; + } Err(e) => return Err(e.to_string()), } } diff --git a/crates/engine/examples/dump_frame.rs b/crates/engine/examples/dump_frame.rs index b41d677..3fb5f31 100644 --- a/crates/engine/examples/dump_frame.rs +++ b/crates/engine/examples/dump_frame.rs @@ -1,5 +1,11 @@ //! Dump decoded frames as PPM for visual inspection. -//! Usage: cargo run -p engine --release --example dump_frame -- +//! Usage: cargo run -p engine --release --example dump_frame -- [seek] +//! +//! With `seek` the frame is reached the way a scrub reaches it -- restart at the +//! random access point at or before it -- instead of by decoding the file from +//! its start. The two must be the same picture, byte for byte, which is what +//! makes a `cmp` of the two dumps a check that seeking into an open GOP decodes +//! the frame it claims and not a smear of missing references. use std::env; use std::fs::File; @@ -9,26 +15,48 @@ fn main() -> engine::Result<()> { let mut args = env::args().skip(1); let path = args .next() - .ok_or("usage: dump_frame ")?; + .ok_or("usage: dump_frame [seek]")?; let target: u32 = args.next().ok_or("missing frame index")?.parse()?; let out = args.next().ok_or("missing output path")?; + let seek = args.next().is_some_and(|a| a == "seek"); let (meta, rx) = engine::DecodeSession::open(&path)?; eprintln!( "{}x{} @ {:.2} fps", meta.width, meta.height, meta.frame_rate ); + if seek { + drop(rx); + let mut session = engine::PlaybackSession::open(&path)?; + session.seek(f64::from(target) / meta.frame_rate); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while std::time::Instant::now() < deadline { + session.tick(); + if let Some(frame) = session.try_frame() { + write_ppm(&out, frame.width, frame.height, &frame.bgra)?; + eprintln!("wrote frame {} (asked {target}) to {out}", frame.index); + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(4)); + } + return Err(format!("no frame arrived within 60 s of seeking to {target}").into()); + } for frame in rx { if frame.index == target { - let mut w = BufWriter::new(File::create(&out)?); - writeln!(w, "P6\n{} {}\n255", frame.width, frame.height)?; - for px in frame.bgra.chunks_exact(4) { - w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB - } + write_ppm(&out, frame.width, frame.height, &frame.bgra)?; eprintln!("wrote frame {target} to {out}"); return Ok(()); } } Err(format!("stream ended before frame {target}").into()) } + +fn write_ppm(out: &str, width: u32, height: u32, bgra: &[u8]) -> engine::Result<()> { + let mut w = BufWriter::new(File::create(out)?); + writeln!(w, "P6\n{width} {height}\n255")?; + for px in bgra.chunks_exact(4) { + w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB + } + Ok(()) +} diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index cb1d0c6..6766d24 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -877,7 +877,13 @@ fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), Stri let Some(mut hw) = open_hw(path, start_frame) else { return Err(codec.needs_plugin()); }; - hw.next_frame().map(|_| ()).map_err(|_| codec.undecodable()) + // End of stream counts as a refusal, not as a pass: a session that hands + // back no picture at all is exactly the black-frame-and-instant-eof this + // probe exists to catch, and `Ok(None)` is how the plugin says it. + match hw.next_frame() { + Ok(Some(_)) => Ok(()), + _ => Err(codec.undecodable()), + } } /// Returns whether the session was handled; `false` only when hardware decode diff --git a/vendor/cros-codecs/src/decoder/stateless/h264.rs b/vendor/cros-codecs/src/decoder/stateless/h264.rs index baa3fbf..9606da8 100644 --- a/vendor/cros-codecs/src/decoder/stateless/h264.rs +++ b/vendor/cros-codecs/src/decoder/stateless/h264.rs @@ -954,13 +954,16 @@ where debug!("frame_num gap detected."); - if !sps.gaps_in_frame_num_value_allowed_flag { - return Err(anyhow!( - "Invalid frame_num: {}. Assuming unintentional loss of pictures", - frame_num - )); - } - + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a gap is filled with + // the §8.2.5.2 non-existing frames whatever the flag says, instead of + // failing the stream. The flag means "this file has no intentional + // gaps", and it is right -- the gap is *ours*: an editor starts decoding + // at a random access point in the middle of a film, and the pictures + // between the previous reference and it were never decoded. Refusing + // here is what made every seek into an open-GOP Blu-ray remux fall back + // to a software decoder (17 of 20 in `bench scrub`), and the standing in + // frames this loop builds are exactly what the reference lists of the + // pictures after the gap look for. let mut unused_short_term_frame_num = (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num(); while unused_short_term_frame_num != frame_num {