forge
Explore
Log in

Don't you dare go Hollow

A 4K wavefront HEVC is 33 entry points, not 32

Browse files at this commit

65ea910e6ecfb00fe9bdf4485eb55ea276768a62Ahmet Kaan GümüşParent: 544d97b
  • fix
    • a 4K wavefront HEVC is 33 entry points, not 32
Show full message
🐛 fix(decode): a 4K wavefront HEVC is 33 entry points, not 32

A 4K wavefront HEVC film (3840x2160, CTB 64,
entropy_coding_sync) writes num_entry_point_offsets = 33 in every slice
header -- exactly
PicHeightInCtbsY - 1, which is what ITU-T H.265 §7.4.7.1 allows -- and the
vendored parser kept them in a [u32; 32]. The 33rd panicked, the plugin edge
caught it, and the user got a black picture and an instant eof.

The list is now sized by the stream. Same shape swept through the rest of the
h265 parser, where a parsed count could outrun a fixed array: tile columns/rows
(the CTB grid allows far more than the 19/21 the VA-API picture parameter
holds), the long-term ref pic block, and sps/vps_max_sub_layers_minus1, which
u(3) can read as 7 into 7-long arrays. Those refuse by name instead.

And the door now asks the plugin for one picture before it lets a file in: a
session that opens and then decodes nothing was the black screen with no
explanation, so it is refused in its own words rather than in the missing-plugin
ones.
crates/engine/src/decode.rsmodified+26 -9
@@ -118,11 +118,10 @@ pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
118118 }
119119 let path = path.to_path_buf();
120120 let (meta, _demuxer) = Demuxer::open(&path)?;
121- if open_hw(&path, 0).is_some() {
122- return Ok((Some(meta.codec), Backend::Hardware));
123- }
124- if meta.codec != Codec::H264 {
125- return Err(meta.codec.needs_plugin().into());
121+ match hw_decodes(&path, 0, meta.codec) {
122+ Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),
123+ Err(e) if meta.codec != Codec::H264 => return Err(e.into()),
124+ Err(_) => {}
126125 }
127126 Ok((Some(meta.codec), Backend::Software))
128127 }
@@ -408,10 +407,11 @@ impl DecodeSession {
408407 // No software HEVC or VP9 decoder exists, so such a file the plugin will
409408 // not take is refused *here*, where the caller still has somewhere to
410409 // show it -- a worker that opened and then produced nothing is a black
411- // screen with no explanation. The probe session is opened and dropped:
412- // it costs one extra VA-API init (~90 ms) and only off the H.264 path.
413- if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() {
414- return Err(meta.codec.needs_plugin().into());
410+ // screen with no explanation. The probe session is opened, made to
411+ // decode one picture and dropped: it costs one extra VA-API init
412+ // (~90 ms) plus that frame, and only off the H.264 path.
413+ if meta.codec != Codec::H264 {
414+ hw_decodes(&path, start_frame, meta.codec)?;
415415 }
416416 let end_frame = end_frame.min(meta.frame_count);
417417 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
@@ -863,6 +863,23 @@ fn open_hw(path: &PathBuf, start_frame: u32) -> Option<HwSession> {
863863 HwSession::open_at(path, start_frame)
864864 }
865865
866+/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
867+/// first picture. Opening only reads the container -- a stream the vendored
868+/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
869+/// then produces nothing, which reaches the user as a black picture with an
870+/// instant `eof` unless the door asks for that first frame. Costs one decoded
871+/// frame per probe.
872+///
873+/// The `Err` says which half failed, because "there is no decoder for this
874+/// codec" and "the decoder here would not take this stream" are different
875+/// refusals and a user acts on them differently.
876+fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> {
877+ let Some(mut hw) = open_hw(path, start_frame) else {
878+ return Err(codec.needs_plugin());
879+ };
880+ hw.next_frame().map(|_| ()).map_err(|_| codec.undecodable())
881+}
882+
866883 /// Returns whether the session was handled; `false` only when hardware decode
867884 /// failed without emitting a single frame, so software can still take over.
868885 ///
crates/engine/src/demux.rsmodified+10 -0
@@ -55,6 +55,16 @@ impl Codec {
5555 name = self.name()
5656 )
5757 }
58+
59+ /// The other refusal: the plugin *is* here and opened the file, and then
60+ /// could not decode a picture out of it. Not a missing decoder, and saying
61+ /// so would send the user installing something they already have.
62+ pub fn undecodable(self) -> String {
63+ format!(
64+ "this {name} stream cannot be decoded — the VA-API plugin opened it, gave no picture",
65+ name = self.name()
66+ )
67+ }
5868 }
5969
6070 #[derive(Debug, Clone, Copy, PartialEq)]
crates/engine/tests/data/test_hevc_4k_wpp.mkvadded+0 -0

Binary file changed

crates/engine/tests/hw_decode.rsmodified+53 -1
@@ -18,7 +18,8 @@ use std::time::Instant;
1818 use engine::DecodeSession;
1919 use engine::colorspace::{ColorDescription, Matrix};
2020 use engine::convert::i420_to_bgra;
21-use engine::demux::Demuxer;
21+use engine::demux::{Codec, Demuxer};
22+use engine::scratch::Scratch;
2223 use engine::hw::HwSession;
2324 use engine::tonemap::{ToneMapper, Transfer};
2425
@@ -79,6 +80,57 @@ fn rejects_unopenable_files() {
7980 );
8081 }
8182
83+/// 24 frames cut from a 2160p HDR remux that used to give a black picture and
84+/// an instant `eof`: at 3840x2160 with CTB 64 the picture is 34 CTB rows, so
85+/// wavefront slices carry `num_entry_point_offsets == 33` (§7.4.7.1 allows up
86+/// to PicHeightInCtbsY - 1) and the vendored parser indexed a `[u32; 32]` with
87+/// 32. Conformant stream, panicking parser -- caught at the plugin edge, which
88+/// is exactly why it reached the user as a silent eof.
89+#[test]
90+#[ignore = "needs libengine_hw.so and a VA-API driver"]
91+fn hardware_decodes_4k_wavefront_slices() {
92+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv");
93+ let mut hw = open_hw(&path);
94+ let mut count = 0usize;
95+ while let Some((_, _, _, w, h)) = hw.next_frame().expect("hardware decode") {
96+ assert_eq!((w, h), (3840, 2160), "frame {count} dims");
97+ count += 1;
98+ }
99+ assert!(count > 0, "4K wavefront stream decoded no pictures");
100+}
101+
102+/// ...and the same file with its slice bytes scrambled -- a stream the plugin
103+/// opens and then cannot decode a picture out of -- is refused at the door, in
104+/// words that do not send the user installing a plugin they already have. The
105+/// case this whole bug arrived as: never a black picture and a silent `eof`.
106+#[test]
107+#[ignore = "needs libengine_hw.so and a VA-API driver"]
108+fn an_undecodable_hevc_stream_is_refused_by_name() {
109+ let good = std::fs::read(
110+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv"),
111+ )
112+ .expect("read the 4K fixture");
113+ // Every SPS in it (`nal_unit_type` 33, so the two header bytes are 42 01)
114+ // gets `sps_max_sub_layers_minus1 = 7`, which §7.4.3.2.1 does not allow and
115+ // the parser now refuses instead of indexing a 7-long array with 7.
116+ let mut broken = good.clone();
117+ let mut patched = 0;
118+ for i in 0..broken.len() - 2 {
119+ if broken[i] == 0x42 && broken[i + 1] == 0x01 {
120+ broken[i + 2] |= 0x0e;
121+ patched += 1;
122+ }
123+ }
124+ assert!(patched > 0, "no SPS found in the fixture");
125+ let path = Scratch::file("undecodable_hevc", "mkv");
126+ std::fs::write(&path, &broken).expect("write the broken copy");
127+
128+ let refused = DecodeSession::open(&path)
129+ .expect_err("a stream with no decodable picture must not open")
130+ .to_string();
131+ assert_eq!(refused, Codec::Hevc.undecodable());
132+}
133+
82134 #[test]
83135 #[ignore = "needs libengine_hw.so and a VA-API driver"]
84136 fn hardware_decodes_baseline() {
vendor/cros-codecs/src/codec/h265/parser.rsmodified+47 -7
@@ -1708,7 +1708,12 @@ pub struct SliceHeader {
17081708 /// num_entry_point_offsets + 1 subsets, with subset index values ranging
17091709 /// from 0 to num_entry_point_offsets, inclusive. See the specification for
17101710 /// more details.
1711- pub entry_point_offset_minus1: [u32; 32],
1711+ ///
1712+ /// Sized by the stream, not by a guess: §7.4.7.1 bounds
1713+ /// `num_entry_point_offsets` by the picture's CTB grid, so a conformant
1714+ /// 2160p WPP stream writes up to PicHeightInCtbsY - 1 == 33 of these and a
1715+ /// tiled one many more. A fixed `[u32; 32]` here panicked on the 34th.
1716+ pub entry_point_offset_minus1: Vec<u32>,
17121717 /// Same as NumPicTotalCurr in the specification.
17131718 pub num_pic_total_curr: u32,
17141719 // Size of slice_header() in bits.
@@ -1804,7 +1809,8 @@ impl<'a> Slice<'a> {
18041809 let segment_address = self.header.segment_address;
18051810
18061811 let offset_len_minus1 = self.header.offset_len_minus1;
1807- let entry_point_offset_minus1 = self.header.entry_point_offset_minus1;
1812+ let entry_point_offset_minus1 =
1813+ std::mem::take(&mut self.header.entry_point_offset_minus1);
18081814 let num_pic_total_curr = self.header.num_pic_total_curr;
18091815 let header_bit_size = self.header.header_bit_size;
18101816 let n_emulation_prevention_bytes = self.header.n_emulation_prevention_bytes;
@@ -2232,6 +2238,15 @@ impl Parser {
22322238
22332239 r.skip_bits(16)?; // vps_reserved_0xffff_16bits
22342240
2241+ // §7.4.3.1: 0..6. The three bits can say 7, and every sub-layer array
2242+ // below is 7 long -- refuse rather than index one out of bounds.
2243+ if vps.max_sub_layers_minus1 > 6 {
2244+ return Err(format!(
2245+ "Invalid vps_max_sub_layers_minus1 {}",
2246+ vps.max_sub_layers_minus1
2247+ ));
2248+ }
2249+
22352250 let ptl = &mut vps.profile_tier_level;
22362251 Self::parse_profile_tier_level(ptl, &mut r, true, vps.max_sub_layers_minus1)?;
22372252
@@ -3091,6 +3106,14 @@ impl Parser {
30913106 ..Default::default()
30923107 };
30933108
3109+ // §7.4.3.2.1: 0..6, and the sub-layer arrays below are 7 long.
3110+ if sps.max_sub_layers_minus1 > 6 {
3111+ return Err(format!(
3112+ "Invalid sps_max_sub_layers_minus1 {}",
3113+ sps.max_sub_layers_minus1
3114+ ));
3115+ }
3116+
30943117 Self::parse_profile_tier_level(
30953118 &mut sps.profile_tier_level,
30963119 &mut r,
@@ -3466,8 +3489,16 @@ impl Parser {
34663489
34673490 // A mix of the rbsp data and the algorithm in 6.5.1
34683491 if pps.tiles_enabled_flag {
3469- pps.num_tile_columns_minus1 = r.read_ue_max(sps.pic_width_in_ctbs_y - 1)?;
3470- pps.num_tile_rows_minus1 = r.read_ue_max(sps.pic_height_in_ctbs_y - 1)?;
3492+ // §7.4.3.3.1 bounds these by the CTB grid, which at 4K is far more
3493+ // tiles than either these arrays or the VA-API picture parameter
3494+ // (`column_width_minus1[19]`, `row_height_minus1[21]`, the level-6
3495+ // tile limits) can hold. Refuse the stream instead of indexing past
3496+ // them -- a decode we could not have handed to the driver anyway.
3497+ let max_cols = pps.column_width_minus1.len() as u32 - 1;
3498+ let max_rows = pps.row_height_minus1.len() as u32 - 1;
3499+ pps.num_tile_columns_minus1 =
3500+ r.read_ue_max((sps.pic_width_in_ctbs_y - 1).min(max_cols))?;
3501+ pps.num_tile_rows_minus1 = r.read_ue_max((sps.pic_height_in_ctbs_y - 1).min(max_rows))?;
34713502 pps.uniform_spacing_flag = r.read_bit()?;
34723503 if !pps.uniform_spacing_flag {
34733504 pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] =
@@ -3849,6 +3880,14 @@ impl Parser {
38493880 )?;
38503881
38513882 let num_lt = hdr.num_long_term_sps + hdr.num_long_term_pics;
3883+ // §7.4.7.1 keeps the sum inside the DPB, so the 16-entry
3884+ // arrays below hold every conformant stream; the two reads
3885+ // above can each say more than that on their own.
3886+ if usize::from(num_lt) > hdr.poc_lsb_lt.len() {
3887+ return Err(format!(
3888+ "Invalid num_long_term_sps + num_long_term_pics {num_lt}"
3889+ ));
3890+ }
38523891 for i in 0..usize::from(num_lt) {
38533892 // The variables `PocLsbLt[ i ]` and `UsedByCurrPicLt[ i ]` are derived as follows:
38543893 //
@@ -4081,9 +4120,10 @@ impl Parser {
40814120 hdr.num_entry_point_offsets = r.read_ue_max(max)?;
40824121 if hdr.num_entry_point_offsets > 0 {
40834122 hdr.offset_len_minus1 = r.read_ue_max(31)?;
4084- for i in 0..hdr.num_entry_point_offsets as usize {
4085- let num_bits = usize::from(hdr.offset_len_minus1 + 1);
4086- hdr.entry_point_offset_minus1[i] = r.read_bits(num_bits)?;
4123+ let num_bits = usize::from(hdr.offset_len_minus1 + 1);
4124+ hdr.entry_point_offset_minus1.clear();
4125+ for _ in 0..hdr.num_entry_point_offsets {
4126+ hdr.entry_point_offset_minus1.push(r.read_bits(num_bits)?);
40874127 }
40884128 }
40894129 }