From a11df786c72d7ca9cf5dff256713f18b20942941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 09:52:09 +0300 Subject: [PATCH] ec-hw: Vulkan H.265 decode behind HwDecoder (shared generic hevc_dpb), bit-exact vs ffmpeg on B-frame/multi-IRAP streams; HwDecoder falls back to VA (replaying the prefix) when Vulkan refuses a stream such as 10-bit --- crates/ec-hw/examples/hw_decode.rs | 168 +++++++-- crates/ec-hw/src/dec/hevc.rs | 302 ++-------------- crates/ec-hw/src/hevc_dpb.rs | 288 +++++++++++++++ crates/ec-hw/src/hw.rs | 112 +++++- crates/ec-hw/src/lib.rs | 2 + crates/ec-hw/src/vkdec265.rs | 540 +++++++++++++++++++++++++++++ 6 files changed, 1088 insertions(+), 324 deletions(-) create mode 100644 crates/ec-hw/src/hevc_dpb.rs create mode 100644 crates/ec-hw/src/vkdec265.rs diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 0aad97de..98e3ed29 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -1,4 +1,4 @@ -//! Decodes ffmpeg libx264 streams with B-frames and three references through HwDecoder and compares luma with ffmpeg's decode. +//! Decodes ffmpeg libx264 and libx265 streams through HwDecoder and compares luma with ffmpeg's decode, frame by frame. //! //! ```text //! cargo run -p ec-hw --example hw_decode -- @@ -8,12 +8,109 @@ use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -use ec_hw::{Codec, HwDecoder, I420}; +use ec_hw::{Backend, Codec, HwDecoder, I420}; + +struct Case { + name: &'static str, + codec: Codec, + size: &'static str, + frames: usize, + encoder: &'static [&'static str], + container: &'static [&'static str], +} + +const H264_BF: &[&str] = &[ + "-c:v", + "libx264", + "-profile:v", + "high", + "-bf", + "2", + "-refs", + "3", +]; +const H264_ANNEXB: &[&str] = &["-bsf:v", "h264_mp4toannexb", "-f", "h264"]; +const H265_BF: &[&str] = &[ + "-c:v", + "libx265", + "-x265-params", + "log-level=error:bframes=3:ref=3", +]; +const H265_KEYINT: &[&str] = &[ + "-c:v", + "libx265", + "-x265-params", + "log-level=error:bframes=3:ref=3:keyint=20", +]; +const HEVC: &[&str] = &["-f", "hevc"]; + +const CASES: &[Case] = &[ + Case { + name: "bf640", + codec: Codec::H264, + size: "640x360", + frames: 60, + encoder: H264_BF, + container: H264_ANNEXB, + }, + Case { + name: "bf1280", + codec: Codec::H264, + size: "1280x720", + frames: 30, + encoder: H264_BF, + container: H264_ANNEXB, + }, + Case { + name: "h265bf640", + codec: Codec::H265, + size: "640x360", + frames: 60, + encoder: H265_BF, + container: HEVC, + }, + Case { + name: "h265idr720", + codec: Codec::H265, + size: "1280x720", + frames: 60, + encoder: H265_KEYINT, + container: HEVC, + }, +]; fn main() { let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); - run(&dir, "bf640", "640x360", 60); - run(&dir, "bf1280", "1280x720", 30); + for case in CASES { + run(&dir, case); + } + ten_bit_falls_back(&dir); +} + +fn ten_bit_falls_back(dir: &std::path::Path) { + let path = dir.join("ten.hevc"); + let p = path.to_str().expect("utf-8 path"); + ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-frames:v", "20", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-x265-params", "log-level=error", p]); + let data = std::fs::read(&path).expect("read 10-bit stream"); + let mut dec = ec_hw::HwDecoder::open(ec_hw::Codec::H265).expect("open"); + let opened = dec.backend(); + let starts: Vec = (0..data.len().saturating_sub(3)) + .filter(|&i| data[i..i + 3] == [0, 0, 1]) + .map(|i| if i > 0 && data[i - 1] == 0 { i - 1 } else { i }) + .chain([data.len()]) + .collect(); + let mut n = 0; + for w in starts.windows(2) { + dec.decode(&data[w[0]..w[1]], 0).expect("decode 10-bit"); + while dec.next_frame().expect("frame").is_some() { + n += 1; + } + } + dec.flush().expect("flush"); + while dec.next_frame().expect("frame").is_some() { + n += 1; + } + println!("ten.hevc: opened {opened:?}, decoded on {:?}, {n} frames", dec.backend()); } fn ffmpeg(args: &[&str]) { @@ -25,34 +122,30 @@ fn ffmpeg(args: &[&str]) { assert!(status.success(), "ffmpeg {args:?}"); } -fn run(dir: &Path, name: &str, size: &str, frames: usize) { - let stream = dir.join(format!("{name}.h264")); - let reference = dir.join(format!("{name}.yuv")); - let source = format!("testsrc2=size={size}:rate=30"); - let frames = frames.to_string(); +fn run(dir: &Path, case: &Case) { + let ext = if case.codec == Codec::H264 { + "h264" + } else { + "hevc" + }; + let stream = dir.join(format!("{}.{ext}", case.name)); + let reference = dir.join(format!("{}.yuv", case.name)); + let source = format!("testsrc2=size={}:rate=30", case.size); + let frames = case.frames.to_string(); let stream_arg = stream.to_str().expect("utf-8 path"); let reference_arg = reference.to_str().expect("utf-8 path"); - ffmpeg(&[ + let mut encode: Vec<&str> = vec![ "-f", "lavfi", "-i", - &source, + source.as_str(), "-frames:v", - &frames, - "-c:v", - "libx264", - "-profile:v", - "high", - "-bf", - "2", - "-refs", - "3", - "-bsf:v", - "h264_mp4toannexb", - "-f", - "h264", - stream_arg, - ]); + frames.as_str(), + ]; + encode.extend_from_slice(case.encoder); + encode.extend_from_slice(case.container); + encode.push(stream_arg); + ffmpeg(&encode); ffmpeg(&[ "-i", stream_arg, @@ -64,8 +157,11 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { ]); let data = fs::read(&stream).expect("read stream"); - let mut decoder = HwDecoder::open(Codec::H264).expect("open H.264 decoder"); + let mut decoder = HwDecoder::open(case.codec).expect("open decoder"); let backend = decoder.backend(); + if case.codec == Codec::H265 { + assert_eq!(backend, Backend::Vk, "H.265 must decode on Vulkan"); + } decoder.decode(&data, 0).expect("decode"); decoder.flush().expect("flush"); let mut decoded: Vec = Vec::new(); @@ -74,7 +170,8 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { } let raw = fs::read(&reference).expect("read reference"); - let (w, h) = size + let (w, h) = case + .size .split_once('x') .map(|(w, h)| { ( @@ -84,6 +181,7 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { }) .expect("size"); let frame_len = w * h * 3 / 2; + let reference_frames = raw.len() / frame_len; let worst = decoded .iter() .zip(raw.chunks_exact(frame_len)) @@ -98,8 +196,18 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { }) .fold(0.0f64, f64::max); println!( - "{name} {backend:?} {size}: decoded {} frames, ffmpeg {} frames, max mean |diff| Y {worst:.6}", + "{} {:?} {:?} {}: decoded {} frames, ffmpeg {} frames, max mean |diff| Y {worst:.6}", + case.name, + case.codec, + backend, + case.size, + decoded.len(), + reference_frames + ); + assert_eq!( decoded.len(), - raw.len() / frame_len + reference_frames, + "{}: frame count", + case.name ); } diff --git a/crates/ec-hw/src/dec/hevc.rs b/crates/ec-hw/src/dec/hevc.rs index 08664411..8bcd30a3 100644 --- a/crates/ec-hw/src/dec/hevc.rs +++ b/crates/ec-hw/src/dec/hevc.rs @@ -20,6 +20,10 @@ use ec_va::{Buffer, Display}; use super::{ReadyFrames, Session, StreamInfo}; use crate::error::{Error, Result}; use crate::frame::{Colour, Frame}; +use crate::hevc_dpb::{ + Dpb, Mark, Rps, StoredPicture, is_bla_picture, is_rasl_picture, is_reference_picture, + is_leading_picture, peek_pps_id, vui_colour_tags, +}; use crate::params::hevc::{ IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PicFields, @@ -31,14 +35,6 @@ use crate::pool::PooledSurface; /// a caller is still holding. const EXTRA_SURFACES: usize = 6; -/// Reference marking of a stored picture (8.3.2). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Mark { - Unused, - ShortTerm, - LongTerm, -} - /// One DPB slot as the parameter builder sees it: its surface, POC and marking. #[derive(Clone, Copy)] struct DpbSlot { @@ -48,7 +44,7 @@ struct DpbSlot { } impl DpbSlot { - fn of(p: &StoredPicture) -> DpbSlot { + fn of(p: &StoredPicture>) -> DpbSlot { DpbSlot { id: p.surface.id(), poc: p.poc, @@ -57,29 +53,6 @@ impl DpbSlot { } } -struct StoredPicture { - surface: Rc, - poc: i32, - timestamp: i64, - mark: Mark, - /// Still to be handed to the caller. - output: bool, -} - -impl StoredPicture { - fn stored(&self) -> bool { - self.output || self.mark != Mark::Unused - } -} - -/// The reference picture set of the picture being decoded, as DPB indices. -#[derive(Debug, Default, Clone)] -struct Rps { - st_curr_before: Vec, - st_curr_after: Vec, - lt_curr: Vec, -} - /// The picture being assembled from its slices. struct Current { surface: Rc, @@ -104,20 +77,14 @@ pub struct HevcDecoder { sps_map: Vec>, pps_map: Vec>, session: Option, - dpb: Vec, + dpb: Dpb>, ready: ReadyFrames, current: Option, - /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1. - prev_tid0_poc: i32, - /// Set once a picture has been decoded since the last reset. - started: bool, /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures /// associated with it must not be decoded or output when set, because /// they predict from pictures before a random-access point this decoder /// never saw. no_rasl_output: bool, - max_reorder: usize, - max_dec_pic_buffering: usize, /// The most recent SPS's VUI colour tags, sticky across pictures. colour_tags: Tags, /// The prefix SEI HDR peak seen so far, merged so a later access unit that @@ -134,14 +101,10 @@ impl HevcDecoder { sps_map: (0..16).map(|_| None).collect(), pps_map: (0..64).map(|_| None).collect(), session: None, - dpb: Vec::new(), + dpb: Dpb::new(), ready: ReadyFrames::default(), current: None, - prev_tid0_poc: 0, - started: false, no_rasl_output: false, - max_reorder: 1, - max_dec_pic_buffering: 6, colour_tags: Tags::default(), colour_light: ContentLight::default(), } @@ -160,8 +123,8 @@ impl HevcDecoder { } NalUnitType::Sps => { let sps = Sps::parse(&nal.rbsp())?; - self.max_reorder = sps.max_num_reorder_pics as usize; - self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; + self.dpb.max_reorder = sps.max_num_reorder_pics as usize; + self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; self.colour_tags = vui_colour_tags(&sps); let id = sps.id as usize; if id < self.sps_map.len() { @@ -222,10 +185,10 @@ impl HevcDecoder { /// Drop all picture state after a seek; parameter sets survive. pub fn reset(&mut self) { self.current = None; - self.dpb.clear(); + self.dpb.pictures.clear(); self.ready.clear(); - self.prev_tid0_poc = 0; - self.started = false; + self.dpb.prev_tid0_poc = 0; + self.dpb.started = false; self.no_rasl_output = false; } @@ -297,14 +260,14 @@ impl HevcDecoder { return Ok(()); } self.current = None; - self.dpb.clear(); + self.dpb.pictures.clear(); self.session = Some(Session::new( &self.display, profile, coded, sps.display_size(), bit_depth, - self.max_dec_pic_buffering + EXTRA_SURFACES, + self.dpb.max_dec_pic_buffering + EXTRA_SURFACES, )?); Ok(()) } @@ -323,13 +286,13 @@ impl HevcDecoder { // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded // video sequence — which a mid-stream start's first IRAP always // is, `self.started` still being false at that point. - self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started; + self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started; } - let poc = self.picture_order_count(sps, sh, nal_type); + let poc = self.dpb.picture_order_count(sps, sh, nal_type); // 8.3.2 runs before the picture is decoded and after its POC is known: // every stored picture the set does not name stops being a reference. - let rps = self.apply_rps(sps, sh, nal_type, poc)?; + let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { // An IRAP that restarts output order: everything ahead of it in the @@ -342,7 +305,7 @@ impl HevcDecoder { "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}", nal_type, sh.poc_lsb, - self.dpb.len(), + self.dpb.pictures.len(), self.ready.len(), rps.st_curr_before.len(), rps.st_curr_after.len(), @@ -364,9 +327,9 @@ impl HevcDecoder { // The driver indexes RefPicList into `reference_frames`, so the mapping // from DPB slot to that array is fixed once, here. - let mut va_index = vec![0xffu8; self.dpb.len()]; + let mut va_index = vec![0xffu8; self.dpb.pictures.len()]; let mut n = 0u8; - for (i, pic) in self.dpb.iter().enumerate() { + for (i, pic) in self.dpb.pictures.iter().enumerate() { if pic.mark != Mark::Unused && n < 15 { va_index[i] = n; n += 1; @@ -400,142 +363,6 @@ impl HevcDecoder { Ok(()) } - /// `PicOrderCntVal` (8.3.1). - fn picture_order_count(&self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType) -> i32 { - if nal_type.is_idr() { - return 0; - } - let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); - let lsb = sh.poc_lsb as i32; - let (prev_msb, prev_lsb) = if !self.started { - (0, 0) - } else { - ( - self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)), - self.prev_tid0_poc.rem_euclid(max_lsb), - ) - }; - // An IRAP that starts a new coded video sequence has no predecessor. - if nal_type.is_irap() && !self.started { - return lsb; - } - let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { - prev_msb + max_lsb - } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { - prev_msb - max_lsb - } else { - prev_msb - }; - msb + lsb - } - - /// Reference picture set derivation and marking (8.3.2). - fn apply_rps( - &mut self, - sps: &Sps, - sh: &SliceHeader, - nal_type: NalUnitType, - poc: i32, - ) -> Result { - if nal_type.is_irap() && (nal_type.is_idr() || !self.started) { - for pic in &mut self.dpb { - pic.mark = Mark::Unused; - } - self.dpb.retain(|p| p.stored()); - return Ok(Rps::default()); - } - - let set = &sh.short_term_ref_pic_set; - let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); - let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term) - for i in 0..set.num_negative as usize { - wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false)); - } - for i in 0..set.num_positive as usize { - wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false)); - } - for lt in &sh.long_term { - // 8.3.2: a long-term entry without an MSB cycle is matched on its - // POC low bits alone, which is how a stream survives an MSB wrap. - let target = if lt.delta_poc_msb_present { - poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb) - + lt.poc_lsb_lt as i32 - } else { - lt.poc_lsb_lt as i32 - }; - wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present)); - } - - let mut rps = Rps::default(); - let mut keep = vec![false; self.dpb.len()]; - let mut missing_used = false; - for (target, used, lsb_only) in wanted { - let found = self.dpb.iter().position(|p| { - if lsb_only { - p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb) - } else { - p.poc == target - } - }); - let Some(idx) = found else { - // 8.3.2: a picture the current one predicts from must be in the - // buffer. One that is not is a broken GOP, and a reference list - // built without it would name a surface that was never decoded. - missing_used |= used; - continue; - }; - keep[idx] = true; - if !used { - continue; - } - // The three "current" lists are what the reference lists are built - // from, in POC order relative to the current picture. - if self.dpb[idx].mark == Mark::LongTerm || lsb_only { - rps.lt_curr.push(idx); - } else if self.dpb[idx].poc < poc { - rps.st_curr_before.push(idx); - } else { - rps.st_curr_after.push(idx); - } - } - rps.st_curr_before - .sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].poc)); - rps.st_curr_after.sort_by_key(|&i| self.dpb[i].poc); - - for (i, pic) in self.dpb.iter_mut().enumerate() { - if !keep[i] { - pic.mark = Mark::Unused; - } - } - // Dropping unreferenced, already-output pictures here is what returns - // their surfaces to the pool; the indices in `rps` are recomputed after. - let mut remap = vec![usize::MAX; self.dpb.len()]; - let mut next = 0usize; - for (i, pic) in self.dpb.iter().enumerate() { - if pic.stored() { - remap[i] = next; - next += 1; - } - } - self.dpb.retain(|p| p.stored()); - if missing_used { - return Err(Error::Stream(ec_core::Error::corrupt( - "HEVC reference picture set names a picture used for prediction that was never decoded", - ))); - } - for list in [ - &mut rps.st_curr_before, - &mut rps.st_curr_after, - &mut rps.lt_curr, - ] { - list.retain(|&i| remap[i] != usize::MAX); - for entry in list.iter_mut() { - *entry = remap[*entry]; - } - } - Ok(rps) - } - fn render_slice( &mut self, sps: &Sps, @@ -555,7 +382,7 @@ impl HevcDecoder { } if current.slices == 0 { - let slots: Vec = self.dpb.iter().map(DpbSlot::of).collect(); + let slots: Vec = self.dpb.pictures.iter().map(DpbSlot::of).collect(); let pic_param = picture_parameters( sps, pps, @@ -678,7 +505,7 @@ impl HevcDecoder { } session.submit(¤t.surface, current.buffers)?; - self.dpb.push(StoredPicture { + self.dpb.pictures.push(StoredPicture { surface: Rc::clone(¤t.surface), poc: current.poc, timestamp: current.timestamp, @@ -690,9 +517,9 @@ impl HevcDecoder { output: current.output, }); if current.is_tid0_anchor { - self.prev_tid0_poc = current.poc; + self.dpb.prev_tid0_poc = current.poc; } - self.started = true; + self.dpb.started = true; self.bump(false); Ok(()) } @@ -703,23 +530,8 @@ impl HevcDecoder { let Some(session) = self.session.as_ref() else { return; }; - loop { - let pending = self.dpb.iter().filter(|p| p.output).count(); - let stored = self.dpb.iter().filter(|p| p.stored()).count(); - if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering { - return; - } - let Some(idx) = self - .dpb - .iter() - .enumerate() - .filter(|(_, p)| p.output) - .min_by_key(|(_, p)| p.poc) - .map(|(i, _)| i) - else { - return; - }; - let pic = &self.dpb[idx]; + while let Some(idx) = self.dpb.next_output(flush) { + let pic = &self.dpb.pictures[idx]; self.ready.push(Frame::new( Rc::clone(&pic.surface), Rc::clone(&self.display), @@ -729,71 +541,11 @@ impl HevcDecoder { session.bit_depth, self.colour(), )); - self.dpb[idx].output = false; - self.dpb.retain(|p| p.stored()); + self.dpb.released(idx); } } } -/// 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()) -} - -/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for -/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no -/// `video_signal_type` at all. -fn vui_colour_tags(sps: &Sps) -> Tags { - let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { - return Tags::default(); - }; - let (_primaries, transfer, matrix) = vst - .colour_description - .map(|cd| { - ( - cd.colour_primaries, - cd.transfer_characteristics, - cd.matrix_coeffs, - ) - }) - .unwrap_or((0, 0, 0)); - Tags::from_codes( - u64::from(matrix), - u64::from(transfer), - if vst.video_full_range_flag { 2 } else { 1 }, - ) -} - -/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's -/// `NoRaslOutputFlag` is 1 (8.1.3). -fn is_rasl_picture(nal_type: NalUnitType) -> bool { - matches!(nal_type.code(), 8 | 9) -} - -/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1 -/// (8.1.3), a broken-link splice point that never has a decodable RASL. -fn is_bla_picture(nal_type: NalUnitType) -> bool { - (16..=18).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); - r.read_bit()?; // first_slice_segment_in_pic_flag - if nal_type.is_irap() { - r.read_bit()?; // no_output_of_prior_pics_flag - } - Ok(r.read_ue()?) -} - /// Reference list construction (8.3.4), as DPB indices. fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec; 2] { let mut out = [Vec::new(), Vec::new()]; diff --git a/crates/ec-hw/src/hevc_dpb.rs b/crates/ec-hw/src/hevc_dpb.rs new file mode 100644 index 00000000..4f3de5f4 --- /dev/null +++ b/crates/ec-hw/src/hevc_dpb.rs @@ -0,0 +1,288 @@ +//! HEVC picture management over any surface type: picture order count (8.3.1), +//! reference picture sets and marking (8.3.2), and output bumping (C.5.2). +//! +//! The VA-API and Vulkan Video decoders both build on this. A stored picture +//! is only its surface, POC, timestamp, marking and output state; the driver +//! sees the reference picture set as DPB indices into [`Dpb::pictures`]. + +use ec_core::color::Tags; +use ec_h265_syntax::{NalUnitType, SliceHeader, Sps}; + +use crate::error::{Error, Result}; + +/// Reference marking of a stored picture (8.3.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Mark { + Unused, + ShortTerm, + LongTerm, +} + +/// One stored picture: its surface, POC, marking and whether it is still to be output. +pub(crate) struct StoredPicture { + pub(crate) surface: S, + pub(crate) poc: i32, + pub(crate) timestamp: i64, + pub(crate) mark: Mark, + /// Still to be handed to the caller. + pub(crate) output: bool, +} + +impl StoredPicture { + pub(crate) fn stored(&self) -> bool { + self.output || self.mark != Mark::Unused + } +} + +/// The reference picture set of the picture being decoded, as DPB indices. +#[derive(Debug, Default, Clone)] +pub(crate) struct Rps { + pub(crate) st_curr_before: Vec, + pub(crate) st_curr_after: Vec, + pub(crate) lt_curr: Vec, +} + +/// The decoded picture buffer and the cross-picture state of 8.3.1 and C.5.2. +pub(crate) struct Dpb { + pub(crate) pictures: Vec>, + /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1. + pub(crate) prev_tid0_poc: i32, + /// Set once a picture has been decoded since the last reset. + pub(crate) started: bool, + pub(crate) max_reorder: usize, + pub(crate) max_dec_pic_buffering: usize, +} + +impl Dpb { + pub(crate) fn new() -> Dpb { + Dpb { + pictures: Vec::new(), + prev_tid0_poc: 0, + started: false, + max_reorder: 1, + max_dec_pic_buffering: 6, + } + } + + /// `PicOrderCntVal` (8.3.1). + pub(crate) fn picture_order_count( + &self, + sps: &Sps, + sh: &SliceHeader, + nal_type: NalUnitType, + ) -> i32 { + if nal_type.is_idr() { + return 0; + } + let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); + let lsb = sh.poc_lsb as i32; + let (prev_msb, prev_lsb) = if !self.started { + (0, 0) + } else { + ( + self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)), + self.prev_tid0_poc.rem_euclid(max_lsb), + ) + }; + // An IRAP that starts a new coded video sequence has no predecessor. + if nal_type.is_irap() && !self.started { + return lsb; + } + let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { + prev_msb + max_lsb + } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { + prev_msb - max_lsb + } else { + prev_msb + }; + msb + lsb + } + + /// Reference picture set derivation and marking (8.3.2). + pub(crate) fn apply_rps( + &mut self, + sps: &Sps, + sh: &SliceHeader, + nal_type: NalUnitType, + poc: i32, + ) -> Result { + if nal_type.is_irap() && (nal_type.is_idr() || !self.started) { + for pic in &mut self.pictures { + pic.mark = Mark::Unused; + } + self.pictures.retain(|p| p.stored()); + return Ok(Rps::default()); + } + + let set = &sh.short_term_ref_pic_set; + let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); + let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term) + for i in 0..set.num_negative as usize { + wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false)); + } + for i in 0..set.num_positive as usize { + wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false)); + } + for lt in &sh.long_term { + // 8.3.2: a long-term entry without an MSB cycle is matched on its + // POC low bits alone, which is how a stream survives an MSB wrap. + let target = if lt.delta_poc_msb_present { + poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb) + + lt.poc_lsb_lt as i32 + } else { + lt.poc_lsb_lt as i32 + }; + wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present)); + } + + let mut rps = Rps::default(); + let mut keep = vec![false; self.pictures.len()]; + let mut missing_used = false; + for (target, used, lsb_only) in wanted { + let found = self.pictures.iter().position(|p| { + if lsb_only { + p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb) + } else { + p.poc == target + } + }); + let Some(idx) = found else { + // 8.3.2: a picture the current one predicts from must be in the + // buffer. One that is not is a broken GOP, and a reference list + // built without it would name a surface that was never decoded. + missing_used |= used; + continue; + }; + keep[idx] = true; + if !used { + continue; + } + // The three "current" lists are what the reference lists are built + // from, in POC order relative to the current picture. + if self.pictures[idx].mark == Mark::LongTerm || lsb_only { + rps.lt_curr.push(idx); + } else if self.pictures[idx].poc < poc { + rps.st_curr_before.push(idx); + } else { + rps.st_curr_after.push(idx); + } + } + rps.st_curr_before + .sort_by_key(|&i| std::cmp::Reverse(self.pictures[i].poc)); + rps.st_curr_after.sort_by_key(|&i| self.pictures[i].poc); + + for (i, pic) in self.pictures.iter_mut().enumerate() { + if !keep[i] { + pic.mark = Mark::Unused; + } + } + // Dropping unreferenced, already-output pictures here is what returns + // their surfaces to the pool; the indices in `rps` are recomputed after. + let mut remap = vec![usize::MAX; self.pictures.len()]; + let mut next = 0usize; + for (i, pic) in self.pictures.iter().enumerate() { + if pic.stored() { + remap[i] = next; + next += 1; + } + } + self.pictures.retain(|p| p.stored()); + if missing_used { + return Err(Error::Stream(ec_core::Error::corrupt( + "HEVC reference picture set names a picture used for prediction that was never decoded", + ))); + } + for list in [ + &mut rps.st_curr_before, + &mut rps.st_curr_after, + &mut rps.lt_curr, + ] { + list.retain(|&i| remap[i] != usize::MAX); + for entry in list.iter_mut() { + *entry = remap[*entry]; + } + } + Ok(rps) + } + /// The next picture to output (C.5.2.4), while the buffer holds more than + /// its reordering or storage limit allows; `flush` outputs every one. + pub(crate) fn next_output(&self, flush: bool) -> Option { + let pending = self.pictures.iter().filter(|p| p.output).count(); + let stored = self.pictures.iter().filter(|p| p.stored()).count(); + if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering { + return None; + } + self.pictures + .iter() + .enumerate() + .filter(|(_, p)| p.output) + .min_by_key(|(_, p)| p.poc) + .map(|(i, _)| i) + } + + /// Marks the picture at `idx` as output and drops it once it is not stored. + pub(crate) fn released(&mut self, idx: usize) { + self.pictures[idx].output = false; + self.pictures.retain(|p| p.stored()); + } +} + +/// True unless the NAL type says sub-layer non-reference (`_N`, an even type +/// below 16). +pub(crate) 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. +pub(crate) fn is_leading_picture(nal_type: NalUnitType) -> bool { + (6..=9).contains(&nal_type.code()) +} + +/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for +/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no +/// `video_signal_type` at all. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn vui_colour_tags(sps: &Sps) -> Tags { + let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { + return Tags::default(); + }; + let (_primaries, transfer, matrix) = vst + .colour_description + .map(|cd| { + ( + cd.colour_primaries, + cd.transfer_characteristics, + cd.matrix_coeffs, + ) + }) + .unwrap_or((0, 0, 0)); + Tags::from_codes( + u64::from(matrix), + u64::from(transfer), + if vst.video_full_range_flag { 2 } else { 1 }, + ) +} + +/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's +/// `NoRaslOutputFlag` is 1 (8.1.3). +pub(crate) fn is_rasl_picture(nal_type: NalUnitType) -> bool { + matches!(nal_type.code(), 8 | 9) +} + +/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1 +/// (8.1.3), a broken-link splice point that never has a decodable RASL. +pub(crate) fn is_bla_picture(nal_type: NalUnitType) -> bool { + (16..=18).contains(&nal_type.code()) +} + +/// `slice_pic_parameter_set_id`, readable without any parameter set. +pub(crate) fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result { + let mut r = ec_core::BitReader::new(rbsp); + r.read_bit()?; // first_slice_segment_in_pic_flag + if nal_type.is_irap() { + r.read_bit()?; // no_output_of_prior_pics_flag + } + Ok(r.read_ue()?) +} diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 6dc1fa42..f83ea548 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -4,6 +4,7 @@ use crate::error::{Error, Result}; use crate::picture::I420; use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode}; use crate::vkdec264::VkH264Decoder; +use crate::vkdec265::VkH265Decoder; #[cfg(target_os = "linux")] use crate::dec::Decoder as VaDecoder; @@ -57,7 +58,8 @@ pub fn capabilities() -> Vec { if let Some(gpu) = vk_gpu() { for caps in gpu.caps().into_iter().filter(|c| { c.direction == ec_vk::Direction::Encode - || (c.direction == ec_vk::Direction::Decode && c.codec == ec_vk::Codec::H264) + || (c.direction == ec_vk::Direction::Decode + && matches!(c.codec, ec_vk::Codec::H264 | ec_vk::Codec::H265)) }) { let codec = match caps.codec { ec_vk::Codec::H264 => Codec::H264, @@ -264,6 +266,7 @@ enum EncInner { /// A hardware encoder on whichever backend opened. pub struct HwEncoder { inner: EncInner, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] size: (usize, usize), } @@ -417,41 +420,81 @@ fn open_va(config: EncoderConfig) -> Result { )) } +enum VkDecoder { + H264(VkH264Decoder), + H265(VkH265Decoder), +} + +impl VkDecoder { + fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + match self { + VkDecoder::H264(d) => d.decode(data, timestamp), + VkDecoder::H265(d) => d.decode(data, timestamp), + } + } + + fn next_frame(&mut self) -> Option<(i64, I420)> { + match self { + VkDecoder::H264(d) => d.next_frame(), + VkDecoder::H265(d) => d.next_frame(), + } + } + + fn flush(&mut self) -> Result<()> { + match self { + VkDecoder::H264(d) => d.flush(), + VkDecoder::H265(d) => d.flush(), + } + } +} + enum DecInner { - Vk(VkH264Decoder), + Vk(VkDecoder), #[cfg(target_os = "linux")] Va(VaDecoder), } +const REPLAY_LIMIT: usize = 64; + /// A hardware decoder on whichever backend opened. pub struct HwDecoder { inner: DecInner, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + codec: Codec, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + replay: Option, i64)>>, } impl HwDecoder { - /// Open a decoder for `codec`. H.264 tries Vulkan Video first, then VA-API (Linux). + /// Open a decoder for `codec`. H.264 and H.265 try Vulkan Video first, then VA-API (Linux). pub fn open(codec: Codec) -> Result { let mut reasons = Vec::new(); - if matches!(codec, Codec::H264) { - match VkH264Decoder::new() { - Ok(inner) => { - return Ok(HwDecoder { - inner: DecInner::Vk(inner), - }); - } - Err(e) => reasons.push(format!("Vk: {e}")), + let vk = match codec { + Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), + Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), + _ => Err(Error::unsupported("Vulkan Video decode", "H.264 and H.265 only")), + }; + match vk { + Ok(inner) => { + return Ok(HwDecoder { + inner: DecInner::Vk(inner), + codec, + replay: Some(Vec::new()), + }); + } + Err(e) if matches!(codec, Codec::H264 | Codec::H265) => { + reasons.push(format!("Vk: {e}")); } + Err(_) => {} } #[cfg(target_os = "linux")] { - let va = (|| -> Result { - let display = ec_va::open()?; - VaDecoder::new(&display, codec) - })(); - match va { + match open_va_decoder(codec) { Ok(inner) => { return Ok(HwDecoder { inner: DecInner::Va(inner), + codec, + replay: None, }); } Err(e) => reasons.push(format!("Va: {e}")), @@ -472,19 +515,44 @@ impl HwDecoder { } } - /// Feed one access unit. + /// Feed one access unit. A stream Vulkan refuses (e.g. 10-bit) before its first + /// picture comes out moves to VA-API on Linux, replaying what was fed so far. pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { - match &mut self.inner { + let result = match &mut self.inner { DecInner::Vk(d) => d.decode(data, timestamp), #[cfg(target_os = "linux")] DecInner::Va(d) => d.decode(data, timestamp), + }; + if let Some(fed) = self.replay.as_mut() { + fed.push((data.to_vec(), timestamp)); + if fed.len() > REPLAY_LIMIT { + self.replay = None; + } + } + #[cfg(target_os = "linux")] + if let Err(Error::Unsupported { .. }) = result + && let Some(fed) = self.replay.take() + && let Ok(mut va) = open_va_decoder(self.codec) + { + for (chunk, ts) in &fed { + va.decode(chunk, *ts)?; + } + self.inner = DecInner::Va(va); + return Ok(()); } + result } /// The next picture in display order, as 8-bit I420 with its timestamp. pub fn next_frame(&mut self) -> Result> { match &mut self.inner { - DecInner::Vk(d) => Ok(d.next_frame()), + DecInner::Vk(d) => { + let frame = d.next_frame(); + if frame.is_some() { + self.replay = None; + } + Ok(frame) + } #[cfg(target_os = "linux")] DecInner::Va(d) => match d.next_frame() { Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))), @@ -502,3 +570,9 @@ impl HwDecoder { } } } + +#[cfg(target_os = "linux")] +fn open_va_decoder(codec: Codec) -> Result { + let display = ec_va::open()?; + VaDecoder::new(&display, codec) +} diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 342e0a11..7763786d 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -63,6 +63,7 @@ pub mod error; pub(crate) mod dpb264; #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) mod h264_common; +pub(crate) mod hevc_dpb; pub mod hw; #[cfg(target_os = "linux")] pub mod frame; @@ -74,6 +75,7 @@ pub mod pool; pub mod reset; pub mod types; pub(crate) mod vkdec264; +pub(crate) mod vkdec265; #[cfg(target_os = "linux")] pub use dec::{Decoder, StreamInfo}; diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs new file mode 100644 index 00000000..38304b35 --- /dev/null +++ b/crates/ec-hw/src/vkdec265.rs @@ -0,0 +1,540 @@ +//! H.265 decoding over Vulkan Video: the shared HEVC DPB over DPB slot indices. + +use std::collections::{HashMap, VecDeque}; + +use ec_h265_syntax::{ + AnnexBNal, NalUnitType, Pps, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, + split_annex_b, +}; +use ec_vk::{ + H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265Pcm, H265Pps, H265ProfileTierLevel, + H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, +}; + +use crate::error::{Error, Result}; +use crate::hevc_dpb::{ + self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, + peek_pps_id, +}; +use crate::picture::{I420, nv12_to_i420}; + +const MAX_SLOTS: u32 = 17; + +struct Session { + h265: H265DecodeSession, + max_width: u32, + max_height: u32, + slots: u32, +} + +struct Current { + slot: u32, + sps_id: u8, + pps_id: u8, + nal_type: NalUnitType, + st_rps_bits: u32, + short_term_ref_pic_set_sps: bool, + poc: i32, + timestamp: i64, + output: bool, + is_tid0_anchor: bool, + st_curr_before: Vec, + st_curr_after: Vec, + lt_curr: Vec, + slices: Vec>, +} + +/// H.265 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. +pub(crate) struct VkH265Decoder { + gpu: ec_vk::Gpu, + session: Option, + params_dirty: bool, + vps_map: Vec>, + sps_map: Vec>, + pps_map: Vec>, + dpb: Dpb, + outputs: HashMap, + current: Option, + ready: VecDeque<(i64, I420)>, + no_rasl_output: bool, +} + +impl VkH265Decoder { + pub(crate) fn new() -> Result { + let gpu = crate::hw::vk_gpu() + .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; + Ok(VkH265Decoder { + gpu, + session: None, + params_dirty: false, + vps_map: vec![None; 16], + sps_map: vec![None; 16], + pps_map: vec![None; 64], + dpb: Dpb::new(), + outputs: HashMap::new(), + current: None, + ready: VecDeque::new(), + no_rasl_output: false, + }) + } + + pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { + for nal in split_annex_b(data) { + match nal.header.nal_type { + NalUnitType::Vps => { + let vps = Vps::parse(&nal.rbsp())?; + let id = usize::from(vps.id); + if let Some(slot) = self.vps_map.get_mut(id) { + self.params_dirty |= store(slot, vps); + } + } + NalUnitType::Sps => { + let sps = Sps::parse(&nal.rbsp())?; + self.dpb.max_reorder = sps.max_num_reorder_pics as usize; + self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; + let id = sps.id as usize; + if let Some(slot) = self.sps_map.get_mut(id) { + self.params_dirty |= store(slot, sps); + } + } + NalUnitType::Pps => { + let pps = Pps::parse(&nal.rbsp())?; + let id = pps.id as usize; + if let Some(slot) = self.pps_map.get_mut(id) { + self.params_dirty |= store(slot, pps); + } + } + t if t.is_vcl() => self.slice(&nal, timestamp)?, + _ => {} + } + } + self.finish_picture() + } + + pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { + self.ready.pop_front() + } + + pub(crate) fn flush(&mut self) -> Result<()> { + self.finish_picture()?; + self.bump(true); + Ok(()) + } + + fn slice(&mut self, nal: &AnnexBNal, timestamp: i64) -> Result<()> { + let rbsp = nal.rbsp(); + let nal_type = nal.header.nal_type; + let pps_id = peek_pps_id(&rbsp, nal_type)?; + let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { + return Ok(()); + }; + let Some(sps) = self + .sps_map + .get(pps.sps_id as usize) + .and_then(|s| s.clone()) + else { + return Ok(()); + }; + let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?; + if sh.first_slice_segment_in_pic { + self.finish_picture()?; + if !(is_rasl_picture(nal_type) && self.no_rasl_output) { + self.start_picture(&sps, &sh, pos.st_rps_bits, nal, timestamp)?; + } + } + if let Some(current) = self.current.as_mut() { + let mut raw = nal.header.to_bytes().to_vec(); + raw.extend_from_slice(nal.payload); + current.slices.push(raw); + } + Ok(()) + } + + fn start_picture( + &mut self, + sps: &Sps, + sh: &SliceHeader, + st_rps_bits: u32, + nal: &AnnexBNal, + timestamp: i64, + ) -> Result<()> { + let nal_type = nal.header.nal_type; + self.ensure_session(sps)?; + if self.params_dirty { + self.set_parameters()?; + } + if nal_type.is_irap() { + self.no_rasl_output = + nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started; + } + let poc = self.dpb.picture_order_count(sps, sh, nal_type); + let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; + let ids = |list: &[usize]| -> Vec { + list.iter().map(|&i| self.dpb.pictures[i].surface).collect() + }; + let (st_curr_before, st_curr_after, lt_curr) = ( + ids(&rps.st_curr_before), + ids(&rps.st_curr_after), + ids(&rps.lt_curr), + ); + if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { + self.bump(true); + } + let slot = self.free_slot()?; + let is_reference = is_reference_picture(nal_type); + self.current = Some(Current { + slot, + sps_id: sps.id as u8, + pps_id: sh.pps_id as u8, + nal_type, + st_rps_bits, + short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag, + poc, + timestamp, + output: sh.pic_output_flag, + is_tid0_anchor: nal.header.temporal_id == 0 + && is_reference + && !is_leading_picture(nal_type), + st_curr_before, + st_curr_after, + lt_curr, + slices: Vec::new(), + }); + Ok(()) + } + + fn ensure_session(&mut self, sps: &Sps) -> Result<()> { + if sps.chroma_format_idc != 1 + || sps.bit_depth_luma_minus8 != 0 + || sps.bit_depth_chroma_minus8 != 0 + { + return Err(Error::unsupported( + "Vulkan H.265 decode", + "only 8-bit 4:2:0", + )); + } + let slots = (sps.max_dec_pic_buffering_minus1 + 2).min(MAX_SLOTS); + let (w, h) = ( + sps.pic_width_in_luma_samples, + sps.pic_height_in_luma_samples, + ); + let (max_width, max_height, slots) = match &self.session { + Some(s) if w <= s.max_width && h <= s.max_height && slots <= s.slots => return Ok(()), + Some(s) => (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)), + None => (w, h, slots), + }; + self.current = None; + self.dpb.pictures.clear(); + self.outputs.clear(); + self.session = None; + let h265 = H265DecodeSession::new( + &self.gpu, + &H265DecodeConfig { + max_width, + max_height, + max_dpb_slots: slots, + }, + )?; + self.session = Some(Session { + h265, + max_width, + max_height, + slots, + }); + self.params_dirty = true; + Ok(()) + } + + fn set_parameters(&mut self) -> Result<()> { + let vps: Vec = self.vps_map.iter().flatten().map(vk_vps).collect(); + let sps: Vec = self.sps_map.iter().flatten().map(vk_sps).collect(); + let pps: Vec = self + .pps_map + .iter() + .flatten() + .filter(|p| { + self.sps_map + .get(p.sps_id as usize) + .is_some_and(Option::is_some) + }) + .map(vk_pps) + .collect(); + let session = self + .session + .as_mut() + .ok_or_else(|| Error::config("H.265 parameters before any SPS"))?; + session.h265.set_parameters(&vps, &sps, &pps)?; + self.params_dirty = false; + Ok(()) + } + + fn free_slot(&self) -> Result { + let session = self + .session + .as_ref() + .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; + (0..session.slots) + .find(|slot| self.dpb.pictures.iter().all(|p| p.surface != *slot)) + .ok_or_else(|| Error::config("H.265 Vulkan decode: every DPB slot is in use")) + } + + fn finish_picture(&mut self) -> Result<()> { + let Some(current) = self.current.take() else { + return Ok(()); + }; + let Some(sps) = self + .sps_map + .get(usize::from(current.sps_id)) + .and_then(|s| s.clone()) + else { + return Ok(()); + }; + let refs: Vec = self + .dpb + .pictures + .iter() + .filter(|p| p.mark != Mark::Unused) + .map(|p| H265RefSlot { + slot: p.surface, + poc: p.poc, + long_term: p.mark == Mark::LongTerm, + }) + .collect(); + let slices: Vec<&[u8]> = current.slices.iter().map(Vec::as_slice).collect(); + let session = self + .session + .as_mut() + .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; + session.h265.decode(&H265DecodePicture { + vps_id: sps.vps_id, + sps_id: current.sps_id, + pps_id: current.pps_id, + irap: current.nal_type.is_irap(), + idr: current.nal_type.is_idr(), + reference: is_reference_picture(current.nal_type), + poc: current.poc, + setup_slot: current.slot, + short_term_ref_pic_set_sps: current.short_term_ref_pic_set_sps, + num_delta_pocs_of_ref_rps_idx: 0, + st_rps_bits: current.st_rps_bits, + st_curr_before: ¤t.st_curr_before, + st_curr_after: ¤t.st_curr_after, + lt_curr: ¤t.lt_curr, + refs: &refs, + slices: &slices, + })?; + let (y, uv) = session.h265.read_output( + sps.pic_width_in_luma_samples, + sps.pic_height_in_luma_samples, + )?; + if current.output { + self.outputs.insert(current.slot, crop(&sps, &y, &uv)); + } + + self.dpb.pictures.push(hevc_dpb::StoredPicture { + surface: current.slot, + poc: current.poc, + timestamp: current.timestamp, + mark: if is_reference_picture(current.nal_type) { + Mark::ShortTerm + } else { + Mark::Unused + }, + output: current.output, + }); + if current.is_tid0_anchor { + self.dpb.prev_tid0_poc = current.poc; + } + self.dpb.started = true; + self.bump(false); + Ok(()) + } + + fn bump(&mut self, flush: bool) { + while let Some(idx) = self.dpb.next_output(flush) { + let pic = &self.dpb.pictures[idx]; + if let Some(frame) = self.outputs.remove(&pic.surface) { + self.ready.push_back((pic.timestamp, frame)); + } + self.dpb.released(idx); + } + } +} + +fn store(slot: &mut Option, value: T) -> bool { + if slot.as_ref() == Some(&value) { + return false; + } + *slot = Some(value); + true +} + +fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 { + let (width, height) = sps.display_size(); + let pitch = sps.pic_width_in_luma_samples as usize; + let left = 2 * sps.conf_win.left as usize; + let top = 2 * sps.conf_win.top as usize; + nv12_to_i420( + &y[top * pitch + left..], + pitch, + &uv[(top / 2) * pitch + left..], + pitch, + width as usize, + height as usize, + ) +} + +fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel { + H265ProfileTierLevel { + tier_flag: p.tier_flag, + progressive_source: p.progressive_source, + interlaced_source: p.interlaced_source, + non_packed_constraint: p.non_packed_constraint, + frame_only_constraint: p.frame_only_constraint, + profile_idc: p.profile_idc, + level_idc: p.level_idc, + } +} + +fn dpbm( + max_latency_increase_plus1: u32, + max_dec_pic_buffering_minus1: u32, + reorder: u32, +) -> ec_vk::H265DecPicBufMgr { + ec_vk::H265DecPicBufMgr { + max_latency_increase_plus1: [max_latency_increase_plus1; 7], + max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7], + max_num_reorder_pics: [reorder as u8; 7], + } +} + +fn lists(l: &ScalingList) -> H265ScalingLists { + let c = &l.coefficients; + H265ScalingLists { + list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()), + list_8x8: std::array::from_fn(|i| c[1][i]), + list_16x16: std::array::from_fn(|i| c[2][i]), + list_32x32: std::array::from_fn(|i| c[3][3 * i]), + dc_16x16: std::array::from_fn(|i| l.dc[2][i]), + dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]), + } +} + +fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet { + let (n0, n1) = (r.num_negative as usize, r.num_positive as usize); + H265ShortTermRefPicSet { + delta_poc_s0: r.delta_poc_s0[..n0].to_vec(), + used_by_curr_pic_s0: r.used_s0[..n0].to_vec(), + delta_poc_s1: r.delta_poc_s1[..n1].to_vec(), + used_by_curr_pic_s1: r.used_s1[..n1].to_vec(), + } +} + +fn vk_vps(vps: &Vps) -> H265Vps { + H265Vps { + id: vps.id, + max_sub_layers_minus1: 0, + profile_tier_level: ptl(&vps.ptl), + dec_pic_buf_mgr: dpbm( + 0, + vps.max_dec_pic_buffering_minus1, + vps.max_num_reorder_pics, + ), + } +} + +fn vk_sps(sps: &Sps) -> H265Sps { + let c = &sps.conf_win; + H265Sps { + id: sps.id as u8, + vps_id: sps.vps_id, + max_sub_layers_minus1: 0, + profile_tier_level: ptl(&sps.ptl), + chroma_format_idc: sps.chroma_format_idc as u8, + pic_width_in_luma_samples: sps.pic_width_in_luma_samples, + pic_height_in_luma_samples: sps.pic_height_in_luma_samples, + conformance_window: [c.left, c.right, c.top, c.bottom], + bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, + log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, + log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, + log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, + log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, + log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8, + max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, + max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, + pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm { + bit_depth_luma_minus1: a as u8, + bit_depth_chroma_minus1: b as u8, + log2_min_luma_coding_block_size_minus3: c as u8, + log2_diff_max_min_luma_coding_block_size: d as u8, + loop_filter_disabled: e, + }), + dec_pic_buf_mgr: dpbm( + sps.max_latency_increase_plus1, + sps.max_dec_pic_buffering_minus1, + sps.max_num_reorder_pics, + ), + scaling_list_enabled: sps.scaling_list_enabled, + scaling_lists: sps.scaling_list.as_ref().map(lists), + amp_enabled: sps.amp_enabled, + sample_adaptive_offset_enabled: sps.sao_enabled, + long_term_ref_pics_present: sps.long_term_ref_pics_present, + long_term_ref_pics_sps: sps + .long_term_ref_pics_sps + .iter() + .map( + |&(poc_lsb, used_by_curr_pic)| ec_vk::H265LongTermRefPicSps { + poc_lsb, + used_by_curr_pic, + }, + ) + .collect(), + temporal_mvp_enabled: sps.temporal_mvp_enabled, + strong_intra_smoothing_enabled: sps.strong_intra_smoothing, + short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(), + } +} + +fn vk_pps(pps: &Pps) -> H265Pps { + H265Pps { + id: pps.id as u8, + sps_id: pps.sps_id as u8, + dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled, + output_flag_present: pps.output_flag_present, + num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, + sign_data_hiding_enabled: pps.sign_data_hiding_enabled, + cabac_init_present: pps.cabac_init_present, + num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, + num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, + init_qp_minus26: pps.init_qp_minus26 as i8, + constrained_intra_pred: pps.constrained_intra_pred, + transform_skip_enabled: pps.transform_skip_enabled, + cu_qp_delta_enabled: pps.cu_qp_delta_enabled, + diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, + cb_qp_offset: pps.cb_qp_offset as i8, + cr_qp_offset: pps.cr_qp_offset as i8, + slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present, + weighted_pred: pps.weighted_pred, + weighted_bipred: pps.weighted_bipred, + transquant_bypass_enabled: pps.transquant_bypass_enabled, + tiles_enabled: pps.tiles_enabled, + entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled, + num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, + num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, + uniform_spacing: pps.uniform_spacing, + column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(), + row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(), + loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled, + loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, + deblocking_filter_control_present: pps.deblocking_filter_control_present, + deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled, + deblocking_filter_disabled: pps.deblocking_filter_disabled, + beta_offset_div2: pps.beta_offset_div2 as i8, + tc_offset_div2: pps.tc_offset_div2 as i8, + scaling_lists: pps.scaling_list.as_ref().map(lists), + lists_modification_present: pps.lists_modification_present, + log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, + slice_segment_header_extension_present: pps.slice_segment_header_extension_present, + } +}