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 {
908908 fn poc_type_0_tracks_the_msb_across_a_wrap() {
909909 let sps = sps_for(0);
910910 let mut dpb = Dpb::default();
911- let poc = dpb
912- .picture_order_count(&sps, &info(0, 0, true, true))
913- .unwrap();
914- assert_eq!(poc.value, 0);
915- dpb.prev_poc_msb = poc.msb;
916- dpb.prev_poc_lsb = poc.lsb;
917-
918- let poc = dpb
919- .picture_order_count(&sps, &info(1, 14, true, false))
920- .unwrap();
921- assert_eq!(poc.value, 14);
922- dpb.prev_poc_msb = poc.msb;
923- dpb.prev_poc_lsb = poc.lsb;
924-
925- // lsb wraps 14 -> 2 with MaxPicOrderCntLsb 16: the msb must step up.
926- let poc = dpb
927- .picture_order_count(&sps, &info(2, 2, true, false))
928- .unwrap();
929- assert_eq!(poc.value, 18);
911+ let mut expect = |info: PicInfo, want: i32| {
912+ let poc = dpb.picture_order_count(&sps, &info).unwrap();
913+ assert_eq!(poc.value, want, "{info:?}");
914+ // What `store` does for a reference picture.
915+ if info.is_reference {
916+ dpb.prev_poc_msb = poc.msb;
917+ dpb.prev_poc_lsb = poc.lsb;
918+ }
919+ };
920+ // MaxPicOrderCntLsb is 16 here, so a step of more than 8 is read as a
921+ // wrap rather than as a jump.
922+ expect(info(0, 0, true, true), 0);
923+ expect(info(1, 7, true, false), 7);
924+ expect(info(2, 14, true, false), 14);
925+ expect(info(3, 2, true, false), 18);
926+ // And a small step back really is a step back.
927+ expect(info(4, 15, true, false), 15);
930928 }
931929
932930 #[test]
crates/ec-hw/src/dec/hevc.rsmodified+64 -10
@@ -69,6 +69,8 @@ struct Current {
6969 poc: i32,
7070 timestamp: i64,
7171 is_reference: bool,
72+ /// True when this picture may be `prevTid0Pic` for the next one (8.3.1).
73+ is_tid0_anchor: bool,
7274 output: bool,
7375 rps: Rps,
7476 buffers: Vec<Buffer>,
@@ -142,7 +144,7 @@ impl HevcDecoder {
142144 }
143145 }
144146 t if t.is_vcl() => {
145- self.slice(t, nal.payload, timestamp)?;
147+ self.slice(t, nal.header.temporal_id, nal.payload, timestamp)?;
146148 }
147149 _ => {}
148150 }
@@ -176,7 +178,13 @@ impl HevcDecoder {
176178 self.session.as_ref().map(Session::info)
177179 }
178180
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<()> {
180188 let rbsp = unescape_rbsp(payload);
181189 // The header cannot be parsed without its PPS, and the PPS names the SPS.
182190 let pps_id = peek_pps_id(&rbsp, nal_type)?;
@@ -194,7 +202,7 @@ impl HevcDecoder {
194202
195203 if sh.first_slice_segment_in_pic {
196204 self.finish_picture()?;
197- self.start_picture(&sps, &sh, nal_type, timestamp)?;
205+ self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?;
198206 }
199207 if self.current.is_none() {
200208 return Ok(());
@@ -243,6 +251,7 @@ impl HevcDecoder {
243251 sps: &Sps,
244252 sh: &SliceHeader,
245253 nal_type: NalUnitType,
254+ temporal_id: u8,
246255 timestamp: i64,
247256 ) -> Result<()> {
248257 self.ensure_session(sps)?;
@@ -258,6 +267,22 @@ impl HevcDecoder {
258267 self.bump(true);
259268 }
260269
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+ }
261286 let session = self
262287 .session
263288 .as_ref()
@@ -283,7 +308,19 @@ impl HevcDecoder {
283308 sps_id: sps.id,
284309 poc,
285310 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),
287324 output: sh.pic_output_flag,
288325 rps,
289326 buffers: Vec::new(),
@@ -430,7 +467,7 @@ impl HevcDecoder {
430467 }
431468
432469 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);
434471 current
435472 .buffers
436473 .push(param_buffer(&session.context, &pic_param)?);
@@ -541,7 +578,9 @@ impl HevcDecoder {
541578 },
542579 output: current.output,
543580 });
544- self.prev_tid0_poc = current.poc;
581+ if current.is_tid0_anchor {
582+ self.prev_tid0_poc = current.poc;
583+ }
545584 self.started = true;
546585 self.bump(false);
547586 Ok(())
@@ -584,6 +623,19 @@ impl HevcDecoder {
584623 }
585624 }
586625
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+
587639 /// `slice_pic_parameter_set_id`, readable without any parameter set.
588640 fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {
589641 let mut r = ec_core::BitReader::new(rbsp);
@@ -641,10 +693,12 @@ fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] {
641693 out
642694 }
643695
696+#[allow(clippy::too_many_arguments)]
644697 fn picture_parameters(
645698 sps: &Sps,
646699 pps: &Pps,
647700 sh: &SliceHeader,
701+ pos: &ParsePositions,
648702 nal_type: NalUnitType,
649703 current: &Current,
650704 dpb: &[StoredPicture],
@@ -681,10 +735,10 @@ fn picture_parameters(
681735 pps_beta_offset_div2: pps.beta_offset_div2 as i8,
682736 pps_tc_offset_div2: pps.tc_offset_div2 as i8,
683737 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 the
685- // parser reports; the field exists so the driver can skip a set the
686- // header carried itself.
687- st_rps_bits: 0,
738+ // The size of an `st_ref_pic_set()` the slice header carried itself,
739+ // so the driver can skip it; zero when the slice named an SPS set,
740+ // which is what the parser reports.
741+ st_rps_bits: pos.st_rps_bits,
688742 ..PictureParameterBufferHEVC::default()
689743 };
690744
crates/ec-hw/src/dec/mod.rsmodified+9 -5
@@ -158,11 +158,11 @@ impl Decoder {
158158
159159 /// Frames waiting to be collected, oldest first.
160160 ///
161-/// The queue is the frame-out design `cros-codecs` uses (a decode call produces
162-/// events rather than returning a picture), minus the event fd: nothing in this
163-/// family polls a decoder from an event loop, and adding a `eventfd(2)` here
164-/// would mean a second FFI surface in a crate whose whole unsafe budget is
165-/// meant to be libva.
161+/// A decode call produces frames rather than returning one, because one access
162+/// unit can complete none, one or several pictures. There is no event fd behind
163+/// it: nothing in this family polls a decoder from an event loop, and adding an
164+/// `eventfd(2)` would mean a second FFI surface in a crate whose whole unsafe
165+/// budget is meant to be libva.
166166 #[derive(Debug, Default)]
167167 pub(crate) struct ReadyFrames {
168168 queue: VecDeque<Frame>,
@@ -180,6 +180,10 @@ impl ReadyFrames {
180180 pub(crate) fn clear(&mut self) {
181181 self.queue.clear();
182182 }
183+
184+ pub(crate) fn len(&self) -> usize {
185+ self.queue.len()
186+ }
183187 }
184188
185189 /// 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 {
305305
306306 /// Deinterleave an NV12 chroma plane into I420 U and V planes.
307307 ///
308-/// Parity with `cros-codecs`' `image_processing::nv12_to_i420`, which is what
309-/// edith calls today; kept as a free function because the conversion is also
310-/// what an encoder input path needs, in reverse.
308+/// The same conversion the software path in edith expects on the way out of a
309+/// hardware frame; kept as a free function because an encoder's input path
310+/// needs it in reverse.
311311 pub fn nv12_to_i420(
312312 y_plane: &[u8],
313313 y_pitch: usize,
crates/ec-hw/tests/gpu.rsmodified+11 -2
@@ -934,6 +934,11 @@ fn real_library_spot_check() {
934934 return;
935935 }
936936
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);
937942 let mut table = Vec::new();
938943 for (path, codec, ten_bit) in &wanted {
939944 let path = Path::new(path);
@@ -946,7 +951,7 @@ fn real_library_spot_check() {
946951 let mut worst = f64::INFINITY;
947952 let mut compared = 0usize;
948953 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| {
950955 let (w, h) = frame.display_size;
951956 let reference = reference
952957 .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs"));
@@ -962,7 +967,11 @@ fn real_library_spot_check() {
962967 failed = Some("frame size disagrees with ffmpeg".to_string());
963968 return;
964969 }
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);
966975 compared += 1;
967976 });
968977 match result {