forge
Explore
Log in

Don't you dare go Hollow

HEVC picture order counts follow prevTid0Pic, not the last picture

Browse files at this commit

5f55768387b33e27c9c583ced7bafd8e0059a869Ahmet Kaan GümüşParent: e63caff
  • fix
    • HEVC picture order counts follow prevTid0Pic, not the last picture
Show full message
fix(hw): HEVC picture order counts follow prevTid0Pic, not the last picture

A 4K HDR release decoded at 19 dB against the software decoder: right
most of the time, wrong wherever it mattered. Two clauses, one cause.

8.3.1 predicts the picture order count MSB from `prevTid0Pic` — the
previous picture with TemporalId 0 that is neither a leading picture nor
a sub-layer non-reference. Predicting from the previous picture instead
works on a stream without temporal sub-layers (every fixture here) and
puts the MSB a wrap out on one that has them, which hands the driver the
wrong references and the wrong output order.

The same NAL types say which pictures may be referenced at all: a "_N"
type is a sub-layer non-reference, and storing it as a short-term
reference lets the next picture's reference picture set match it by
picture order count.

Also passes `st_rps_bits` through, so a driver that skips a reference
picture set the slice header carried itself knows how long it was, and
adds an `EC_HW_DEBUG` trace of the per-picture DPB state — this bug was
found with it.

Five files from the real library now decode identically to the software
decoder, including the one that failed: 2160p HEVC Main10 HDR, 1080p
HEVC 10-bit, 1080p AV1 10-bit and two 1440p H.264 screen captures.
crates/ec-hw/src/dec/dpb264.rsmodified+17 -19
@@ -908,25 +908,23 @@ mod tests {
908 fn poc_type_0_tracks_the_msb_across_a_wrap() {908 fn poc_type_0_tracks_the_msb_across_a_wrap() {
909 let sps = sps_for(0);909 let sps = sps_for(0);
910 let mut dpb = Dpb::default();910 let mut dpb = Dpb::default();
911- let poc = dpb911+ let mut expect = |info: PicInfo, want: i32| {
912- .picture_order_count(&sps, &info(0, 0, true, true))912+ let poc = dpb.picture_order_count(&sps, &info).unwrap();
913- .unwrap();913+ assert_eq!(poc.value, want, "{info:?}");
914- assert_eq!(poc.value, 0);914+ // What `store` does for a reference picture.
915- dpb.prev_poc_msb = poc.msb;915+ if info.is_reference {
916- dpb.prev_poc_lsb = poc.lsb;916+ dpb.prev_poc_msb = poc.msb;
917-917+ dpb.prev_poc_lsb = poc.lsb;
918- let poc = dpb918+ }
919- .picture_order_count(&sps, &info(1, 14, true, false))919+ };
920- .unwrap();920+ // MaxPicOrderCntLsb is 16 here, so a step of more than 8 is read as a
921- assert_eq!(poc.value, 14);921+ // wrap rather than as a jump.
922- dpb.prev_poc_msb = poc.msb;922+ expect(info(0, 0, true, true), 0);
923- dpb.prev_poc_lsb = poc.lsb;923+ expect(info(1, 7, true, false), 7);
924-924+ expect(info(2, 14, true, false), 14);
925- // lsb wraps 14 -> 2 with MaxPicOrderCntLsb 16: the msb must step up.925+ expect(info(3, 2, true, false), 18);
926- let poc = dpb926+ // And a small step back really is a step back.
927- .picture_order_count(&sps, &info(2, 2, true, false))927+ expect(info(4, 15, true, false), 15);
928- .unwrap();
929- assert_eq!(poc.value, 18);
930 }928 }
931 929
932 #[test]930 #[test]
crates/ec-hw/src/dec/hevc.rsmodified+64 -10
@@ -69,6 +69,8 @@ struct Current {
69 poc: i32,69 poc: i32,
70 timestamp: i64,70 timestamp: i64,
71 is_reference: bool,71 is_reference: bool,
72+ /// True when this picture may be `prevTid0Pic` for the next one (8.3.1).
73+ is_tid0_anchor: bool,
72 output: bool,74 output: bool,
73 rps: Rps,75 rps: Rps,
74 buffers: Vec<Buffer>,76 buffers: Vec<Buffer>,
@@ -142,7 +144,7 @@ impl HevcDecoder {
142 }144 }
143 }145 }
144 t if t.is_vcl() => {146 t if t.is_vcl() => {
145- self.slice(t, nal.payload, timestamp)?;147+ self.slice(t, nal.header.temporal_id, nal.payload, timestamp)?;
146 }148 }
147 _ => {}149 _ => {}
148 }150 }
@@ -176,7 +178,13 @@ impl HevcDecoder {
176 self.session.as_ref().map(Session::info)178 self.session.as_ref().map(Session::info)
177 }179 }
178 180
179- fn slice(&mut self, nal_type: NalUnitType, payload: &[u8], timestamp: i64) -> Result<()> {181+ fn slice(
182+ &mut self,
183+ nal_type: NalUnitType,
184+ temporal_id: u8,
185+ payload: &[u8],
186+ timestamp: i64,
187+ ) -> Result<()> {
180 let rbsp = unescape_rbsp(payload);188 let rbsp = unescape_rbsp(payload);
181 // The header cannot be parsed without its PPS, and the PPS names the SPS.189 // The header cannot be parsed without its PPS, and the PPS names the SPS.
182 let pps_id = peek_pps_id(&rbsp, nal_type)?;190 let pps_id = peek_pps_id(&rbsp, nal_type)?;
@@ -194,7 +202,7 @@ impl HevcDecoder {
194 202
195 if sh.first_slice_segment_in_pic {203 if sh.first_slice_segment_in_pic {
196 self.finish_picture()?;204 self.finish_picture()?;
197- self.start_picture(&sps, &sh, nal_type, timestamp)?;205+ self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?;
198 }206 }
199 if self.current.is_none() {207 if self.current.is_none() {
200 return Ok(());208 return Ok(());
@@ -243,6 +251,7 @@ impl HevcDecoder {
243 sps: &Sps,251 sps: &Sps,
244 sh: &SliceHeader,252 sh: &SliceHeader,
245 nal_type: NalUnitType,253 nal_type: NalUnitType,
254+ temporal_id: u8,
246 timestamp: i64,255 timestamp: i64,
247 ) -> Result<()> {256 ) -> Result<()> {
248 self.ensure_session(sps)?;257 self.ensure_session(sps)?;
@@ -258,6 +267,22 @@ impl HevcDecoder {
258 self.bump(true);267 self.bump(true);
259 }268 }
260 269
270+ if std::env::var_os("EC_HW_DEBUG").is_some() {
271+ eprintln!(
272+ "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}",
273+ nal_type,
274+ sh.poc_lsb,
275+ self.dpb.len(),
276+ self.ready.len(),
277+ rps.st_curr_before.len(),
278+ rps.st_curr_after.len(),
279+ rps.lt_curr.len(),
280+ self.session
281+ .as_ref()
282+ .map(|s| s.pool.available())
283+ .unwrap_or(0),
284+ );
285+ }
261 let session = self286 let session = self
262 .session287 .session
263 .as_ref()288 .as_ref()
@@ -283,7 +308,19 @@ impl HevcDecoder {
283 sps_id: sps.id,308 sps_id: sps.id,
284 poc,309 poc,
285 timestamp,310 timestamp,
286- is_reference: true,311+ // A "_N" picture (an even NAL type below 16) is a sub-layer
312+ // non-reference: nothing in its own sub-layer may predict from it,
313+ // and a decoder that stores it as a reference lets the next
314+ // picture's reference picture set match the wrong picture by POC.
315+ is_reference: is_reference_picture(nal_type),
316+ // 8.3.1: `prevTid0Pic` is the previous picture with TemporalId 0
317+ // that is neither RASL, RADL nor sub-layer non-reference. Taking
318+ // the previous picture instead — which a stream with temporal
319+ // sub-layers immediately punishes — puts the picture order count
320+ // MSB one wrap out and hands the driver the wrong references.
321+ is_tid0_anchor: temporal_id == 0
322+ && is_reference_picture(nal_type)
323+ && !is_leading_picture(nal_type),
287 output: sh.pic_output_flag,324 output: sh.pic_output_flag,
288 rps,325 rps,
289 buffers: Vec::new(),326 buffers: Vec::new(),
@@ -430,7 +467,7 @@ impl HevcDecoder {
430 }467 }
431 468
432 if current.slices == 0 {469 if current.slices == 0 {
433- let pic_param = picture_parameters(sps, pps, sh, nal_type, current, &self.dpb);470+ let pic_param = picture_parameters(sps, pps, sh, pos, nal_type, current, &self.dpb);
434 current471 current
435 .buffers472 .buffers
436 .push(param_buffer(&session.context, &pic_param)?);473 .push(param_buffer(&session.context, &pic_param)?);
@@ -541,7 +578,9 @@ impl HevcDecoder {
541 },578 },
542 output: current.output,579 output: current.output,
543 });580 });
544- self.prev_tid0_poc = current.poc;581+ if current.is_tid0_anchor {
582+ self.prev_tid0_poc = current.poc;
583+ }
545 self.started = true;584 self.started = true;
546 self.bump(false);585 self.bump(false);
547 Ok(())586 Ok(())
@@ -584,6 +623,19 @@ impl HevcDecoder {
584 }623 }
585 }624 }
586 625
626+/// True unless the NAL type says sub-layer non-reference (`_N`, an even type
627+/// below 16).
628+fn is_reference_picture(nal_type: NalUnitType) -> bool {
629+ let code = nal_type.code();
630+ code >= 16 || code % 2 == 1
631+}
632+
633+/// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1
634+/// excludes from the picture order count prediction.
635+fn is_leading_picture(nal_type: NalUnitType) -> bool {
636+ (6..=9).contains(&nal_type.code())
637+}
638+
587 /// `slice_pic_parameter_set_id`, readable without any parameter set.639 /// `slice_pic_parameter_set_id`, readable without any parameter set.
588 fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {640 fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {
589 let mut r = ec_core::BitReader::new(rbsp);641 let mut r = ec_core::BitReader::new(rbsp);
@@ -641,10 +693,12 @@ fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] {
641 out693 out
642 }694 }
643 695
696+#[allow(clippy::too_many_arguments)]
644 fn picture_parameters(697 fn picture_parameters(
645 sps: &Sps,698 sps: &Sps,
646 pps: &Pps,699 pps: &Pps,
647 sh: &SliceHeader,700 sh: &SliceHeader,
701+ pos: &ParsePositions,
648 nal_type: NalUnitType,702 nal_type: NalUnitType,
649 current: &Current,703 current: &Current,
650 dpb: &[StoredPicture],704 dpb: &[StoredPicture],
@@ -681,10 +735,10 @@ fn picture_parameters(
681 pps_beta_offset_div2: pps.beta_offset_div2 as i8,735 pps_beta_offset_div2: pps.beta_offset_div2 as i8,
682 pps_tc_offset_div2: pps.tc_offset_div2 as i8,736 pps_tc_offset_div2: pps.tc_offset_div2 as i8,
683 num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8,737 num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8,
684- // Zero when the slice took its set from the SPS, which is what the738+ // The size of an `st_ref_pic_set()` the slice header carried itself,
685- // parser reports; the field exists so the driver can skip a set the739+ // so the driver can skip it; zero when the slice named an SPS set,
686- // header carried itself.740+ // which is what the parser reports.
687- st_rps_bits: 0,741+ st_rps_bits: pos.st_rps_bits,
688 ..PictureParameterBufferHEVC::default()742 ..PictureParameterBufferHEVC::default()
689 };743 };
690 744
crates/ec-hw/src/dec/mod.rsmodified+9 -5
@@ -158,11 +158,11 @@ impl Decoder {
158 158
159 /// Frames waiting to be collected, oldest first.159 /// Frames waiting to be collected, oldest first.
160 ///160 ///
161-/// The queue is the frame-out design `cros-codecs` uses (a decode call produces161+/// A decode call produces frames rather than returning one, because one access
162-/// events rather than returning a picture), minus the event fd: nothing in this162+/// unit can complete none, one or several pictures. There is no event fd behind
163-/// family polls a decoder from an event loop, and adding a `eventfd(2)` here163+/// it: nothing in this family polls a decoder from an event loop, and adding an
164-/// would mean a second FFI surface in a crate whose whole unsafe budget is164+/// `eventfd(2)` would mean a second FFI surface in a crate whose whole unsafe
165-/// meant to be libva.165+/// budget is meant to be libva.
166 #[derive(Debug, Default)]166 #[derive(Debug, Default)]
167 pub(crate) struct ReadyFrames {167 pub(crate) struct ReadyFrames {
168 queue: VecDeque<Frame>,168 queue: VecDeque<Frame>,
@@ -180,6 +180,10 @@ impl ReadyFrames {
180 pub(crate) fn clear(&mut self) {180 pub(crate) fn clear(&mut self) {
181 self.queue.clear();181 self.queue.clear();
182 }182 }
183+
184+ pub(crate) fn len(&self) -> usize {
185+ self.queue.len()
186+ }
183 }187 }
184 188
185 /// The GPU-side state one decoded stream needs: config, context, surfaces.189 /// The GPU-side state one decoded stream needs: config, context, surfaces.
crates/ec-hw/src/frame.rsmodified+3 -3
@@ -305,9 +305,9 @@ impl std::fmt::Debug for Frame {
305 305
306 /// Deinterleave an NV12 chroma plane into I420 U and V planes.306 /// Deinterleave an NV12 chroma plane into I420 U and V planes.
307 ///307 ///
308-/// Parity with `cros-codecs`' `image_processing::nv12_to_i420`, which is what308+/// The same conversion the software path in edith expects on the way out of a
309-/// edith calls today; kept as a free function because the conversion is also309+/// hardware frame; kept as a free function because an encoder's input path
310-/// what an encoder input path needs, in reverse.310+/// needs it in reverse.
311 pub fn nv12_to_i420(311 pub fn nv12_to_i420(
312 y_plane: &[u8],312 y_plane: &[u8],
313 y_pitch: usize,313 y_pitch: usize,
crates/ec-hw/tests/gpu.rsmodified+11 -2
@@ -934,6 +934,11 @@ fn real_library_spot_check() {
934 return;934 return;
935 }935 }
936 936
937+ // 500 frames per file by default; a diagnostic run can ask for fewer.
938+ let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES")
939+ .ok()
940+ .and_then(|v| v.parse().ok())
941+ .unwrap_or(500);
937 let mut table = Vec::new();942 let mut table = Vec::new();
938 for (path, codec, ten_bit) in &wanted {943 for (path, codec, ten_bit) in &wanted {
939 let path = Path::new(path);944 let path = Path::new(path);
@@ -946,7 +951,7 @@ fn real_library_spot_check() {
946 let mut worst = f64::INFINITY;951 let mut worst = f64::INFINITY;
947 let mut compared = 0usize;952 let mut compared = 0usize;
948 let mut failed: Option<String> = None;953 let mut failed: Option<String> = None;
949- let result = decode_stream(&mut decoder, *codec, &data, 500, |frame| {954+ let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| {
950 let (w, h) = frame.display_size;955 let (w, h) = frame.display_size;
951 let reference = reference956 let reference = reference
952 .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs"));957 .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs"));
@@ -962,7 +967,11 @@ fn real_library_spot_check() {
962 failed = Some("frame size disagrees with ffmpeg".to_string());967 failed = Some("frame size disagrees with ffmpeg".to_string());
963 return;968 return;
964 }969 }
965- worst = worst.min(psnr(&got, &want));970+ let db = psnr(&got, &want);
971+ if std::env::var_os("EC_HW_DEBUG").is_some() {
972+ eprintln!(" {} frame {compared}: {db:.1} dB", short(path));
973+ }
974+ worst = worst.min(db);
966 compared += 1;975 compared += 1;
967 });976 });
968 match result {977 match result {