diff --git a/crates/ec-hw/src/dec/dpb264.rs b/crates/ec-hw/src/dec/dpb264.rs index 56c30652..50a53308 100644 --- a/crates/ec-hw/src/dec/dpb264.rs +++ b/crates/ec-hw/src/dec/dpb264.rs @@ -908,25 +908,23 @@ mod tests { fn poc_type_0_tracks_the_msb_across_a_wrap() { let sps = sps_for(0); let mut dpb = Dpb::default(); - let poc = dpb - .picture_order_count(&sps, &info(0, 0, true, true)) - .unwrap(); - assert_eq!(poc.value, 0); - dpb.prev_poc_msb = poc.msb; - dpb.prev_poc_lsb = poc.lsb; - - let poc = dpb - .picture_order_count(&sps, &info(1, 14, true, false)) - .unwrap(); - assert_eq!(poc.value, 14); - dpb.prev_poc_msb = poc.msb; - dpb.prev_poc_lsb = poc.lsb; - - // lsb wraps 14 -> 2 with MaxPicOrderCntLsb 16: the msb must step up. - let poc = dpb - .picture_order_count(&sps, &info(2, 2, true, false)) - .unwrap(); - assert_eq!(poc.value, 18); + let mut expect = |info: PicInfo, want: i32| { + let poc = dpb.picture_order_count(&sps, &info).unwrap(); + assert_eq!(poc.value, want, "{info:?}"); + // What `store` does for a reference picture. + if info.is_reference { + dpb.prev_poc_msb = poc.msb; + dpb.prev_poc_lsb = poc.lsb; + } + }; + // MaxPicOrderCntLsb is 16 here, so a step of more than 8 is read as a + // wrap rather than as a jump. + expect(info(0, 0, true, true), 0); + expect(info(1, 7, true, false), 7); + expect(info(2, 14, true, false), 14); + expect(info(3, 2, true, false), 18); + // And a small step back really is a step back. + expect(info(4, 15, true, false), 15); } #[test] diff --git a/crates/ec-hw/src/dec/hevc.rs b/crates/ec-hw/src/dec/hevc.rs index 8d370f06..c23a2183 100644 --- a/crates/ec-hw/src/dec/hevc.rs +++ b/crates/ec-hw/src/dec/hevc.rs @@ -69,6 +69,8 @@ struct Current { poc: i32, timestamp: i64, is_reference: bool, + /// True when this picture may be `prevTid0Pic` for the next one (8.3.1). + is_tid0_anchor: bool, output: bool, rps: Rps, buffers: Vec, @@ -142,7 +144,7 @@ impl HevcDecoder { } } t if t.is_vcl() => { - self.slice(t, nal.payload, timestamp)?; + self.slice(t, nal.header.temporal_id, nal.payload, timestamp)?; } _ => {} } @@ -176,7 +178,13 @@ impl HevcDecoder { self.session.as_ref().map(Session::info) } - fn slice(&mut self, nal_type: NalUnitType, payload: &[u8], timestamp: i64) -> Result<()> { + fn slice( + &mut self, + nal_type: NalUnitType, + temporal_id: u8, + payload: &[u8], + timestamp: i64, + ) -> Result<()> { let rbsp = unescape_rbsp(payload); // The header cannot be parsed without its PPS, and the PPS names the SPS. let pps_id = peek_pps_id(&rbsp, nal_type)?; @@ -194,7 +202,7 @@ impl HevcDecoder { if sh.first_slice_segment_in_pic { self.finish_picture()?; - self.start_picture(&sps, &sh, nal_type, timestamp)?; + self.start_picture(&sps, &sh, nal_type, temporal_id, timestamp)?; } if self.current.is_none() { return Ok(()); @@ -243,6 +251,7 @@ impl HevcDecoder { sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType, + temporal_id: u8, timestamp: i64, ) -> Result<()> { self.ensure_session(sps)?; @@ -258,6 +267,22 @@ impl HevcDecoder { self.bump(true); } + if std::env::var_os("EC_HW_DEBUG").is_some() { + eprintln!( + "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}", + nal_type, + sh.poc_lsb, + self.dpb.len(), + self.ready.len(), + rps.st_curr_before.len(), + rps.st_curr_after.len(), + rps.lt_curr.len(), + self.session + .as_ref() + .map(|s| s.pool.available()) + .unwrap_or(0), + ); + } let session = self .session .as_ref() @@ -283,7 +308,19 @@ impl HevcDecoder { sps_id: sps.id, poc, timestamp, - is_reference: true, + // A "_N" picture (an even NAL type below 16) is a sub-layer + // non-reference: nothing in its own sub-layer may predict from it, + // and a decoder that stores it as a reference lets the next + // picture's reference picture set match the wrong picture by POC. + is_reference: is_reference_picture(nal_type), + // 8.3.1: `prevTid0Pic` is the previous picture with TemporalId 0 + // that is neither RASL, RADL nor sub-layer non-reference. Taking + // the previous picture instead — which a stream with temporal + // sub-layers immediately punishes — puts the picture order count + // MSB one wrap out and hands the driver the wrong references. + is_tid0_anchor: temporal_id == 0 + && is_reference_picture(nal_type) + && !is_leading_picture(nal_type), output: sh.pic_output_flag, rps, buffers: Vec::new(), @@ -430,7 +467,7 @@ impl HevcDecoder { } if current.slices == 0 { - let pic_param = picture_parameters(sps, pps, sh, nal_type, current, &self.dpb); + let pic_param = picture_parameters(sps, pps, sh, pos, nal_type, current, &self.dpb); current .buffers .push(param_buffer(&session.context, &pic_param)?); @@ -541,7 +578,9 @@ impl HevcDecoder { }, output: current.output, }); - self.prev_tid0_poc = current.poc; + if current.is_tid0_anchor { + self.prev_tid0_poc = current.poc; + } self.started = true; self.bump(false); Ok(()) @@ -584,6 +623,19 @@ impl HevcDecoder { } } +/// True unless the NAL type says sub-layer non-reference (`_N`, an even type +/// below 16). +fn is_reference_picture(nal_type: NalUnitType) -> bool { + let code = nal_type.code(); + code >= 16 || code % 2 == 1 +} + +/// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1 +/// excludes from the picture order count prediction. +fn is_leading_picture(nal_type: NalUnitType) -> bool { + (6..=9).contains(&nal_type.code()) +} + /// `slice_pic_parameter_set_id`, readable without any parameter set. fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result { let mut r = ec_core::BitReader::new(rbsp); @@ -641,10 +693,12 @@ fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec; 2] { out } +#[allow(clippy::too_many_arguments)] fn picture_parameters( sps: &Sps, pps: &Pps, sh: &SliceHeader, + pos: &ParsePositions, nal_type: NalUnitType, current: &Current, dpb: &[StoredPicture], @@ -681,10 +735,10 @@ fn picture_parameters( pps_beta_offset_div2: pps.beta_offset_div2 as i8, pps_tc_offset_div2: pps.tc_offset_div2 as i8, num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, - // Zero when the slice took its set from the SPS, which is what the - // parser reports; the field exists so the driver can skip a set the - // header carried itself. - st_rps_bits: 0, + // The size of an `st_ref_pic_set()` the slice header carried itself, + // so the driver can skip it; zero when the slice named an SPS set, + // which is what the parser reports. + st_rps_bits: pos.st_rps_bits, ..PictureParameterBufferHEVC::default() }; diff --git a/crates/ec-hw/src/dec/mod.rs b/crates/ec-hw/src/dec/mod.rs index e10249c1..d152ba73 100644 --- a/crates/ec-hw/src/dec/mod.rs +++ b/crates/ec-hw/src/dec/mod.rs @@ -158,11 +158,11 @@ impl Decoder { /// Frames waiting to be collected, oldest first. /// -/// The queue is the frame-out design `cros-codecs` uses (a decode call produces -/// events rather than returning a picture), minus the event fd: nothing in this -/// family polls a decoder from an event loop, and adding a `eventfd(2)` here -/// would mean a second FFI surface in a crate whose whole unsafe budget is -/// meant to be libva. +/// A decode call produces frames rather than returning one, because one access +/// unit can complete none, one or several pictures. There is no event fd behind +/// it: nothing in this family polls a decoder from an event loop, and adding an +/// `eventfd(2)` would mean a second FFI surface in a crate whose whole unsafe +/// budget is meant to be libva. #[derive(Debug, Default)] pub(crate) struct ReadyFrames { queue: VecDeque, @@ -180,6 +180,10 @@ impl ReadyFrames { pub(crate) fn clear(&mut self) { self.queue.clear(); } + + pub(crate) fn len(&self) -> usize { + self.queue.len() + } } /// The GPU-side state one decoded stream needs: config, context, surfaces. diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 2ec8b5f2..3488e4c1 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -305,9 +305,9 @@ impl std::fmt::Debug for Frame { /// Deinterleave an NV12 chroma plane into I420 U and V planes. /// -/// Parity with `cros-codecs`' `image_processing::nv12_to_i420`, which is what -/// edith calls today; kept as a free function because the conversion is also -/// what an encoder input path needs, in reverse. +/// The same conversion the software path in edith expects on the way out of a +/// hardware frame; kept as a free function because an encoder's input path +/// needs it in reverse. pub fn nv12_to_i420( y_plane: &[u8], y_pitch: usize, diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index ab09cdc3..cd68306e 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -934,6 +934,11 @@ fn real_library_spot_check() { return; } + // 500 frames per file by default; a diagnostic run can ask for fewer. + let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(500); let mut table = Vec::new(); for (path, codec, ten_bit) in &wanted { let path = Path::new(path); @@ -946,7 +951,7 @@ fn real_library_spot_check() { let mut worst = f64::INFINITY; let mut compared = 0usize; let mut failed: Option = None; - let result = decode_stream(&mut decoder, *codec, &data, 500, |frame| { + let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { let (w, h) = frame.display_size; let reference = reference .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); @@ -962,7 +967,11 @@ fn real_library_spot_check() { failed = Some("frame size disagrees with ffmpeg".to_string()); return; } - worst = worst.min(psnr(&got, &want)); + let db = psnr(&got, &want); + if std::env::var_os("EC_HW_DEBUG").is_some() { + eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); + } + worst = worst.min(db); compared += 1; }); match result {