diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index fed7327..cb1d0c6 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -118,11 +118,10 @@ pub fn probe(path: &Path) -> crate::Result<(Option, Backend)> { } let path = path.to_path_buf(); let (meta, _demuxer) = Demuxer::open(&path)?; - if open_hw(&path, 0).is_some() { - return Ok((Some(meta.codec), Backend::Hardware)); - } - if meta.codec != Codec::H264 { - return Err(meta.codec.needs_plugin().into()); + match hw_decodes(&path, 0, meta.codec) { + Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)), + Err(e) if meta.codec != Codec::H264 => return Err(e.into()), + Err(_) => {} } Ok((Some(meta.codec), Backend::Software)) } @@ -408,10 +407,11 @@ impl DecodeSession { // No software HEVC or VP9 decoder exists, so such a file the plugin will // not take is refused *here*, where the caller still has somewhere to // show it -- a worker that opened and then produced nothing is a black - // screen with no explanation. The probe session is opened and dropped: - // it costs one extra VA-API init (~90 ms) and only off the H.264 path. - if meta.codec != Codec::H264 && open_hw(&path, start_frame).is_none() { - return Err(meta.codec.needs_plugin().into()); + // screen with no explanation. The probe session is opened, made to + // decode one picture and dropped: it costs one extra VA-API init + // (~90 ms) plus that frame, and only off the H.264 path. + if meta.codec != Codec::H264 { + hw_decodes(&path, start_frame, meta.codec)?; } let end_frame = end_frame.min(meta.frame_count); // 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::open_at(path, start_frame) } +/// `Ok` when the plugin really decodes this file: it opens *and* hands back a +/// first picture. Opening only reads the container -- a stream the vendored +/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and +/// then produces nothing, which reaches the user as a black picture with an +/// instant `eof` unless the door asks for that first frame. Costs one decoded +/// frame per probe. +/// +/// The `Err` says which half failed, because "there is no decoder for this +/// codec" and "the decoder here would not take this stream" are different +/// refusals and a user acts on them differently. +fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> { + let Some(mut hw) = open_hw(path, start_frame) else { + return Err(codec.needs_plugin()); + }; + hw.next_frame().map(|_| ()).map_err(|_| codec.undecodable()) +} + /// Returns whether the session was handled; `false` only when hardware decode /// failed without emitting a single frame, so software can still take over. /// diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index fed72f5..ac08cbe 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -55,6 +55,16 @@ impl Codec { name = self.name() ) } + + /// The other refusal: the plugin *is* here and opened the file, and then + /// could not decode a picture out of it. Not a missing decoder, and saying + /// so would send the user installing something they already have. + pub fn undecodable(self) -> String { + format!( + "this {name} stream cannot be decoded — the VA-API plugin opened it, gave no picture", + name = self.name() + ) + } } #[derive(Debug, Clone, Copy, PartialEq)] diff --git a/crates/engine/tests/data/test_hevc_4k_wpp.mkv b/crates/engine/tests/data/test_hevc_4k_wpp.mkv new file mode 100644 index 0000000000000000000000000000000000000000..172e0141665343b63469a61a0da7bcad86474fad GIT binary patch literal 8430 zcmd6teQ*;&rCM}7yHfRe0O1oeV0wXjDr7tMw?sh{H?~-P^iIju0h1#a{MXD{J z!p-fbu?-Z5P`pBEwqkriJ9r#dkuj)u^t`K6MW>27I8Sm|>{x|$ z|Ja?(=6U-)zu))yJipEEPG*?j4+NNc0WqTjVm=d;%tb-PczjiBYVTiPQ?Z6=5R}Zr z0-@!2Hv)W+$EVm@YlFSsFW$ABv-LD`2fRtvr%Smmp(9$G>U^$(>k>Y-^=#)3cyDs{ zxw$S6p^H|Nxt z(;}n6w1WO&y{6M|e{adT{`P-Ob{DNRJ^E{tn%(N7{A?sJtcYIN>s@-HL-$-XZj^FH zKsB%UYF^nt+LF<@txbSAN89R3?seDu?<%x8%(<2{E0>pMG2fL_C!kwCtn(6^L*?N> zwjeS1J`v!`@(=*Uk5dQH91;M!BhfUE zz&GDsx&)A*BmsezLUHKwWjsKEM=0>8S=+6f4G5MoC}Mh5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954L_u#bIndd0GHV%@x4uwND^=a#HO7VV14 zm(*Ii`HL{IA2e~UAwBbT^<%jgHup?Ef2a)L?1fodC%*tY|8aWBrhQGTVlsw5+?E3i zzBG((8D0$<_p|q;Lko{zqFu{NwV2-|8S@T&%WNJDFVr`F9pf(ZZE@TXJ8eX{g1pA} gZ1^7ryL-I_Z^!TN*>PBaW7|dr^r=TtJ0hsR1IFPJ1ONa4 literal 0 HcmV?d00001 diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index 3fbf5fc..86c2d34 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -18,7 +18,8 @@ use std::time::Instant; use engine::DecodeSession; use engine::colorspace::{ColorDescription, Matrix}; use engine::convert::i420_to_bgra; -use engine::demux::Demuxer; +use engine::demux::{Codec, Demuxer}; +use engine::scratch::Scratch; use engine::hw::HwSession; use engine::tonemap::{ToneMapper, Transfer}; @@ -79,6 +80,57 @@ fn rejects_unopenable_files() { ); } +/// 24 frames cut from a 2160p HDR remux that used to give a black picture and +/// an instant `eof`: at 3840x2160 with CTB 64 the picture is 34 CTB rows, so +/// wavefront slices carry `num_entry_point_offsets == 33` (§7.4.7.1 allows up +/// to PicHeightInCtbsY - 1) and the vendored parser indexed a `[u32; 32]` with +/// 32. Conformant stream, panicking parser -- caught at the plugin edge, which +/// is exactly why it reached the user as a silent eof. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn hardware_decodes_4k_wavefront_slices() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv"); + let mut hw = open_hw(&path); + let mut count = 0usize; + while let Some((_, _, _, w, h)) = hw.next_frame().expect("hardware decode") { + assert_eq!((w, h), (3840, 2160), "frame {count} dims"); + count += 1; + } + assert!(count > 0, "4K wavefront stream decoded no pictures"); +} + +/// ...and the same file with its slice bytes scrambled -- a stream the plugin +/// opens and then cannot decode a picture out of -- is refused at the door, in +/// words that do not send the user installing a plugin they already have. The +/// case this whole bug arrived as: never a black picture and a silent `eof`. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver"] +fn an_undecodable_hevc_stream_is_refused_by_name() { + let good = std::fs::read( + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/test_hevc_4k_wpp.mkv"), + ) + .expect("read the 4K fixture"); + // Every SPS in it (`nal_unit_type` 33, so the two header bytes are 42 01) + // gets `sps_max_sub_layers_minus1 = 7`, which §7.4.3.2.1 does not allow and + // the parser now refuses instead of indexing a 7-long array with 7. + let mut broken = good.clone(); + let mut patched = 0; + for i in 0..broken.len() - 2 { + if broken[i] == 0x42 && broken[i + 1] == 0x01 { + broken[i + 2] |= 0x0e; + patched += 1; + } + } + assert!(patched > 0, "no SPS found in the fixture"); + let path = Scratch::file("undecodable_hevc", "mkv"); + std::fs::write(&path, &broken).expect("write the broken copy"); + + let refused = DecodeSession::open(&path) + .expect_err("a stream with no decodable picture must not open") + .to_string(); + assert_eq!(refused, Codec::Hevc.undecodable()); +} + #[test] #[ignore = "needs libengine_hw.so and a VA-API driver"] fn hardware_decodes_baseline() { diff --git a/vendor/cros-codecs/src/codec/h265/parser.rs b/vendor/cros-codecs/src/codec/h265/parser.rs index c3bb75c..d9a9cff 100644 --- a/vendor/cros-codecs/src/codec/h265/parser.rs +++ b/vendor/cros-codecs/src/codec/h265/parser.rs @@ -1708,7 +1708,12 @@ pub struct SliceHeader { /// num_entry_point_offsets + 1 subsets, with subset index values ranging /// from 0 to num_entry_point_offsets, inclusive. See the specification for /// more details. - pub entry_point_offset_minus1: [u32; 32], + /// + /// Sized by the stream, not by a guess: §7.4.7.1 bounds + /// `num_entry_point_offsets` by the picture's CTB grid, so a conformant + /// 2160p WPP stream writes up to PicHeightInCtbsY - 1 == 33 of these and a + /// tiled one many more. A fixed `[u32; 32]` here panicked on the 34th. + pub entry_point_offset_minus1: Vec, /// Same as NumPicTotalCurr in the specification. pub num_pic_total_curr: u32, // Size of slice_header() in bits. @@ -1804,7 +1809,8 @@ impl<'a> Slice<'a> { let segment_address = self.header.segment_address; let offset_len_minus1 = self.header.offset_len_minus1; - let entry_point_offset_minus1 = self.header.entry_point_offset_minus1; + let entry_point_offset_minus1 = + std::mem::take(&mut self.header.entry_point_offset_minus1); let num_pic_total_curr = self.header.num_pic_total_curr; let header_bit_size = self.header.header_bit_size; let n_emulation_prevention_bytes = self.header.n_emulation_prevention_bytes; @@ -2232,6 +2238,15 @@ impl Parser { r.skip_bits(16)?; // vps_reserved_0xffff_16bits + // §7.4.3.1: 0..6. The three bits can say 7, and every sub-layer array + // below is 7 long -- refuse rather than index one out of bounds. + if vps.max_sub_layers_minus1 > 6 { + return Err(format!( + "Invalid vps_max_sub_layers_minus1 {}", + vps.max_sub_layers_minus1 + )); + } + let ptl = &mut vps.profile_tier_level; Self::parse_profile_tier_level(ptl, &mut r, true, vps.max_sub_layers_minus1)?; @@ -3091,6 +3106,14 @@ impl Parser { ..Default::default() }; + // §7.4.3.2.1: 0..6, and the sub-layer arrays below are 7 long. + if sps.max_sub_layers_minus1 > 6 { + return Err(format!( + "Invalid sps_max_sub_layers_minus1 {}", + sps.max_sub_layers_minus1 + )); + } + Self::parse_profile_tier_level( &mut sps.profile_tier_level, &mut r, @@ -3466,8 +3489,16 @@ impl Parser { // A mix of the rbsp data and the algorithm in 6.5.1 if pps.tiles_enabled_flag { - pps.num_tile_columns_minus1 = r.read_ue_max(sps.pic_width_in_ctbs_y - 1)?; - pps.num_tile_rows_minus1 = r.read_ue_max(sps.pic_height_in_ctbs_y - 1)?; + // §7.4.3.3.1 bounds these by the CTB grid, which at 4K is far more + // tiles than either these arrays or the VA-API picture parameter + // (`column_width_minus1[19]`, `row_height_minus1[21]`, the level-6 + // tile limits) can hold. Refuse the stream instead of indexing past + // them -- a decode we could not have handed to the driver anyway. + let max_cols = pps.column_width_minus1.len() as u32 - 1; + let max_rows = pps.row_height_minus1.len() as u32 - 1; + pps.num_tile_columns_minus1 = + r.read_ue_max((sps.pic_width_in_ctbs_y - 1).min(max_cols))?; + pps.num_tile_rows_minus1 = r.read_ue_max((sps.pic_height_in_ctbs_y - 1).min(max_rows))?; pps.uniform_spacing_flag = r.read_bit()?; if !pps.uniform_spacing_flag { pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] = @@ -3849,6 +3880,14 @@ impl Parser { )?; let num_lt = hdr.num_long_term_sps + hdr.num_long_term_pics; + // §7.4.7.1 keeps the sum inside the DPB, so the 16-entry + // arrays below hold every conformant stream; the two reads + // above can each say more than that on their own. + if usize::from(num_lt) > hdr.poc_lsb_lt.len() { + return Err(format!( + "Invalid num_long_term_sps + num_long_term_pics {num_lt}" + )); + } for i in 0..usize::from(num_lt) { // The variables `PocLsbLt[ i ]` and `UsedByCurrPicLt[ i ]` are derived as follows: // @@ -4081,9 +4120,10 @@ impl Parser { hdr.num_entry_point_offsets = r.read_ue_max(max)?; if hdr.num_entry_point_offsets > 0 { hdr.offset_len_minus1 = r.read_ue_max(31)?; - for i in 0..hdr.num_entry_point_offsets as usize { - let num_bits = usize::from(hdr.offset_len_minus1 + 1); - hdr.entry_point_offset_minus1[i] = r.read_bits(num_bits)?; + let num_bits = usize::from(hdr.offset_len_minus1 + 1); + hdr.entry_point_offset_minus1.clear(); + for _ in 0..hdr.num_entry_point_offsets { + hdr.entry_point_offset_minus1.push(r.read_bits(num_bits)?); } } }