vk-video-ffi, ec-hw: VP9 decode over Vulkan Video
Browse files at this commit21341285a63609503a8cde2fe0673690696096ffParent: abe484f12 changed files +941 -27
- crates/ec-hw/examples/hw_decode.rs +52 -1
- crates/ec-hw/examples/hw_decode_rgb.rs +3 -1
- crates/ec-hw/src/dec/av1.rs +1 -1
- crates/ec-hw/src/dec/vp9.rs +11 -13
- crates/ec-hw/src/hw.rs +9 -7
- crates/ec-hw/src/lib.rs +2 -1
- crates/ec-hw/src/av1_refs.rs → crates/ec-hw/src/ref_slots.rs +1 -1
- crates/ec-hw/src/vkdec_av1.rs +1 -1
- crates/ec-hw/src/vkdec_vp9.rs +345 -0
- crates/ec-vk/src/lib.rs +3 -1
- shims/vk-video-ffi/src/lib.rs +5 -0
- shims/vk-video-ffi/src/vp9_decode.rs +508 -0
crates/ec-hw/examples/hw_decode.rsmodified+52 -1
| @@ -1,4 +1,4 @@ | ||
| 1 | -//! Decodes ffmpeg libx264, libx265, SVT-AV1 and libaom AV1 streams, plus our own Vulkan AV1 encoder's, through HwDecoder and compares luma with ffmpeg's decode, frame by frame. | |
| 1 | +//! Decodes ffmpeg libx264, libx265, libvpx VP9, SVT-AV1 and libaom AV1 streams, plus our own Vulkan AV1 encoder's, through HwDecoder and compares luma with ffmpeg's decode, frame by frame. | |
| 2 | 2 | //! The 10-bit H.265 and AV1 streams run on Vulkan and are compared with the VA-API decode of the same stream. |
| 3 | 3 | //! |
| 4 | 4 | //! ```text |
| @@ -106,6 +106,57 @@ fn main() { | ||
| 106 | 106 | } |
| 107 | 107 | ten_bit(&dir); |
| 108 | 108 | own_av1(&dir); |
| 109 | + vp9_cases(&dir); | |
| 110 | +} | |
| 111 | + | |
| 112 | +fn vp9_cases(dir: &Path) { | |
| 113 | + vp9_case(dir, "vp9_640", "640x360", 60, &[], "yuv420p", 8); | |
| 114 | + vp9_case( | |
| 115 | + dir, | |
| 116 | + "vp9_720", | |
| 117 | + "1280x720", | |
| 118 | + 30, | |
| 119 | + &["-lag-in-frames", "0", "-deadline", "realtime"], | |
| 120 | + "yuv420p", | |
| 121 | + 8, | |
| 122 | + ); | |
| 123 | + vp9_case(dir, "vp9_10", "640x360", 30, &["-profile:v", "2"], "yuv420p10le", 10); | |
| 124 | +} | |
| 125 | + | |
| 126 | +fn vp9_case(dir: &Path, name: &str, size: &str, frames: usize, encoder: &[&str], pix_fmt: &str, bits: u32) { | |
| 127 | + let stream = dir.join(format!("{name}.ivf")); | |
| 128 | + let reference = dir.join(format!("{name}.yuv")); | |
| 129 | + let source = format!("testsrc2=size={size}:rate=30"); | |
| 130 | + let frames = frames.to_string(); | |
| 131 | + let stream_arg = stream.to_str().expect("utf-8 path"); | |
| 132 | + let reference_arg = reference.to_str().expect("utf-8 path"); | |
| 133 | + let mut encode = vec!["-f", "lavfi", "-i", source.as_str(), "-frames:v", frames.as_str(), "-c:v", "libvpx-vp9", "-pix_fmt", pix_fmt]; | |
| 134 | + encode.extend_from_slice(encoder); | |
| 135 | + encode.extend_from_slice(&["-f", "ivf", stream_arg]); | |
| 136 | + ffmpeg(&encode); | |
| 137 | + ffmpeg(&["-i", stream_arg, "-f", "rawvideo", "-pix_fmt", pix_fmt, reference_arg]); | |
| 138 | + | |
| 139 | + let data = fs::read(&stream).expect("read VP9 stream"); | |
| 140 | + let mut decoder = HwDecoder::open(Codec::Vp9).expect("open decoder"); | |
| 141 | + let backend = decoder.backend(); | |
| 142 | + assert_eq!(backend, Backend::Vk, "{name}: VP9 must decode on Vulkan"); | |
| 143 | + let mut decoded: Vec<I420> = Vec::new(); | |
| 144 | + for (pts, unit) in ivf_units(&data).into_iter().enumerate() { | |
| 145 | + decoder.decode(unit, pts as i64).expect("decode"); | |
| 146 | + drain(&mut decoder, &mut decoded); | |
| 147 | + } | |
| 148 | + decoder.flush().expect("flush"); | |
| 149 | + drain(&mut decoder, &mut decoded); | |
| 150 | + | |
| 151 | + let raw = fs::read(&reference).expect("read reference"); | |
| 152 | + let raw: Vec<u8> = if bits == 10 { | |
| 153 | + raw.chunks_exact(2) | |
| 154 | + .map(|p| (u16::from_le_bytes([p[0], p[1]]) >> 2) as u8) | |
| 155 | + .collect() | |
| 156 | + } else { | |
| 157 | + raw | |
| 158 | + }; | |
| 159 | + compare(name, Codec::Vp9, backend, dims(size), &decoded, &raw); | |
| 109 | 160 | } |
| 110 | 161 | |
| 111 | 162 | fn ten_bit(dir: &Path) { |
crates/ec-hw/examples/hw_decode_rgb.rsmodified+3 -1
| @@ -18,13 +18,15 @@ const FILES: &[(&str, Codec)] = &[ | ||
| 18 | 18 | ("h265idr720.hevc", Codec::H265), |
| 19 | 19 | ("av1aom720.ivf", Codec::Av1), |
| 20 | 20 | ("ten.hevc", Codec::H265), |
| 21 | + ("vp9_640.ivf", Codec::Vp9), | |
| 22 | + ("vp9_720.ivf", Codec::Vp9), | |
| 21 | 23 | ]; |
| 22 | 24 | |
| 23 | 25 | fn main() { |
| 24 | 26 | let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); |
| 25 | 27 | for &(name, codec) in FILES { |
| 26 | 28 | let data = fs::read(dir.join(name)).expect("read stream"); |
| 27 | - let units = if codec == Codec::Av1 { | |
| 29 | + let units = if matches!(codec, Codec::Av1 | Codec::Vp9) { | |
| 28 | 30 | ivf_units(&data) |
| 29 | 31 | } else { |
| 30 | 32 | vec![data.as_slice()] |
crates/ec-hw/src/dec/av1.rsmodified+1 -1
| @@ -11,7 +11,7 @@ use ec_va::va::BufferType; | ||
| 11 | 11 | use ec_va::{Display, picture}; |
| 12 | 12 | |
| 13 | 13 | use super::{ReadyFrames, Session, StreamInfo}; |
| 14 | -use crate::av1_refs::RefSlots; | |
| 14 | +use crate::ref_slots::RefSlots; | |
| 15 | 15 | use crate::error::{Error, Result}; |
| 16 | 16 | use crate::frame::Frame; |
| 17 | 17 | use crate::params::av1::{ |
crates/ec-hw/src/dec/vp9.rsmodified+11 -13
| @@ -18,6 +18,7 @@ use crate::params::vp9::{ | ||
| 18 | 18 | SliceParameterBufferVP9, |
| 19 | 19 | }; |
| 20 | 20 | use crate::pool::PooledSurface; |
| 21 | +use crate::ref_slots::RefSlots; | |
| 21 | 22 | |
| 22 | 23 | /// Reference slots plus the picture being decoded plus caller-held frames. |
| 23 | 24 | const EXTRA_SURFACES: usize = 6; |
| @@ -28,7 +29,7 @@ pub struct Vp9Decoder { | ||
| 28 | 29 | parser: Vp9Parser, |
| 29 | 30 | session: Option<Session>, |
| 30 | 31 | /// The eight reference slots, as surfaces. |
| 31 | - refs: [Option<Rc<PooledSurface>>; NUM_REF_FRAMES], | |
| 32 | + refs: RefSlots<Rc<PooledSurface>>, | |
| 32 | 33 | ready: ReadyFrames, |
| 33 | 34 | } |
| 34 | 35 | |
| @@ -39,7 +40,7 @@ impl Vp9Decoder { | ||
| 39 | 40 | display: Rc::clone(display), |
| 40 | 41 | parser: Vp9Parser::new(), |
| 41 | 42 | session: None, |
| 42 | - refs: [const { None }; NUM_REF_FRAMES], | |
| 43 | + refs: RefSlots::new(), | |
| 43 | 44 | ready: ReadyFrames::default(), |
| 44 | 45 | } |
| 45 | 46 | } |
| @@ -70,7 +71,7 @@ impl Vp9Decoder { | ||
| 70 | 71 | /// Drop reference state after a seek. |
| 71 | 72 | pub fn reset(&mut self) { |
| 72 | 73 | self.parser = Vp9Parser::new(); |
| 73 | - self.refs = [const { None }; NUM_REF_FRAMES]; | |
| 74 | + self.refs = RefSlots::new(); | |
| 74 | 75 | self.ready.clear(); |
| 75 | 76 | } |
| 76 | 77 | |
| @@ -87,7 +88,7 @@ impl Vp9Decoder { | ||
| 87 | 88 | // slot as well, so the surface is shared, not moved. |
| 88 | 89 | let slot = usize::from(header.frame_to_show_map_idx); |
| 89 | 90 | let (Some(surface), Some(session)) = ( |
| 90 | - self.refs.get(slot).and_then(|s| s.clone()), | |
| 91 | + self.refs.get(slot).cloned(), | |
| 91 | 92 | self.session.as_ref(), |
| 92 | 93 | ) else { |
| 93 | 94 | return Err(Error::Stream(ec_core::Error::corrupt( |
| @@ -112,7 +113,7 @@ impl Vp9Decoder { | ||
| 112 | 113 | // and the driver would read VA_INVALID_SURFACE: refuse the broken GOP. |
| 113 | 114 | if header.frame_type == FrameType::Inter { |
| 114 | 115 | for (ref_index, &slot) in header.ref_frame_idx[..3].iter().enumerate() { |
| 115 | - if self.refs[usize::from(slot)].is_none() { | |
| 116 | + if self.refs.get(usize::from(slot)).is_none() { | |
| 116 | 117 | return Err(Error::Stream(ec_core::Error::corrupt(format!( |
| 117 | 118 | "VP9 inter frame names reference slot {slot} (ref {ref_index}), \ |
| 118 | 119 | which no decoded frame has filled" |
| @@ -140,11 +141,8 @@ impl Vp9Decoder { | ||
| 140 | 141 | |
| 141 | 142 | // Reference slot refresh (spec 8.10), after the submission that used |
| 142 | 143 | // the old contents. |
| 143 | - for slot in 0..NUM_REF_FRAMES { | |
| 144 | - if header.refresh_frame_flags & (1 << slot) != 0 { | |
| 145 | - self.refs[slot] = Some(Rc::clone(&surface)); | |
| 146 | - } | |
| 147 | - } | |
| 144 | + self.refs | |
| 145 | + .refresh(header.refresh_frame_flags, Some(Rc::clone(&surface))); | |
| 148 | 146 | |
| 149 | 147 | if header.show_frame { |
| 150 | 148 | self.ready.push(Frame::new( |
| @@ -184,7 +182,7 @@ impl Vp9Decoder { | ||
| 184 | 182 | { |
| 185 | 183 | return Ok(()); |
| 186 | 184 | } |
| 187 | - self.refs = [const { None }; NUM_REF_FRAMES]; | |
| 185 | + self.refs = RefSlots::new(); | |
| 188 | 186 | self.session = Some(Session::new( |
| 189 | 187 | &self.display, |
| 190 | 188 | profile, |
| @@ -249,8 +247,8 @@ fn picture_parameters( | ||
| 249 | 247 | } |
| 250 | 248 | |
| 251 | 249 | /// The surface id in each reference slot, `None` for an empty one. |
| 252 | -fn slot_ids(refs: &[Option<Rc<PooledSurface>>; NUM_REF_FRAMES]) -> [Option<u32>; NUM_REF_FRAMES] { | |
| 253 | - refs.each_ref().map(|s| s.as_ref().map(|s| s.id())) | |
| 250 | +fn slot_ids(refs: &RefSlots<Rc<PooledSurface>>) -> [Option<u32>; NUM_REF_FRAMES] { | |
| 251 | + std::array::from_fn(|slot| refs.get(slot).map(|s| s.id())) | |
| 254 | 252 | } |
| 255 | 253 | |
| 256 | 254 | /// Feeds a run of VP9 chunks (each a frame or a superframe, see |
crates/ec-hw/src/hw.rsmodified+9 -7
| @@ -16,6 +16,7 @@ use crate::types::{ | ||
| 16 | 16 | Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings, |
| 17 | 17 | }; |
| 18 | 18 | use crate::vkdec_av1::VkAv1Decoder; |
| 19 | +use crate::vkdec_vp9::VkVp9Decoder; | |
| 19 | 20 | use crate::vkdec264::VkH264Decoder; |
| 20 | 21 | use crate::vkdec265::VkH265Decoder; |
| 21 | 22 | |
| @@ -74,7 +75,7 @@ pub fn capabilities() -> Vec<Capability> { | ||
| 74 | 75 | || (c.direction == ec_vk::Direction::Decode |
| 75 | 76 | && matches!( |
| 76 | 77 | c.codec, |
| 77 | - ec_vk::Codec::H264 | ec_vk::Codec::H265 | ec_vk::Codec::Av1 | |
| 78 | + ec_vk::Codec::H264 | ec_vk::Codec::H265 | ec_vk::Codec::Av1 | ec_vk::Codec::Vp9 | |
| 78 | 79 | )) |
| 79 | 80 | }) { |
| 80 | 81 | let codec = match caps.codec { |
| @@ -540,6 +541,7 @@ enum VkDecoder { | ||
| 540 | 541 | H264(VkH264Decoder), |
| 541 | 542 | H265(VkH265Decoder), |
| 542 | 543 | Av1(VkAv1Decoder), |
| 544 | + Vp9(VkVp9Decoder), | |
| 543 | 545 | } |
| 544 | 546 | |
| 545 | 547 | impl VkDecoder { |
| @@ -548,6 +550,7 @@ impl VkDecoder { | ||
| 548 | 550 | VkDecoder::H264(d) => d.decode(data, timestamp), |
| 549 | 551 | VkDecoder::H265(d) => d.decode(data, timestamp), |
| 550 | 552 | VkDecoder::Av1(d) => d.decode(data, timestamp), |
| 553 | + VkDecoder::Vp9(d) => d.decode(data, timestamp), | |
| 551 | 554 | } |
| 552 | 555 | } |
| 553 | 556 | |
| @@ -556,6 +559,7 @@ impl VkDecoder { | ||
| 556 | 559 | VkDecoder::H264(d) => d.next_frame(), |
| 557 | 560 | VkDecoder::H265(d) => d.next_frame(), |
| 558 | 561 | VkDecoder::Av1(d) => d.next_frame(), |
| 562 | + VkDecoder::Vp9(d) => d.next_frame(), | |
| 559 | 563 | } |
| 560 | 564 | } |
| 561 | 565 | |
| @@ -564,6 +568,7 @@ impl VkDecoder { | ||
| 564 | 568 | VkDecoder::H264(d) => d.flush(), |
| 565 | 569 | VkDecoder::H265(d) => d.flush(), |
| 566 | 570 | VkDecoder::Av1(d) => d.flush(), |
| 571 | + VkDecoder::Vp9(d) => d.flush(), | |
| 567 | 572 | } |
| 568 | 573 | } |
| 569 | 574 | } |
| @@ -602,7 +607,7 @@ pub struct HwDecoder { | ||
| 602 | 607 | } |
| 603 | 608 | |
| 604 | 609 | impl HwDecoder { |
| 605 | - /// Open a decoder for `codec` that hands out I420. H.264, H.265 and AV1 try Vulkan Video first, then VA-API (Linux). | |
| 610 | + /// Open a decoder for `codec` that hands out I420. Every codec tries Vulkan Video first, then VA-API (Linux). | |
| 606 | 611 | pub fn open(codec: Codec) -> Result<HwDecoder> { |
| 607 | 612 | HwDecoder::open_mode(codec, Mode::I420) |
| 608 | 613 | } |
| @@ -622,7 +627,7 @@ impl HwDecoder { | ||
| 622 | 627 | Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264), |
| 623 | 628 | Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265), |
| 624 | 629 | Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1), |
| 625 | - _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), | |
| 630 | + Codec::Vp9 => VkVp9Decoder::new(rgb).map(VkDecoder::Vp9), | |
| 626 | 631 | }; |
| 627 | 632 | match vk { |
| 628 | 633 | Ok(inner) => { |
| @@ -633,10 +638,7 @@ impl HwDecoder { | ||
| 633 | 638 | replay: Some(Vec::new()), |
| 634 | 639 | }); |
| 635 | 640 | } |
| 636 | - Err(e) if matches!(codec, Codec::H264 | Codec::H265 | Codec::Av1) => { | |
| 637 | - reasons.push(format!("Vk: {e}")); | |
| 638 | - } | |
| 639 | - Err(_) => {} | |
| 641 | + Err(e) => reasons.push(format!("Vk: {e}")), | |
| 640 | 642 | } |
| 641 | 643 | #[cfg(target_os = "linux")] |
| 642 | 644 | { |
crates/ec-hw/src/lib.rsmodified+2 -1
| @@ -63,7 +63,8 @@ pub mod error; | ||
| 63 | 63 | pub(crate) mod dpb264; |
| 64 | 64 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 65 | 65 | pub(crate) mod h264_common; |
| 66 | -pub(crate) mod av1_refs; | |
| 66 | +pub(crate) mod ref_slots; | |
| 67 | +pub(crate) mod vkdec_vp9; | |
| 67 | 68 | pub(crate) mod hevc_dpb; |
| 68 | 69 | pub mod hw; |
| 69 | 70 | #[cfg(target_os = "linux")] |
crates/ec-hw/src/av1_refs.rs → crates/ec-hw/src/ref_slots.rsrenamed+1 -1
| @@ -1,4 +1,4 @@ | ||
| 1 | -//! The eight AV1 reference slots (spec 7.20), shared by the VA-API and Vulkan decoders. | |
| 1 | +//! The eight reference slots (AV1 spec 7.20, VP9 spec 8.10), shared by the VA-API and Vulkan decoders. | |
| 2 | 2 | |
| 3 | 3 | use ec_av1_syntax::NUM_REF_FRAMES; |
| 4 | 4 |
crates/ec-hw/src/vkdec_av1.rsmodified+1 -1
| @@ -15,7 +15,7 @@ use ec_vk::{ | ||
| 15 | 15 | Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, |
| 16 | 16 | }; |
| 17 | 17 | |
| 18 | -use crate::av1_refs::RefSlots; | |
| 18 | +use crate::ref_slots::RefSlots; | |
| 19 | 19 | use crate::error::{Error, Result}; |
| 20 | 20 | use ec_core::color::{ColorDescription, Tags}; |
| 21 | 21 |
crates/ec-hw/src/vkdec_vp9.rsadded+345 -0
| @@ -0,0 +1,345 @@ | ||
| 1 | +//! VP9 decoding over Vulkan Video: the reference slots over DPB slot indices. | |
| 2 | + | |
| 3 | +use std::collections::VecDeque; | |
| 4 | +use std::rc::Rc; | |
| 5 | + | |
| 6 | +use ec_core::color::{ColorDescription, Tags}; | |
| 7 | +use ec_vk::{ | |
| 8 | + Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, | |
| 9 | + Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, | |
| 10 | +}; | |
| 11 | +use ec_vp9_syntax::{ | |
| 12 | + ColorSpace, FrameHeader, FrameType, InterpolationFilter, NUM_REF_FRAMES, REFS_PER_FRAME, | |
| 13 | + Vp9Parser, superframe, | |
| 14 | +}; | |
| 15 | + | |
| 16 | +use crate::error::{Error, Result}; | |
| 17 | +use crate::hw::{RgbOrder, RgbOutput}; | |
| 18 | +use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb}; | |
| 19 | +use crate::ref_slots::RefSlots; | |
| 20 | + | |
| 21 | +const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; | |
| 22 | + | |
| 23 | +struct Session { | |
| 24 | + vp9: Vp9DecodeSession, | |
| 25 | + bit_depth: u8, | |
| 26 | + width: u32, | |
| 27 | + height: u32, | |
| 28 | +} | |
| 29 | + | |
| 30 | +struct Reference { | |
| 31 | + slot: u32, | |
| 32 | + picture: Decoded, | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// What the next frame needs from the one before it (spec 7.2, UsePrevFrameMvs). | |
| 36 | +#[derive(Clone, Copy)] | |
| 37 | +struct PreviousFrame { | |
| 38 | + width: u32, | |
| 39 | + height: u32, | |
| 40 | + show_frame: bool, | |
| 41 | + intra_only: bool, | |
| 42 | +} | |
| 43 | + | |
| 44 | +/// VP9 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. | |
| 45 | +pub(crate) struct VkVp9Decoder { | |
| 46 | + gpu: ec_vk::Gpu, | |
| 47 | + parser: Vp9Parser, | |
| 48 | + session: Option<Session>, | |
| 49 | + refs: RefSlots<Rc<Reference>>, | |
| 50 | + previous: Option<PreviousFrame>, | |
| 51 | + ready: VecDeque<(i64, Decoded)>, | |
| 52 | + rgb: Option<RgbOutput>, | |
| 53 | +} | |
| 54 | + | |
| 55 | +impl VkVp9Decoder { | |
| 56 | + pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> { | |
| 57 | + let gpu = crate::hw::vk_gpu() | |
| 58 | + .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?; | |
| 59 | + Ok(VkVp9Decoder { | |
| 60 | + gpu, | |
| 61 | + parser: Vp9Parser::new(), | |
| 62 | + session: None, | |
| 63 | + refs: RefSlots::new(), | |
| 64 | + previous: None, | |
| 65 | + ready: VecDeque::new(), | |
| 66 | + rgb, | |
| 67 | + }) | |
| 68 | + } | |
| 69 | + | |
| 70 | + pub(crate) fn decode(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | |
| 71 | + if data.is_empty() { | |
| 72 | + return Ok(()); | |
| 73 | + } | |
| 74 | + for frame in superframe::split(data)? { | |
| 75 | + self.decode_frame(frame, timestamp)?; | |
| 76 | + } | |
| 77 | + Ok(()) | |
| 78 | + } | |
| 79 | + | |
| 80 | + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { | |
| 81 | + self.ready.pop_front() | |
| 82 | + } | |
| 83 | + | |
| 84 | + pub(crate) fn flush(&mut self) -> Result<()> { | |
| 85 | + Ok(()) | |
| 86 | + } | |
| 87 | + | |
| 88 | + fn decode_frame(&mut self, data: &[u8], timestamp: i64) -> Result<()> { | |
| 89 | + let header = self.parser.parse_frame(data)?; | |
| 90 | + if header.show_existing_frame { | |
| 91 | + let reference = self | |
| 92 | + .refs | |
| 93 | + .get(usize::from(header.frame_to_show_map_idx)) | |
| 94 | + .cloned() | |
| 95 | + .ok_or_else(|| { | |
| 96 | + Error::Stream(ec_core::Error::corrupt( | |
| 97 | + "VP9 show_existing_frame names an empty reference slot", | |
| 98 | + )) | |
| 99 | + })?; | |
| 100 | + self.ready.push_back((timestamp, reference.picture.clone())); | |
| 101 | + if let Some(previous) = self.previous.as_mut() { | |
| 102 | + previous.show_frame = true; | |
| 103 | + } | |
| 104 | + return Ok(()); | |
| 105 | + } | |
| 106 | + check_supported(&header)?; | |
| 107 | + self.ensure_session(&header)?; | |
| 108 | + | |
| 109 | + let mut ref_name_slot = [-1i32; REFS_PER_FRAME]; | |
| 110 | + let mut refs: Vec<u32> = Vec::new(); | |
| 111 | + if !header.frame_is_intra { | |
| 112 | + for (name, &index) in header.ref_frame_idx.iter().enumerate() { | |
| 113 | + let reference = self.refs.get(usize::from(index)).ok_or_else(|| { | |
| 114 | + Error::Stream(ec_core::Error::corrupt(format!( | |
| 115 | + "VP9 inter frame names reference slot {index} (ref {name}), \ | |
| 116 | + which no decoded frame has filled" | |
| 117 | + ))) | |
| 118 | + })?; | |
| 119 | + ref_name_slot[name] = reference.slot as i32; | |
| 120 | + if !refs.contains(&reference.slot) { | |
| 121 | + refs.push(reference.slot); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + } | |
| 125 | + | |
| 126 | + let setup_slot = self.free_slot()?; | |
| 127 | + let use_prev_frame_mvs = !header.error_resilient_mode | |
| 128 | + && self.previous.is_some_and(|p| { | |
| 129 | + p.width == header.width | |
| 130 | + && p.height == header.height | |
| 131 | + && p.show_frame | |
| 132 | + && !p.intra_only | |
| 133 | + }); | |
| 134 | + let frame = frame_header(&header, use_prev_frame_mvs); | |
| 135 | + let picture = Vp9DecodePicture { | |
| 136 | + header: &frame, | |
| 137 | + setup_slot, | |
| 138 | + ref_name_slot, | |
| 139 | + refs: &refs, | |
| 140 | + data, | |
| 141 | + }; | |
| 142 | + let session = self | |
| 143 | + .session | |
| 144 | + .as_mut() | |
| 145 | + .ok_or_else(|| Error::config("VP9 picture before any session"))?; | |
| 146 | + session.vp9.decode(&picture)?; | |
| 147 | + self.previous = Some(PreviousFrame { | |
| 148 | + width: header.width, | |
| 149 | + height: header.height, | |
| 150 | + show_frame: header.show_frame, | |
| 151 | + intra_only: header.intra_only, | |
| 152 | + }); | |
| 153 | + | |
| 154 | + if !(header.show_frame || header.refresh_frame_flags != 0) { | |
| 155 | + return Ok(()); | |
| 156 | + } | |
| 157 | + let (width, height) = (header.width, header.height); | |
| 158 | + let decoded = match self.rgb { | |
| 159 | + None => { | |
| 160 | + let (y, uv) = session.vp9.read_output(width, height)?; | |
| 161 | + Decoded::I420(semi_planar_to_i420( | |
| 162 | + session.bit_depth, | |
| 163 | + &y, | |
| 164 | + &uv, | |
| 165 | + width as usize, | |
| 166 | + (0, 0), | |
| 167 | + (width, height), | |
| 168 | + )?) | |
| 169 | + } | |
| 170 | + Some(rgb) => { | |
| 171 | + let codes = Tags::from_codes( | |
| 172 | + u64::from(header.color_space.h273().map_or(2, |c| c.2)), | |
| 173 | + 0, | |
| 174 | + 0, | |
| 175 | + ); | |
| 176 | + let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; | |
| 177 | + let (w, h) = rgb_size(width, height, rgb.max_width); | |
| 178 | + let data = session.vp9.read_output_rgb( | |
| 179 | + (0, 0, width, height), | |
| 180 | + (w, h), | |
| 181 | + rgb.order == RgbOrder::Bgra, | |
| 182 | + yuv_to_rgb(matrix).words(), | |
| 183 | + )?; | |
| 184 | + Decoded::Rgb(RgbPicture::new(data, w, h)) | |
| 185 | + } | |
| 186 | + }; | |
| 187 | + if header.show_frame { | |
| 188 | + self.ready.push_back((timestamp, decoded.clone())); | |
| 189 | + } | |
| 190 | + if header.refresh_frame_flags != 0 { | |
| 191 | + let reference = Rc::new(Reference { | |
| 192 | + slot: setup_slot, | |
| 193 | + picture: decoded, | |
| 194 | + }); | |
| 195 | + self.refs | |
| 196 | + .refresh(header.refresh_frame_flags, Some(reference)); | |
| 197 | + } | |
| 198 | + Ok(()) | |
| 199 | + } | |
| 200 | + | |
| 201 | + fn ensure_session(&mut self, header: &FrameHeader) -> Result<()> { | |
| 202 | + if let Some(s) = &self.session | |
| 203 | + && s.bit_depth == header.bit_depth | |
| 204 | + && header.width <= s.width | |
| 205 | + && header.height <= s.height | |
| 206 | + { | |
| 207 | + return Ok(()); | |
| 208 | + } | |
| 209 | + let (width, height) = match &self.session { | |
| 210 | + Some(s) if s.bit_depth == header.bit_depth => { | |
| 211 | + (header.width.max(s.width), header.height.max(s.height)) | |
| 212 | + } | |
| 213 | + _ => (header.width, header.height), | |
| 214 | + }; | |
| 215 | + self.refs = RefSlots::new(); | |
| 216 | + let vp9 = Vp9DecodeSession::new( | |
| 217 | + &self.gpu, | |
| 218 | + &Vp9DecodeConfig { | |
| 219 | + max_width: width, | |
| 220 | + max_height: height, | |
| 221 | + max_dpb_slots: DPB_SLOTS, | |
| 222 | + bit_depth: header.bit_depth, | |
| 223 | + }, | |
| 224 | + )?; | |
| 225 | + self.session = Some(Session { | |
| 226 | + vp9, | |
| 227 | + bit_depth: header.bit_depth, | |
| 228 | + width, | |
| 229 | + height, | |
| 230 | + }); | |
| 231 | + Ok(()) | |
| 232 | + } | |
| 233 | + | |
| 234 | + fn free_slot(&self) -> Result<u32> { | |
| 235 | + (0..DPB_SLOTS) | |
| 236 | + .find(|slot| self.refs.filled().all(|r| r.slot != *slot)) | |
| 237 | + .ok_or_else(|| Error::config("VP9 Vulkan decode: every DPB slot is in use")) | |
| 238 | + } | |
| 239 | +} | |
| 240 | + | |
| 241 | +fn check_supported(h: &FrameHeader) -> Result<()> { | |
| 242 | + if !matches!((h.profile, h.bit_depth), (0, 8) | (2, 10)) | |
| 243 | + || h.subsampling_x != 1 | |
| 244 | + || h.subsampling_y != 1 | |
| 245 | + { | |
| 246 | + return Err(Error::unsupported( | |
| 247 | + "Vulkan VP9 decode", | |
| 248 | + "only 4:2:0 profile 0 8-bit and profile 2 10-bit", | |
| 249 | + )); | |
| 250 | + } | |
| 251 | + if h.width % 2 != 0 || h.height % 2 != 0 { | |
| 252 | + return Err(Error::unsupported("Vulkan VP9 decode", "odd frame size")); | |
| 253 | + } | |
| 254 | + Ok(()) | |
| 255 | +} | |
| 256 | + | |
| 257 | +fn color_code(c: ColorSpace) -> u8 { | |
| 258 | + match c { | |
| 259 | + ColorSpace::Unknown => 0, | |
| 260 | + ColorSpace::Bt601 => 1, | |
| 261 | + ColorSpace::Bt709 => 2, | |
| 262 | + ColorSpace::Smpte170 => 3, | |
| 263 | + ColorSpace::Smpte240 => 4, | |
| 264 | + ColorSpace::Bt2020 => 5, | |
| 265 | + ColorSpace::Reserved => 6, | |
| 266 | + ColorSpace::Rgb => 7, | |
| 267 | + } | |
| 268 | +} | |
| 269 | + | |
| 270 | +fn interpolation(f: InterpolationFilter) -> Vp9InterpolationFilter { | |
| 271 | + match f { | |
| 272 | + InterpolationFilter::Eighttap => Vp9InterpolationFilter::EightTap, | |
| 273 | + InterpolationFilter::EighttapSmooth => Vp9InterpolationFilter::EightTapSmooth, | |
| 274 | + InterpolationFilter::EighttapSharp => Vp9InterpolationFilter::EightTapSharp, | |
| 275 | + InterpolationFilter::Bilinear => Vp9InterpolationFilter::Bilinear, | |
| 276 | + InterpolationFilter::Switchable => Vp9InterpolationFilter::Switchable, | |
| 277 | + } | |
| 278 | +} | |
| 279 | + | |
| 280 | +fn frame_header(h: &FrameHeader, use_prev_frame_mvs: bool) -> Vp9FrameHeader { | |
| 281 | + let s = &h.segmentation; | |
| 282 | + let feature_enabled = std::array::from_fn(|segment| { | |
| 283 | + (0..s.feature_enabled[segment].len()) | |
| 284 | + .filter(|&f| s.feature_enabled[segment][f]) | |
| 285 | + .fold(0u8, |mask, f| mask | 1 << f) | |
| 286 | + }); | |
| 287 | + let sign_bias = h | |
| 288 | + .ref_frame_sign_bias | |
| 289 | + .iter() | |
| 290 | + .enumerate() | |
| 291 | + .filter(|(_, set)| **set) | |
| 292 | + .fold(0u8, |mask, (name, _)| mask | 1 << (name + 1)); | |
| 293 | + let lf = &h.loop_filter; | |
| 294 | + Vp9FrameHeader { | |
| 295 | + key_frame: h.frame_type == FrameType::Key, | |
| 296 | + show_frame: h.show_frame, | |
| 297 | + error_resilient_mode: h.error_resilient_mode, | |
| 298 | + intra_only: h.intra_only, | |
| 299 | + allow_high_precision_mv: h.allow_high_precision_mv, | |
| 300 | + refresh_frame_context: h.refresh_frame_context, | |
| 301 | + frame_parallel_decoding_mode: h.frame_parallel_decoding_mode, | |
| 302 | + use_prev_frame_mvs, | |
| 303 | + frame_context_idx: h.frame_context_idx, | |
| 304 | + reset_frame_context: h.reset_frame_context, | |
| 305 | + refresh_frame_flags: h.refresh_frame_flags, | |
| 306 | + ref_frame_sign_bias_mask: sign_bias, | |
| 307 | + interpolation_filter: interpolation(h.interpolation_filter), | |
| 308 | + base_q_idx: h.quantization.base_q_idx, | |
| 309 | + delta_q_y_dc: h.quantization.delta_q_y_dc, | |
| 310 | + delta_q_uv_dc: h.quantization.delta_q_uv_dc, | |
| 311 | + delta_q_uv_ac: h.quantization.delta_q_uv_ac, | |
| 312 | + tile_cols_log2: h.tile_info.cols_log2, | |
| 313 | + tile_rows_log2: h.tile_info.rows_log2, | |
| 314 | + width: h.width, | |
| 315 | + height: h.height, | |
| 316 | + bit_depth: h.bit_depth, | |
| 317 | + color: Vp9ColorConfig { | |
| 318 | + color_space: color_code(h.color_space), | |
| 319 | + color_range: h.color_range, | |
| 320 | + subsampling_x: h.subsampling_x, | |
| 321 | + subsampling_y: h.subsampling_y, | |
| 322 | + }, | |
| 323 | + loop_filter: Vp9LoopFilter { | |
| 324 | + level: lf.level, | |
| 325 | + sharpness: lf.sharpness, | |
| 326 | + delta_enabled: lf.delta_enabled, | |
| 327 | + delta_update: lf.delta_update, | |
| 328 | + ref_deltas: lf.ref_deltas, | |
| 329 | + mode_deltas: lf.mode_deltas, | |
| 330 | + }, | |
| 331 | + segmentation: Vp9Segmentation { | |
| 332 | + enabled: s.enabled, | |
| 333 | + update_map: s.update_map, | |
| 334 | + temporal_update: s.temporal_update, | |
| 335 | + update_data: s.update_data, | |
| 336 | + abs_or_delta_update: s.abs_or_delta_update, | |
| 337 | + tree_probs: s.tree_probs, | |
| 338 | + pred_probs: s.pred_probs, | |
| 339 | + feature_enabled, | |
| 340 | + feature_data: s.feature_data, | |
| 341 | + }, | |
| 342 | + uncompressed_header_size: u32::from(h.uncompressed_header_size), | |
| 343 | + compressed_header_size: u32::from(h.header_size_in_bytes), | |
| 344 | + } | |
| 345 | +} |
crates/ec-vk/src/lib.rsmodified+3 -1
| @@ -19,7 +19,9 @@ pub use vk_video_ffi::{ | ||
| 19 | 19 | Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, |
| 20 | 20 | H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, |
| 21 | 21 | H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, |
| 22 | - H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, | |
| 22 | + H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, Vp9ColorConfig, | |
| 23 | + Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter, | |
| 24 | + Vp9LoopFilter, Vp9Segmentation, | |
| 23 | 25 | }; |
| 24 | 26 | |
| 25 | 27 | /// Encoder settings. |
shims/vk-video-ffi/src/lib.rsmodified+5 -0
| @@ -17,6 +17,7 @@ mod h265_encode; | ||
| 17 | 17 | mod rgb_convert; |
| 18 | 18 | mod rgb_decode; |
| 19 | 19 | mod session; |
| 20 | +mod vp9_decode; | |
| 20 | 21 | |
| 21 | 22 | pub use av1_decode::{ |
| 22 | 23 | Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, |
| @@ -27,6 +28,10 @@ pub use av1_decode::{ | ||
| 27 | 28 | pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; |
| 28 | 29 | #[cfg(target_os = "linux")] |
| 29 | 30 | pub use dmabuf::DmaBuf; |
| 31 | +pub use vp9_decode::{ | |
| 32 | + Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, | |
| 33 | + Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, | |
| 34 | +}; | |
| 30 | 35 | pub use h264_decode::{ |
| 31 | 36 | H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, |
| 32 | 37 | ScalingLists, |
shims/vk-video-ffi/src/vp9_decode.rsadded+508 -0
| @@ -0,0 +1,508 @@ | ||
| 1 | +use std::ffi::c_void; | |
| 2 | + | |
| 3 | +use vulkanalia::prelude::v1_3::*; | |
| 4 | + | |
| 5 | +use crate::session::{ | |
| 6 | + Decoder, VideoSession, align, align_u64, component_bit_depth, picture_resource, video_caps, | |
| 7 | + zeroed, | |
| 8 | +}; | |
| 9 | +use crate::{Error, Gpu}; | |
| 10 | + | |
| 11 | +/// Settings fixed for the life of a VP9 decode session. | |
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 13 | +pub struct Vp9DecodeConfig { | |
| 14 | + /// Largest frame width in luma samples. | |
| 15 | + pub max_width: u32, | |
| 16 | + /// Largest frame height in luma samples. | |
| 17 | + pub max_height: u32, | |
| 18 | + /// DPB slots, including the slot the picture is decoded into. | |
| 19 | + pub max_dpb_slots: u32, | |
| 20 | + /// Luma and chroma bit depth: 8 (profile 0) or 10 (profile 2). | |
| 21 | + pub bit_depth: u8, | |
| 22 | +} | |
| 23 | + | |
| 24 | +/// Interpolation filter, as `StdVideoVP9InterpolationFilter`. | |
| 25 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 26 | +#[repr(u8)] | |
| 27 | +pub enum Vp9InterpolationFilter { | |
| 28 | + /// EIGHTTAP. | |
| 29 | + EightTap = 0, | |
| 30 | + /// EIGHTTAP_SMOOTH. | |
| 31 | + EightTapSmooth = 1, | |
| 32 | + /// EIGHTTAP_SHARP. | |
| 33 | + EightTapSharp = 2, | |
| 34 | + /// BILINEAR. | |
| 35 | + Bilinear = 3, | |
| 36 | + /// SWITCHABLE. | |
| 37 | + Switchable = 4, | |
| 38 | +} | |
| 39 | + | |
| 40 | +/// Colour configuration of a frame (spec 6.2, `color_config`). | |
| 41 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 42 | +pub struct Vp9ColorConfig { | |
| 43 | + /// color_space, the VP9 code point. | |
| 44 | + pub color_space: u8, | |
| 45 | + /// color_range. | |
| 46 | + pub color_range: bool, | |
| 47 | + /// subsampling_x. | |
| 48 | + pub subsampling_x: u8, | |
| 49 | + /// subsampling_y. | |
| 50 | + pub subsampling_y: u8, | |
| 51 | +} | |
| 52 | + | |
| 53 | +/// Loop filter parameters of a frame. | |
| 54 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 55 | +pub struct Vp9LoopFilter { | |
| 56 | + /// loop_filter_level. | |
| 57 | + pub level: u8, | |
| 58 | + /// loop_filter_sharpness. | |
| 59 | + pub sharpness: u8, | |
| 60 | + /// loop_filter_delta_enabled. | |
| 61 | + pub delta_enabled: bool, | |
| 62 | + /// loop_filter_delta_update. | |
| 63 | + pub delta_update: bool, | |
| 64 | + /// loop_filter_ref_deltas. | |
| 65 | + pub ref_deltas: [i8; 4], | |
| 66 | + /// loop_filter_mode_deltas. | |
| 67 | + pub mode_deltas: [i8; 2], | |
| 68 | +} | |
| 69 | + | |
| 70 | +/// Segmentation parameters of a frame. | |
| 71 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 72 | +pub struct Vp9Segmentation { | |
| 73 | + /// segmentation_enabled. | |
| 74 | + pub enabled: bool, | |
| 75 | + /// segmentation_update_map. | |
| 76 | + pub update_map: bool, | |
| 77 | + /// segmentation_temporal_update. | |
| 78 | + pub temporal_update: bool, | |
| 79 | + /// segmentation_update_data. | |
| 80 | + pub update_data: bool, | |
| 81 | + /// segmentation_abs_or_delta_update. | |
| 82 | + pub abs_or_delta_update: bool, | |
| 83 | + /// segmentation_tree_probs. | |
| 84 | + pub tree_probs: [u8; 7], | |
| 85 | + /// segmentation_pred_prob. | |
| 86 | + pub pred_probs: [u8; 3], | |
| 87 | + /// Per segment, a bit mask of the features enabled (bit n is feature n). | |
| 88 | + pub feature_enabled: [u8; 8], | |
| 89 | + /// FeatureData[segment][feature]. | |
| 90 | + pub feature_data: [[i16; 4]; 8], | |
| 91 | +} | |
| 92 | + | |
| 93 | +/// One VP9 frame's uncompressed header fields, in the shape `StdVideoDecodeVP9PictureInfo` takes them. | |
| 94 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 95 | +pub struct Vp9FrameHeader { | |
| 96 | + /// True for a key frame. | |
| 97 | + pub key_frame: bool, | |
| 98 | + /// show_frame. | |
| 99 | + pub show_frame: bool, | |
| 100 | + /// error_resilient_mode. | |
| 101 | + pub error_resilient_mode: bool, | |
| 102 | + /// intra_only. | |
| 103 | + pub intra_only: bool, | |
| 104 | + /// allow_high_precision_mv. | |
| 105 | + pub allow_high_precision_mv: bool, | |
| 106 | + /// refresh_frame_context. | |
| 107 | + pub refresh_frame_context: bool, | |
| 108 | + /// frame_parallel_decoding_mode. | |
| 109 | + pub frame_parallel_decoding_mode: bool, | |
| 110 | + /// UsePrevFrameMvs, derived by the caller from the previous frame. | |
| 111 | + pub use_prev_frame_mvs: bool, | |
| 112 | + /// frame_context_idx. | |
| 113 | + pub frame_context_idx: u8, | |
| 114 | + /// reset_frame_context. | |
| 115 | + pub reset_frame_context: u8, | |
| 116 | + /// refresh_frame_flags. | |
| 117 | + pub refresh_frame_flags: u8, | |
| 118 | + /// Sign bias per reference name, bit n for reference name n (LAST = 1). | |
| 119 | + pub ref_frame_sign_bias_mask: u8, | |
| 120 | + /// interp_filter. | |
| 121 | + pub interpolation_filter: Vp9InterpolationFilter, | |
| 122 | + /// base_q_idx. | |
| 123 | + pub base_q_idx: u8, | |
| 124 | + /// DeltaQYDc. | |
| 125 | + pub delta_q_y_dc: i8, | |
| 126 | + /// DeltaQUVDc. | |
| 127 | + pub delta_q_uv_dc: i8, | |
| 128 | + /// DeltaQUVAc. | |
| 129 | + pub delta_q_uv_ac: i8, | |
| 130 | + /// tile_cols_log2. | |
| 131 | + pub tile_cols_log2: u8, | |
| 132 | + /// tile_rows_log2. | |
| 133 | + pub tile_rows_log2: u8, | |
| 134 | + /// FrameWidth. | |
| 135 | + pub width: u32, | |
| 136 | + /// FrameHeight. | |
| 137 | + pub height: u32, | |
| 138 | + /// BitDepth, 8 or 10. | |
| 139 | + pub bit_depth: u8, | |
| 140 | + /// Colour configuration. | |
| 141 | + pub color: Vp9ColorConfig, | |
| 142 | + /// Loop filter parameters. | |
| 143 | + pub loop_filter: Vp9LoopFilter, | |
| 144 | + /// Segmentation parameters. | |
| 145 | + pub segmentation: Vp9Segmentation, | |
| 146 | + /// Length of the uncompressed header in bytes, from the start of the frame. | |
| 147 | + pub uncompressed_header_size: u32, | |
| 148 | + /// Length of the compressed header in bytes, after the uncompressed header. | |
| 149 | + pub compressed_header_size: u32, | |
| 150 | +} | |
| 151 | + | |
| 152 | +/// One frame to decode; the frame data holds the uncompressed header, compressed header and tiles. | |
| 153 | +#[derive(Debug, Clone, Copy)] | |
| 154 | +pub struct Vp9DecodePicture<'a> { | |
| 155 | + /// Frame header. | |
| 156 | + pub header: &'a Vp9FrameHeader, | |
| 157 | + /// DPB slot the picture is decoded into. | |
| 158 | + pub setup_slot: u32, | |
| 159 | + /// DPB slot of each reference name LAST, GOLDEN and ALTREF, -1 when unused. | |
| 160 | + pub ref_name_slot: [i32; 3], | |
| 161 | + /// Distinct DPB slots the frame references. | |
| 162 | + pub refs: &'a [u32], | |
| 163 | + /// The whole frame, uncompressed header through the last tile. | |
| 164 | + pub data: &'a [u8], | |
| 165 | +} | |
| 166 | + | |
| 167 | +struct Caps { | |
| 168 | + std_header_version: vk::ExtensionProperties, | |
| 169 | + max_extent: vk::Extent2D, | |
| 170 | + size_align: u64, | |
| 171 | + max_dpb_slots: u32, | |
| 172 | + max_active_refs: u32, | |
| 173 | + distinct: bool, | |
| 174 | +} | |
| 175 | + | |
| 176 | +struct Profile { | |
| 177 | + info: vk::VideoProfileInfoKHR, | |
| 178 | + vp9: vk::VideoDecodeVP9ProfileInfoKHR, | |
| 179 | +} | |
| 180 | + | |
| 181 | +impl Profile { | |
| 182 | + fn new(bit_depth: u8) -> Box<Self> { | |
| 183 | + let component = component_bit_depth(bit_depth); | |
| 184 | + let std_profile = if bit_depth == 10 { | |
| 185 | + vk::video::STD_VIDEO_VP9_PROFILE_2 | |
| 186 | + } else { | |
| 187 | + vk::video::STD_VIDEO_VP9_PROFILE_0 | |
| 188 | + }; | |
| 189 | + let mut p = Box::new(Profile { | |
| 190 | + info: vk::VideoProfileInfoKHR::builder() | |
| 191 | + .video_codec_operation(vk::VideoCodecOperationFlagsKHR::DECODE_VP9) | |
| 192 | + .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) | |
| 193 | + .luma_bit_depth(component) | |
| 194 | + .chroma_bit_depth(component) | |
| 195 | + .build(), | |
| 196 | + vp9: vk::VideoDecodeVP9ProfileInfoKHR::builder() | |
| 197 | + .std_profile(std_profile) | |
| 198 | + .build(), | |
| 199 | + }); | |
| 200 | + p.info.next = &p.vp9 as *const _ as *const c_void; | |
| 201 | + p | |
| 202 | + } | |
| 203 | +} | |
| 204 | + | |
| 205 | +/// A VP9 profile 0 or 2 Vulkan Video decode session: DPB images per slot and a separate output image. | |
| 206 | +pub struct Vp9DecodeSession { | |
| 207 | + dec: Decoder, | |
| 208 | + bit_depth: u8, | |
| 209 | +} | |
| 210 | + | |
| 211 | +impl Vp9DecodeSession { | |
| 212 | + /// Creates a session with its DPB, bitstream and readback buffers. | |
| 213 | + pub fn new(gpu: &Gpu, cfg: &Vp9DecodeConfig) -> Result<Self, Error> { | |
| 214 | + if cfg.max_width == 0 || cfg.max_height == 0 || cfg.max_dpb_slots == 0 { | |
| 215 | + return Err(Error::Invalid( | |
| 216 | + "decode size or DPB slot count is zero".into(), | |
| 217 | + )); | |
| 218 | + } | |
| 219 | + if !matches!(cfg.bit_depth, 8 | 10) { | |
| 220 | + return Err(Error::Invalid("bit depth is not 8 or 10".into())); | |
| 221 | + } | |
| 222 | + let family = gpu | |
| 223 | + .decode_family() | |
| 224 | + .ok_or_else(|| Error::Unsupported("VP9 decode queue family".into()))?; | |
| 225 | + let graphics = gpu | |
| 226 | + .graphics_family() | |
| 227 | + .ok_or_else(|| Error::Unsupported("graphics queue family for readback".into()))?; | |
| 228 | + if !gpu | |
| 229 | + .device() | |
| 230 | + .extensions() | |
| 231 | + .contains(&vk::KHR_VIDEO_DECODE_VP9_EXTENSION.name) | |
| 232 | + { | |
| 233 | + return Err(Error::Unsupported("VP9 decode".into())); | |
| 234 | + } | |
| 235 | + let width = align(cfg.max_width, 16); | |
| 236 | + let height = align(cfg.max_height, 16); | |
| 237 | + let profile = Profile::new(cfg.bit_depth); | |
| 238 | + let caps = query_caps(gpu, &profile.info)?; | |
| 239 | + if width > caps.max_extent.width | |
| 240 | + || height > caps.max_extent.height | |
| 241 | + || cfg.max_dpb_slots > caps.max_dpb_slots | |
| 242 | + { | |
| 243 | + return Err(Error::Unsupported(format!("VP9 decode {width}x{height}"))); | |
| 244 | + } | |
| 245 | + if !caps.distinct { | |
| 246 | + return Err(Error::Unsupported( | |
| 247 | + "VP9 decode with DPB and output in one image".into(), | |
| 248 | + )); | |
| 249 | + } | |
| 250 | + let max_active = caps.max_active_refs.min(cfg.max_dpb_slots); | |
| 251 | + let max_extent = vk::Extent2D { width, height }; | |
| 252 | + let vs = VideoSession::new( | |
| 253 | + gpu, | |
| 254 | + family, | |
| 255 | + &profile.info, | |
| 256 | + &caps.std_header_version, | |
| 257 | + max_extent, | |
| 258 | + cfg.max_dpb_slots, | |
| 259 | + max_active, | |
| 260 | + )?; | |
| 261 | + let dec = Decoder::new( | |
| 262 | + vs, | |
| 263 | + &profile.info, | |
| 264 | + graphics, | |
| 265 | + max_extent, | |
| 266 | + cfg.max_dpb_slots, | |
| 267 | + max_active, | |
| 268 | + caps.size_align, | |
| 269 | + )?; | |
| 270 | + Ok(Vp9DecodeSession { | |
| 271 | + dec, | |
| 272 | + bit_depth: cfg.bit_depth, | |
| 273 | + }) | |
| 274 | + } | |
| 275 | + | |
| 276 | + /// Decodes one frame into its setup slot, referencing the given DPB slots. | |
| 277 | + pub fn decode(&mut self, pic: &Vp9DecodePicture) -> Result<(), Error> { | |
| 278 | + let h = pic.header; | |
| 279 | + if h.bit_depth != self.bit_depth { | |
| 280 | + return Err(Error::Invalid( | |
| 281 | + "frame bit depth differs from session".into(), | |
| 282 | + )); | |
| 283 | + } | |
| 284 | + let extent = vk::Extent2D { | |
| 285 | + width: h.width, | |
| 286 | + height: h.height, | |
| 287 | + }; | |
| 288 | + if extent.width == 0 | |
| 289 | + || extent.height == 0 | |
| 290 | + || extent.width > self.dec.max_extent.width | |
| 291 | + || extent.height > self.dec.max_extent.height | |
| 292 | + { | |
| 293 | + return Err(Error::Invalid("frame size".into())); | |
| 294 | + } | |
| 295 | + if pic.data.len() as u64 > self.dec.bitstream.size { | |
| 296 | + return Err(Error::Invalid("frame larger than bitstream buffer".into())); | |
| 297 | + } | |
| 298 | + let compressed_end = | |
| 299 | + u64::from(h.uncompressed_header_size) + u64::from(h.compressed_header_size); | |
| 300 | + if compressed_end > pic.data.len() as u64 { | |
| 301 | + return Err(Error::Invalid("headers outside frame data".into())); | |
| 302 | + } | |
| 303 | + if pic.setup_slot >= self.dec.max_dpb_slots { | |
| 304 | + return Err(Error::Invalid("setup DPB slot".into())); | |
| 305 | + } | |
| 306 | + if pic.refs.len() > self.dec.max_active_refs as usize { | |
| 307 | + return Err(Error::Invalid("too many reference pictures".into())); | |
| 308 | + } | |
| 309 | + for (i, &slot) in pic.refs.iter().enumerate() { | |
| 310 | + if slot >= self.dec.max_dpb_slots | |
| 311 | + || slot == pic.setup_slot | |
| 312 | + || pic.refs[..i].contains(&slot) | |
| 313 | + { | |
| 314 | + return Err(Error::Invalid("reference DPB slot".into())); | |
| 315 | + } | |
| 316 | + } | |
| 317 | + if pic | |
| 318 | + .ref_name_slot | |
| 319 | + .iter() | |
| 320 | + .any(|&s| s >= 0 && !pic.refs.iter().any(|&r| i32::try_from(r) == Ok(s))) | |
| 321 | + { | |
| 322 | + return Err(Error::Invalid( | |
| 323 | + "reference name without a reference slot".into(), | |
| 324 | + )); | |
| 325 | + } | |
| 326 | + | |
| 327 | + let ptr = self | |
| 328 | + .dec | |
| 329 | + .bitstream | |
| 330 | + .ptr | |
| 331 | + .ok_or_else(|| Error::Invalid("bitstream buffer not mapped".into()))?; | |
| 332 | + let buf = unsafe { std::slice::from_raw_parts_mut(ptr, self.dec.bitstream.size as usize) }; | |
| 333 | + buf[..pic.data.len()].copy_from_slice(pic.data); | |
| 334 | + let range = align_u64(pic.data.len() as u64, self.dec.size_align); | |
| 335 | + | |
| 336 | + let pr: Vec<vk::VideoPictureResourceInfoKHR> = self | |
| 337 | + .dec | |
| 338 | + .dpb | |
| 339 | + .iter() | |
| 340 | + .map(|i| picture_resource(i.view, extent)) | |
| 341 | + .collect(); | |
| 342 | + let setup = vk::VideoReferenceSlotInfoKHR::builder() | |
| 343 | + .slot_index(pic.setup_slot as i32) | |
| 344 | + .picture_resource(&pr[pic.setup_slot as usize]) | |
| 345 | + .build(); | |
| 346 | + let refs: Vec<vk::VideoReferenceSlotInfoKHR> = pic | |
| 347 | + .refs | |
| 348 | + .iter() | |
| 349 | + .map(|&slot| { | |
| 350 | + vk::VideoReferenceSlotInfoKHR::builder() | |
| 351 | + .slot_index(slot as i32) | |
| 352 | + .picture_resource(&pr[slot as usize]) | |
| 353 | + .build() | |
| 354 | + }) | |
| 355 | + .collect(); | |
| 356 | + let mut begin: Vec<vk::VideoReferenceSlotInfoKHR> = vec![ | |
| 357 | + vk::VideoReferenceSlotInfoKHR::builder() | |
| 358 | + .slot_index(-1) | |
| 359 | + .picture_resource(&pr[pic.setup_slot as usize]) | |
| 360 | + .build(), | |
| 361 | + ]; | |
| 362 | + begin.extend(refs.iter().copied()); | |
| 363 | + | |
| 364 | + let color = std_color(h); | |
| 365 | + let lf = std_loop_filter(&h.loop_filter); | |
| 366 | + let seg = std_segmentation(&h.segmentation); | |
| 367 | + let mut std_pic = zeroed::<vk::video::StdVideoDecodeVP9PictureInfo>(); | |
| 368 | + std_pic.flags = picture_flags(h); | |
| 369 | + std_pic.profile = if self.bit_depth == 10 { | |
| 370 | + vk::video::STD_VIDEO_VP9_PROFILE_2 | |
| 371 | + } else { | |
| 372 | + vk::video::STD_VIDEO_VP9_PROFILE_0 | |
| 373 | + }; | |
| 374 | + std_pic.frame_type = if h.key_frame { | |
| 375 | + vk::video::STD_VIDEO_VP9_FRAME_TYPE_KEY | |
| 376 | + } else { | |
| 377 | + vk::video::STD_VIDEO_VP9_FRAME_TYPE_NON_KEY | |
| 378 | + }; | |
| 379 | + std_pic.frame_context_idx = h.frame_context_idx; | |
| 380 | + std_pic.reset_frame_context = h.reset_frame_context; | |
| 381 | + std_pic.refresh_frame_flags = h.refresh_frame_flags; | |
| 382 | + std_pic.ref_frame_sign_bias_mask = h.ref_frame_sign_bias_mask; | |
| 383 | + std_pic.interpolation_filter = | |
| 384 | + vk::video::StdVideoVP9InterpolationFilter(i32::from(h.interpolation_filter as u8)); | |
| 385 | + std_pic.base_q_idx = h.base_q_idx; | |
| 386 | + std_pic.delta_q_y_dc = h.delta_q_y_dc; | |
| 387 | + std_pic.delta_q_uv_dc = h.delta_q_uv_dc; | |
| 388 | + std_pic.delta_q_uv_ac = h.delta_q_uv_ac; | |
| 389 | + std_pic.tile_cols_log2 = h.tile_cols_log2; | |
| 390 | + std_pic.tile_rows_log2 = h.tile_rows_log2; | |
| 391 | + std_pic.pColorConfig = &color; | |
| 392 | + std_pic.pLoopFilter = &lf; | |
| 393 | + std_pic.pSegmentation = &seg; | |
| 394 | + | |
| 395 | + let mut vp9 = vk::VideoDecodeVP9PictureInfoKHR { | |
| 396 | + std_picture_info: &std_pic, | |
| 397 | + reference_name_slot_indices: pic.ref_name_slot, | |
| 398 | + uncompressed_header_offset: 0, | |
| 399 | + compressed_header_offset: h.uncompressed_header_size, | |
| 400 | + tiles_offset: compressed_end as u32, | |
| 401 | + ..Default::default() | |
| 402 | + }; | |
| 403 | + let decode = vk::VideoDecodeInfoKHR::builder() | |
| 404 | + .src_buffer(self.dec.bitstream.buffer) | |
| 405 | + .src_buffer_offset(0) | |
| 406 | + .src_buffer_range(range) | |
| 407 | + .dst_picture_resource(picture_resource(self.dec.output.view, extent)) | |
| 408 | + .setup_reference_slot(&setup) | |
| 409 | + .reference_slots(&refs) | |
| 410 | + .push_next(&mut vp9) | |
| 411 | + .build(); | |
| 412 | + self.dec.run(&begin, &decode) | |
| 413 | + } | |
| 414 | + | |
| 415 | + /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). | |
| 416 | + pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { | |
| 417 | + self.dec.read_nv12(width, height) | |
| 418 | + } | |
| 419 | + | |
| 420 | + /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order. | |
| 421 | + pub fn read_output_rgb( | |
| 422 | + &mut self, | |
| 423 | + crop: (u32, u32, u32, u32), | |
| 424 | + out: (u32, u32), | |
| 425 | + bgra: bool, | |
| 426 | + coeffs: [i32; 5], | |
| 427 | + ) -> Result<Vec<u8>, Error> { | |
| 428 | + self.dec.read_rgb(crop, out, bgra, coeffs) | |
| 429 | + } | |
| 430 | +} | |
| 431 | + | |
| 432 | +fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { | |
| 433 | + let mut vp9 = vk::VideoDecodeVP9CapabilitiesKHR::builder(); | |
| 434 | + let mut decode = vk::VideoDecodeCapabilitiesKHR::builder(); | |
| 435 | + let mut caps = vk::VideoCapabilitiesKHR::builder() | |
| 436 | + .push_next(&mut vp9) | |
| 437 | + .push_next(&mut decode); | |
| 438 | + video_caps(gpu, profile, &mut caps) | |
| 439 | + .map_err(|_| Error::Unsupported("VP9 decode profile".into()))?; | |
| 440 | + let caps = caps.build(); | |
| 441 | + let decode = decode.build(); | |
| 442 | + Ok(Caps { | |
| 443 | + std_header_version: caps.std_header_version, | |
| 444 | + max_extent: caps.max_coded_extent, | |
| 445 | + size_align: caps.min_bitstream_buffer_size_alignment, | |
| 446 | + max_dpb_slots: caps.max_dpb_slots, | |
| 447 | + max_active_refs: caps.max_active_reference_pictures, | |
| 448 | + distinct: decode | |
| 449 | + .flags | |
| 450 | + .contains(vk::VideoDecodeCapabilityFlagsKHR::DPB_AND_OUTPUT_DISTINCT), | |
| 451 | + }) | |
| 452 | +} | |
| 453 | + | |
| 454 | +fn std_color(h: &Vp9FrameHeader) -> vk::video::StdVideoVP9ColorConfig { | |
| 455 | + let mut flags = zeroed::<vk::video::StdVideoVP9ColorConfigFlags>(); | |
| 456 | + flags.set_color_range(u32::from(h.color.color_range)); | |
| 457 | + vk::video::StdVideoVP9ColorConfig { | |
| 458 | + flags, | |
| 459 | + BitDepth: h.bit_depth, | |
| 460 | + subsampling_x: h.color.subsampling_x, | |
| 461 | + subsampling_y: h.color.subsampling_y, | |
| 462 | + reserved1: 0, | |
| 463 | + color_space: vk::video::StdVideoVP9ColorSpace(i32::from(h.color.color_space)), | |
| 464 | + } | |
| 465 | +} | |
| 466 | + | |
| 467 | +fn std_loop_filter(l: &Vp9LoopFilter) -> vk::video::StdVideoVP9LoopFilter { | |
| 468 | + let mut flags = zeroed::<vk::video::StdVideoVP9LoopFilterFlags>(); | |
| 469 | + flags.set_loop_filter_delta_enabled(u32::from(l.delta_enabled)); | |
| 470 | + flags.set_loop_filter_delta_update(u32::from(l.delta_update)); | |
| 471 | + vk::video::StdVideoVP9LoopFilter { | |
| 472 | + flags, | |
| 473 | + loop_filter_level: l.level, | |
| 474 | + loop_filter_sharpness: l.sharpness, | |
| 475 | + update_ref_delta: u8::from(l.delta_update), | |
| 476 | + loop_filter_ref_deltas: l.ref_deltas, | |
| 477 | + update_mode_delta: u8::from(l.delta_update), | |
| 478 | + loop_filter_mode_deltas: l.mode_deltas, | |
| 479 | + } | |
| 480 | +} | |
| 481 | + | |
| 482 | +fn std_segmentation(s: &Vp9Segmentation) -> vk::video::StdVideoVP9Segmentation { | |
| 483 | + let mut flags = zeroed::<vk::video::StdVideoVP9SegmentationFlags>(); | |
| 484 | + flags.set_segmentation_update_map(u32::from(s.update_map)); | |
| 485 | + flags.set_segmentation_temporal_update(u32::from(s.temporal_update)); | |
| 486 | + flags.set_segmentation_update_data(u32::from(s.update_data)); | |
| 487 | + flags.set_segmentation_abs_or_delta_update(u32::from(s.abs_or_delta_update)); | |
| 488 | + vk::video::StdVideoVP9Segmentation { | |
| 489 | + flags, | |
| 490 | + segmentation_tree_probs: s.tree_probs, | |
| 491 | + segmentation_pred_prob: s.pred_probs, | |
| 492 | + FeatureEnabled: s.feature_enabled, | |
| 493 | + FeatureData: s.feature_data, | |
| 494 | + } | |
| 495 | +} | |
| 496 | + | |
| 497 | +fn picture_flags(h: &Vp9FrameHeader) -> vk::video::StdVideoDecodeVP9PictureInfoFlags { | |
| 498 | + let mut f = zeroed::<vk::video::StdVideoDecodeVP9PictureInfoFlags>(); | |
| 499 | + f.set_error_resilient_mode(u32::from(h.error_resilient_mode)); | |
| 500 | + f.set_intra_only(u32::from(h.intra_only)); | |
| 501 | + f.set_allow_high_precision_mv(u32::from(h.allow_high_precision_mv)); | |
| 502 | + f.set_refresh_frame_context(u32::from(h.refresh_frame_context)); | |
| 503 | + f.set_frame_parallel_decoding_mode(u32::from(h.frame_parallel_decoding_mode)); | |
| 504 | + f.set_segmentation_enabled(u32::from(h.segmentation.enabled)); | |
| 505 | + f.set_show_frame(u32::from(h.show_frame)); | |
| 506 | + f.set_UsePrevFrameMvs(u32::from(h.use_prev_frame_mvs)); | |
| 507 | + f | |
| 508 | +} |