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
Browse files at this commita11df786c72d7ca9cf5dff256713f18b20942941Parent: 6c869846 changed files +1088 -324
- crates/ec-hw/examples/hw_decode.rs +138 -30
- crates/ec-hw/src/dec/hevc.rs +27 -275
- crates/ec-hw/src/hevc_dpb.rs +288 -0
- crates/ec-hw/src/hw.rs +93 -19
- crates/ec-hw/src/lib.rs +2 -0
- crates/ec-hw/src/vkdec265.rs +540 -0
crates/ec-hw/examples/hw_decode.rsmodified+138 -30
| @@ -1,4 +1,4 @@ | |||
| 1 | -//! Decodes ffmpeg libx264 streams with B-frames and three references through HwDecoder and compares luma with ffmpeg's decode. | 1 | +//! Decodes ffmpeg libx264 and libx265 streams through HwDecoder and compares luma with ffmpeg's decode, frame by frame. |
| 2 | //! | 2 | //! |
| 3 | //! ```text | 3 | //! ```text |
| 4 | //! cargo run -p ec-hw --example hw_decode -- <scratch dir> | 4 | //! cargo run -p ec-hw --example hw_decode -- <scratch dir> |
| @@ -8,12 +8,109 @@ use std::fs; | |||
| 8 | use std::path::{Path, PathBuf}; | 8 | use std::path::{Path, PathBuf}; |
| 9 | use std::process::Command; | 9 | use std::process::Command; |
| 10 | 10 | ||
| 11 | -use ec_hw::{Codec, HwDecoder, I420}; | 11 | +use ec_hw::{Backend, Codec, HwDecoder, I420}; |
| 12 | + | ||
| 13 | +struct Case { | ||
| 14 | + name: &'static str, | ||
| 15 | + codec: Codec, | ||
| 16 | + size: &'static str, | ||
| 17 | + frames: usize, | ||
| 18 | + encoder: &'static [&'static str], | ||
| 19 | + container: &'static [&'static str], | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +const H264_BF: &[&str] = &[ | ||
| 23 | + "-c:v", | ||
| 24 | + "libx264", | ||
| 25 | + "-profile:v", | ||
| 26 | + "high", | ||
| 27 | + "-bf", | ||
| 28 | + "2", | ||
| 29 | + "-refs", | ||
| 30 | + "3", | ||
| 31 | +]; | ||
| 32 | +const H264_ANNEXB: &[&str] = &["-bsf:v", "h264_mp4toannexb", "-f", "h264"]; | ||
| 33 | +const H265_BF: &[&str] = &[ | ||
| 34 | + "-c:v", | ||
| 35 | + "libx265", | ||
| 36 | + "-x265-params", | ||
| 37 | + "log-level=error:bframes=3:ref=3", | ||
| 38 | +]; | ||
| 39 | +const H265_KEYINT: &[&str] = &[ | ||
| 40 | + "-c:v", | ||
| 41 | + "libx265", | ||
| 42 | + "-x265-params", | ||
| 43 | + "log-level=error:bframes=3:ref=3:keyint=20", | ||
| 44 | +]; | ||
| 45 | +const HEVC: &[&str] = &["-f", "hevc"]; | ||
| 46 | + | ||
| 47 | +const CASES: &[Case] = &[ | ||
| 48 | + Case { | ||
| 49 | + name: "bf640", | ||
| 50 | + codec: Codec::H264, | ||
| 51 | + size: "640x360", | ||
| 52 | + frames: 60, | ||
| 53 | + encoder: H264_BF, | ||
| 54 | + container: H264_ANNEXB, | ||
| 55 | + }, | ||
| 56 | + Case { | ||
| 57 | + name: "bf1280", | ||
| 58 | + codec: Codec::H264, | ||
| 59 | + size: "1280x720", | ||
| 60 | + frames: 30, | ||
| 61 | + encoder: H264_BF, | ||
| 62 | + container: H264_ANNEXB, | ||
| 63 | + }, | ||
| 64 | + Case { | ||
| 65 | + name: "h265bf640", | ||
| 66 | + codec: Codec::H265, | ||
| 67 | + size: "640x360", | ||
| 68 | + frames: 60, | ||
| 69 | + encoder: H265_BF, | ||
| 70 | + container: HEVC, | ||
| 71 | + }, | ||
| 72 | + Case { | ||
| 73 | + name: "h265idr720", | ||
| 74 | + codec: Codec::H265, | ||
| 75 | + size: "1280x720", | ||
| 76 | + frames: 60, | ||
| 77 | + encoder: H265_KEYINT, | ||
| 78 | + container: HEVC, | ||
| 79 | + }, | ||
| 80 | +]; | ||
| 12 | 81 | ||
| 13 | fn main() { | 82 | fn main() { |
| 14 | let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); | 83 | let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); |
| 15 | - run(&dir, "bf640", "640x360", 60); | 84 | + for case in CASES { |
| 16 | - run(&dir, "bf1280", "1280x720", 30); | 85 | + run(&dir, case); |
| 86 | + } | ||
| 87 | + ten_bit_falls_back(&dir); | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +fn ten_bit_falls_back(dir: &std::path::Path) { | ||
| 91 | + let path = dir.join("ten.hevc"); | ||
| 92 | + let p = path.to_str().expect("utf-8 path"); | ||
| 93 | + ffmpeg(&["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=30", "-frames:v", "20", "-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-x265-params", "log-level=error", p]); | ||
| 94 | + let data = std::fs::read(&path).expect("read 10-bit stream"); | ||
| 95 | + let mut dec = ec_hw::HwDecoder::open(ec_hw::Codec::H265).expect("open"); | ||
| 96 | + let opened = dec.backend(); | ||
| 97 | + let starts: Vec<usize> = (0..data.len().saturating_sub(3)) | ||
| 98 | + .filter(|&i| data[i..i + 3] == [0, 0, 1]) | ||
| 99 | + .map(|i| if i > 0 && data[i - 1] == 0 { i - 1 } else { i }) | ||
| 100 | + .chain([data.len()]) | ||
| 101 | + .collect(); | ||
| 102 | + let mut n = 0; | ||
| 103 | + for w in starts.windows(2) { | ||
| 104 | + dec.decode(&data[w[0]..w[1]], 0).expect("decode 10-bit"); | ||
| 105 | + while dec.next_frame().expect("frame").is_some() { | ||
| 106 | + n += 1; | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + dec.flush().expect("flush"); | ||
| 110 | + while dec.next_frame().expect("frame").is_some() { | ||
| 111 | + n += 1; | ||
| 112 | + } | ||
| 113 | + println!("ten.hevc: opened {opened:?}, decoded on {:?}, {n} frames", dec.backend()); | ||
| 17 | } | 114 | } |
| 18 | 115 | ||
| 19 | fn ffmpeg(args: &[&str]) { | 116 | fn ffmpeg(args: &[&str]) { |
| @@ -25,34 +122,30 @@ fn ffmpeg(args: &[&str]) { | |||
| 25 | assert!(status.success(), "ffmpeg {args:?}"); | 122 | assert!(status.success(), "ffmpeg {args:?}"); |
| 26 | } | 123 | } |
| 27 | 124 | ||
| 28 | -fn run(dir: &Path, name: &str, size: &str, frames: usize) { | 125 | +fn run(dir: &Path, case: &Case) { |
| 29 | - let stream = dir.join(format!("{name}.h264")); | 126 | + let ext = if case.codec == Codec::H264 { |
| 30 | - let reference = dir.join(format!("{name}.yuv")); | 127 | + "h264" |
| 31 | - let source = format!("testsrc2=size={size}:rate=30"); | 128 | + } else { |
| 32 | - let frames = frames.to_string(); | 129 | + "hevc" |
| 130 | + }; | ||
| 131 | + let stream = dir.join(format!("{}.{ext}", case.name)); | ||
| 132 | + let reference = dir.join(format!("{}.yuv", case.name)); | ||
| 133 | + let source = format!("testsrc2=size={}:rate=30", case.size); | ||
| 134 | + let frames = case.frames.to_string(); | ||
| 33 | let stream_arg = stream.to_str().expect("utf-8 path"); | 135 | let stream_arg = stream.to_str().expect("utf-8 path"); |
| 34 | let reference_arg = reference.to_str().expect("utf-8 path"); | 136 | let reference_arg = reference.to_str().expect("utf-8 path"); |
| 35 | - ffmpeg(&[ | 137 | + let mut encode: Vec<&str> = vec![ |
| 36 | "-f", | 138 | "-f", |
| 37 | "lavfi", | 139 | "lavfi", |
| 38 | "-i", | 140 | "-i", |
| 39 | - &source, | 141 | + source.as_str(), |
| 40 | "-frames:v", | 142 | "-frames:v", |
| 41 | - &frames, | 143 | + frames.as_str(), |
| 42 | - "-c:v", | 144 | + ]; |
| 43 | - "libx264", | 145 | + encode.extend_from_slice(case.encoder); |
| 44 | - "-profile:v", | 146 | + encode.extend_from_slice(case.container); |
| 45 | - "high", | 147 | + encode.push(stream_arg); |
| 46 | - "-bf", | 148 | + ffmpeg(&encode); |
| 47 | - "2", | ||
| 48 | - "-refs", | ||
| 49 | - "3", | ||
| 50 | - "-bsf:v", | ||
| 51 | - "h264_mp4toannexb", | ||
| 52 | - "-f", | ||
| 53 | - "h264", | ||
| 54 | - stream_arg, | ||
| 55 | - ]); | ||
| 56 | ffmpeg(&[ | 149 | ffmpeg(&[ |
| 57 | "-i", | 150 | "-i", |
| 58 | stream_arg, | 151 | stream_arg, |
| @@ -64,8 +157,11 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { | |||
| 64 | ]); | 157 | ]); |
| 65 | 158 | ||
| 66 | let data = fs::read(&stream).expect("read stream"); | 159 | let data = fs::read(&stream).expect("read stream"); |
| 67 | - let mut decoder = HwDecoder::open(Codec::H264).expect("open H.264 decoder"); | 160 | + let mut decoder = HwDecoder::open(case.codec).expect("open decoder"); |
| 68 | let backend = decoder.backend(); | 161 | let backend = decoder.backend(); |
| 162 | + if case.codec == Codec::H265 { | ||
| 163 | + assert_eq!(backend, Backend::Vk, "H.265 must decode on Vulkan"); | ||
| 164 | + } | ||
| 69 | decoder.decode(&data, 0).expect("decode"); | 165 | decoder.decode(&data, 0).expect("decode"); |
| 70 | decoder.flush().expect("flush"); | 166 | decoder.flush().expect("flush"); |
| 71 | let mut decoded: Vec<I420> = Vec::new(); | 167 | let mut decoded: Vec<I420> = Vec::new(); |
| @@ -74,7 +170,8 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { | |||
| 74 | } | 170 | } |
| 75 | 171 | ||
| 76 | let raw = fs::read(&reference).expect("read reference"); | 172 | let raw = fs::read(&reference).expect("read reference"); |
| 77 | - let (w, h) = size | 173 | + let (w, h) = case |
| 174 | + .size | ||
| 78 | .split_once('x') | 175 | .split_once('x') |
| 79 | .map(|(w, h)| { | 176 | .map(|(w, h)| { |
| 80 | ( | 177 | ( |
| @@ -84,6 +181,7 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { | |||
| 84 | }) | 181 | }) |
| 85 | .expect("size"); | 182 | .expect("size"); |
| 86 | let frame_len = w * h * 3 / 2; | 183 | let frame_len = w * h * 3 / 2; |
| 184 | + let reference_frames = raw.len() / frame_len; | ||
| 87 | let worst = decoded | 185 | let worst = decoded |
| 88 | .iter() | 186 | .iter() |
| 89 | .zip(raw.chunks_exact(frame_len)) | 187 | .zip(raw.chunks_exact(frame_len)) |
| @@ -98,8 +196,18 @@ fn run(dir: &Path, name: &str, size: &str, frames: usize) { | |||
| 98 | }) | 196 | }) |
| 99 | .fold(0.0f64, f64::max); | 197 | .fold(0.0f64, f64::max); |
| 100 | println!( | 198 | println!( |
| 101 | - "{name} {backend:?} {size}: decoded {} frames, ffmpeg {} frames, max mean |diff| Y {worst:.6}", | 199 | + "{} {:?} {:?} {}: decoded {} frames, ffmpeg {} frames, max mean |diff| Y {worst:.6}", |
| 200 | + case.name, | ||
| 201 | + case.codec, | ||
| 202 | + backend, | ||
| 203 | + case.size, | ||
| 204 | + decoded.len(), | ||
| 205 | + reference_frames | ||
| 206 | + ); | ||
| 207 | + assert_eq!( | ||
| 102 | decoded.len(), | 208 | decoded.len(), |
| 103 | - raw.len() / frame_len | 209 | + reference_frames, |
| 210 | + "{}: frame count", | ||
| 211 | + case.name | ||
| 104 | ); | 212 | ); |
| 105 | } | 213 | } |
crates/ec-hw/src/dec/hevc.rsmodified+27 -275
| @@ -20,6 +20,10 @@ use ec_va::{Buffer, Display}; | |||
| 20 | use super::{ReadyFrames, Session, StreamInfo}; | 20 | use super::{ReadyFrames, Session, StreamInfo}; |
| 21 | use crate::error::{Error, Result}; | 21 | use crate::error::{Error, Result}; |
| 22 | use crate::frame::{Colour, Frame}; | 22 | use crate::frame::{Colour, Frame}; |
| 23 | +use crate::hevc_dpb::{ | ||
| 24 | + Dpb, Mark, Rps, StoredPicture, is_bla_picture, is_rasl_picture, is_reference_picture, | ||
| 25 | + is_leading_picture, peek_pps_id, vui_colour_tags, | ||
| 26 | +}; | ||
| 23 | use crate::params::hevc::{ | 27 | use crate::params::hevc::{ |
| 24 | IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, | 28 | IQMatrixBufferHEVC, LongSliceFlags, PICTURE_INVALID, PICTURE_LONG_TERM_REFERENCE, |
| 25 | PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PicFields, | 29 | PICTURE_RPS_LT_CURR, PICTURE_RPS_ST_CURR_AFTER, PICTURE_RPS_ST_CURR_BEFORE, PicFields, |
| @@ -31,14 +35,6 @@ use crate::pool::PooledSurface; | |||
| 31 | /// a caller is still holding. | 35 | /// a caller is still holding. |
| 32 | const EXTRA_SURFACES: usize = 6; | 36 | const EXTRA_SURFACES: usize = 6; |
| 33 | 37 | ||
| 34 | -/// Reference marking of a stored picture (8.3.2). | ||
| 35 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 36 | -enum Mark { | ||
| 37 | - Unused, | ||
| 38 | - ShortTerm, | ||
| 39 | - LongTerm, | ||
| 40 | -} | ||
| 41 | - | ||
| 42 | /// One DPB slot as the parameter builder sees it: its surface, POC and marking. | 38 | /// One DPB slot as the parameter builder sees it: its surface, POC and marking. |
| 43 | #[derive(Clone, Copy)] | 39 | #[derive(Clone, Copy)] |
| 44 | struct DpbSlot { | 40 | struct DpbSlot { |
| @@ -48,7 +44,7 @@ struct DpbSlot { | |||
| 48 | } | 44 | } |
| 49 | 45 | ||
| 50 | impl DpbSlot { | 46 | impl DpbSlot { |
| 51 | - fn of(p: &StoredPicture) -> DpbSlot { | 47 | + fn of(p: &StoredPicture<Rc<PooledSurface>>) -> DpbSlot { |
| 52 | DpbSlot { | 48 | DpbSlot { |
| 53 | id: p.surface.id(), | 49 | id: p.surface.id(), |
| 54 | poc: p.poc, | 50 | poc: p.poc, |
| @@ -57,29 +53,6 @@ impl DpbSlot { | |||
| 57 | } | 53 | } |
| 58 | } | 54 | } |
| 59 | 55 | ||
| 60 | -struct StoredPicture { | ||
| 61 | - surface: Rc<PooledSurface>, | ||
| 62 | - poc: i32, | ||
| 63 | - timestamp: i64, | ||
| 64 | - mark: Mark, | ||
| 65 | - /// Still to be handed to the caller. | ||
| 66 | - output: bool, | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -impl StoredPicture { | ||
| 70 | - fn stored(&self) -> bool { | ||
| 71 | - self.output || self.mark != Mark::Unused | ||
| 72 | - } | ||
| 73 | -} | ||
| 74 | - | ||
| 75 | -/// The reference picture set of the picture being decoded, as DPB indices. | ||
| 76 | -#[derive(Debug, Default, Clone)] | ||
| 77 | -struct Rps { | ||
| 78 | - st_curr_before: Vec<usize>, | ||
| 79 | - st_curr_after: Vec<usize>, | ||
| 80 | - lt_curr: Vec<usize>, | ||
| 81 | -} | ||
| 82 | - | ||
| 83 | /// The picture being assembled from its slices. | 56 | /// The picture being assembled from its slices. |
| 84 | struct Current { | 57 | struct Current { |
| 85 | surface: Rc<PooledSurface>, | 58 | surface: Rc<PooledSurface>, |
| @@ -104,20 +77,14 @@ pub struct HevcDecoder { | |||
| 104 | sps_map: Vec<Option<Sps>>, | 77 | sps_map: Vec<Option<Sps>>, |
| 105 | pps_map: Vec<Option<Pps>>, | 78 | pps_map: Vec<Option<Pps>>, |
| 106 | session: Option<Session>, | 79 | session: Option<Session>, |
| 107 | - dpb: Vec<StoredPicture>, | 80 | + dpb: Dpb<Rc<PooledSurface>>, |
| 108 | ready: ReadyFrames, | 81 | ready: ReadyFrames, |
| 109 | current: Option<Current>, | 82 | current: Option<Current>, |
| 110 | - /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1. | ||
| 111 | - prev_tid0_poc: i32, | ||
| 112 | - /// Set once a picture has been decoded since the last reset. | ||
| 113 | - started: bool, | ||
| 114 | /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures | 83 | /// `NoRaslOutputFlag` (8.1.3) of the most recent IRAP: RASL pictures |
| 115 | /// associated with it must not be decoded or output when set, because | 84 | /// associated with it must not be decoded or output when set, because |
| 116 | /// they predict from pictures before a random-access point this decoder | 85 | /// they predict from pictures before a random-access point this decoder |
| 117 | /// never saw. | 86 | /// never saw. |
| 118 | no_rasl_output: bool, | 87 | no_rasl_output: bool, |
| 119 | - max_reorder: usize, | ||
| 120 | - max_dec_pic_buffering: usize, | ||
| 121 | /// The most recent SPS's VUI colour tags, sticky across pictures. | 88 | /// The most recent SPS's VUI colour tags, sticky across pictures. |
| 122 | colour_tags: Tags, | 89 | colour_tags: Tags, |
| 123 | /// The prefix SEI HDR peak seen so far, merged so a later access unit that | 90 | /// The prefix SEI HDR peak seen so far, merged so a later access unit that |
| @@ -134,14 +101,10 @@ impl HevcDecoder { | |||
| 134 | sps_map: (0..16).map(|_| None).collect(), | 101 | sps_map: (0..16).map(|_| None).collect(), |
| 135 | pps_map: (0..64).map(|_| None).collect(), | 102 | pps_map: (0..64).map(|_| None).collect(), |
| 136 | session: None, | 103 | session: None, |
| 137 | - dpb: Vec::new(), | 104 | + dpb: Dpb::new(), |
| 138 | ready: ReadyFrames::default(), | 105 | ready: ReadyFrames::default(), |
| 139 | current: None, | 106 | current: None, |
| 140 | - prev_tid0_poc: 0, | ||
| 141 | - started: false, | ||
| 142 | no_rasl_output: false, | 107 | no_rasl_output: false, |
| 143 | - max_reorder: 1, | ||
| 144 | - max_dec_pic_buffering: 6, | ||
| 145 | colour_tags: Tags::default(), | 108 | colour_tags: Tags::default(), |
| 146 | colour_light: ContentLight::default(), | 109 | colour_light: ContentLight::default(), |
| 147 | } | 110 | } |
| @@ -160,8 +123,8 @@ impl HevcDecoder { | |||
| 160 | } | 123 | } |
| 161 | NalUnitType::Sps => { | 124 | NalUnitType::Sps => { |
| 162 | let sps = Sps::parse(&nal.rbsp())?; | 125 | let sps = Sps::parse(&nal.rbsp())?; |
| 163 | - self.max_reorder = sps.max_num_reorder_pics as usize; | 126 | + self.dpb.max_reorder = sps.max_num_reorder_pics as usize; |
| 164 | - self.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; | 127 | + self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; |
| 165 | self.colour_tags = vui_colour_tags(&sps); | 128 | self.colour_tags = vui_colour_tags(&sps); |
| 166 | let id = sps.id as usize; | 129 | let id = sps.id as usize; |
| 167 | if id < self.sps_map.len() { | 130 | if id < self.sps_map.len() { |
| @@ -222,10 +185,10 @@ impl HevcDecoder { | |||
| 222 | /// Drop all picture state after a seek; parameter sets survive. | 185 | /// Drop all picture state after a seek; parameter sets survive. |
| 223 | pub fn reset(&mut self) { | 186 | pub fn reset(&mut self) { |
| 224 | self.current = None; | 187 | self.current = None; |
| 225 | - self.dpb.clear(); | 188 | + self.dpb.pictures.clear(); |
| 226 | self.ready.clear(); | 189 | self.ready.clear(); |
| 227 | - self.prev_tid0_poc = 0; | 190 | + self.dpb.prev_tid0_poc = 0; |
| 228 | - self.started = false; | 191 | + self.dpb.started = false; |
| 229 | self.no_rasl_output = false; | 192 | self.no_rasl_output = false; |
| 230 | } | 193 | } |
| 231 | 194 | ||
| @@ -297,14 +260,14 @@ impl HevcDecoder { | |||
| 297 | return Ok(()); | 260 | return Ok(()); |
| 298 | } | 261 | } |
| 299 | self.current = None; | 262 | self.current = None; |
| 300 | - self.dpb.clear(); | 263 | + self.dpb.pictures.clear(); |
| 301 | self.session = Some(Session::new( | 264 | self.session = Some(Session::new( |
| 302 | &self.display, | 265 | &self.display, |
| 303 | profile, | 266 | profile, |
| 304 | coded, | 267 | coded, |
| 305 | sps.display_size(), | 268 | sps.display_size(), |
| 306 | bit_depth, | 269 | bit_depth, |
| 307 | - self.max_dec_pic_buffering + EXTRA_SURFACES, | 270 | + self.dpb.max_dec_pic_buffering + EXTRA_SURFACES, |
| 308 | )?); | 271 | )?); |
| 309 | Ok(()) | 272 | Ok(()) |
| 310 | } | 273 | } |
| @@ -323,13 +286,13 @@ impl HevcDecoder { | |||
| 323 | // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded | 286 | // 8.1.3: 1 for an IDR, a BLA, or the first picture of a coded |
| 324 | // video sequence — which a mid-stream start's first IRAP always | 287 | // video sequence — which a mid-stream start's first IRAP always |
| 325 | // is, `self.started` still being false at that point. | 288 | // is, `self.started` still being false at that point. |
| 326 | - self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.started; | 289 | + self.no_rasl_output = nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started; |
| 327 | } | 290 | } |
| 328 | 291 | ||
| 329 | - let poc = self.picture_order_count(sps, sh, nal_type); | 292 | + let poc = self.dpb.picture_order_count(sps, sh, nal_type); |
| 330 | // 8.3.2 runs before the picture is decoded and after its POC is known: | 293 | // 8.3.2 runs before the picture is decoded and after its POC is known: |
| 331 | // every stored picture the set does not name stops being a reference. | 294 | // every stored picture the set does not name stops being a reference. |
| 332 | - let rps = self.apply_rps(sps, sh, nal_type, poc)?; | 295 | + let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; |
| 333 | 296 | ||
| 334 | if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { | 297 | if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { |
| 335 | // An IRAP that restarts output order: everything ahead of it in the | 298 | // An IRAP that restarts output order: everything ahead of it in the |
| @@ -342,7 +305,7 @@ impl HevcDecoder { | |||
| 342 | "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}", | 305 | "pic poc {poc} nal {:?} tid {temporal_id} lsb {} dpb {} ready {} (st {}/{} lt {}) free {}", |
| 343 | nal_type, | 306 | nal_type, |
| 344 | sh.poc_lsb, | 307 | sh.poc_lsb, |
| 345 | - self.dpb.len(), | 308 | + self.dpb.pictures.len(), |
| 346 | self.ready.len(), | 309 | self.ready.len(), |
| 347 | rps.st_curr_before.len(), | 310 | rps.st_curr_before.len(), |
| 348 | rps.st_curr_after.len(), | 311 | rps.st_curr_after.len(), |
| @@ -364,9 +327,9 @@ impl HevcDecoder { | |||
| 364 | 327 | ||
| 365 | // The driver indexes RefPicList into `reference_frames`, so the mapping | 328 | // The driver indexes RefPicList into `reference_frames`, so the mapping |
| 366 | // from DPB slot to that array is fixed once, here. | 329 | // from DPB slot to that array is fixed once, here. |
| 367 | - let mut va_index = vec![0xffu8; self.dpb.len()]; | 330 | + let mut va_index = vec![0xffu8; self.dpb.pictures.len()]; |
| 368 | let mut n = 0u8; | 331 | let mut n = 0u8; |
| 369 | - for (i, pic) in self.dpb.iter().enumerate() { | 332 | + for (i, pic) in self.dpb.pictures.iter().enumerate() { |
| 370 | if pic.mark != Mark::Unused && n < 15 { | 333 | if pic.mark != Mark::Unused && n < 15 { |
| 371 | va_index[i] = n; | 334 | va_index[i] = n; |
| 372 | n += 1; | 335 | n += 1; |
| @@ -400,142 +363,6 @@ impl HevcDecoder { | |||
| 400 | Ok(()) | 363 | Ok(()) |
| 401 | } | 364 | } |
| 402 | 365 | ||
| 403 | - /// `PicOrderCntVal` (8.3.1). | ||
| 404 | - fn picture_order_count(&self, sps: &Sps, sh: &SliceHeader, nal_type: NalUnitType) -> i32 { | ||
| 405 | - if nal_type.is_idr() { | ||
| 406 | - return 0; | ||
| 407 | - } | ||
| 408 | - let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); | ||
| 409 | - let lsb = sh.poc_lsb as i32; | ||
| 410 | - let (prev_msb, prev_lsb) = if !self.started { | ||
| 411 | - (0, 0) | ||
| 412 | - } else { | ||
| 413 | - ( | ||
| 414 | - self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)), | ||
| 415 | - self.prev_tid0_poc.rem_euclid(max_lsb), | ||
| 416 | - ) | ||
| 417 | - }; | ||
| 418 | - // An IRAP that starts a new coded video sequence has no predecessor. | ||
| 419 | - if nal_type.is_irap() && !self.started { | ||
| 420 | - return lsb; | ||
| 421 | - } | ||
| 422 | - let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { | ||
| 423 | - prev_msb + max_lsb | ||
| 424 | - } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { | ||
| 425 | - prev_msb - max_lsb | ||
| 426 | - } else { | ||
| 427 | - prev_msb | ||
| 428 | - }; | ||
| 429 | - msb + lsb | ||
| 430 | - } | ||
| 431 | - | ||
| 432 | - /// Reference picture set derivation and marking (8.3.2). | ||
| 433 | - fn apply_rps( | ||
| 434 | - &mut self, | ||
| 435 | - sps: &Sps, | ||
| 436 | - sh: &SliceHeader, | ||
| 437 | - nal_type: NalUnitType, | ||
| 438 | - poc: i32, | ||
| 439 | - ) -> Result<Rps> { | ||
| 440 | - if nal_type.is_irap() && (nal_type.is_idr() || !self.started) { | ||
| 441 | - for pic in &mut self.dpb { | ||
| 442 | - pic.mark = Mark::Unused; | ||
| 443 | - } | ||
| 444 | - self.dpb.retain(|p| p.stored()); | ||
| 445 | - return Ok(Rps::default()); | ||
| 446 | - } | ||
| 447 | - | ||
| 448 | - let set = &sh.short_term_ref_pic_set; | ||
| 449 | - let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); | ||
| 450 | - let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term) | ||
| 451 | - for i in 0..set.num_negative as usize { | ||
| 452 | - wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false)); | ||
| 453 | - } | ||
| 454 | - for i in 0..set.num_positive as usize { | ||
| 455 | - wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false)); | ||
| 456 | - } | ||
| 457 | - for lt in &sh.long_term { | ||
| 458 | - // 8.3.2: a long-term entry without an MSB cycle is matched on its | ||
| 459 | - // POC low bits alone, which is how a stream survives an MSB wrap. | ||
| 460 | - let target = if lt.delta_poc_msb_present { | ||
| 461 | - poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb) | ||
| 462 | - + lt.poc_lsb_lt as i32 | ||
| 463 | - } else { | ||
| 464 | - lt.poc_lsb_lt as i32 | ||
| 465 | - }; | ||
| 466 | - wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present)); | ||
| 467 | - } | ||
| 468 | - | ||
| 469 | - let mut rps = Rps::default(); | ||
| 470 | - let mut keep = vec![false; self.dpb.len()]; | ||
| 471 | - let mut missing_used = false; | ||
| 472 | - for (target, used, lsb_only) in wanted { | ||
| 473 | - let found = self.dpb.iter().position(|p| { | ||
| 474 | - if lsb_only { | ||
| 475 | - p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb) | ||
| 476 | - } else { | ||
| 477 | - p.poc == target | ||
| 478 | - } | ||
| 479 | - }); | ||
| 480 | - let Some(idx) = found else { | ||
| 481 | - // 8.3.2: a picture the current one predicts from must be in the | ||
| 482 | - // buffer. One that is not is a broken GOP, and a reference list | ||
| 483 | - // built without it would name a surface that was never decoded. | ||
| 484 | - missing_used |= used; | ||
| 485 | - continue; | ||
| 486 | - }; | ||
| 487 | - keep[idx] = true; | ||
| 488 | - if !used { | ||
| 489 | - continue; | ||
| 490 | - } | ||
| 491 | - // The three "current" lists are what the reference lists are built | ||
| 492 | - // from, in POC order relative to the current picture. | ||
| 493 | - if self.dpb[idx].mark == Mark::LongTerm || lsb_only { | ||
| 494 | - rps.lt_curr.push(idx); | ||
| 495 | - } else if self.dpb[idx].poc < poc { | ||
| 496 | - rps.st_curr_before.push(idx); | ||
| 497 | - } else { | ||
| 498 | - rps.st_curr_after.push(idx); | ||
| 499 | - } | ||
| 500 | - } | ||
| 501 | - rps.st_curr_before | ||
| 502 | - .sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].poc)); | ||
| 503 | - rps.st_curr_after.sort_by_key(|&i| self.dpb[i].poc); | ||
| 504 | - | ||
| 505 | - for (i, pic) in self.dpb.iter_mut().enumerate() { | ||
| 506 | - if !keep[i] { | ||
| 507 | - pic.mark = Mark::Unused; | ||
| 508 | - } | ||
| 509 | - } | ||
| 510 | - // Dropping unreferenced, already-output pictures here is what returns | ||
| 511 | - // their surfaces to the pool; the indices in `rps` are recomputed after. | ||
| 512 | - let mut remap = vec![usize::MAX; self.dpb.len()]; | ||
| 513 | - let mut next = 0usize; | ||
| 514 | - for (i, pic) in self.dpb.iter().enumerate() { | ||
| 515 | - if pic.stored() { | ||
| 516 | - remap[i] = next; | ||
| 517 | - next += 1; | ||
| 518 | - } | ||
| 519 | - } | ||
| 520 | - self.dpb.retain(|p| p.stored()); | ||
| 521 | - if missing_used { | ||
| 522 | - return Err(Error::Stream(ec_core::Error::corrupt( | ||
| 523 | - "HEVC reference picture set names a picture used for prediction that was never decoded", | ||
| 524 | - ))); | ||
| 525 | - } | ||
| 526 | - for list in [ | ||
| 527 | - &mut rps.st_curr_before, | ||
| 528 | - &mut rps.st_curr_after, | ||
| 529 | - &mut rps.lt_curr, | ||
| 530 | - ] { | ||
| 531 | - list.retain(|&i| remap[i] != usize::MAX); | ||
| 532 | - for entry in list.iter_mut() { | ||
| 533 | - *entry = remap[*entry]; | ||
| 534 | - } | ||
| 535 | - } | ||
| 536 | - Ok(rps) | ||
| 537 | - } | ||
| 538 | - | ||
| 539 | fn render_slice( | 366 | fn render_slice( |
| 540 | &mut self, | 367 | &mut self, |
| 541 | sps: &Sps, | 368 | sps: &Sps, |
| @@ -555,7 +382,7 @@ impl HevcDecoder { | |||
| 555 | } | 382 | } |
| 556 | 383 | ||
| 557 | if current.slices == 0 { | 384 | if current.slices == 0 { |
| 558 | - let slots: Vec<DpbSlot> = self.dpb.iter().map(DpbSlot::of).collect(); | 385 | + let slots: Vec<DpbSlot> = self.dpb.pictures.iter().map(DpbSlot::of).collect(); |
| 559 | let pic_param = picture_parameters( | 386 | let pic_param = picture_parameters( |
| 560 | sps, | 387 | sps, |
| 561 | pps, | 388 | pps, |
| @@ -678,7 +505,7 @@ impl HevcDecoder { | |||
| 678 | } | 505 | } |
| 679 | session.submit(¤t.surface, current.buffers)?; | 506 | session.submit(¤t.surface, current.buffers)?; |
| 680 | 507 | ||
| 681 | - self.dpb.push(StoredPicture { | 508 | + self.dpb.pictures.push(StoredPicture { |
| 682 | surface: Rc::clone(¤t.surface), | 509 | surface: Rc::clone(¤t.surface), |
| 683 | poc: current.poc, | 510 | poc: current.poc, |
| 684 | timestamp: current.timestamp, | 511 | timestamp: current.timestamp, |
| @@ -690,9 +517,9 @@ impl HevcDecoder { | |||
| 690 | output: current.output, | 517 | output: current.output, |
| 691 | }); | 518 | }); |
| 692 | if current.is_tid0_anchor { | 519 | if current.is_tid0_anchor { |
| 693 | - self.prev_tid0_poc = current.poc; | 520 | + self.dpb.prev_tid0_poc = current.poc; |
| 694 | } | 521 | } |
| 695 | - self.started = true; | 522 | + self.dpb.started = true; |
| 696 | self.bump(false); | 523 | self.bump(false); |
| 697 | Ok(()) | 524 | Ok(()) |
| 698 | } | 525 | } |
| @@ -703,23 +530,8 @@ impl HevcDecoder { | |||
| 703 | let Some(session) = self.session.as_ref() else { | 530 | let Some(session) = self.session.as_ref() else { |
| 704 | return; | 531 | return; |
| 705 | }; | 532 | }; |
| 706 | - loop { | 533 | + while let Some(idx) = self.dpb.next_output(flush) { |
| 707 | - let pending = self.dpb.iter().filter(|p| p.output).count(); | 534 | + let pic = &self.dpb.pictures[idx]; |
| 708 | - let stored = self.dpb.iter().filter(|p| p.stored()).count(); | ||
| 709 | - if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering { | ||
| 710 | - return; | ||
| 711 | - } | ||
| 712 | - let Some(idx) = self | ||
| 713 | - .dpb | ||
| 714 | - .iter() | ||
| 715 | - .enumerate() | ||
| 716 | - .filter(|(_, p)| p.output) | ||
| 717 | - .min_by_key(|(_, p)| p.poc) | ||
| 718 | - .map(|(i, _)| i) | ||
| 719 | - else { | ||
| 720 | - return; | ||
| 721 | - }; | ||
| 722 | - let pic = &self.dpb[idx]; | ||
| 723 | self.ready.push(Frame::new( | 535 | self.ready.push(Frame::new( |
| 724 | Rc::clone(&pic.surface), | 536 | Rc::clone(&pic.surface), |
| 725 | Rc::clone(&self.display), | 537 | Rc::clone(&self.display), |
| @@ -729,71 +541,11 @@ impl HevcDecoder { | |||
| 729 | session.bit_depth, | 541 | session.bit_depth, |
| 730 | self.colour(), | 542 | self.colour(), |
| 731 | )); | 543 | )); |
| 732 | - self.dpb[idx].output = false; | 544 | + self.dpb.released(idx); |
| 733 | - self.dpb.retain(|p| p.stored()); | ||
| 734 | } | 545 | } |
| 735 | } | 546 | } |
| 736 | } | 547 | } |
| 737 | 548 | ||
| 738 | -/// True unless the NAL type says sub-layer non-reference (`_N`, an even type | ||
| 739 | -/// below 16). | ||
| 740 | -fn is_reference_picture(nal_type: NalUnitType) -> bool { | ||
| 741 | - let code = nal_type.code(); | ||
| 742 | - code >= 16 || code % 2 == 1 | ||
| 743 | -} | ||
| 744 | - | ||
| 745 | -/// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1 | ||
| 746 | -/// excludes from the picture order count prediction. | ||
| 747 | -fn is_leading_picture(nal_type: NalUnitType) -> bool { | ||
| 748 | - (6..=9).contains(&nal_type.code()) | ||
| 749 | -} | ||
| 750 | - | ||
| 751 | -/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for | ||
| 752 | -/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no | ||
| 753 | -/// `video_signal_type` at all. | ||
| 754 | -fn vui_colour_tags(sps: &Sps) -> Tags { | ||
| 755 | - let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { | ||
| 756 | - return Tags::default(); | ||
| 757 | - }; | ||
| 758 | - let (_primaries, transfer, matrix) = vst | ||
| 759 | - .colour_description | ||
| 760 | - .map(|cd| { | ||
| 761 | - ( | ||
| 762 | - cd.colour_primaries, | ||
| 763 | - cd.transfer_characteristics, | ||
| 764 | - cd.matrix_coeffs, | ||
| 765 | - ) | ||
| 766 | - }) | ||
| 767 | - .unwrap_or((0, 0, 0)); | ||
| 768 | - Tags::from_codes( | ||
| 769 | - u64::from(matrix), | ||
| 770 | - u64::from(transfer), | ||
| 771 | - if vst.video_full_range_flag { 2 } else { 1 }, | ||
| 772 | - ) | ||
| 773 | -} | ||
| 774 | - | ||
| 775 | -/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's | ||
| 776 | -/// `NoRaslOutputFlag` is 1 (8.1.3). | ||
| 777 | -fn is_rasl_picture(nal_type: NalUnitType) -> bool { | ||
| 778 | - matches!(nal_type.code(), 8 | 9) | ||
| 779 | -} | ||
| 780 | - | ||
| 781 | -/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1 | ||
| 782 | -/// (8.1.3), a broken-link splice point that never has a decodable RASL. | ||
| 783 | -fn is_bla_picture(nal_type: NalUnitType) -> bool { | ||
| 784 | - (16..=18).contains(&nal_type.code()) | ||
| 785 | -} | ||
| 786 | - | ||
| 787 | -/// `slice_pic_parameter_set_id`, readable without any parameter set. | ||
| 788 | -fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> { | ||
| 789 | - let mut r = ec_core::BitReader::new(rbsp); | ||
| 790 | - r.read_bit()?; // first_slice_segment_in_pic_flag | ||
| 791 | - if nal_type.is_irap() { | ||
| 792 | - r.read_bit()?; // no_output_of_prior_pics_flag | ||
| 793 | - } | ||
| 794 | - Ok(r.read_ue()?) | ||
| 795 | -} | ||
| 796 | - | ||
| 797 | /// Reference list construction (8.3.4), as DPB indices. | 549 | /// Reference list construction (8.3.4), as DPB indices. |
| 798 | fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] { | 550 | fn reference_lists(sh: &SliceHeader, rps: &Rps) -> [Vec<usize>; 2] { |
| 799 | let mut out = [Vec::new(), Vec::new()]; | 551 | let mut out = [Vec::new(), Vec::new()]; |
crates/ec-hw/src/hevc_dpb.rsadded+288 -0
| @@ -0,0 +1,288 @@ | |||
| 1 | +//! HEVC picture management over any surface type: picture order count (8.3.1), | ||
| 2 | +//! reference picture sets and marking (8.3.2), and output bumping (C.5.2). | ||
| 3 | +//! | ||
| 4 | +//! The VA-API and Vulkan Video decoders both build on this. A stored picture | ||
| 5 | +//! is only its surface, POC, timestamp, marking and output state; the driver | ||
| 6 | +//! sees the reference picture set as DPB indices into [`Dpb::pictures`]. | ||
| 7 | + | ||
| 8 | +use ec_core::color::Tags; | ||
| 9 | +use ec_h265_syntax::{NalUnitType, SliceHeader, Sps}; | ||
| 10 | + | ||
| 11 | +use crate::error::{Error, Result}; | ||
| 12 | + | ||
| 13 | +/// Reference marking of a stored picture (8.3.2). | ||
| 14 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 15 | +pub(crate) enum Mark { | ||
| 16 | + Unused, | ||
| 17 | + ShortTerm, | ||
| 18 | + LongTerm, | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +/// One stored picture: its surface, POC, marking and whether it is still to be output. | ||
| 22 | +pub(crate) struct StoredPicture<S> { | ||
| 23 | + pub(crate) surface: S, | ||
| 24 | + pub(crate) poc: i32, | ||
| 25 | + pub(crate) timestamp: i64, | ||
| 26 | + pub(crate) mark: Mark, | ||
| 27 | + /// Still to be handed to the caller. | ||
| 28 | + pub(crate) output: bool, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl<S> StoredPicture<S> { | ||
| 32 | + pub(crate) fn stored(&self) -> bool { | ||
| 33 | + self.output || self.mark != Mark::Unused | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// The reference picture set of the picture being decoded, as DPB indices. | ||
| 38 | +#[derive(Debug, Default, Clone)] | ||
| 39 | +pub(crate) struct Rps { | ||
| 40 | + pub(crate) st_curr_before: Vec<usize>, | ||
| 41 | + pub(crate) st_curr_after: Vec<usize>, | ||
| 42 | + pub(crate) lt_curr: Vec<usize>, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// The decoded picture buffer and the cross-picture state of 8.3.1 and C.5.2. | ||
| 46 | +pub(crate) struct Dpb<S> { | ||
| 47 | + pub(crate) pictures: Vec<StoredPicture<S>>, | ||
| 48 | + /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1. | ||
| 49 | + pub(crate) prev_tid0_poc: i32, | ||
| 50 | + /// Set once a picture has been decoded since the last reset. | ||
| 51 | + pub(crate) started: bool, | ||
| 52 | + pub(crate) max_reorder: usize, | ||
| 53 | + pub(crate) max_dec_pic_buffering: usize, | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +impl<S> Dpb<S> { | ||
| 57 | + pub(crate) fn new() -> Dpb<S> { | ||
| 58 | + Dpb { | ||
| 59 | + pictures: Vec::new(), | ||
| 60 | + prev_tid0_poc: 0, | ||
| 61 | + started: false, | ||
| 62 | + max_reorder: 1, | ||
| 63 | + max_dec_pic_buffering: 6, | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + /// `PicOrderCntVal` (8.3.1). | ||
| 68 | + pub(crate) fn picture_order_count( | ||
| 69 | + &self, | ||
| 70 | + sps: &Sps, | ||
| 71 | + sh: &SliceHeader, | ||
| 72 | + nal_type: NalUnitType, | ||
| 73 | + ) -> i32 { | ||
| 74 | + if nal_type.is_idr() { | ||
| 75 | + return 0; | ||
| 76 | + } | ||
| 77 | + let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); | ||
| 78 | + let lsb = sh.poc_lsb as i32; | ||
| 79 | + let (prev_msb, prev_lsb) = if !self.started { | ||
| 80 | + (0, 0) | ||
| 81 | + } else { | ||
| 82 | + ( | ||
| 83 | + self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)), | ||
| 84 | + self.prev_tid0_poc.rem_euclid(max_lsb), | ||
| 85 | + ) | ||
| 86 | + }; | ||
| 87 | + // An IRAP that starts a new coded video sequence has no predecessor. | ||
| 88 | + if nal_type.is_irap() && !self.started { | ||
| 89 | + return lsb; | ||
| 90 | + } | ||
| 91 | + let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { | ||
| 92 | + prev_msb + max_lsb | ||
| 93 | + } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { | ||
| 94 | + prev_msb - max_lsb | ||
| 95 | + } else { | ||
| 96 | + prev_msb | ||
| 97 | + }; | ||
| 98 | + msb + lsb | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + /// Reference picture set derivation and marking (8.3.2). | ||
| 102 | + pub(crate) fn apply_rps( | ||
| 103 | + &mut self, | ||
| 104 | + sps: &Sps, | ||
| 105 | + sh: &SliceHeader, | ||
| 106 | + nal_type: NalUnitType, | ||
| 107 | + poc: i32, | ||
| 108 | + ) -> Result<Rps> { | ||
| 109 | + if nal_type.is_irap() && (nal_type.is_idr() || !self.started) { | ||
| 110 | + for pic in &mut self.pictures { | ||
| 111 | + pic.mark = Mark::Unused; | ||
| 112 | + } | ||
| 113 | + self.pictures.retain(|p| p.stored()); | ||
| 114 | + return Ok(Rps::default()); | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + let set = &sh.short_term_ref_pic_set; | ||
| 118 | + let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4); | ||
| 119 | + let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term) | ||
| 120 | + for i in 0..set.num_negative as usize { | ||
| 121 | + wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false)); | ||
| 122 | + } | ||
| 123 | + for i in 0..set.num_positive as usize { | ||
| 124 | + wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false)); | ||
| 125 | + } | ||
| 126 | + for lt in &sh.long_term { | ||
| 127 | + // 8.3.2: a long-term entry without an MSB cycle is matched on its | ||
| 128 | + // POC low bits alone, which is how a stream survives an MSB wrap. | ||
| 129 | + let target = if lt.delta_poc_msb_present { | ||
| 130 | + poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb) | ||
| 131 | + + lt.poc_lsb_lt as i32 | ||
| 132 | + } else { | ||
| 133 | + lt.poc_lsb_lt as i32 | ||
| 134 | + }; | ||
| 135 | + wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present)); | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + let mut rps = Rps::default(); | ||
| 139 | + let mut keep = vec![false; self.pictures.len()]; | ||
| 140 | + let mut missing_used = false; | ||
| 141 | + for (target, used, lsb_only) in wanted { | ||
| 142 | + let found = self.pictures.iter().position(|p| { | ||
| 143 | + if lsb_only { | ||
| 144 | + p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb) | ||
| 145 | + } else { | ||
| 146 | + p.poc == target | ||
| 147 | + } | ||
| 148 | + }); | ||
| 149 | + let Some(idx) = found else { | ||
| 150 | + // 8.3.2: a picture the current one predicts from must be in the | ||
| 151 | + // buffer. One that is not is a broken GOP, and a reference list | ||
| 152 | + // built without it would name a surface that was never decoded. | ||
| 153 | + missing_used |= used; | ||
| 154 | + continue; | ||
| 155 | + }; | ||
| 156 | + keep[idx] = true; | ||
| 157 | + if !used { | ||
| 158 | + continue; | ||
| 159 | + } | ||
| 160 | + // The three "current" lists are what the reference lists are built | ||
| 161 | + // from, in POC order relative to the current picture. | ||
| 162 | + if self.pictures[idx].mark == Mark::LongTerm || lsb_only { | ||
| 163 | + rps.lt_curr.push(idx); | ||
| 164 | + } else if self.pictures[idx].poc < poc { | ||
| 165 | + rps.st_curr_before.push(idx); | ||
| 166 | + } else { | ||
| 167 | + rps.st_curr_after.push(idx); | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | + rps.st_curr_before | ||
| 171 | + .sort_by_key(|&i| std::cmp::Reverse(self.pictures[i].poc)); | ||
| 172 | + rps.st_curr_after.sort_by_key(|&i| self.pictures[i].poc); | ||
| 173 | + | ||
| 174 | + for (i, pic) in self.pictures.iter_mut().enumerate() { | ||
| 175 | + if !keep[i] { | ||
| 176 | + pic.mark = Mark::Unused; | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + // Dropping unreferenced, already-output pictures here is what returns | ||
| 180 | + // their surfaces to the pool; the indices in `rps` are recomputed after. | ||
| 181 | + let mut remap = vec![usize::MAX; self.pictures.len()]; | ||
| 182 | + let mut next = 0usize; | ||
| 183 | + for (i, pic) in self.pictures.iter().enumerate() { | ||
| 184 | + if pic.stored() { | ||
| 185 | + remap[i] = next; | ||
| 186 | + next += 1; | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + self.pictures.retain(|p| p.stored()); | ||
| 190 | + if missing_used { | ||
| 191 | + return Err(Error::Stream(ec_core::Error::corrupt( | ||
| 192 | + "HEVC reference picture set names a picture used for prediction that was never decoded", | ||
| 193 | + ))); | ||
| 194 | + } | ||
| 195 | + for list in [ | ||
| 196 | + &mut rps.st_curr_before, | ||
| 197 | + &mut rps.st_curr_after, | ||
| 198 | + &mut rps.lt_curr, | ||
| 199 | + ] { | ||
| 200 | + list.retain(|&i| remap[i] != usize::MAX); | ||
| 201 | + for entry in list.iter_mut() { | ||
| 202 | + *entry = remap[*entry]; | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | + Ok(rps) | ||
| 206 | + } | ||
| 207 | + /// The next picture to output (C.5.2.4), while the buffer holds more than | ||
| 208 | + /// its reordering or storage limit allows; `flush` outputs every one. | ||
| 209 | + pub(crate) fn next_output(&self, flush: bool) -> Option<usize> { | ||
| 210 | + let pending = self.pictures.iter().filter(|p| p.output).count(); | ||
| 211 | + let stored = self.pictures.iter().filter(|p| p.stored()).count(); | ||
| 212 | + if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering { | ||
| 213 | + return None; | ||
| 214 | + } | ||
| 215 | + self.pictures | ||
| 216 | + .iter() | ||
| 217 | + .enumerate() | ||
| 218 | + .filter(|(_, p)| p.output) | ||
| 219 | + .min_by_key(|(_, p)| p.poc) | ||
| 220 | + .map(|(i, _)| i) | ||
| 221 | + } | ||
| 222 | + | ||
| 223 | + /// Marks the picture at `idx` as output and drops it once it is not stored. | ||
| 224 | + pub(crate) fn released(&mut self, idx: usize) { | ||
| 225 | + self.pictures[idx].output = false; | ||
| 226 | + self.pictures.retain(|p| p.stored()); | ||
| 227 | + } | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +/// True unless the NAL type says sub-layer non-reference (`_N`, an even type | ||
| 231 | +/// below 16). | ||
| 232 | +pub(crate) fn is_reference_picture(nal_type: NalUnitType) -> bool { | ||
| 233 | + let code = nal_type.code(); | ||
| 234 | + code >= 16 || code % 2 == 1 | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +/// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1 | ||
| 238 | +/// excludes from the picture order count prediction. | ||
| 239 | +pub(crate) fn is_leading_picture(nal_type: NalUnitType) -> bool { | ||
| 240 | + (6..=9).contains(&nal_type.code()) | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for | ||
| 244 | +/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no | ||
| 245 | +/// `video_signal_type` at all. | ||
| 246 | +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 247 | +pub(crate) fn vui_colour_tags(sps: &Sps) -> Tags { | ||
| 248 | + let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else { | ||
| 249 | + return Tags::default(); | ||
| 250 | + }; | ||
| 251 | + let (_primaries, transfer, matrix) = vst | ||
| 252 | + .colour_description | ||
| 253 | + .map(|cd| { | ||
| 254 | + ( | ||
| 255 | + cd.colour_primaries, | ||
| 256 | + cd.transfer_characteristics, | ||
| 257 | + cd.matrix_coeffs, | ||
| 258 | + ) | ||
| 259 | + }) | ||
| 260 | + .unwrap_or((0, 0, 0)); | ||
| 261 | + Tags::from_codes( | ||
| 262 | + u64::from(matrix), | ||
| 263 | + u64::from(transfer), | ||
| 264 | + if vst.video_full_range_flag { 2 } else { 1 }, | ||
| 265 | + ) | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's | ||
| 269 | +/// `NoRaslOutputFlag` is 1 (8.1.3). | ||
| 270 | +pub(crate) fn is_rasl_picture(nal_type: NalUnitType) -> bool { | ||
| 271 | + matches!(nal_type.code(), 8 | 9) | ||
| 272 | +} | ||
| 273 | + | ||
| 274 | +/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1 | ||
| 275 | +/// (8.1.3), a broken-link splice point that never has a decodable RASL. | ||
| 276 | +pub(crate) fn is_bla_picture(nal_type: NalUnitType) -> bool { | ||
| 277 | + (16..=18).contains(&nal_type.code()) | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +/// `slice_pic_parameter_set_id`, readable without any parameter set. | ||
| 281 | +pub(crate) fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> { | ||
| 282 | + let mut r = ec_core::BitReader::new(rbsp); | ||
| 283 | + r.read_bit()?; // first_slice_segment_in_pic_flag | ||
| 284 | + if nal_type.is_irap() { | ||
| 285 | + r.read_bit()?; // no_output_of_prior_pics_flag | ||
| 286 | + } | ||
| 287 | + Ok(r.read_ue()?) | ||
| 288 | +} | ||
crates/ec-hw/src/hw.rsmodified+93 -19
| @@ -4,6 +4,7 @@ use crate::error::{Error, Result}; | |||
| 4 | use crate::picture::I420; | 4 | use crate::picture::I420; |
| 5 | use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode}; | 5 | use crate::types::{Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode}; |
| 6 | use crate::vkdec264::VkH264Decoder; | 6 | use crate::vkdec264::VkH264Decoder; |
| 7 | +use crate::vkdec265::VkH265Decoder; | ||
| 7 | 8 | ||
| 8 | #[cfg(target_os = "linux")] | 9 | #[cfg(target_os = "linux")] |
| 9 | use crate::dec::Decoder as VaDecoder; | 10 | use crate::dec::Decoder as VaDecoder; |
| @@ -57,7 +58,8 @@ pub fn capabilities() -> Vec<Capability> { | |||
| 57 | if let Some(gpu) = vk_gpu() { | 58 | if let Some(gpu) = vk_gpu() { |
| 58 | for caps in gpu.caps().into_iter().filter(|c| { | 59 | for caps in gpu.caps().into_iter().filter(|c| { |
| 59 | c.direction == ec_vk::Direction::Encode | 60 | c.direction == ec_vk::Direction::Encode |
| 60 | - || (c.direction == ec_vk::Direction::Decode && c.codec == ec_vk::Codec::H264) | 61 | + || (c.direction == ec_vk::Direction::Decode |
| 62 | + && matches!(c.codec, ec_vk::Codec::H264 | ec_vk::Codec::H265)) | ||
| 61 | }) { | 63 | }) { |
| 62 | let codec = match caps.codec { | 64 | let codec = match caps.codec { |
| 63 | ec_vk::Codec::H264 => Codec::H264, | 65 | ec_vk::Codec::H264 => Codec::H264, |
| @@ -264,6 +266,7 @@ enum EncInner { | |||
| 264 | /// A hardware encoder on whichever backend opened. | 266 | /// A hardware encoder on whichever backend opened. |
| 265 | pub struct HwEncoder { | 267 | pub struct HwEncoder { |
| 266 | inner: EncInner, | 268 | inner: EncInner, |
| 269 | + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 267 | size: (usize, usize), | 270 | size: (usize, usize), |
| 268 | } | 271 | } |
| 269 | 272 | ||
| @@ -417,41 +420,81 @@ fn open_va(config: EncoderConfig) -> Result<EncInner> { | |||
| 417 | )) | 420 | )) |
| 418 | } | 421 | } |
| 419 | 422 | ||
| 423 | +enum VkDecoder { | ||
| 424 | + H264(VkH264Decoder), | ||
| 425 | + H265(VkH265Decoder), | ||
| 426 | +} | ||
| 427 | + | ||
| 428 | +impl VkDecoder { | ||
| 429 | + fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 430 | + match self { | ||
| 431 | + VkDecoder::H264(d) => d.decode(data, timestamp), | ||
| 432 | + VkDecoder::H265(d) => d.decode(data, timestamp), | ||
| 433 | + } | ||
| 434 | + } | ||
| 435 | + | ||
| 436 | + fn next_frame(&mut self) -> Option<(i64, I420)> { | ||
| 437 | + match self { | ||
| 438 | + VkDecoder::H264(d) => d.next_frame(), | ||
| 439 | + VkDecoder::H265(d) => d.next_frame(), | ||
| 440 | + } | ||
| 441 | + } | ||
| 442 | + | ||
| 443 | + fn flush(&mut self) -> Result<()> { | ||
| 444 | + match self { | ||
| 445 | + VkDecoder::H264(d) => d.flush(), | ||
| 446 | + VkDecoder::H265(d) => d.flush(), | ||
| 447 | + } | ||
| 448 | + } | ||
| 449 | +} | ||
| 450 | + | ||
| 420 | enum DecInner { | 451 | enum DecInner { |
| 421 | - Vk(VkH264Decoder), | 452 | + Vk(VkDecoder), |
| 422 | #[cfg(target_os = "linux")] | 453 | #[cfg(target_os = "linux")] |
| 423 | Va(VaDecoder), | 454 | Va(VaDecoder), |
| 424 | } | 455 | } |
| 425 | 456 | ||
| 457 | +const REPLAY_LIMIT: usize = 64; | ||
| 458 | + | ||
| 426 | /// A hardware decoder on whichever backend opened. | 459 | /// A hardware decoder on whichever backend opened. |
| 427 | pub struct HwDecoder { | 460 | pub struct HwDecoder { |
| 428 | inner: DecInner, | 461 | inner: DecInner, |
| 462 | + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 463 | + codec: Codec, | ||
| 464 | + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | ||
| 465 | + replay: Option<Vec<(Vec<u8>, i64)>>, | ||
| 429 | } | 466 | } |
| 430 | 467 | ||
| 431 | impl HwDecoder { | 468 | impl HwDecoder { |
| 432 | - /// Open a decoder for `codec`. H.264 tries Vulkan Video first, then VA-API (Linux). | 469 | + /// Open a decoder for `codec`. H.264 and H.265 try Vulkan Video first, then VA-API (Linux). |
| 433 | pub fn open(codec: Codec) -> Result<HwDecoder> { | 470 | pub fn open(codec: Codec) -> Result<HwDecoder> { |
| 434 | let mut reasons = Vec::new(); | 471 | let mut reasons = Vec::new(); |
| 435 | - if matches!(codec, Codec::H264) { | 472 | + let vk = match codec { |
| 436 | - match VkH264Decoder::new() { | 473 | + Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), |
| 437 | - Ok(inner) => { | 474 | + Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), |
| 438 | - return Ok(HwDecoder { | 475 | + _ => Err(Error::unsupported("Vulkan Video decode", "H.264 and H.265 only")), |
| 439 | - inner: DecInner::Vk(inner), | 476 | + }; |
| 440 | - }); | 477 | + match vk { |
| 441 | - } | 478 | + Ok(inner) => { |
| 442 | - Err(e) => reasons.push(format!("Vk: {e}")), | 479 | + return Ok(HwDecoder { |
| 480 | + inner: DecInner::Vk(inner), | ||
| 481 | + codec, | ||
| 482 | + replay: Some(Vec::new()), | ||
| 483 | + }); | ||
| 484 | + } | ||
| 485 | + Err(e) if matches!(codec, Codec::H264 | Codec::H265) => { | ||
| 486 | + reasons.push(format!("Vk: {e}")); | ||
| 443 | } | 487 | } |
| 488 | + Err(_) => {} | ||
| 444 | } | 489 | } |
| 445 | #[cfg(target_os = "linux")] | 490 | #[cfg(target_os = "linux")] |
| 446 | { | 491 | { |
| 447 | - let va = (|| -> Result<VaDecoder> { | 492 | + match open_va_decoder(codec) { |
| 448 | - let display = ec_va::open()?; | ||
| 449 | - VaDecoder::new(&display, codec) | ||
| 450 | - })(); | ||
| 451 | - match va { | ||
| 452 | Ok(inner) => { | 493 | Ok(inner) => { |
| 453 | return Ok(HwDecoder { | 494 | return Ok(HwDecoder { |
| 454 | inner: DecInner::Va(inner), | 495 | inner: DecInner::Va(inner), |
| 496 | + codec, | ||
| 497 | + replay: None, | ||
| 455 | }); | 498 | }); |
| 456 | } | 499 | } |
| 457 | Err(e) => reasons.push(format!("Va: {e}")), | 500 | Err(e) => reasons.push(format!("Va: {e}")), |
| @@ -472,19 +515,44 @@ impl HwDecoder { | |||
| 472 | } | 515 | } |
| 473 | } | 516 | } |
| 474 | 517 | ||
| 475 | - /// Feed one access unit. | 518 | + /// Feed one access unit. A stream Vulkan refuses (e.g. 10-bit) before its first |
| 519 | + /// picture comes out moves to VA-API on Linux, replaying what was fed so far. | ||
| 476 | pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | 520 | pub fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { |
| 477 | - match &mut self.inner { | 521 | + let result = match &mut self.inner { |
| 478 | DecInner::Vk(d) => d.decode(data, timestamp), | 522 | DecInner::Vk(d) => d.decode(data, timestamp), |
| 479 | #[cfg(target_os = "linux")] | 523 | #[cfg(target_os = "linux")] |
| 480 | DecInner::Va(d) => d.decode(data, timestamp), | 524 | DecInner::Va(d) => d.decode(data, timestamp), |
| 525 | + }; | ||
| 526 | + if let Some(fed) = self.replay.as_mut() { | ||
| 527 | + fed.push((data.to_vec(), timestamp)); | ||
| 528 | + if fed.len() > REPLAY_LIMIT { | ||
| 529 | + self.replay = None; | ||
| 530 | + } | ||
| 531 | + } | ||
| 532 | + #[cfg(target_os = "linux")] | ||
| 533 | + if let Err(Error::Unsupported { .. }) = result | ||
| 534 | + && let Some(fed) = self.replay.take() | ||
| 535 | + && let Ok(mut va) = open_va_decoder(self.codec) | ||
| 536 | + { | ||
| 537 | + for (chunk, ts) in &fed { | ||
| 538 | + va.decode(chunk, *ts)?; | ||
| 539 | + } | ||
| 540 | + self.inner = DecInner::Va(va); | ||
| 541 | + return Ok(()); | ||
| 481 | } | 542 | } |
| 543 | + result | ||
| 482 | } | 544 | } |
| 483 | 545 | ||
| 484 | /// The next picture in display order, as 8-bit I420 with its timestamp. | 546 | /// The next picture in display order, as 8-bit I420 with its timestamp. |
| 485 | pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { | 547 | pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { |
| 486 | match &mut self.inner { | 548 | match &mut self.inner { |
| 487 | - DecInner::Vk(d) => Ok(d.next_frame()), | 549 | + DecInner::Vk(d) => { |
| 550 | + let frame = d.next_frame(); | ||
| 551 | + if frame.is_some() { | ||
| 552 | + self.replay = None; | ||
| 553 | + } | ||
| 554 | + Ok(frame) | ||
| 555 | + } | ||
| 488 | #[cfg(target_os = "linux")] | 556 | #[cfg(target_os = "linux")] |
| 489 | DecInner::Va(d) => match d.next_frame() { | 557 | DecInner::Va(d) => match d.next_frame() { |
| 490 | Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))), | 558 | Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))), |
| @@ -502,3 +570,9 @@ impl HwDecoder { | |||
| 502 | } | 570 | } |
| 503 | } | 571 | } |
| 504 | } | 572 | } |
| 573 | + | ||
| 574 | +#[cfg(target_os = "linux")] | ||
| 575 | +fn open_va_decoder(codec: Codec) -> Result<VaDecoder> { | ||
| 576 | + let display = ec_va::open()?; | ||
| 577 | + VaDecoder::new(&display, codec) | ||
| 578 | +} | ||
crates/ec-hw/src/lib.rsmodified+2 -0
| @@ -63,6 +63,7 @@ pub mod error; | |||
| 63 | pub(crate) mod dpb264; | 63 | pub(crate) mod dpb264; |
| 64 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | 64 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 65 | pub(crate) mod h264_common; | 65 | pub(crate) mod h264_common; |
| 66 | +pub(crate) mod hevc_dpb; | ||
| 66 | pub mod hw; | 67 | pub mod hw; |
| 67 | #[cfg(target_os = "linux")] | 68 | #[cfg(target_os = "linux")] |
| 68 | pub mod frame; | 69 | pub mod frame; |
| @@ -74,6 +75,7 @@ pub mod pool; | |||
| 74 | pub mod reset; | 75 | pub mod reset; |
| 75 | pub mod types; | 76 | pub mod types; |
| 76 | pub(crate) mod vkdec264; | 77 | pub(crate) mod vkdec264; |
| 78 | +pub(crate) mod vkdec265; | ||
| 77 | 79 | ||
| 78 | #[cfg(target_os = "linux")] | 80 | #[cfg(target_os = "linux")] |
| 79 | pub use dec::{Decoder, StreamInfo}; | 81 | pub use dec::{Decoder, StreamInfo}; |
crates/ec-hw/src/vkdec265.rsadded+540 -0
| @@ -0,0 +1,540 @@ | |||
| 1 | +//! H.265 decoding over Vulkan Video: the shared HEVC DPB over DPB slot indices. | ||
| 2 | + | ||
| 3 | +use std::collections::{HashMap, VecDeque}; | ||
| 4 | + | ||
| 5 | +use ec_h265_syntax::{ | ||
| 6 | + AnnexBNal, NalUnitType, Pps, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, | ||
| 7 | + split_annex_b, | ||
| 8 | +}; | ||
| 9 | +use ec_vk::{ | ||
| 10 | + H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265Pcm, H265Pps, H265ProfileTierLevel, | ||
| 11 | + H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, | ||
| 12 | +}; | ||
| 13 | + | ||
| 14 | +use crate::error::{Error, Result}; | ||
| 15 | +use crate::hevc_dpb::{ | ||
| 16 | + self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, | ||
| 17 | + peek_pps_id, | ||
| 18 | +}; | ||
| 19 | +use crate::picture::{I420, nv12_to_i420}; | ||
| 20 | + | ||
| 21 | +const MAX_SLOTS: u32 = 17; | ||
| 22 | + | ||
| 23 | +struct Session { | ||
| 24 | + h265: H265DecodeSession, | ||
| 25 | + max_width: u32, | ||
| 26 | + max_height: u32, | ||
| 27 | + slots: u32, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +struct Current { | ||
| 31 | + slot: u32, | ||
| 32 | + sps_id: u8, | ||
| 33 | + pps_id: u8, | ||
| 34 | + nal_type: NalUnitType, | ||
| 35 | + st_rps_bits: u32, | ||
| 36 | + short_term_ref_pic_set_sps: bool, | ||
| 37 | + poc: i32, | ||
| 38 | + timestamp: i64, | ||
| 39 | + output: bool, | ||
| 40 | + is_tid0_anchor: bool, | ||
| 41 | + st_curr_before: Vec<u32>, | ||
| 42 | + st_curr_after: Vec<u32>, | ||
| 43 | + lt_curr: Vec<u32>, | ||
| 44 | + slices: Vec<Vec<u8>>, | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// H.265 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. | ||
| 48 | +pub(crate) struct VkH265Decoder { | ||
| 49 | + gpu: ec_vk::Gpu, | ||
| 50 | + session: Option<Session>, | ||
| 51 | + params_dirty: bool, | ||
| 52 | + vps_map: Vec<Option<Vps>>, | ||
| 53 | + sps_map: Vec<Option<Sps>>, | ||
| 54 | + pps_map: Vec<Option<Pps>>, | ||
| 55 | + dpb: Dpb<u32>, | ||
| 56 | + outputs: HashMap<u32, I420>, | ||
| 57 | + current: Option<Current>, | ||
| 58 | + ready: VecDeque<(i64, I420)>, | ||
| 59 | + no_rasl_output: bool, | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +impl VkH265Decoder { | ||
| 63 | + pub(crate) fn new() -> Result<Self> { | ||
| 64 | + let gpu = crate::hw::vk_gpu() | ||
| 65 | + .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; | ||
| 66 | + Ok(VkH265Decoder { | ||
| 67 | + gpu, | ||
| 68 | + session: None, | ||
| 69 | + params_dirty: false, | ||
| 70 | + vps_map: vec![None; 16], | ||
| 71 | + sps_map: vec![None; 16], | ||
| 72 | + pps_map: vec![None; 64], | ||
| 73 | + dpb: Dpb::new(), | ||
| 74 | + outputs: HashMap::new(), | ||
| 75 | + current: None, | ||
| 76 | + ready: VecDeque::new(), | ||
| 77 | + no_rasl_output: false, | ||
| 78 | + }) | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | ||
| 82 | + for nal in split_annex_b(data) { | ||
| 83 | + match nal.header.nal_type { | ||
| 84 | + NalUnitType::Vps => { | ||
| 85 | + let vps = Vps::parse(&nal.rbsp())?; | ||
| 86 | + let id = usize::from(vps.id); | ||
| 87 | + if let Some(slot) = self.vps_map.get_mut(id) { | ||
| 88 | + self.params_dirty |= store(slot, vps); | ||
| 89 | + } | ||
| 90 | + } | ||
| 91 | + NalUnitType::Sps => { | ||
| 92 | + let sps = Sps::parse(&nal.rbsp())?; | ||
| 93 | + self.dpb.max_reorder = sps.max_num_reorder_pics as usize; | ||
| 94 | + self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering_minus1 as usize + 1; | ||
| 95 | + let id = sps.id as usize; | ||
| 96 | + if let Some(slot) = self.sps_map.get_mut(id) { | ||
| 97 | + self.params_dirty |= store(slot, sps); | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + NalUnitType::Pps => { | ||
| 101 | + let pps = Pps::parse(&nal.rbsp())?; | ||
| 102 | + let id = pps.id as usize; | ||
| 103 | + if let Some(slot) = self.pps_map.get_mut(id) { | ||
| 104 | + self.params_dirty |= store(slot, pps); | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | + t if t.is_vcl() => self.slice(&nal, timestamp)?, | ||
| 108 | + _ => {} | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + self.finish_picture() | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { | ||
| 115 | + self.ready.pop_front() | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + pub(crate) fn flush(&mut self) -> Result<()> { | ||
| 119 | + self.finish_picture()?; | ||
| 120 | + self.bump(true); | ||
| 121 | + Ok(()) | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + fn slice(&mut self, nal: &AnnexBNal, timestamp: i64) -> Result<()> { | ||
| 125 | + let rbsp = nal.rbsp(); | ||
| 126 | + let nal_type = nal.header.nal_type; | ||
| 127 | + let pps_id = peek_pps_id(&rbsp, nal_type)?; | ||
| 128 | + let Some(pps) = self.pps_map.get(pps_id as usize).and_then(|p| p.clone()) else { | ||
| 129 | + return Ok(()); | ||
| 130 | + }; | ||
| 131 | + let Some(sps) = self | ||
| 132 | + .sps_map | ||
| 133 | + .get(pps.sps_id as usize) | ||
| 134 | + .and_then(|s| s.clone()) | ||
| 135 | + else { | ||
| 136 | + return Ok(()); | ||
| 137 | + }; | ||
| 138 | + let (sh, pos) = SliceHeader::parse(&rbsp, &sps, &pps, nal_type)?; | ||
| 139 | + if sh.first_slice_segment_in_pic { | ||
| 140 | + self.finish_picture()?; | ||
| 141 | + if !(is_rasl_picture(nal_type) && self.no_rasl_output) { | ||
| 142 | + self.start_picture(&sps, &sh, pos.st_rps_bits, nal, timestamp)?; | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + if let Some(current) = self.current.as_mut() { | ||
| 146 | + let mut raw = nal.header.to_bytes().to_vec(); | ||
| 147 | + raw.extend_from_slice(nal.payload); | ||
| 148 | + current.slices.push(raw); | ||
| 149 | + } | ||
| 150 | + Ok(()) | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + fn start_picture( | ||
| 154 | + &mut self, | ||
| 155 | + sps: &Sps, | ||
| 156 | + sh: &SliceHeader, | ||
| 157 | + st_rps_bits: u32, | ||
| 158 | + nal: &AnnexBNal, | ||
| 159 | + timestamp: i64, | ||
| 160 | + ) -> Result<()> { | ||
| 161 | + let nal_type = nal.header.nal_type; | ||
| 162 | + self.ensure_session(sps)?; | ||
| 163 | + if self.params_dirty { | ||
| 164 | + self.set_parameters()?; | ||
| 165 | + } | ||
| 166 | + if nal_type.is_irap() { | ||
| 167 | + self.no_rasl_output = | ||
| 168 | + nal_type.is_idr() || is_bla_picture(nal_type) || !self.dpb.started; | ||
| 169 | + } | ||
| 170 | + let poc = self.dpb.picture_order_count(sps, sh, nal_type); | ||
| 171 | + let rps = self.dpb.apply_rps(sps, sh, nal_type, poc)?; | ||
| 172 | + let ids = |list: &[usize]| -> Vec<u32> { | ||
| 173 | + list.iter().map(|&i| self.dpb.pictures[i].surface).collect() | ||
| 174 | + }; | ||
| 175 | + let (st_curr_before, st_curr_after, lt_curr) = ( | ||
| 176 | + ids(&rps.st_curr_before), | ||
| 177 | + ids(&rps.st_curr_after), | ||
| 178 | + ids(&rps.lt_curr), | ||
| 179 | + ); | ||
| 180 | + if nal_type.is_irap() && (nal_type.is_idr() || sh.no_output_of_prior_pics) { | ||
| 181 | + self.bump(true); | ||
| 182 | + } | ||
| 183 | + let slot = self.free_slot()?; | ||
| 184 | + let is_reference = is_reference_picture(nal_type); | ||
| 185 | + self.current = Some(Current { | ||
| 186 | + slot, | ||
| 187 | + sps_id: sps.id as u8, | ||
| 188 | + pps_id: sh.pps_id as u8, | ||
| 189 | + nal_type, | ||
| 190 | + st_rps_bits, | ||
| 191 | + short_term_ref_pic_set_sps: sh.short_term_ref_pic_set_sps_flag, | ||
| 192 | + poc, | ||
| 193 | + timestamp, | ||
| 194 | + output: sh.pic_output_flag, | ||
| 195 | + is_tid0_anchor: nal.header.temporal_id == 0 | ||
| 196 | + && is_reference | ||
| 197 | + && !is_leading_picture(nal_type), | ||
| 198 | + st_curr_before, | ||
| 199 | + st_curr_after, | ||
| 200 | + lt_curr, | ||
| 201 | + slices: Vec::new(), | ||
| 202 | + }); | ||
| 203 | + Ok(()) | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + fn ensure_session(&mut self, sps: &Sps) -> Result<()> { | ||
| 207 | + if sps.chroma_format_idc != 1 | ||
| 208 | + || sps.bit_depth_luma_minus8 != 0 | ||
| 209 | + || sps.bit_depth_chroma_minus8 != 0 | ||
| 210 | + { | ||
| 211 | + return Err(Error::unsupported( | ||
| 212 | + "Vulkan H.265 decode", | ||
| 213 | + "only 8-bit 4:2:0", | ||
| 214 | + )); | ||
| 215 | + } | ||
| 216 | + let slots = (sps.max_dec_pic_buffering_minus1 + 2).min(MAX_SLOTS); | ||
| 217 | + let (w, h) = ( | ||
| 218 | + sps.pic_width_in_luma_samples, | ||
| 219 | + sps.pic_height_in_luma_samples, | ||
| 220 | + ); | ||
| 221 | + let (max_width, max_height, slots) = match &self.session { | ||
| 222 | + Some(s) if w <= s.max_width && h <= s.max_height && slots <= s.slots => return Ok(()), | ||
| 223 | + Some(s) => (w.max(s.max_width), h.max(s.max_height), slots.max(s.slots)), | ||
| 224 | + None => (w, h, slots), | ||
| 225 | + }; | ||
| 226 | + self.current = None; | ||
| 227 | + self.dpb.pictures.clear(); | ||
| 228 | + self.outputs.clear(); | ||
| 229 | + self.session = None; | ||
| 230 | + let h265 = H265DecodeSession::new( | ||
| 231 | + &self.gpu, | ||
| 232 | + &H265DecodeConfig { | ||
| 233 | + max_width, | ||
| 234 | + max_height, | ||
| 235 | + max_dpb_slots: slots, | ||
| 236 | + }, | ||
| 237 | + )?; | ||
| 238 | + self.session = Some(Session { | ||
| 239 | + h265, | ||
| 240 | + max_width, | ||
| 241 | + max_height, | ||
| 242 | + slots, | ||
| 243 | + }); | ||
| 244 | + self.params_dirty = true; | ||
| 245 | + Ok(()) | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + fn set_parameters(&mut self) -> Result<()> { | ||
| 249 | + let vps: Vec<H265Vps> = self.vps_map.iter().flatten().map(vk_vps).collect(); | ||
| 250 | + let sps: Vec<H265Sps> = self.sps_map.iter().flatten().map(vk_sps).collect(); | ||
| 251 | + let pps: Vec<H265Pps> = self | ||
| 252 | + .pps_map | ||
| 253 | + .iter() | ||
| 254 | + .flatten() | ||
| 255 | + .filter(|p| { | ||
| 256 | + self.sps_map | ||
| 257 | + .get(p.sps_id as usize) | ||
| 258 | + .is_some_and(Option::is_some) | ||
| 259 | + }) | ||
| 260 | + .map(vk_pps) | ||
| 261 | + .collect(); | ||
| 262 | + let session = self | ||
| 263 | + .session | ||
| 264 | + .as_mut() | ||
| 265 | + .ok_or_else(|| Error::config("H.265 parameters before any SPS"))?; | ||
| 266 | + session.h265.set_parameters(&vps, &sps, &pps)?; | ||
| 267 | + self.params_dirty = false; | ||
| 268 | + Ok(()) | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + fn free_slot(&self) -> Result<u32> { | ||
| 272 | + let session = self | ||
| 273 | + .session | ||
| 274 | + .as_ref() | ||
| 275 | + .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; | ||
| 276 | + (0..session.slots) | ||
| 277 | + .find(|slot| self.dpb.pictures.iter().all(|p| p.surface != *slot)) | ||
| 278 | + .ok_or_else(|| Error::config("H.265 Vulkan decode: every DPB slot is in use")) | ||
| 279 | + } | ||
| 280 | + | ||
| 281 | + fn finish_picture(&mut self) -> Result<()> { | ||
| 282 | + let Some(current) = self.current.take() else { | ||
| 283 | + return Ok(()); | ||
| 284 | + }; | ||
| 285 | + let Some(sps) = self | ||
| 286 | + .sps_map | ||
| 287 | + .get(usize::from(current.sps_id)) | ||
| 288 | + .and_then(|s| s.clone()) | ||
| 289 | + else { | ||
| 290 | + return Ok(()); | ||
| 291 | + }; | ||
| 292 | + let refs: Vec<H265RefSlot> = self | ||
| 293 | + .dpb | ||
| 294 | + .pictures | ||
| 295 | + .iter() | ||
| 296 | + .filter(|p| p.mark != Mark::Unused) | ||
| 297 | + .map(|p| H265RefSlot { | ||
| 298 | + slot: p.surface, | ||
| 299 | + poc: p.poc, | ||
| 300 | + long_term: p.mark == Mark::LongTerm, | ||
| 301 | + }) | ||
| 302 | + .collect(); | ||
| 303 | + let slices: Vec<&[u8]> = current.slices.iter().map(Vec::as_slice).collect(); | ||
| 304 | + let session = self | ||
| 305 | + .session | ||
| 306 | + .as_mut() | ||
| 307 | + .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; | ||
| 308 | + session.h265.decode(&H265DecodePicture { | ||
| 309 | + vps_id: sps.vps_id, | ||
| 310 | + sps_id: current.sps_id, | ||
| 311 | + pps_id: current.pps_id, | ||
| 312 | + irap: current.nal_type.is_irap(), | ||
| 313 | + idr: current.nal_type.is_idr(), | ||
| 314 | + reference: is_reference_picture(current.nal_type), | ||
| 315 | + poc: current.poc, | ||
| 316 | + setup_slot: current.slot, | ||
| 317 | + short_term_ref_pic_set_sps: current.short_term_ref_pic_set_sps, | ||
| 318 | + num_delta_pocs_of_ref_rps_idx: 0, | ||
| 319 | + st_rps_bits: current.st_rps_bits, | ||
| 320 | + st_curr_before: ¤t.st_curr_before, | ||
| 321 | + st_curr_after: ¤t.st_curr_after, | ||
| 322 | + lt_curr: ¤t.lt_curr, | ||
| 323 | + refs: &refs, | ||
| 324 | + slices: &slices, | ||
| 325 | + })?; | ||
| 326 | + let (y, uv) = session.h265.read_output( | ||
| 327 | + sps.pic_width_in_luma_samples, | ||
| 328 | + sps.pic_height_in_luma_samples, | ||
| 329 | + )?; | ||
| 330 | + if current.output { | ||
| 331 | + self.outputs.insert(current.slot, crop(&sps, &y, &uv)); | ||
| 332 | + } | ||
| 333 | + | ||
| 334 | + self.dpb.pictures.push(hevc_dpb::StoredPicture { | ||
| 335 | + surface: current.slot, | ||
| 336 | + poc: current.poc, | ||
| 337 | + timestamp: current.timestamp, | ||
| 338 | + mark: if is_reference_picture(current.nal_type) { | ||
| 339 | + Mark::ShortTerm | ||
| 340 | + } else { | ||
| 341 | + Mark::Unused | ||
| 342 | + }, | ||
| 343 | + output: current.output, | ||
| 344 | + }); | ||
| 345 | + if current.is_tid0_anchor { | ||
| 346 | + self.dpb.prev_tid0_poc = current.poc; | ||
| 347 | + } | ||
| 348 | + self.dpb.started = true; | ||
| 349 | + self.bump(false); | ||
| 350 | + Ok(()) | ||
| 351 | + } | ||
| 352 | + | ||
| 353 | + fn bump(&mut self, flush: bool) { | ||
| 354 | + while let Some(idx) = self.dpb.next_output(flush) { | ||
| 355 | + let pic = &self.dpb.pictures[idx]; | ||
| 356 | + if let Some(frame) = self.outputs.remove(&pic.surface) { | ||
| 357 | + self.ready.push_back((pic.timestamp, frame)); | ||
| 358 | + } | ||
| 359 | + self.dpb.released(idx); | ||
| 360 | + } | ||
| 361 | + } | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +fn store<T: PartialEq>(slot: &mut Option<T>, value: T) -> bool { | ||
| 365 | + if slot.as_ref() == Some(&value) { | ||
| 366 | + return false; | ||
| 367 | + } | ||
| 368 | + *slot = Some(value); | ||
| 369 | + true | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 { | ||
| 373 | + let (width, height) = sps.display_size(); | ||
| 374 | + let pitch = sps.pic_width_in_luma_samples as usize; | ||
| 375 | + let left = 2 * sps.conf_win.left as usize; | ||
| 376 | + let top = 2 * sps.conf_win.top as usize; | ||
| 377 | + nv12_to_i420( | ||
| 378 | + &y[top * pitch + left..], | ||
| 379 | + pitch, | ||
| 380 | + &uv[(top / 2) * pitch + left..], | ||
| 381 | + pitch, | ||
| 382 | + width as usize, | ||
| 383 | + height as usize, | ||
| 384 | + ) | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel { | ||
| 388 | + H265ProfileTierLevel { | ||
| 389 | + tier_flag: p.tier_flag, | ||
| 390 | + progressive_source: p.progressive_source, | ||
| 391 | + interlaced_source: p.interlaced_source, | ||
| 392 | + non_packed_constraint: p.non_packed_constraint, | ||
| 393 | + frame_only_constraint: p.frame_only_constraint, | ||
| 394 | + profile_idc: p.profile_idc, | ||
| 395 | + level_idc: p.level_idc, | ||
| 396 | + } | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +fn dpbm( | ||
| 400 | + max_latency_increase_plus1: u32, | ||
| 401 | + max_dec_pic_buffering_minus1: u32, | ||
| 402 | + reorder: u32, | ||
| 403 | +) -> ec_vk::H265DecPicBufMgr { | ||
| 404 | + ec_vk::H265DecPicBufMgr { | ||
| 405 | + max_latency_increase_plus1: [max_latency_increase_plus1; 7], | ||
| 406 | + max_dec_pic_buffering_minus1: [max_dec_pic_buffering_minus1 as u8; 7], | ||
| 407 | + max_num_reorder_pics: [reorder as u8; 7], | ||
| 408 | + } | ||
| 409 | +} | ||
| 410 | + | ||
| 411 | +fn lists(l: &ScalingList) -> H265ScalingLists { | ||
| 412 | + let c = &l.coefficients; | ||
| 413 | + H265ScalingLists { | ||
| 414 | + list_4x4: std::array::from_fn(|i| c[0][i][..16].try_into().unwrap()), | ||
| 415 | + list_8x8: std::array::from_fn(|i| c[1][i]), | ||
| 416 | + list_16x16: std::array::from_fn(|i| c[2][i]), | ||
| 417 | + list_32x32: std::array::from_fn(|i| c[3][3 * i]), | ||
| 418 | + dc_16x16: std::array::from_fn(|i| l.dc[2][i]), | ||
| 419 | + dc_32x32: std::array::from_fn(|i| l.dc[3][3 * i]), | ||
| 420 | + } | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +fn rps(r: &ShortTermRefPicSet) -> H265ShortTermRefPicSet { | ||
| 424 | + let (n0, n1) = (r.num_negative as usize, r.num_positive as usize); | ||
| 425 | + H265ShortTermRefPicSet { | ||
| 426 | + delta_poc_s0: r.delta_poc_s0[..n0].to_vec(), | ||
| 427 | + used_by_curr_pic_s0: r.used_s0[..n0].to_vec(), | ||
| 428 | + delta_poc_s1: r.delta_poc_s1[..n1].to_vec(), | ||
| 429 | + used_by_curr_pic_s1: r.used_s1[..n1].to_vec(), | ||
| 430 | + } | ||
| 431 | +} | ||
| 432 | + | ||
| 433 | +fn vk_vps(vps: &Vps) -> H265Vps { | ||
| 434 | + H265Vps { | ||
| 435 | + id: vps.id, | ||
| 436 | + max_sub_layers_minus1: 0, | ||
| 437 | + profile_tier_level: ptl(&vps.ptl), | ||
| 438 | + dec_pic_buf_mgr: dpbm( | ||
| 439 | + 0, | ||
| 440 | + vps.max_dec_pic_buffering_minus1, | ||
| 441 | + vps.max_num_reorder_pics, | ||
| 442 | + ), | ||
| 443 | + } | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +fn vk_sps(sps: &Sps) -> H265Sps { | ||
| 447 | + let c = &sps.conf_win; | ||
| 448 | + H265Sps { | ||
| 449 | + id: sps.id as u8, | ||
| 450 | + vps_id: sps.vps_id, | ||
| 451 | + max_sub_layers_minus1: 0, | ||
| 452 | + profile_tier_level: ptl(&sps.ptl), | ||
| 453 | + chroma_format_idc: sps.chroma_format_idc as u8, | ||
| 454 | + pic_width_in_luma_samples: sps.pic_width_in_luma_samples, | ||
| 455 | + pic_height_in_luma_samples: sps.pic_height_in_luma_samples, | ||
| 456 | + conformance_window: [c.left, c.right, c.top, c.bottom], | ||
| 457 | + bit_depth_luma_minus8: sps.bit_depth_luma_minus8 as u8, | ||
| 458 | + bit_depth_chroma_minus8: sps.bit_depth_chroma_minus8 as u8, | ||
| 459 | + log2_max_pic_order_cnt_lsb_minus4: sps.log2_max_poc_lsb_minus4 as u8, | ||
| 460 | + log2_min_luma_coding_block_size_minus3: sps.log2_min_cb_size_minus3 as u8, | ||
| 461 | + log2_diff_max_min_luma_coding_block_size: sps.log2_diff_max_min_cb_size as u8, | ||
| 462 | + log2_min_luma_transform_block_size_minus2: sps.log2_min_tb_size_minus2 as u8, | ||
| 463 | + log2_diff_max_min_luma_transform_block_size: sps.log2_diff_max_min_tb_size as u8, | ||
| 464 | + max_transform_hierarchy_depth_inter: sps.max_transform_hierarchy_depth_inter as u8, | ||
| 465 | + max_transform_hierarchy_depth_intra: sps.max_transform_hierarchy_depth_intra as u8, | ||
| 466 | + pcm: sps.pcm.map(|(a, b, c, d, e)| H265Pcm { | ||
| 467 | + bit_depth_luma_minus1: a as u8, | ||
| 468 | + bit_depth_chroma_minus1: b as u8, | ||
| 469 | + log2_min_luma_coding_block_size_minus3: c as u8, | ||
| 470 | + log2_diff_max_min_luma_coding_block_size: d as u8, | ||
| 471 | + loop_filter_disabled: e, | ||
| 472 | + }), | ||
| 473 | + dec_pic_buf_mgr: dpbm( | ||
| 474 | + sps.max_latency_increase_plus1, | ||
| 475 | + sps.max_dec_pic_buffering_minus1, | ||
| 476 | + sps.max_num_reorder_pics, | ||
| 477 | + ), | ||
| 478 | + scaling_list_enabled: sps.scaling_list_enabled, | ||
| 479 | + scaling_lists: sps.scaling_list.as_ref().map(lists), | ||
| 480 | + amp_enabled: sps.amp_enabled, | ||
| 481 | + sample_adaptive_offset_enabled: sps.sao_enabled, | ||
| 482 | + long_term_ref_pics_present: sps.long_term_ref_pics_present, | ||
| 483 | + long_term_ref_pics_sps: sps | ||
| 484 | + .long_term_ref_pics_sps | ||
| 485 | + .iter() | ||
| 486 | + .map( | ||
| 487 | + |&(poc_lsb, used_by_curr_pic)| ec_vk::H265LongTermRefPicSps { | ||
| 488 | + poc_lsb, | ||
| 489 | + used_by_curr_pic, | ||
| 490 | + }, | ||
| 491 | + ) | ||
| 492 | + .collect(), | ||
| 493 | + temporal_mvp_enabled: sps.temporal_mvp_enabled, | ||
| 494 | + strong_intra_smoothing_enabled: sps.strong_intra_smoothing, | ||
| 495 | + short_term_ref_pic_sets: sps.short_term_ref_pic_sets.iter().map(rps).collect(), | ||
| 496 | + } | ||
| 497 | +} | ||
| 498 | + | ||
| 499 | +fn vk_pps(pps: &Pps) -> H265Pps { | ||
| 500 | + H265Pps { | ||
| 501 | + id: pps.id as u8, | ||
| 502 | + sps_id: pps.sps_id as u8, | ||
| 503 | + dependent_slice_segments_enabled: pps.dependent_slice_segments_enabled, | ||
| 504 | + output_flag_present: pps.output_flag_present, | ||
| 505 | + num_extra_slice_header_bits: pps.num_extra_slice_header_bits as u8, | ||
| 506 | + sign_data_hiding_enabled: pps.sign_data_hiding_enabled, | ||
| 507 | + cabac_init_present: pps.cabac_init_present, | ||
| 508 | + num_ref_idx_l0_default_active_minus1: pps.num_ref_idx_l0_default_active_minus1 as u8, | ||
| 509 | + num_ref_idx_l1_default_active_minus1: pps.num_ref_idx_l1_default_active_minus1 as u8, | ||
| 510 | + init_qp_minus26: pps.init_qp_minus26 as i8, | ||
| 511 | + constrained_intra_pred: pps.constrained_intra_pred, | ||
| 512 | + transform_skip_enabled: pps.transform_skip_enabled, | ||
| 513 | + cu_qp_delta_enabled: pps.cu_qp_delta_enabled, | ||
| 514 | + diff_cu_qp_delta_depth: pps.diff_cu_qp_delta_depth as u8, | ||
| 515 | + cb_qp_offset: pps.cb_qp_offset as i8, | ||
| 516 | + cr_qp_offset: pps.cr_qp_offset as i8, | ||
| 517 | + slice_chroma_qp_offsets_present: pps.slice_chroma_qp_offsets_present, | ||
| 518 | + weighted_pred: pps.weighted_pred, | ||
| 519 | + weighted_bipred: pps.weighted_bipred, | ||
| 520 | + transquant_bypass_enabled: pps.transquant_bypass_enabled, | ||
| 521 | + tiles_enabled: pps.tiles_enabled, | ||
| 522 | + entropy_coding_sync_enabled: pps.entropy_coding_sync_enabled, | ||
| 523 | + num_tile_columns_minus1: pps.num_tile_columns_minus1 as u8, | ||
| 524 | + num_tile_rows_minus1: pps.num_tile_rows_minus1 as u8, | ||
| 525 | + uniform_spacing: pps.uniform_spacing, | ||
| 526 | + column_width_minus1: pps.column_width_minus1.iter().map(|&w| w as u16).collect(), | ||
| 527 | + row_height_minus1: pps.row_height_minus1.iter().map(|&h| h as u16).collect(), | ||
| 528 | + loop_filter_across_tiles_enabled: pps.loop_filter_across_tiles_enabled, | ||
| 529 | + loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, | ||
| 530 | + deblocking_filter_control_present: pps.deblocking_filter_control_present, | ||
| 531 | + deblocking_filter_override_enabled: pps.deblocking_filter_override_enabled, | ||
| 532 | + deblocking_filter_disabled: pps.deblocking_filter_disabled, | ||
| 533 | + beta_offset_div2: pps.beta_offset_div2 as i8, | ||
| 534 | + tc_offset_div2: pps.tc_offset_div2 as i8, | ||
| 535 | + scaling_lists: pps.scaling_list.as_ref().map(lists), | ||
| 536 | + lists_modification_present: pps.lists_modification_present, | ||
| 537 | + log2_parallel_merge_level_minus2: pps.log2_parallel_merge_level_minus2 as u8, | ||
| 538 | + slice_segment_header_extension_present: pps.slice_segment_header_extension_present, | ||
| 539 | + } | ||
| 540 | +} | ||