From b411317dadc07a6a07b17d62e61662883502c907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 14:46:21 +0300 Subject: [PATCH] HwDecoder::open_rgb/next_rgb: GPU YUV->BGRA/RGBA with box downscale (nv12_to_rgb.comp), matrix from bitstream (601/709 limited), VA fallback via ec-dsp i420_to_packed with the same coefficients; hw_decode_rgb example --- crates/ec-dsp/src/rgb.rs | 92 +++++++++- crates/ec-hw/examples/hw_decode_rgb.rs | 170 ++++++++++++++++++ crates/ec-hw/src/hw.rs | 107 +++++++++++- crates/ec-hw/src/lib.rs | 5 +- crates/ec-hw/src/picture.rs | 54 +++++- crates/ec-hw/src/vkdec264.rs | 42 +++-- crates/ec-hw/src/vkdec265.rs | 46 +++-- crates/ec-hw/src/vkdec_av1.rs | 49 ++++-- shims/vk-video-ffi/shaders/nv12_to_rgb.comp | 68 ++++++++ shims/vk-video-ffi/shaders/nv12_to_rgb.spv | Bin 0 -> 7664 bytes shims/vk-video-ffi/src/av1_decode.rs | 11 ++ shims/vk-video-ffi/src/h264_decode.rs | 11 ++ shims/vk-video-ffi/src/h265_decode.rs | 11 ++ shims/vk-video-ffi/src/lib.rs | 1 + shims/vk-video-ffi/src/rgb_decode.rs | 181 ++++++++++++++++++++ shims/vk-video-ffi/src/session.rs | 145 ++++++++++++++-- 16 files changed, 933 insertions(+), 60 deletions(-) create mode 100644 crates/ec-hw/examples/hw_decode_rgb.rs create mode 100644 shims/vk-video-ffi/shaders/nv12_to_rgb.comp create mode 100644 shims/vk-video-ffi/shaders/nv12_to_rgb.spv create mode 100644 shims/vk-video-ffi/src/rgb_decode.rs diff --git a/crates/ec-dsp/src/rgb.rs b/crates/ec-dsp/src/rgb.rs index 669cf69c..50f600d9 100644 --- a/crates/ec-dsp/src/rgb.rs +++ b/crates/ec-dsp/src/rgb.rs @@ -34,7 +34,10 @@ pub fn rgb_box_downscale( dw: usize, dh: usize, ) { - assert!(sw >= dw && sh >= dh && dw > 0 && dh > 0, "source smaller than output"); + assert!( + sw >= dw && sh >= dh && dw > 0 && dh > 0, + "source smaller than output" + ); assert!(stride >= sw * 4 && src.len() >= stride * sh); assert_eq!(dst.len(), dw * dh * 4); for oy in 0..dh { @@ -57,6 +60,93 @@ pub fn rgb_box_downscale( } } +/// Integer 8-bit limited-range YUV to RGB: `R = (ky*(Y-16) + rv*(V-128) + 128) >> 8`, and `G` and `B` alike. The one source of these numbers: the Vulkan shader takes them as push constants. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct YuvToRgb { + /// Luma scale. + pub ky: i32, + /// Red from Cr. + pub rv: i32, + /// Green from Cb. + pub gu: i32, + /// Green from Cr. + pub gv: i32, + /// Blue from Cb. + pub bu: i32, +} + +impl YuvToRgb { + /// The five coefficients in shader push-constant order. + pub fn words(self) -> [i32; 5] { + [self.ky, self.rv, self.gu, self.gv, self.bu] + } +} + +/// BT.601, limited range. +pub const BT601_LIMITED: YuvToRgb = YuvToRgb { + ky: 298, + rv: 409, + gu: -100, + gv: -208, + bu: 516, +}; + +/// BT.709, limited range. +pub const BT709_LIMITED: YuvToRgb = YuvToRgb { + ky: 298, + rv: 459, + gu: -55, + gv: -136, + bu: 541, +}; + +/// Planar 8-bit I420 (`u` and `v` at half size, nearest chroma) to packed 4-byte pixels at `dst` x `dst` size, box-downscaled with the footprints of [`rgb_box_downscale`]; each channel is the rounded mean of the converted source pixels. Alpha is 255. `bgra` picks the byte order. +pub fn i420_to_packed( + y: &[u8], + u: &[u8], + v: &[u8], + (w, h): (usize, usize), + (dw, dh): (usize, usize), + bgra: bool, + k: &YuvToRgb, +) -> Vec { + assert!(w % 2 == 0 && h % 2 == 0, "width and height must be even"); + assert!( + w >= dw && h >= dh && dw > 0 && dh > 0, + "source smaller than output" + ); + assert!(y.len() == w * h && u.len() == w * h / 4 && v.len() == w * h / 4); + let cw = w / 2; + let mut out = vec![255u8; dw * dh * 4]; + for oy in 0..dh { + let (y0, y1) = footprint(oy, h, dh); + for ox in 0..dw { + let (x0, x1) = footprint(ox, w, dw); + let mut sum = [0u32; 3]; + for sy in y0..y1 { + for sx in x0..x1 { + let c = (sy / 2) * cw + sx / 2; + let yy = i32::from(y[sy * w + sx]) - 16; + let uu = i32::from(u[c]) - 128; + let vv = i32::from(v[c]) - 128; + let r = ((k.ky * yy + k.rv * vv + 128) >> 8).clamp(0, 255); + let g = ((k.ky * yy + k.gu * uu + k.gv * vv + 128) >> 8).clamp(0, 255); + let b = ((k.ky * yy + k.bu * uu + 128) >> 8).clamp(0, 255); + for (s, c) in sum.iter_mut().zip([r, g, b]) { + *s += c as u32; + } + } + } + let n = ((x1 - x0) * (y1 - y0)) as u32; + let [r, g, b] = sum.map(|s| ((s + n / 2) / n) as u8); + let o = (oy * dw + ox) * 4; + let px = if bgra { [b, g, r] } else { [r, g, b] }; + out[o..o + 3].copy_from_slice(&px); + } + } + out +} + fn footprint(o: usize, n_in: usize, n_out: usize) -> (usize, usize) { (o * n_in / n_out, ((o + 1) * n_in).div_ceil(n_out)) } diff --git a/crates/ec-hw/examples/hw_decode_rgb.rs b/crates/ec-hw/examples/hw_decode_rgb.rs new file mode 100644 index 00000000..ab838738 --- /dev/null +++ b/crates/ec-hw/examples/hw_decode_rgb.rs @@ -0,0 +1,170 @@ +//! Decodes streams through `HwDecoder::open_rgb` at native size and at `max_width` 640, and compares every picture with the CPU reference: the I420 decode of the same stream through `ec_dsp::rgb::i420_to_packed`. Times the decode loop of the RGB and I420 paths. +//! +//! Streams are assumed untagged, so the matrix is BT.709 from 720 lines up and BT.601 below. +//! +//! ```text +//! cargo run --release -p ec-hw --example hw_decode_rgb -- +//! ``` + +use std::fs; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use ec_dsp::rgb::{YuvToRgb, i420_to_packed}; +use ec_hw::{Backend, Codec, HwDecoder, I420, RgbOrder, RgbOutput, RgbPicture}; + +const FILES: &[(&str, Codec)] = &[ + ("bf1280.h264", Codec::H264), + ("h265idr720.hevc", Codec::H265), + ("av1aom720.ivf", Codec::Av1), + ("ten.hevc", Codec::H265), +]; + +fn main() { + let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); + for &(name, codec) in FILES { + let data = fs::read(dir.join(name)).expect("read stream"); + let units = if codec == Codec::Av1 { + ivf_units(&data) + } else { + vec![data.as_slice()] + }; + let (_, reference, i420_time) = decode_i420(codec, &units); + let expected_frames = reference.len(); + for max_width in [None, Some(640)] { + let order = if max_width.is_some() { + RgbOrder::Rgba + } else { + RgbOrder::Bgra + }; + let output = RgbOutput { order, max_width }; + let (backend, got, rgb_time) = decode_rgb(codec, &units, output); + let expected: Vec<(Vec, u32, u32)> = reference + .iter() + .map(|f| { + let (w, h) = out_size(f.width, f.height, max_width); + let coeffs = matrix_for(f.height); + let data = i420_to_packed( + &f.y, + &f.u, + &f.v, + (f.width as usize, f.height as usize), + (w as usize, h as usize), + order == RgbOrder::Bgra, + &coeffs, + ); + (data, w, h) + }) + .collect(); + let (w, h) = expected.first().map_or((0, 0), |e| (e.1, e.2)); + let max_diff = max_diff(&got, &expected); + println!( + "{name} {backend:?} {w}x{h} frames {} max |diff| {max_diff}{}", + got.len(), + if got.len() == expected_frames { + "" + } else { + " (frame count differs from I420)" + } + ); + if max_width.is_none() { + println!( + "{name} ms/frame I420 {:.3} RGB {:.3}", + ms_per_frame(i420_time, reference.len()), + ms_per_frame(rgb_time, got.len()) + ); + } + } + } +} + +fn matrix_for(height: u32) -> YuvToRgb { + if height >= 720 { + ec_dsp::rgb::BT709_LIMITED + } else { + ec_dsp::rgb::BT601_LIMITED + } +} + +fn out_size(w: u32, h: u32, max_width: Option) -> (u32, u32) { + match max_width { + Some(max) if w > max => { + let even = 2 * ((u64::from(h) * u64::from(max) + u64::from(w)) / (2 * u64::from(w))); + (max, (even as u32).clamp(2, h)) + } + _ => (w, h), + } +} + +fn max_diff(got: &[RgbPicture], expected: &[(Vec, u32, u32)]) -> u32 { + got.iter() + .zip(expected) + .map(|(g, (data, w, h))| { + if g.width != *w || g.height != *h || g.stride != w * 4 || g.data.len() != data.len() { + return 255; + } + g.data + .iter() + .zip(data) + .map(|(a, b)| u32::from(a.abs_diff(*b))) + .max() + .unwrap_or(0) + }) + .max() + .unwrap_or(0) +} + +fn ms_per_frame(elapsed: Duration, frames: usize) -> f64 { + elapsed.as_secs_f64() * 1000.0 / frames.max(1) as f64 +} + +fn decode_i420(codec: Codec, units: &[&[u8]]) -> (Backend, Vec, Duration) { + let mut decoder = HwDecoder::open(codec).expect("open decoder"); + let backend = decoder.backend(); + let mut out = Vec::new(); + let start = Instant::now(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode"); + while let Some((_, frame)) = decoder.next_frame().expect("next frame") { + out.push(frame); + } + } + decoder.flush().expect("flush"); + while let Some((_, frame)) = decoder.next_frame().expect("next frame") { + out.push(frame); + } + (backend, out, start.elapsed()) +} + +fn decode_rgb( + codec: Codec, + units: &[&[u8]], + output: RgbOutput, +) -> (Backend, Vec, Duration) { + let mut decoder = HwDecoder::open_rgb(codec, output).expect("open RGB decoder"); + let backend = decoder.backend(); + let mut out = Vec::new(); + let start = Instant::now(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode"); + while let Some((_, picture)) = decoder.next_rgb().expect("next RGB") { + out.push(picture); + } + } + decoder.flush().expect("flush"); + while let Some((_, picture)) = decoder.next_rgb().expect("next RGB") { + out.push(picture); + } + (backend, out, start.elapsed()) +} + +fn ivf_units(ivf: &[u8]) -> Vec<&[u8]> { + let mut pos = usize::from(u16::from_le_bytes([ivf[6], ivf[7]])); + let mut units = Vec::new(); + while pos + 12 <= ivf.len() { + let len = u32::from_le_bytes(ivf[pos..pos + 4].try_into().expect("frame size")) as usize; + units.push(&ivf[pos + 12..pos + 12 + len]); + pos += 12 + len; + } + units +} diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index c8fb62e9..ee4f1152 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -1,7 +1,11 @@ //! One API over Vulkan Video and VA-API. use crate::error::{Error, Result}; -use crate::picture::I420; +use crate::picture::{Decoded, I420, RgbPicture}; +#[cfg(target_os = "linux")] +use crate::picture::{rgb_size, yuv_to_rgb}; +#[cfg(target_os = "linux")] +use ec_core::color::{ColorDescription, Matrix, Tags}; use crate::types::{ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings, }; @@ -476,7 +480,7 @@ impl VkDecoder { } } - fn next_frame(&mut self) -> Option<(i64, I420)> { + fn next_frame(&mut self) -> Option<(i64, Decoded)> { match self { VkDecoder::H264(d) => d.next_frame(), VkDecoder::H265(d) => d.next_frame(), @@ -501,23 +505,52 @@ enum DecInner { const REPLAY_LIMIT: usize = 64; +/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RgbOutput { + /// Byte order of each output pixel. + pub order: RgbOrder, + /// Scale pictures wider than this down to it, keeping the aspect ratio. + pub max_width: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + I420, + Rgb(RgbOutput), +} + /// A hardware decoder on whichever backend opened. pub struct HwDecoder { inner: DecInner, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] codec: Codec, + mode: Mode, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] replay: Option, i64)>>, } impl HwDecoder { - /// Open a decoder for `codec`. H.264, H.265 and AV1 try Vulkan Video first, then VA-API (Linux). + /// Open a decoder for `codec` that hands out I420. H.264, H.265 and AV1 try Vulkan Video first, then VA-API (Linux). pub fn open(codec: Codec) -> Result { + HwDecoder::open_mode(codec, Mode::I420) + } + + /// Open a decoder for `codec` that hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API. + pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result { + HwDecoder::open_mode(codec, Mode::Rgb(output)) + } + + fn open_mode(codec: Codec, mode: Mode) -> Result { + let rgb = match mode { + Mode::I420 => None, + Mode::Rgb(output) => Some(output), + }; let mut reasons = Vec::new(); let vk = match codec { - Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), - Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), - Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), + Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264), + Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265), + Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1), _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), }; match vk { @@ -525,6 +558,7 @@ impl HwDecoder { return Ok(HwDecoder { inner: DecInner::Vk(inner), codec, + mode, replay: Some(Vec::new()), }); } @@ -540,6 +574,7 @@ impl HwDecoder { return Ok(HwDecoder { inner: DecInner::Va(inner), codec, + mode, replay: None, }); } @@ -589,8 +624,31 @@ impl HwDecoder { result } - /// The next picture in display order, as 8-bit I420 with its timestamp. + /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`]. pub fn next_frame(&mut self) -> Result> { + if let Mode::Rgb(_) = self.mode { + return Err(Error::config("next_frame on an RGB decoder; use next_rgb")); + } + match self.pull()? { + None => Ok(None), + Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))), + Some((_, Decoded::Rgb(_))) => Err(Error::config("RGB picture from an I420 decoder")), + } + } + + /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder opened with [`HwDecoder::open`]. + pub fn next_rgb(&mut self) -> Result> { + if let Mode::I420 = self.mode { + return Err(Error::config("next_rgb on an I420 decoder; use open_rgb")); + } + match self.pull()? { + None => Ok(None), + Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))), + Some((_, Decoded::I420(_))) => Err(Error::config("I420 picture from an RGB decoder")), + } + } + + fn pull(&mut self) -> Result> { match &mut self.inner { DecInner::Vk(d) => { let frame = d.next_frame(); @@ -601,7 +659,20 @@ impl HwDecoder { } #[cfg(target_os = "linux")] DecInner::Va(d) => match d.next_frame() { - Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))), + Some(frame) => { + let i420 = frame.to_i420()?; + let decoded = match self.mode { + Mode::I420 => Decoded::I420(i420), + Mode::Rgb(output) => { + let matrix = frame + .colour + .map(|c| c.description.matrix) + .unwrap_or_else(|| default_matrix(i420.height)); + Decoded::Rgb(va_rgb(&i420, output, matrix)) + } + }; + Ok(Some((frame.timestamp, decoded))) + } None => Ok(None), }, } @@ -617,6 +688,26 @@ impl HwDecoder { } } +#[cfg(target_os = "linux")] +fn default_matrix(height: u32) -> Matrix { + ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix +} + +#[cfg(target_os = "linux")] +fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture { + let (w, h) = rgb_size(frame.width, frame.height, output.max_width); + let data = ec_dsp::rgb::i420_to_packed( + &frame.y, + &frame.u, + &frame.v, + (frame.width as usize, frame.height as usize), + (w as usize, h as usize), + output.order == RgbOrder::Bgra, + &yuv_to_rgb(matrix), + ); + RgbPicture::new(data, w, h) +} + #[cfg(target_os = "linux")] fn open_va_decoder(codec: Codec) -> Result { let display = ec_va::open()?; diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 9b1f7998..0d124455 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -85,11 +85,12 @@ pub use dec::{Decoder, StreamInfo}; pub use enc::Encoder; pub use error::{Error, Result}; pub use hw::{ - Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, capabilities, + Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput, + capabilities, }; #[cfg(target_os = "linux")] pub use frame::Frame; -pub use picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; +pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420}; #[cfg(target_os = "linux")] pub use pool::{PooledSurface, SurfacePool}; pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset}; diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs index cebadec2..bea704b4 100644 --- a/crates/ec-hw/src/picture.rs +++ b/crates/ec-hw/src/picture.rs @@ -1,7 +1,7 @@ //! Pixel buffers and conversions that need no VA-API: planar I420 and its //! 10-bit sibling, the colour metadata, and the NV12 conversions. -use ec_core::color::{ColorDescription, ContentLight}; +use ec_core::color::{ColorDescription, ContentLight, Matrix}; use crate::error::{Error, Result}; @@ -34,6 +34,58 @@ pub struct I420 { pub height: u32, } +/// A packed 32-bit RGB picture, alpha 255, `stride` bytes per row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RgbPicture { + /// Pixels, `stride * height` bytes. + pub data: Vec, + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Row stride in bytes: `width * 4`. + pub stride: u32, +} + +impl RgbPicture { + pub(crate) fn new(data: Vec, width: u32, height: u32) -> Self { + RgbPicture { + data, + width, + height, + stride: width * 4, + } + } +} + +/// One decoded picture in the decoder's output form. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Decoded { + I420(I420), + Rgb(RgbPicture), +} + +/// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here. +pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb { + match matrix { + Matrix::Bt601 => ec_dsp::rgb::BT601_LIMITED, + Matrix::Bt709 | Matrix::Bt2020Ncl => ec_dsp::rgb::BT709_LIMITED, + } +} + +/// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even. +pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option) -> (u32, u32) { + match max_width { + Some(max) if max > 0 && width > max => { + let (w, h) = (u64::from(width), u64::from(height)); + let max = u64::from(max); + let even = 2 * ((h * max + w) / (2 * w)); + (max as u32, even.clamp(2, h) as u32) + } + _ => (width, height), + } +} + /// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits. #[derive(Debug, Clone, PartialEq, Eq)] pub struct I420_16 { diff --git a/crates/ec-hw/src/vkdec264.rs b/crates/ec-hw/src/vkdec264.rs index 7b35bea4..68f065f6 100644 --- a/crates/ec-hw/src/vkdec264.rs +++ b/crates/ec-hw/src/vkdec264.rs @@ -13,8 +13,10 @@ use ec_vk::{ use crate::dpb264::{self, Mark, PicInfo, Poc}; use crate::error::{Error, Result}; -use crate::h264_common::peek_pps_id; -use crate::picture::{I420, nv12_to_i420}; +use crate::h264_common::{peek_pps_id, vui_colour_tags}; +use crate::hw::{RgbOrder, RgbOutput}; +use crate::picture::{Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, yuv_to_rgb}; +use ec_core::color::{ColorDescription, Tags}; const MAX_SLOTS: u32 = 17; @@ -43,7 +45,7 @@ struct Current { struct Side { fields: [i32; 2], - output: Option<(i64, I420)>, + output: Option<(i64, Decoded)>, } /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. @@ -56,12 +58,13 @@ pub(crate) struct VkH264Decoder { dpb: Dpb, pics: HashMap, current: Option, - ready: VecDeque<(i64, I420)>, + ready: VecDeque<(i64, Decoded)>, rbsp: Vec, + rgb: Option, } impl VkH264Decoder { - pub(crate) fn new() -> Result { + pub(crate) fn new(rgb: Option) -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; Ok(VkH264Decoder { @@ -75,6 +78,7 @@ impl VkH264Decoder { current: None, ready: VecDeque::new(), rbsp: Vec::new(), + rgb, }) } @@ -117,7 +121,7 @@ impl VkH264Decoder { self.finish_picture() } - pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { self.ready.pop_front() } @@ -315,10 +319,28 @@ impl VkH264Decoder { refs: &refs, slices: &slices, })?; - let (y, uv) = session - .h264 - .read_output(sps.coded_width, sps.coded_height)?; - let out = crop(&sps, &y, &uv); + let out = match self.rgb { + None => { + let (y, uv) = session + .h264 + .read_output(sps.coded_width, sps.coded_height)?; + Decoded::I420(crop(&sps, &y, &uv)) + } + Some(rgb) => { + let (left, _, top, _) = sps.crop; + let matrix = + ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height) + .matrix; + let (w, h) = rgb_size(sps.width, sps.height, rgb.max_width); + let data = session.h264.read_output_rgb( + (left, top, sps.width, sps.height), + (w, h), + rgb.order == RgbOrder::Bgra, + yuv_to_rgb(matrix).words(), + )?; + Decoded::Rgb(RgbPicture::new(data, w, h)) + } + }; let picture = Picture { id: current.id, diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs index 53fbbb53..60de62d5 100644 --- a/crates/ec-hw/src/vkdec265.rs +++ b/crates/ec-hw/src/vkdec265.rs @@ -14,9 +14,12 @@ use ec_vk::{ use crate::error::{Error, Result}; use crate::hevc_dpb::{ self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, - peek_pps_id, + peek_pps_id, vui_colour_tags, }; -use crate::picture::{I420, semi_planar_to_i420}; +use ec_core::color::{ColorDescription, Tags}; + +use crate::hw::{RgbOrder, RgbOutput}; +use crate::picture::{Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb}; const MAX_SLOTS: u32 = 17; @@ -54,14 +57,15 @@ pub(crate) struct VkH265Decoder { sps_map: Vec>, pps_map: Vec>, dpb: Dpb, - outputs: HashMap, + outputs: HashMap, current: Option, - ready: VecDeque<(i64, I420)>, + ready: VecDeque<(i64, Decoded)>, no_rasl_output: bool, + rgb: Option, } impl VkH265Decoder { - pub(crate) fn new() -> Result { + pub(crate) fn new(rgb: Option) -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; Ok(VkH265Decoder { @@ -76,6 +80,7 @@ impl VkH265Decoder { current: None, ready: VecDeque::new(), no_rasl_output: false, + rgb, }) } @@ -112,7 +117,7 @@ impl VkH265Decoder { self.finish_picture() } - pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { self.ready.pop_front() } @@ -336,12 +341,31 @@ impl VkH265Decoder { refs: &refs, slices: &slices, })?; - let (y, uv) = session.h265.read_output( - sps.pic_width_in_luma_samples, - sps.pic_height_in_luma_samples, - )?; if current.output { - let frame = crop(&sps, &y, &uv)?; + let frame = match self.rgb { + None => { + let (y, uv) = session.h265.read_output( + sps.pic_width_in_luma_samples, + sps.pic_height_in_luma_samples, + )?; + Decoded::I420(crop(&sps, &y, &uv)?) + } + Some(rgb) => { + let (width, height) = sps.display_size(); + let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32); + let matrix = + ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height) + .matrix; + let (w, h) = rgb_size(width, height, rgb.max_width); + let data = session.h265.read_output_rgb( + (origin.0, origin.1, width, height), + (w, h), + rgb.order == RgbOrder::Bgra, + yuv_to_rgb(matrix).words(), + )?; + Decoded::Rgb(RgbPicture::new(data, w, h)) + } + }; self.outputs.insert(current.slot, frame); } diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index e2f926ff..f1ba8cc1 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -17,7 +17,10 @@ use ec_vk::{ use crate::av1_refs::RefSlots; use crate::error::{Error, Result}; -use crate::picture::{I420, semi_planar_to_i420}; +use ec_core::color::{ColorDescription, Tags}; + +use crate::hw::{RgbOrder, RgbOutput}; +use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb}; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; @@ -31,7 +34,7 @@ struct Session { struct Reference { state: Av1RefSlot, - picture: I420, + picture: Decoded, } /// AV1 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. @@ -40,11 +43,12 @@ pub(crate) struct VkAv1Decoder { parser: Av1Parser, session: Option, refs: RefSlots>, - ready: VecDeque<(i64, I420)>, + ready: VecDeque<(i64, Decoded)>, + rgb: Option, } impl VkAv1Decoder { - pub(crate) fn new() -> Result { + pub(crate) fn new(rgb: Option) -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?; Ok(VkAv1Decoder { @@ -53,6 +57,7 @@ impl VkAv1Decoder { session: None, refs: RefSlots::new(), ready: VecDeque::new(), + rgb, }) } @@ -81,7 +86,7 @@ impl VkAv1Decoder { Ok(()) } - pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { self.ready.pop_front() } @@ -161,15 +166,31 @@ impl VkAv1Decoder { if !(header.show_frame || header.refresh_frame_flags != 0) { return Ok(()); } - let (y, uv) = session.av1.read_output(width, height)?; - let decoded = semi_planar_to_i420( - session.bit_depth, - &y, - &uv, - width as usize, - (0, 0), - (width, height), - )?; + let decoded = match self.rgb { + None => { + let (y, uv) = session.av1.read_output(width, height)?; + Decoded::I420(semi_planar_to_i420( + session.bit_depth, + &y, + &uv, + width as usize, + (0, 0), + (width, height), + )?) + } + Some(rgb) => { + let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0); + let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; + let (w, h) = rgb_size(width, height, rgb.max_width); + let data = session.av1.read_output_rgb( + (0, 0, width, height), + (w, h), + rgb.order == RgbOrder::Bgra, + yuv_to_rgb(matrix).words(), + )?; + Decoded::Rgb(RgbPicture::new(data, w, h)) + } + }; let state = Av1RefSlot { slot: setup_slot, frame_type: av1_frame_type(header.frame_type), diff --git a/shims/vk-video-ffi/shaders/nv12_to_rgb.comp b/shims/vk-video-ffi/shaders/nv12_to_rgb.comp new file mode 100644 index 00000000..b3b698a9 --- /dev/null +++ b/shims/vk-video-ffi/shaders/nv12_to_rgb.comp @@ -0,0 +1,68 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 8) in; + +layout(std430, set = 0, binding = 0) readonly buffer Src { + uint src[]; +}; + +layout(std430, set = 0, binding = 1) writeonly buffer Dst { + uint dst[]; +}; + +layout(push_constant) uniform Push { + uint w; + uint h; + uint out_w; + uint out_h; + uint bytes; + uint bgra; + int ky; + int rv; + int gu; + int gv; + int bu; +} pc; + +uint byte_at(uint o) { + return (src[o >> 2] >> ((o & 3u) * 8u)) & 255u; +} + +uint sample_at(uint e) { + return byte_at(e * pc.bytes + pc.bytes - 1u); +} + +ivec3 rgb_at(uint x, uint y) { + int yy = int(sample_at(y * pc.w + x)) - 16; + uint c = pc.w * pc.h + (y / 2u) * pc.w + 2u * (x / 2u); + int u = int(sample_at(c)) - 128; + int v = int(sample_at(c + 1u)) - 128; + int r = (pc.ky * yy + pc.rv * v + 128) >> 8; + int g = (pc.ky * yy + pc.gu * u + pc.gv * v + 128) >> 8; + int b = (pc.ky * yy + pc.bu * u + 128) >> 8; + return clamp(ivec3(r, g, b), 0, 255); +} + +void main() { + uint ox = gl_GlobalInvocationID.x; + uint oy = gl_GlobalInvocationID.y; + if (ox >= pc.out_w || oy >= pc.out_h) { + return; + } + uint x0 = ox * pc.w / pc.out_w; + uint x1 = ((ox + 1u) * pc.w + pc.out_w - 1u) / pc.out_w; + uint y0 = oy * pc.h / pc.out_h; + uint y1 = ((oy + 1u) * pc.h + pc.out_h - 1u) / pc.out_h; + uvec3 sum = uvec3(0u); + for (uint y = y0; y < y1; ++y) { + for (uint x = x0; x < x1; ++x) { + sum += uvec3(rgb_at(x, y)); + } + } + uint n = (x1 - x0) * (y1 - y0); + uvec3 c = (sum + uvec3(n / 2u)) / uvec3(n); + uint px = pc.bgra != 0u + ? (c.b | (c.g << 8) | (c.r << 16)) + : (c.r | (c.g << 8) | (c.b << 16)); + dst[oy * pc.out_w + ox] = px | 0xFF000000u; +} diff --git a/shims/vk-video-ffi/shaders/nv12_to_rgb.spv b/shims/vk-video-ffi/shaders/nv12_to_rgb.spv new file mode 100644 index 0000000000000000000000000000000000000000..d19fd4ff1976df2298164fbc2acff685dd4ffb2b GIT binary patch literal 7664 zcmZvh2b5J;6^8#a@6ABy1PEym2q`FpKtc^dLIN3xC@A(e4#S9JhT;?q8a2ikd+*(~ zY|&_py)Ts{#@>7Hy=$r_aee#lf9CSmduzRQ&;HLoyPtB;ZFDS}AQes4R9#XOznSU~ z&B^MDXZQA9+m{WG>{+&Q)p8i7sS$keOjnmWB{e1O>mArn$2%m=P*-3xB~8pf{0%kK zA?ZkA%p`Sh@9EyLqkH?7p1y+zdxl325BB#A4(#vm*)uTI-#0RFs2{$GHNJuUeS@QW z>I|J~9;Lrioth+R_u-NLp5Bqgqbt^{Qw<#>>42n8b!n=k;of}*2gf+T8=4}iKY3YDmrB|>I{bJbq6E$FNi~{S z!9aBBCuRpmM|vur3L^_(bw2Wd-@~=B>M#J6gqKnWTe#w3}K-yLYH}U&dr3@i|=eZE5MdL{eY!JxbDOw3~W#3m-g(vhQ&% zeNVvdl<{P2%=QcLIood~PM2ZB#Hh`^gFW4Y2X^-kZrgw8Kwt03z=8eSHYe}3@P@q& zeTFd8baW8JhKsTCk00XMW*l z1EjBR;m;c1nY5D9;juCuU zwfOT=DeBt%Z_F5y|F@+sVvfGIr>)?`2bwuRz1aSDW=`S1Ci{rbY<1|mnjas{T*CLq zv>CZe)fLY_OCbw+{B7U-!g^TMp6462$9#fD-iA`uQD8|kpIm#`b1_Cs_gEkEiF)Es z4p*x)_*rZC5rf;+5xS8{{j-=H2X%KX78xe>>s9y344fXp6nxan!Th> zlZZOaep08|PfR19J;gLn_LVw)YSNq38M%B{=9_$M$T|6LDe#SIL_DC)|DNP0p5}kA z6gd3E3)+3}%a}5rxpjTcKh_2Fyg%{l)EV{k0V&3TU!!JVACv;WO$~iG^LMA3fqzH} zj9k*T+>c0Mk9B`6byKJ2`M4Cgb$>#Nao~5TV@xhOZ_$LX<&$X(H48sFvFp<{yWshh z6c~2VzDp(A@LB(7TjKM%w2^hxJV&I!uZokcbb}P*!0p?OZQ^>96!_IS?(;booLo`M zVAk`6wB?HA|DqHaxwf7!wXyHZQsB1lD^iRF_qeaNvF~eA;MVtbDaL|dnKpbw3cPN^ zH`~bimK3;s{k9Zi!SR)O3T9uw+fp0fOPQ?Q=J~!9xc&Np6yw0{*AH`Cy{3L71#Vk@ zEX7!GY+;Q6v!0)(Esn#_q`>Mv|GbTTzmNjAeZQ1qEV%9aRU7+$Ed_3UzmZ}rxa0m? zDe$@tziT7w_fp{Y^$${v1;#^Of;*-EUz_u2 zA?LADo!{8=POHvbQM>dlD$?1d$|Y@NbN)D;8Y~JQE&Gg8;pRCrd02DIv$!bm8*@Ln zS5aV`fp1Fe-bEpcKFeB?vg+rWrA2{T)>%b?aelX~Wkn&6K4Qdq35*)US85dhtY>)} zJu8X=H_th3{5rQNaNDx7D6qO;tBOJveU`O4Wl<}R(VC*bEo*I2V0FLN6@@(d>=#(w zFZ{F2^NPZEcsWBtyYKvR^ttMSteg6oZc|aM${(nd*qe(e(OCc z->Hsdjm?t+!$<2qMb*1Kdg=FA-p}bX%{xCjZcbU;4}kIR>-d~ryPL4iGxFV?K9A*| z0-X2ayVVhN-9PR=XtdhW5KOGD8VISDKjM;gaJ8=Alw%^=ea7Vx-qRBXG_N+%a_X zex3P(-j*0^3^Ir%nCsxaZEW2x1#X`ECr|y%y+aDz{_K=u9Ju{?K*q)U=PoHQ)2WWY0yq7NmYBU#3LbF#@G2?f(`W3}Qs8yJULyr=zgU;Stn0P8mYaT^6uz5&y%b|O zkFz(uL5eZ((P#Wks?IE|=lqSoS&BPb?rr%`(ZrDRmb`oA4jY+_hnM}3KK8@^1F)u& AnE(I) literal 0 HcmV?d00001 diff --git a/shims/vk-video-ffi/src/av1_decode.rs b/shims/vk-video-ffi/src/av1_decode.rs index 86c64a6c..cba422c9 100644 --- a/shims/vk-video-ffi/src/av1_decode.rs +++ b/shims/vk-video-ffi/src/av1_decode.rs @@ -856,6 +856,17 @@ impl Av1DecodeSession { pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { self.dec.read_nv12(width, height) } + + /// 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. + pub fn read_output_rgb( + &mut self, + crop: (u32, u32, u32, u32), + out: (u32, u32), + bgra: bool, + coeffs: [i32; 5], + ) -> Result, Error> { + self.dec.read_rgb(crop, out, bgra, coeffs) + } } fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { diff --git a/shims/vk-video-ffi/src/h264_decode.rs b/shims/vk-video-ffi/src/h264_decode.rs index 73016e9e..7fea220b 100644 --- a/shims/vk-video-ffi/src/h264_decode.rs +++ b/shims/vk-video-ffi/src/h264_decode.rs @@ -460,6 +460,17 @@ impl H264DecodeSession { pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { self.dec.read_nv12(width, height) } + + /// 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. + pub fn read_output_rgb( + &mut self, + crop: (u32, u32, u32, u32), + out: (u32, u32), + bgra: bool, + coeffs: [i32; 5], + ) -> Result, Error> { + self.dec.read_rgb(crop, out, bgra, coeffs) + } } fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { diff --git a/shims/vk-video-ffi/src/h265_decode.rs b/shims/vk-video-ffi/src/h265_decode.rs index cfbfdce6..8d44e682 100644 --- a/shims/vk-video-ffi/src/h265_decode.rs +++ b/shims/vk-video-ffi/src/h265_decode.rs @@ -697,6 +697,17 @@ impl H265DecodeSession { pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { self.dec.read_nv12(width, height) } + + /// 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. + pub fn read_output_rgb( + &mut self, + crop: (u32, u32, u32, u32), + out: (u32, u32), + bgra: bool, + coeffs: [i32; 5], + ) -> Result, Error> { + self.dec.read_rgb(crop, out, bgra, coeffs) + } } fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result { diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index 9cc67ddb..169ad9d7 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -13,6 +13,7 @@ mod h264_encode; mod h265_decode; mod h265_encode; mod rgb_convert; +mod rgb_decode; mod session; pub use av1_decode::{ diff --git a/shims/vk-video-ffi/src/rgb_decode.rs b/shims/vk-video-ffi/src/rgb_decode.rs new file mode 100644 index 00000000..c3c1384b --- /dev/null +++ b/shims/vk-video-ffi/src/rgb_decode.rs @@ -0,0 +1,181 @@ +use vulkanalia::prelude::v1_3::*; + +use crate::session::vk; +use crate::{Error, Gpu}; + +const SPV: &[u8] = include_bytes!("../shaders/nv12_to_rgb.spv"); + +pub(crate) struct RgbPass { + set_layout: vk::DescriptorSetLayout, + pool: vk::DescriptorPool, + set: vk::DescriptorSet, + layout: vk::PipelineLayout, + pipeline: vk::Pipeline, +} + +pub(crate) struct Params { + pub(crate) w: u32, + pub(crate) h: u32, + pub(crate) out: (u32, u32), + pub(crate) bytes: u32, + pub(crate) bgra: bool, + pub(crate) coeffs: [i32; 5], +} + +impl RgbPass { + pub(crate) fn new( + gpu: &Gpu, + input: (vk::Buffer, u64), + output: (vk::Buffer, u64), + ) -> Result { + let d = gpu.device(); + let bindings = [storage(0), storage(1)]; + let set_info = vk::DescriptorSetLayoutCreateInfo::builder().bindings(&bindings); + let set_layout = unsafe { + vk( + d.create_descriptor_set_layout(&set_info, None), + "vkCreateDescriptorSetLayout", + )? + }; + let push = vk::PushConstantRange::builder() + .stage_flags(vk::ShaderStageFlags::COMPUTE) + .offset(0) + .size(44) + .build(); + let set_layouts = [set_layout]; + let pushes = [push]; + let layout_info = vk::PipelineLayoutCreateInfo::builder() + .set_layouts(&set_layouts) + .push_constant_ranges(&pushes); + let layout = unsafe { + vk( + d.create_pipeline_layout(&layout_info, None), + "vkCreatePipelineLayout", + )? + }; + + let words: Vec = SPV + .chunks_exact(4) + .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + let module_info = vk::ShaderModuleCreateInfo::builder() + .code_size(SPV.len()) + .code(&words); + let module = unsafe { + vk( + d.create_shader_module(&module_info, None), + "vkCreateShaderModule", + )? + }; + let stage = vk::PipelineShaderStageCreateInfo::builder() + .stage(vk::ShaderStageFlags::COMPUTE) + .module(module) + .name(b"main\0"); + let pipeline_info = vk::ComputePipelineCreateInfo::builder() + .stage(stage) + .layout(layout); + let pipelines = unsafe { + d.create_compute_pipelines(vk::PipelineCache::null(), &[pipeline_info], None) + }; + unsafe { d.destroy_shader_module(module, None) }; + let pipeline = pipelines + .map_err(|c| Error::Vk(c.as_raw(), "vkCreateComputePipelines"))? + .0[0]; + + let sizes = [vk::DescriptorPoolSize { + type_: vk::DescriptorType::STORAGE_BUFFER, + descriptor_count: 2, + }]; + let pool_info = vk::DescriptorPoolCreateInfo::builder() + .max_sets(1) + .pool_sizes(&sizes); + let pool = unsafe { + vk( + d.create_descriptor_pool(&pool_info, None), + "vkCreateDescriptorPool", + )? + }; + let alloc = vk::DescriptorSetAllocateInfo::builder() + .descriptor_pool(pool) + .set_layouts(&set_layouts); + let set = unsafe { + vk( + d.allocate_descriptor_sets(&alloc), + "vkAllocateDescriptorSets", + )?[0] + }; + let infos = [ + [vk::DescriptorBufferInfo { + buffer: input.0, + offset: 0, + range: input.1, + }], + [vk::DescriptorBufferInfo { + buffer: output.0, + offset: 0, + range: output.1, + }], + ]; + let writes = [ + vk::WriteDescriptorSet::builder() + .dst_set(set) + .dst_binding(0) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .buffer_info(&infos[0]) + .build(), + vk::WriteDescriptorSet::builder() + .dst_set(set) + .dst_binding(1) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .buffer_info(&infos[1]) + .build(), + ]; + unsafe { d.update_descriptor_sets(&writes, &[] as &[vk::CopyDescriptorSet]) }; + + Ok(RgbPass { + set_layout, + pool, + set, + layout, + pipeline, + }) + } + + pub(crate) fn record(&self, d: &Device, cb: vk::CommandBuffer, p: &Params) { + let words = [p.w, p.h, p.out.0, p.out.1, p.bytes, p.bgra as u32]; + let mut push: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + push.extend(p.coeffs.iter().flat_map(|c| c.to_le_bytes())); + let sets = [self.set]; + unsafe { + d.cmd_bind_pipeline(cb, vk::PipelineBindPoint::COMPUTE, self.pipeline); + d.cmd_bind_descriptor_sets( + cb, + vk::PipelineBindPoint::COMPUTE, + self.layout, + 0, + &sets, + &[], + ); + d.cmd_push_constants(cb, self.layout, vk::ShaderStageFlags::COMPUTE, 0, &push); + d.cmd_dispatch(cb, p.out.0.div_ceil(8), p.out.1.div_ceil(8), 1); + } + } + + pub(crate) fn destroy(&self, d: &Device) { + unsafe { + d.destroy_descriptor_pool(self.pool, None); + d.destroy_pipeline(self.pipeline, None); + d.destroy_pipeline_layout(self.layout, None); + d.destroy_descriptor_set_layout(self.set_layout, None); + } + } +} + +fn storage(binding: u32) -> vk::DescriptorSetLayoutBinding { + vk::DescriptorSetLayoutBinding::builder() + .binding(binding) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .descriptor_count(1) + .stage_flags(vk::ShaderStageFlags::COMPUTE) + .build() +} diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index d5af6be2..135038b6 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -5,6 +5,7 @@ use vulkanalia::vk::{ }; use crate::rgb_convert::{Input, RgbConverter}; +use crate::rgb_decode::{Params, RgbPass}; use crate::{Error, Gpu, RateControl}; pub(crate) const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM; @@ -120,6 +121,15 @@ pub(crate) fn copy_region( aspect: vk::ImageAspectFlags, width: u32, height: u32, +) -> vk::BufferImageCopy { + copy_rect(offset, aspect, (0, 0), (width, height)) +} + +pub(crate) fn copy_rect( + offset: u64, + aspect: vk::ImageAspectFlags, + origin: (u32, u32), + (width, height): (u32, u32), ) -> vk::BufferImageCopy { vk::BufferImageCopy::builder() .buffer_offset(offset) @@ -129,6 +139,11 @@ pub(crate) fn copy_region( base_array_layer: 0, layer_count: 1, }) + .image_offset(vk::Offset3D { + x: origin.0 as i32, + y: origin.1 as i32, + z: 0, + }) .image_extent(vk::Extent3D { width, height, @@ -906,6 +921,8 @@ pub(crate) struct Decoder { pub(crate) output: Image, pub(crate) bitstream: Buffer, readback: Buffer, + rgb_out: Buffer, + rgb: Option, pub(crate) coded: bool, } @@ -935,6 +952,8 @@ impl Decoder { output: Default::default(), bitstream: Default::default(), readback: Default::default(), + rgb_out: Default::default(), + rgb: None, coded: false, }; let mut list = vk::VideoProfileListInfoKHR::builder() @@ -969,12 +988,25 @@ impl Decoder { vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, Some(&mut list), )?; + let readback_size = max_extent.width as u64 * max_extent.height as u64 * 3 / 2 * bytes; dec.readback = dec.vs.buffer( - max_extent.width as u64 * max_extent.height as u64 * 3 / 2 * bytes, - vk::BufferUsageFlags::TRANSFER_DST, + readback_size, + vk::BufferUsageFlags::TRANSFER_DST | vk::BufferUsageFlags::STORAGE_BUFFER, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, None, )?; + let rgb_size = max_extent.width as u64 * max_extent.height as u64 * 4; + dec.rgb_out = dec.vs.buffer( + rgb_size, + vk::BufferUsageFlags::STORAGE_BUFFER, + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, + None, + )?; + dec.rgb = Some(RgbPass::new( + &gpu, + (dec.readback.buffer, readback_size), + (dec.rgb_out.buffer, rgb_size), + )?); let d = gpu.device(); let cb = dec.decode.cb; @@ -1047,8 +1079,6 @@ impl Decoder { } let gpu = self.vs.gpu.clone(); let d = gpu.device(); - let cb = self.graphics.cb; - let image = self.output.image; let bytes = bytes_per_sample(self.vs.format); let luma = width as usize * height as usize * bytes; let copies = [ @@ -1056,6 +1086,99 @@ impl Decoder { copy_region(luma as u64, PLANE_1, width / 2, height / 2), ]; self.graphics.begin()?; + self.copy_to_readback(d, self.graphics.cb, &copies); + self.graphics.end()?; + self.graphics.submit()?; + let ptr = self + .readback + .ptr + .ok_or_else(|| Error::Invalid("readback buffer not mapped".into()))?; + let bytes = unsafe { std::slice::from_raw_parts(ptr, luma * 3 / 2) }; + Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec())) + } + + /// Copies the crop window `(x, y, width, height)` of the last decoded picture as packed 4-byte pixels, box-downscaled to `out` and converted to RGB on the GPU with the integer `coeffs` `[ky, rv, gu, gv, bu]`. `bgra` picks the byte order; alpha is 255. + pub(crate) fn read_rgb( + &mut self, + crop: (u32, u32, u32, u32), + out: (u32, u32), + bgra: bool, + coeffs: [i32; 5], + ) -> Result, Error> { + let (x, y, width, height) = crop; + if !self.coded { + return Err(Error::Invalid("nothing decoded".into())); + } + if width == 0 + || height == 0 + || width % 2 != 0 + || height % 2 != 0 + || x % 2 != 0 + || y % 2 != 0 + || x + width > self.max_extent.width + || y + height > self.max_extent.height + || out.0 == 0 + || out.1 == 0 + || out.0 > width + || out.1 > height + { + return Err(Error::Invalid("RGB readback size".into())); + } + let pass = self + .rgb + .as_ref() + .ok_or_else(|| Error::Invalid("RGB readback not set up".into()))?; + let gpu = self.vs.gpu.clone(); + let d = gpu.device(); + let cb = self.graphics.cb; + let bytes = bytes_per_sample(self.vs.format); + let luma = width as usize * height as usize * bytes; + let copies = [ + copy_rect(0, PLANE_0, (x, y), (width, height)), + copy_rect(luma as u64, PLANE_1, (x / 2, y / 2), (width / 2, height / 2)), + ]; + self.graphics.begin()?; + self.copy_to_readback(d, cb, &copies); + let barrier = vk::BufferMemoryBarrier2::builder() + .src_stage_mask(vk::PipelineStageFlags2::COPY) + .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE) + .dst_stage_mask(vk::PipelineStageFlags2::COMPUTE_SHADER) + .dst_access_mask(vk::AccessFlags2::SHADER_STORAGE_READ) + .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) + .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) + .buffer(self.readback.buffer) + .offset(0) + .size(vk::WHOLE_SIZE) + .build(); + let barriers = [barrier]; + let dep = vk::DependencyInfo::builder().buffer_memory_barriers(&barriers); + unsafe { + d.cmd_pipeline_barrier2(cb, &dep); + } + pass.record( + d, + cb, + &Params { + w: width, + h: height, + out, + bytes: bytes as u32, + bgra, + coeffs, + }, + ); + self.graphics.end()?; + self.graphics.submit()?; + let ptr = self + .rgb_out + .ptr + .ok_or_else(|| Error::Invalid("RGB buffer not mapped".into()))?; + let len = out.0 as usize * out.1 as usize * 4; + Ok(unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()) + } + + fn copy_to_readback(&self, d: &Device, cb: vk::CommandBuffer, copies: &[vk::BufferImageCopy]) { + let image = self.output.image; unsafe { barrier( d, @@ -1077,7 +1200,7 @@ impl Decoder { image, vk::ImageLayout::TRANSFER_SRC_OPTIMAL, self.readback.buffer, - &copies, + copies, ); barrier( d, @@ -1095,14 +1218,6 @@ impl Decoder { ), ); } - self.graphics.end()?; - self.graphics.submit()?; - let ptr = self - .readback - .ptr - .ok_or_else(|| Error::Invalid("readback buffer not mapped".into()))?; - let bytes = unsafe { std::slice::from_raw_parts(ptr, luma * 3 / 2) }; - Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec())) } } @@ -1118,5 +1233,9 @@ impl Drop for Decoder { } self.bitstream.destroy(d); self.readback.destroy(d); + self.rgb_out.destroy(d); + if let Some(rgb) = &self.rgb { + rgb.destroy(d); + } } }