forge
Explore
Log in

Don't you dare go Hollow

A seek into an open GOP is hardware's to finish

Browse files at this commit

7652adab7d199d893f675eba15fb6d4567b1a422Ahmet Kaan GümüşParent: 0e324ec
  • fix
    • a seek into an open GOP is hardware's to finish
Show full message
🐛 fix(decode): a seek into an open GOP is hardware's to finish

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 <file> <n> <out> seek` is what a picture reached by
a seek can be compared with the same picture reached by decoding from the
start.
Cargo.tomlmodified+6 -1
@@ -20,7 +20,12 @@ edition = "2024"
20 # cros-libva - fails to build against libva >= 1.23 headers20 # cros-libva - fails to build against libva >= 1.23 headers
21 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;21 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;
22 # and creates every decode context as 8-bit 4:2:0, which no HEVC22 # and creates every decode context as 8-bit 4:2:0, which no HEVC
23-# Main 10 stream can decode into (its own TODO, its own answer)23+# Main 10 stream can decode into (its own TODO, its own answer);
24+# and refuses an H.264 frame_num gap outright unless the stream
25+# declared one, which fails every seek into an open-GOP Blu-ray
26+# remux -- the gap is the *editor's*, made by restarting at a
27+# random access point, so the patch fills it with the §8.2.5.2
28+# non-existing frames the loop right below it already builds
24 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per29 # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per
25 # term (the fast path in the same file serves the encoder only),30 # term (the fast path in the same file serves the encoder only),
26 # which is 4x slower than real time for 5.1 and therefore not31 # which is 4x slower than real time for 5.1 and therefore not
crates/engine-hw/src/lib.rsmodified+40 -0
@@ -104,6 +104,13 @@ type Av1Encoder = Av1StatelessEncoder<
104 /// exists so a misbehaving driver returns an error instead of hanging the app.104 /// exists so a misbehaving driver returns an error instead of hanging the app.
105 const STALL_LIMIT: u32 = 10_000;105 const STALL_LIMIT: u32 = 10_000;
106 106
107+/// How many undecodable access units a seek may drop before the session gives
108+/// up and calls the stream broken. An open GOP's leading pictures are a handful
109+/// (a Blu-ray remux's are 8-16); a file that keeps failing past this is not one
110+/// we restarted in the middle of, so the error is real and the caller still
111+/// hears it.
112+const LEADING_LIMIT: u32 = 64;
113+
107 struct Session {114 struct Session {
108 decoder: Decoder,115 decoder: Decoder,
109 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,116 /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`,
@@ -122,6 +129,11 @@ struct Session {
122 flushed: bool,129 flushed: bool,
123 /// Pictures still to be decoded and thrown away to land on a seek target.130 /// Pictures still to be decoded and thrown away to land on a seek target.
124 skip: u32,131 skip: u32,
132+ /// Access units dropped because they referenced pictures this session never
133+ /// decoded -- see [`Session::pump`]. Counted rather than flagged so the
134+ /// tolerance ends somewhere, and raised to [`LEADING_LIMIT`] the moment a
135+ /// picture is handed out, which is where the window closes.
136+ leading: u32,
125 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,137 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
126 /// which is exactly why the pointers are only valid until the next call.138 /// which is exactly why the pointers are only valid until the next call.
127 out: Vec<u8>,139 out: Vec<u8>,
@@ -260,6 +272,12 @@ impl Session {
260 timestamp: 0,272 timestamp: 0,
261 flushed: false,273 flushed: false,
262 skip: 0,274 skip: 0,
275+ // A stream read from its own beginning has no missing references
276+ // and therefore no leading pictures to forgive: the window opens
277+ // only for a session positioned somewhere else ([`Session::open_at`]),
278+ // so a file whose first picture will not decode is still refused at
279+ // the door rather than opening onto nothing.
280+ leading: LEADING_LIMIT,
263 out: Vec::new(),281 out: Vec::new(),
264 luma: 0,282 luma: 0,
265 chroma: 0,283 chroma: 0,
@@ -277,6 +295,9 @@ impl Session {
277 let target_frame = target_sample.saturating_sub(1);295 let target_frame = target_sample.saturating_sub(1);
278 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);296 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
279 session.skip = (i64::from(target_frame) - first).max(0) as u32;297 session.skip = (i64::from(target_frame) - first).max(0) as u32;
298+ if target_frame > 0 {
299+ session.leading = 0;
300+ }
280 Some(session)301 Some(session)
281 }302 }
282 303
@@ -309,6 +330,9 @@ impl Session {
309 continue;330 continue;
310 }331 }
311 self.emit(handle);332 self.emit(handle);
333+ // Past the random access point's leading pictures: a decode
334+ // error from here on is a real one again.
335+ self.leading = LEADING_LIMIT;
312 return Ok(true);336 return Ok(true);
313 }337 }
314 if self.flushed {338 if self.flushed {
@@ -332,6 +356,7 @@ impl Session {
332 pool,356 pool,
333 pending,357 pending,
334 timestamp,358 timestamp,
359+ leading,
335 ..360 ..
336 } = self;361 } = self;
337 match decoder362 match decoder
@@ -353,6 +378,21 @@ impl Session {
353 return Err("decoder stalled waiting for output buffers".into());378 return Err("decoder stalled waiting for output buffers".into());
354 }379 }
355 }380 }
381+ // A picture that references pictures we never decoded, which is
382+ // what an open GOP's leading pictures are after a seek: they
383+ // display *before* the random access point we restarted at, so
384+ // they are not ours to show and the stream is not broken. Drop
385+ // the rest of the access unit (they are picture-aligned) and
386+ // walk on -- failing here is what used to make a Blu-ray remux
387+ // fall back to software on 17 seeks out of 20.
388+ Err(e) if *leading < LEADING_LIMIT => {
389+ if *leading == 0 {
390+ eprintln!("engine_hw: skipping leading pictures after seek ({e})");
391+ }
392+ *leading += 1;
393+ pending.clear();
394+ *timestamp += 1;
395+ }
356 Err(e) => return Err(e.to_string()),396 Err(e) => return Err(e.to_string()),
357 }397 }
358 }398 }
crates/engine/examples/dump_frame.rsmodified+35 -7
@@ -1,5 +1,11 @@
1 //! Dump decoded frames as PPM for visual inspection.1 //! Dump decoded frames as PPM for visual inspection.
2-//! Usage: cargo run -p engine --release --example dump_frame -- <video.mp4> <frame_index> <out.ppm>2+//! Usage: cargo run -p engine --release --example dump_frame -- <video.mp4> <frame_index> <out.ppm> [seek]
3+//!
4+//! With `seek` the frame is reached the way a scrub reaches it -- restart at the
5+//! random access point at or before it -- instead of by decoding the file from
6+//! its start. The two must be the same picture, byte for byte, which is what
7+//! makes a `cmp` of the two dumps a check that seeking into an open GOP decodes
8+//! the frame it claims and not a smear of missing references.
3 9
4 use std::env;10 use std::env;
5 use std::fs::File;11 use std::fs::File;
@@ -9,26 +15,48 @@ fn main() -> engine::Result<()> {
9 let mut args = env::args().skip(1);15 let mut args = env::args().skip(1);
10 let path = args16 let path = args
11 .next()17 .next()
12- .ok_or("usage: dump_frame <video.mp4> <frame_index> <out.ppm>")?;18+ .ok_or("usage: dump_frame <video.mp4> <frame_index> <out.ppm> [seek]")?;
13 let target: u32 = args.next().ok_or("missing frame index")?.parse()?;19 let target: u32 = args.next().ok_or("missing frame index")?.parse()?;
14 let out = args.next().ok_or("missing output path")?;20 let out = args.next().ok_or("missing output path")?;
21+ let seek = args.next().is_some_and(|a| a == "seek");
15 22
16 let (meta, rx) = engine::DecodeSession::open(&path)?;23 let (meta, rx) = engine::DecodeSession::open(&path)?;
17 eprintln!(24 eprintln!(
18 "{}x{} @ {:.2} fps",25 "{}x{} @ {:.2} fps",
19 meta.width, meta.height, meta.frame_rate26 meta.width, meta.height, meta.frame_rate
20 );27 );
28+ if seek {
29+ drop(rx);
30+ let mut session = engine::PlaybackSession::open(&path)?;
31+ session.seek(f64::from(target) / meta.frame_rate);
32+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
33+ while std::time::Instant::now() < deadline {
34+ session.tick();
35+ if let Some(frame) = session.try_frame() {
36+ write_ppm(&out, frame.width, frame.height, &frame.bgra)?;
37+ eprintln!("wrote frame {} (asked {target}) to {out}", frame.index);
38+ return Ok(());
39+ }
40+ std::thread::sleep(std::time::Duration::from_millis(4));
41+ }
42+ return Err(format!("no frame arrived within 60 s of seeking to {target}").into());
43+ }
21 44
22 for frame in rx {45 for frame in rx {
23 if frame.index == target {46 if frame.index == target {
24- let mut w = BufWriter::new(File::create(&out)?);47+ write_ppm(&out, frame.width, frame.height, &frame.bgra)?;
25- writeln!(w, "P6\n{} {}\n255", frame.width, frame.height)?;
26- for px in frame.bgra.chunks_exact(4) {
27- w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB
28- }
29 eprintln!("wrote frame {target} to {out}");48 eprintln!("wrote frame {target} to {out}");
30 return Ok(());49 return Ok(());
31 }50 }
32 }51 }
33 Err(format!("stream ended before frame {target}").into())52 Err(format!("stream ended before frame {target}").into())
34 }53 }
54+
55+fn write_ppm(out: &str, width: u32, height: u32, bgra: &[u8]) -> engine::Result<()> {
56+ let mut w = BufWriter::new(File::create(out)?);
57+ writeln!(w, "P6\n{width} {height}\n255")?;
58+ for px in bgra.chunks_exact(4) {
59+ w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB
60+ }
61+ Ok(())
62+}
crates/engine/src/decode.rsmodified+7 -1
@@ -877,7 +877,13 @@ fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), Stri
877 let Some(mut hw) = open_hw(path, start_frame) else {877 let Some(mut hw) = open_hw(path, start_frame) else {
878 return Err(codec.needs_plugin());878 return Err(codec.needs_plugin());
879 };879 };
880- hw.next_frame().map(|_| ()).map_err(|_| codec.undecodable())880+ // End of stream counts as a refusal, not as a pass: a session that hands
881+ // back no picture at all is exactly the black-frame-and-instant-eof this
882+ // probe exists to catch, and `Ok(None)` is how the plugin says it.
883+ match hw.next_frame() {
884+ Ok(Some(_)) => Ok(()),
885+ _ => Err(codec.undecodable()),
886+ }
881 }887 }
882 888
883 /// Returns whether the session was handled; `false` only when hardware decode889 /// Returns whether the session was handled; `false` only when hardware decode
vendor/cros-codecs/src/decoder/stateless/h264.rsmodified+10 -7
@@ -954,13 +954,16 @@ where
954 954
955 debug!("frame_num gap detected.");955 debug!("frame_num gap detected.");
956 956
957- if !sps.gaps_in_frame_num_value_allowed_flag {957+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a gap is filled with
958- return Err(anyhow!(958+ // the §8.2.5.2 non-existing frames whatever the flag says, instead of
959- "Invalid frame_num: {}. Assuming unintentional loss of pictures",959+ // failing the stream. The flag means "this file has no intentional
960- frame_num960+ // gaps", and it is right -- the gap is *ours*: an editor starts decoding
961- ));961+ // at a random access point in the middle of a film, and the pictures
962- }962+ // between the previous reference and it were never decoded. Refusing
963-963+ // here is what made every seek into an open-GOP Blu-ray remux fall back
964+ // to a software decoder (17 of 20 in `bench scrub`), and the standing in
965+ // frames this loop builds are exactly what the reference lists of the
966+ // pictures after the gap look for.
964 let mut unused_short_term_frame_num =967 let mut unused_short_term_frame_num =
965 (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num();968 (self.codec.prev_ref_pic_info.frame_num + 1) % sps.max_frame_num();
966 while unused_short_term_frame_num != frame_num {969 while unused_short_term_frame_num != frame_num {