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
Browse files at this commitb411317dadc07a6a07b17d62e61662883502c907Parent: 8352fa116 changed files +933 -60
- crates/ec-dsp/src/rgb.rs +91 -1
- crates/ec-hw/examples/hw_decode_rgb.rs +170 -0
- crates/ec-hw/src/hw.rs +99 -8
- crates/ec-hw/src/lib.rs +3 -2
- crates/ec-hw/src/picture.rs +53 -1
- crates/ec-hw/src/vkdec264.rs +32 -10
- crates/ec-hw/src/vkdec265.rs +35 -11
- crates/ec-hw/src/vkdec_av1.rs +35 -14
- shims/vk-video-ffi/shaders/nv12_to_rgb.comp +68 -0
- shims/vk-video-ffi/shaders/nv12_to_rgb.spv +0 -0
- shims/vk-video-ffi/src/av1_decode.rs +11 -0
- shims/vk-video-ffi/src/h264_decode.rs +11 -0
- shims/vk-video-ffi/src/h265_decode.rs +11 -0
- shims/vk-video-ffi/src/lib.rs +1 -0
- shims/vk-video-ffi/src/rgb_decode.rs +181 -0
- shims/vk-video-ffi/src/session.rs +132 -13
crates/ec-dsp/src/rgb.rsmodified+91 -1
| @@ -34,7 +34,10 @@ pub fn rgb_box_downscale( | |||
| 34 | dw: usize, | 34 | dw: usize, |
| 35 | dh: usize, | 35 | dh: usize, |
| 36 | ) { | 36 | ) { |
| 37 | - assert!(sw >= dw && sh >= dh && dw > 0 && dh > 0, "source smaller than output"); | 37 | + assert!( |
| 38 | + sw >= dw && sh >= dh && dw > 0 && dh > 0, | ||
| 39 | + "source smaller than output" | ||
| 40 | + ); | ||
| 38 | assert!(stride >= sw * 4 && src.len() >= stride * sh); | 41 | assert!(stride >= sw * 4 && src.len() >= stride * sh); |
| 39 | assert_eq!(dst.len(), dw * dh * 4); | 42 | assert_eq!(dst.len(), dw * dh * 4); |
| 40 | for oy in 0..dh { | 43 | for oy in 0..dh { |
| @@ -57,6 +60,93 @@ pub fn rgb_box_downscale( | |||
| 57 | } | 60 | } |
| 58 | } | 61 | } |
| 59 | 62 | ||
| 63 | +/// 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. | ||
| 64 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 65 | +pub struct YuvToRgb { | ||
| 66 | + /// Luma scale. | ||
| 67 | + pub ky: i32, | ||
| 68 | + /// Red from Cr. | ||
| 69 | + pub rv: i32, | ||
| 70 | + /// Green from Cb. | ||
| 71 | + pub gu: i32, | ||
| 72 | + /// Green from Cr. | ||
| 73 | + pub gv: i32, | ||
| 74 | + /// Blue from Cb. | ||
| 75 | + pub bu: i32, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +impl YuvToRgb { | ||
| 79 | + /// The five coefficients in shader push-constant order. | ||
| 80 | + pub fn words(self) -> [i32; 5] { | ||
| 81 | + [self.ky, self.rv, self.gu, self.gv, self.bu] | ||
| 82 | + } | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// BT.601, limited range. | ||
| 86 | +pub const BT601_LIMITED: YuvToRgb = YuvToRgb { | ||
| 87 | + ky: 298, | ||
| 88 | + rv: 409, | ||
| 89 | + gu: -100, | ||
| 90 | + gv: -208, | ||
| 91 | + bu: 516, | ||
| 92 | +}; | ||
| 93 | + | ||
| 94 | +/// BT.709, limited range. | ||
| 95 | +pub const BT709_LIMITED: YuvToRgb = YuvToRgb { | ||
| 96 | + ky: 298, | ||
| 97 | + rv: 459, | ||
| 98 | + gu: -55, | ||
| 99 | + gv: -136, | ||
| 100 | + bu: 541, | ||
| 101 | +}; | ||
| 102 | + | ||
| 103 | +/// 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. | ||
| 104 | +pub fn i420_to_packed( | ||
| 105 | + y: &[u8], | ||
| 106 | + u: &[u8], | ||
| 107 | + v: &[u8], | ||
| 108 | + (w, h): (usize, usize), | ||
| 109 | + (dw, dh): (usize, usize), | ||
| 110 | + bgra: bool, | ||
| 111 | + k: &YuvToRgb, | ||
| 112 | +) -> Vec<u8> { | ||
| 113 | + assert!(w % 2 == 0 && h % 2 == 0, "width and height must be even"); | ||
| 114 | + assert!( | ||
| 115 | + w >= dw && h >= dh && dw > 0 && dh > 0, | ||
| 116 | + "source smaller than output" | ||
| 117 | + ); | ||
| 118 | + assert!(y.len() == w * h && u.len() == w * h / 4 && v.len() == w * h / 4); | ||
| 119 | + let cw = w / 2; | ||
| 120 | + let mut out = vec![255u8; dw * dh * 4]; | ||
| 121 | + for oy in 0..dh { | ||
| 122 | + let (y0, y1) = footprint(oy, h, dh); | ||
| 123 | + for ox in 0..dw { | ||
| 124 | + let (x0, x1) = footprint(ox, w, dw); | ||
| 125 | + let mut sum = [0u32; 3]; | ||
| 126 | + for sy in y0..y1 { | ||
| 127 | + for sx in x0..x1 { | ||
| 128 | + let c = (sy / 2) * cw + sx / 2; | ||
| 129 | + let yy = i32::from(y[sy * w + sx]) - 16; | ||
| 130 | + let uu = i32::from(u[c]) - 128; | ||
| 131 | + let vv = i32::from(v[c]) - 128; | ||
| 132 | + let r = ((k.ky * yy + k.rv * vv + 128) >> 8).clamp(0, 255); | ||
| 133 | + let g = ((k.ky * yy + k.gu * uu + k.gv * vv + 128) >> 8).clamp(0, 255); | ||
| 134 | + let b = ((k.ky * yy + k.bu * uu + 128) >> 8).clamp(0, 255); | ||
| 135 | + for (s, c) in sum.iter_mut().zip([r, g, b]) { | ||
| 136 | + *s += c as u32; | ||
| 137 | + } | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + let n = ((x1 - x0) * (y1 - y0)) as u32; | ||
| 141 | + let [r, g, b] = sum.map(|s| ((s + n / 2) / n) as u8); | ||
| 142 | + let o = (oy * dw + ox) * 4; | ||
| 143 | + let px = if bgra { [b, g, r] } else { [r, g, b] }; | ||
| 144 | + out[o..o + 3].copy_from_slice(&px); | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + out | ||
| 148 | +} | ||
| 149 | + | ||
| 60 | fn footprint(o: usize, n_in: usize, n_out: usize) -> (usize, usize) { | 150 | fn footprint(o: usize, n_in: usize, n_out: usize) -> (usize, usize) { |
| 61 | (o * n_in / n_out, ((o + 1) * n_in).div_ceil(n_out)) | 151 | (o * n_in / n_out, ((o + 1) * n_in).div_ceil(n_out)) |
| 62 | } | 152 | } |
crates/ec-hw/examples/hw_decode_rgb.rsadded+170 -0
| @@ -0,0 +1,170 @@ | |||
| 1 | +//! 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. | ||
| 2 | +//! | ||
| 3 | +//! Streams are assumed untagged, so the matrix is BT.709 from 720 lines up and BT.601 below. | ||
| 4 | +//! | ||
| 5 | +//! ```text | ||
| 6 | +//! cargo run --release -p ec-hw --example hw_decode_rgb -- <scratch dir> | ||
| 7 | +//! ``` | ||
| 8 | + | ||
| 9 | +use std::fs; | ||
| 10 | +use std::path::PathBuf; | ||
| 11 | +use std::time::{Duration, Instant}; | ||
| 12 | + | ||
| 13 | +use ec_dsp::rgb::{YuvToRgb, i420_to_packed}; | ||
| 14 | +use ec_hw::{Backend, Codec, HwDecoder, I420, RgbOrder, RgbOutput, RgbPicture}; | ||
| 15 | + | ||
| 16 | +const FILES: &[(&str, Codec)] = &[ | ||
| 17 | + ("bf1280.h264", Codec::H264), | ||
| 18 | + ("h265idr720.hevc", Codec::H265), | ||
| 19 | + ("av1aom720.ivf", Codec::Av1), | ||
| 20 | + ("ten.hevc", Codec::H265), | ||
| 21 | +]; | ||
| 22 | + | ||
| 23 | +fn main() { | ||
| 24 | + let dir = PathBuf::from(std::env::args().nth(1).expect("scratch dir argument")); | ||
| 25 | + for &(name, codec) in FILES { | ||
| 26 | + let data = fs::read(dir.join(name)).expect("read stream"); | ||
| 27 | + let units = if codec == Codec::Av1 { | ||
| 28 | + ivf_units(&data) | ||
| 29 | + } else { | ||
| 30 | + vec![data.as_slice()] | ||
| 31 | + }; | ||
| 32 | + let (_, reference, i420_time) = decode_i420(codec, &units); | ||
| 33 | + let expected_frames = reference.len(); | ||
| 34 | + for max_width in [None, Some(640)] { | ||
| 35 | + let order = if max_width.is_some() { | ||
| 36 | + RgbOrder::Rgba | ||
| 37 | + } else { | ||
| 38 | + RgbOrder::Bgra | ||
| 39 | + }; | ||
| 40 | + let output = RgbOutput { order, max_width }; | ||
| 41 | + let (backend, got, rgb_time) = decode_rgb(codec, &units, output); | ||
| 42 | + let expected: Vec<(Vec<u8>, u32, u32)> = reference | ||
| 43 | + .iter() | ||
| 44 | + .map(|f| { | ||
| 45 | + let (w, h) = out_size(f.width, f.height, max_width); | ||
| 46 | + let coeffs = matrix_for(f.height); | ||
| 47 | + let data = i420_to_packed( | ||
| 48 | + &f.y, | ||
| 49 | + &f.u, | ||
| 50 | + &f.v, | ||
| 51 | + (f.width as usize, f.height as usize), | ||
| 52 | + (w as usize, h as usize), | ||
| 53 | + order == RgbOrder::Bgra, | ||
| 54 | + &coeffs, | ||
| 55 | + ); | ||
| 56 | + (data, w, h) | ||
| 57 | + }) | ||
| 58 | + .collect(); | ||
| 59 | + let (w, h) = expected.first().map_or((0, 0), |e| (e.1, e.2)); | ||
| 60 | + let max_diff = max_diff(&got, &expected); | ||
| 61 | + println!( | ||
| 62 | + "{name} {backend:?} {w}x{h} frames {} max |diff| {max_diff}{}", | ||
| 63 | + got.len(), | ||
| 64 | + if got.len() == expected_frames { | ||
| 65 | + "" | ||
| 66 | + } else { | ||
| 67 | + " (frame count differs from I420)" | ||
| 68 | + } | ||
| 69 | + ); | ||
| 70 | + if max_width.is_none() { | ||
| 71 | + println!( | ||
| 72 | + "{name} ms/frame I420 {:.3} RGB {:.3}", | ||
| 73 | + ms_per_frame(i420_time, reference.len()), | ||
| 74 | + ms_per_frame(rgb_time, got.len()) | ||
| 75 | + ); | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +fn matrix_for(height: u32) -> YuvToRgb { | ||
| 82 | + if height >= 720 { | ||
| 83 | + ec_dsp::rgb::BT709_LIMITED | ||
| 84 | + } else { | ||
| 85 | + ec_dsp::rgb::BT601_LIMITED | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +fn out_size(w: u32, h: u32, max_width: Option<u32>) -> (u32, u32) { | ||
| 90 | + match max_width { | ||
| 91 | + Some(max) if w > max => { | ||
| 92 | + let even = 2 * ((u64::from(h) * u64::from(max) + u64::from(w)) / (2 * u64::from(w))); | ||
| 93 | + (max, (even as u32).clamp(2, h)) | ||
| 94 | + } | ||
| 95 | + _ => (w, h), | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +fn max_diff(got: &[RgbPicture], expected: &[(Vec<u8>, u32, u32)]) -> u32 { | ||
| 100 | + got.iter() | ||
| 101 | + .zip(expected) | ||
| 102 | + .map(|(g, (data, w, h))| { | ||
| 103 | + if g.width != *w || g.height != *h || g.stride != w * 4 || g.data.len() != data.len() { | ||
| 104 | + return 255; | ||
| 105 | + } | ||
| 106 | + g.data | ||
| 107 | + .iter() | ||
| 108 | + .zip(data) | ||
| 109 | + .map(|(a, b)| u32::from(a.abs_diff(*b))) | ||
| 110 | + .max() | ||
| 111 | + .unwrap_or(0) | ||
| 112 | + }) | ||
| 113 | + .max() | ||
| 114 | + .unwrap_or(0) | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +fn ms_per_frame(elapsed: Duration, frames: usize) -> f64 { | ||
| 118 | + elapsed.as_secs_f64() * 1000.0 / frames.max(1) as f64 | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +fn decode_i420(codec: Codec, units: &[&[u8]]) -> (Backend, Vec<I420>, Duration) { | ||
| 122 | + let mut decoder = HwDecoder::open(codec).expect("open decoder"); | ||
| 123 | + let backend = decoder.backend(); | ||
| 124 | + let mut out = Vec::new(); | ||
| 125 | + let start = Instant::now(); | ||
| 126 | + for (pts, unit) in units.iter().enumerate() { | ||
| 127 | + decoder.decode(unit, pts as i64).expect("decode"); | ||
| 128 | + while let Some((_, frame)) = decoder.next_frame().expect("next frame") { | ||
| 129 | + out.push(frame); | ||
| 130 | + } | ||
| 131 | + } | ||
| 132 | + decoder.flush().expect("flush"); | ||
| 133 | + while let Some((_, frame)) = decoder.next_frame().expect("next frame") { | ||
| 134 | + out.push(frame); | ||
| 135 | + } | ||
| 136 | + (backend, out, start.elapsed()) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +fn decode_rgb( | ||
| 140 | + codec: Codec, | ||
| 141 | + units: &[&[u8]], | ||
| 142 | + output: RgbOutput, | ||
| 143 | +) -> (Backend, Vec<RgbPicture>, Duration) { | ||
| 144 | + let mut decoder = HwDecoder::open_rgb(codec, output).expect("open RGB decoder"); | ||
| 145 | + let backend = decoder.backend(); | ||
| 146 | + let mut out = Vec::new(); | ||
| 147 | + let start = Instant::now(); | ||
| 148 | + for (pts, unit) in units.iter().enumerate() { | ||
| 149 | + decoder.decode(unit, pts as i64).expect("decode"); | ||
| 150 | + while let Some((_, picture)) = decoder.next_rgb().expect("next RGB") { | ||
| 151 | + out.push(picture); | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + decoder.flush().expect("flush"); | ||
| 155 | + while let Some((_, picture)) = decoder.next_rgb().expect("next RGB") { | ||
| 156 | + out.push(picture); | ||
| 157 | + } | ||
| 158 | + (backend, out, start.elapsed()) | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +fn ivf_units(ivf: &[u8]) -> Vec<&[u8]> { | ||
| 162 | + let mut pos = usize::from(u16::from_le_bytes([ivf[6], ivf[7]])); | ||
| 163 | + let mut units = Vec::new(); | ||
| 164 | + while pos + 12 <= ivf.len() { | ||
| 165 | + let len = u32::from_le_bytes(ivf[pos..pos + 4].try_into().expect("frame size")) as usize; | ||
| 166 | + units.push(&ivf[pos + 12..pos + 12 + len]); | ||
| 167 | + pos += 12 + len; | ||
| 168 | + } | ||
| 169 | + units | ||
| 170 | +} | ||
crates/ec-hw/src/hw.rsmodified+99 -8
| @@ -1,7 +1,11 @@ | |||
| 1 | //! One API over Vulkan Video and VA-API. | 1 | //! One API over Vulkan Video and VA-API. |
| 2 | 2 | ||
| 3 | use crate::error::{Error, Result}; | 3 | use crate::error::{Error, Result}; |
| 4 | -use crate::picture::I420; | 4 | +use crate::picture::{Decoded, I420, RgbPicture}; |
| 5 | +#[cfg(target_os = "linux")] | ||
| 6 | +use crate::picture::{rgb_size, yuv_to_rgb}; | ||
| 7 | +#[cfg(target_os = "linux")] | ||
| 8 | +use ec_core::color::{ColorDescription, Matrix, Tags}; | ||
| 5 | use crate::types::{ | 9 | use crate::types::{ |
| 6 | Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings, | 10 | Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, RateControlMode, Tunings, |
| 7 | }; | 11 | }; |
| @@ -476,7 +480,7 @@ impl VkDecoder { | |||
| 476 | } | 480 | } |
| 477 | } | 481 | } |
| 478 | 482 | ||
| 479 | - fn next_frame(&mut self) -> Option<(i64, I420)> { | 483 | + fn next_frame(&mut self) -> Option<(i64, Decoded)> { |
| 480 | match self { | 484 | match self { |
| 481 | VkDecoder::H264(d) => d.next_frame(), | 485 | VkDecoder::H264(d) => d.next_frame(), |
| 482 | VkDecoder::H265(d) => d.next_frame(), | 486 | VkDecoder::H265(d) => d.next_frame(), |
| @@ -501,23 +505,52 @@ enum DecInner { | |||
| 501 | 505 | ||
| 502 | const REPLAY_LIMIT: usize = 64; | 506 | const REPLAY_LIMIT: usize = 64; |
| 503 | 507 | ||
| 508 | +/// What a decoder hands out: 8-bit I420, or packed RGB converted on the way out. | ||
| 509 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 510 | +pub struct RgbOutput { | ||
| 511 | + /// Byte order of each output pixel. | ||
| 512 | + pub order: RgbOrder, | ||
| 513 | + /// Scale pictures wider than this down to it, keeping the aspect ratio. | ||
| 514 | + pub max_width: Option<u32>, | ||
| 515 | +} | ||
| 516 | + | ||
| 517 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 518 | +enum Mode { | ||
| 519 | + I420, | ||
| 520 | + Rgb(RgbOutput), | ||
| 521 | +} | ||
| 522 | + | ||
| 504 | /// A hardware decoder on whichever backend opened. | 523 | /// A hardware decoder on whichever backend opened. |
| 505 | pub struct HwDecoder { | 524 | pub struct HwDecoder { |
| 506 | inner: DecInner, | 525 | inner: DecInner, |
| 507 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | 526 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 508 | codec: Codec, | 527 | codec: Codec, |
| 528 | + mode: Mode, | ||
| 509 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] | 529 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 510 | replay: Option<Vec<(Vec<u8>, i64)>>, | 530 | replay: Option<Vec<(Vec<u8>, i64)>>, |
| 511 | } | 531 | } |
| 512 | 532 | ||
| 513 | impl HwDecoder { | 533 | impl HwDecoder { |
| 514 | - /// Open a decoder for `codec`. H.264, H.265 and AV1 try Vulkan Video first, then VA-API (Linux). | 534 | + /// Open a decoder for `codec` that hands out I420. H.264, H.265 and AV1 try Vulkan Video first, then VA-API (Linux). |
| 515 | pub fn open(codec: Codec) -> Result<HwDecoder> { | 535 | pub fn open(codec: Codec) -> Result<HwDecoder> { |
| 536 | + HwDecoder::open_mode(codec, Mode::I420) | ||
| 537 | + } | ||
| 538 | + | ||
| 539 | + /// Open a decoder for `codec` that hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API. | ||
| 540 | + pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result<HwDecoder> { | ||
| 541 | + HwDecoder::open_mode(codec, Mode::Rgb(output)) | ||
| 542 | + } | ||
| 543 | + | ||
| 544 | + fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> { | ||
| 545 | + let rgb = match mode { | ||
| 546 | + Mode::I420 => None, | ||
| 547 | + Mode::Rgb(output) => Some(output), | ||
| 548 | + }; | ||
| 516 | let mut reasons = Vec::new(); | 549 | let mut reasons = Vec::new(); |
| 517 | let vk = match codec { | 550 | let vk = match codec { |
| 518 | - Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), | 551 | + Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264), |
| 519 | - Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), | 552 | + Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265), |
| 520 | - Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), | 553 | + Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1), |
| 521 | _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), | 554 | _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), |
| 522 | }; | 555 | }; |
| 523 | match vk { | 556 | match vk { |
| @@ -525,6 +558,7 @@ impl HwDecoder { | |||
| 525 | return Ok(HwDecoder { | 558 | return Ok(HwDecoder { |
| 526 | inner: DecInner::Vk(inner), | 559 | inner: DecInner::Vk(inner), |
| 527 | codec, | 560 | codec, |
| 561 | + mode, | ||
| 528 | replay: Some(Vec::new()), | 562 | replay: Some(Vec::new()), |
| 529 | }); | 563 | }); |
| 530 | } | 564 | } |
| @@ -540,6 +574,7 @@ impl HwDecoder { | |||
| 540 | return Ok(HwDecoder { | 574 | return Ok(HwDecoder { |
| 541 | inner: DecInner::Va(inner), | 575 | inner: DecInner::Va(inner), |
| 542 | codec, | 576 | codec, |
| 577 | + mode, | ||
| 543 | replay: None, | 578 | replay: None, |
| 544 | }); | 579 | }); |
| 545 | } | 580 | } |
| @@ -589,8 +624,31 @@ impl HwDecoder { | |||
| 589 | result | 624 | result |
| 590 | } | 625 | } |
| 591 | 626 | ||
| 592 | - /// The next picture in display order, as 8-bit I420 with its timestamp. | 627 | + /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`]. |
| 593 | pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { | 628 | pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> { |
| 629 | + if let Mode::Rgb(_) = self.mode { | ||
| 630 | + return Err(Error::config("next_frame on an RGB decoder; use next_rgb")); | ||
| 631 | + } | ||
| 632 | + match self.pull()? { | ||
| 633 | + None => Ok(None), | ||
| 634 | + Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))), | ||
| 635 | + Some((_, Decoded::Rgb(_))) => Err(Error::config("RGB picture from an I420 decoder")), | ||
| 636 | + } | ||
| 637 | + } | ||
| 638 | + | ||
| 639 | + /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder opened with [`HwDecoder::open`]. | ||
| 640 | + pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> { | ||
| 641 | + if let Mode::I420 = self.mode { | ||
| 642 | + return Err(Error::config("next_rgb on an I420 decoder; use open_rgb")); | ||
| 643 | + } | ||
| 644 | + match self.pull()? { | ||
| 645 | + None => Ok(None), | ||
| 646 | + Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))), | ||
| 647 | + Some((_, Decoded::I420(_))) => Err(Error::config("I420 picture from an RGB decoder")), | ||
| 648 | + } | ||
| 649 | + } | ||
| 650 | + | ||
| 651 | + fn pull(&mut self) -> Result<Option<(i64, Decoded)>> { | ||
| 594 | match &mut self.inner { | 652 | match &mut self.inner { |
| 595 | DecInner::Vk(d) => { | 653 | DecInner::Vk(d) => { |
| 596 | let frame = d.next_frame(); | 654 | let frame = d.next_frame(); |
| @@ -601,7 +659,20 @@ impl HwDecoder { | |||
| 601 | } | 659 | } |
| 602 | #[cfg(target_os = "linux")] | 660 | #[cfg(target_os = "linux")] |
| 603 | DecInner::Va(d) => match d.next_frame() { | 661 | DecInner::Va(d) => match d.next_frame() { |
| 604 | - Some(frame) => Ok(Some((frame.timestamp, frame.to_i420()?))), | 662 | + Some(frame) => { |
| 663 | + let i420 = frame.to_i420()?; | ||
| 664 | + let decoded = match self.mode { | ||
| 665 | + Mode::I420 => Decoded::I420(i420), | ||
| 666 | + Mode::Rgb(output) => { | ||
| 667 | + let matrix = frame | ||
| 668 | + .colour | ||
| 669 | + .map(|c| c.description.matrix) | ||
| 670 | + .unwrap_or_else(|| default_matrix(i420.height)); | ||
| 671 | + Decoded::Rgb(va_rgb(&i420, output, matrix)) | ||
| 672 | + } | ||
| 673 | + }; | ||
| 674 | + Ok(Some((frame.timestamp, decoded))) | ||
| 675 | + } | ||
| 605 | None => Ok(None), | 676 | None => Ok(None), |
| 606 | }, | 677 | }, |
| 607 | } | 678 | } |
| @@ -617,6 +688,26 @@ impl HwDecoder { | |||
| 617 | } | 688 | } |
| 618 | } | 689 | } |
| 619 | 690 | ||
| 691 | +#[cfg(target_os = "linux")] | ||
| 692 | +fn default_matrix(height: u32) -> Matrix { | ||
| 693 | + ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix | ||
| 694 | +} | ||
| 695 | + | ||
| 696 | +#[cfg(target_os = "linux")] | ||
| 697 | +fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture { | ||
| 698 | + let (w, h) = rgb_size(frame.width, frame.height, output.max_width); | ||
| 699 | + let data = ec_dsp::rgb::i420_to_packed( | ||
| 700 | + &frame.y, | ||
| 701 | + &frame.u, | ||
| 702 | + &frame.v, | ||
| 703 | + (frame.width as usize, frame.height as usize), | ||
| 704 | + (w as usize, h as usize), | ||
| 705 | + output.order == RgbOrder::Bgra, | ||
| 706 | + &yuv_to_rgb(matrix), | ||
| 707 | + ); | ||
| 708 | + RgbPicture::new(data, w, h) | ||
| 709 | +} | ||
| 710 | + | ||
| 620 | #[cfg(target_os = "linux")] | 711 | #[cfg(target_os = "linux")] |
| 621 | fn open_va_decoder(codec: Codec) -> Result<VaDecoder> { | 712 | fn open_va_decoder(codec: Codec) -> Result<VaDecoder> { |
| 622 | let display = ec_va::open()?; | 713 | let display = ec_va::open()?; |
crates/ec-hw/src/lib.rsmodified+3 -2
| @@ -85,11 +85,12 @@ pub use dec::{Decoder, StreamInfo}; | |||
| 85 | pub use enc::Encoder; | 85 | pub use enc::Encoder; |
| 86 | pub use error::{Error, Result}; | 86 | pub use error::{Error, Result}; |
| 87 | pub use hw::{ | 87 | pub use hw::{ |
| 88 | - Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, capabilities, | 88 | + Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput, |
| 89 | + capabilities, | ||
| 89 | }; | 90 | }; |
| 90 | #[cfg(target_os = "linux")] | 91 | #[cfg(target_os = "linux")] |
| 91 | pub use frame::Frame; | 92 | pub use frame::Frame; |
| 92 | -pub use picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; | 93 | +pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420}; |
| 93 | #[cfg(target_os = "linux")] | 94 | #[cfg(target_os = "linux")] |
| 94 | pub use pool::{PooledSurface, SurfacePool}; | 95 | pub use pool::{PooledSurface, SurfacePool}; |
| 95 | pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset}; | 96 | pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset}; |
crates/ec-hw/src/picture.rsmodified+53 -1
| @@ -1,7 +1,7 @@ | |||
| 1 | //! Pixel buffers and conversions that need no VA-API: planar I420 and its | 1 | //! Pixel buffers and conversions that need no VA-API: planar I420 and its |
| 2 | //! 10-bit sibling, the colour metadata, and the NV12 conversions. | 2 | //! 10-bit sibling, the colour metadata, and the NV12 conversions. |
| 3 | 3 | ||
| 4 | -use ec_core::color::{ColorDescription, ContentLight}; | 4 | +use ec_core::color::{ColorDescription, ContentLight, Matrix}; |
| 5 | 5 | ||
| 6 | use crate::error::{Error, Result}; | 6 | use crate::error::{Error, Result}; |
| 7 | 7 | ||
| @@ -34,6 +34,58 @@ pub struct I420 { | |||
| 34 | pub height: u32, | 34 | pub height: u32, |
| 35 | } | 35 | } |
| 36 | 36 | ||
| 37 | +/// A packed 32-bit RGB picture, alpha 255, `stride` bytes per row. | ||
| 38 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 39 | +pub struct RgbPicture { | ||
| 40 | + /// Pixels, `stride * height` bytes. | ||
| 41 | + pub data: Vec<u8>, | ||
| 42 | + /// Width in pixels. | ||
| 43 | + pub width: u32, | ||
| 44 | + /// Height in pixels. | ||
| 45 | + pub height: u32, | ||
| 46 | + /// Row stride in bytes: `width * 4`. | ||
| 47 | + pub stride: u32, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +impl RgbPicture { | ||
| 51 | + pub(crate) fn new(data: Vec<u8>, width: u32, height: u32) -> Self { | ||
| 52 | + RgbPicture { | ||
| 53 | + data, | ||
| 54 | + width, | ||
| 55 | + height, | ||
| 56 | + stride: width * 4, | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// One decoded picture in the decoder's output form. | ||
| 62 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 63 | +pub(crate) enum Decoded { | ||
| 64 | + I420(I420), | ||
| 65 | + Rgb(RgbPicture), | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here. | ||
| 69 | +pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb { | ||
| 70 | + match matrix { | ||
| 71 | + Matrix::Bt601 => ec_dsp::rgb::BT601_LIMITED, | ||
| 72 | + Matrix::Bt709 | Matrix::Bt2020Ncl => ec_dsp::rgb::BT709_LIMITED, | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even. | ||
| 77 | +pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option<u32>) -> (u32, u32) { | ||
| 78 | + match max_width { | ||
| 79 | + Some(max) if max > 0 && width > max => { | ||
| 80 | + let (w, h) = (u64::from(width), u64::from(height)); | ||
| 81 | + let max = u64::from(max); | ||
| 82 | + let even = 2 * ((h * max + w) / (2 * w)); | ||
| 83 | + (max as u32, even.clamp(2, h) as u32) | ||
| 84 | + } | ||
| 85 | + _ => (width, height), | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 37 | /// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits. | 89 | /// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits. |
| 38 | #[derive(Debug, Clone, PartialEq, Eq)] | 90 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 39 | pub struct I420_16 { | 91 | pub struct I420_16 { |
crates/ec-hw/src/vkdec264.rsmodified+32 -10
| @@ -13,8 +13,10 @@ use ec_vk::{ | |||
| 13 | 13 | ||
| 14 | use crate::dpb264::{self, Mark, PicInfo, Poc}; | 14 | use crate::dpb264::{self, Mark, PicInfo, Poc}; |
| 15 | use crate::error::{Error, Result}; | 15 | use crate::error::{Error, Result}; |
| 16 | -use crate::h264_common::peek_pps_id; | 16 | +use crate::h264_common::{peek_pps_id, vui_colour_tags}; |
| 17 | -use crate::picture::{I420, nv12_to_i420}; | 17 | +use crate::hw::{RgbOrder, RgbOutput}; |
| 18 | +use crate::picture::{Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, yuv_to_rgb}; | ||
| 19 | +use ec_core::color::{ColorDescription, Tags}; | ||
| 18 | 20 | ||
| 19 | const MAX_SLOTS: u32 = 17; | 21 | const MAX_SLOTS: u32 = 17; |
| 20 | 22 | ||
| @@ -43,7 +45,7 @@ struct Current { | |||
| 43 | 45 | ||
| 44 | struct Side { | 46 | struct Side { |
| 45 | fields: [i32; 2], | 47 | fields: [i32; 2], |
| 46 | - output: Option<(i64, I420)>, | 48 | + output: Option<(i64, Decoded)>, |
| 47 | } | 49 | } |
| 48 | 50 | ||
| 49 | /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. | 51 | /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. |
| @@ -56,12 +58,13 @@ pub(crate) struct VkH264Decoder { | |||
| 56 | dpb: Dpb, | 58 | dpb: Dpb, |
| 57 | pics: HashMap<i32, Side>, | 59 | pics: HashMap<i32, Side>, |
| 58 | current: Option<Current>, | 60 | current: Option<Current>, |
| 59 | - ready: VecDeque<(i64, I420)>, | 61 | + ready: VecDeque<(i64, Decoded)>, |
| 60 | rbsp: Vec<u8>, | 62 | rbsp: Vec<u8>, |
| 63 | + rgb: Option<RgbOutput>, | ||
| 61 | } | 64 | } |
| 62 | 65 | ||
| 63 | impl VkH264Decoder { | 66 | impl VkH264Decoder { |
| 64 | - pub(crate) fn new() -> Result<Self> { | 67 | + pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> { |
| 65 | let gpu = crate::hw::vk_gpu() | 68 | let gpu = crate::hw::vk_gpu() |
| 66 | .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; | 69 | .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; |
| 67 | Ok(VkH264Decoder { | 70 | Ok(VkH264Decoder { |
| @@ -75,6 +78,7 @@ impl VkH264Decoder { | |||
| 75 | current: None, | 78 | current: None, |
| 76 | ready: VecDeque::new(), | 79 | ready: VecDeque::new(), |
| 77 | rbsp: Vec::new(), | 80 | rbsp: Vec::new(), |
| 81 | + rgb, | ||
| 78 | }) | 82 | }) |
| 79 | } | 83 | } |
| 80 | 84 | ||
| @@ -117,7 +121,7 @@ impl VkH264Decoder { | |||
| 117 | self.finish_picture() | 121 | self.finish_picture() |
| 118 | } | 122 | } |
| 119 | 123 | ||
| 120 | - pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { | 124 | + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { |
| 121 | self.ready.pop_front() | 125 | self.ready.pop_front() |
| 122 | } | 126 | } |
| 123 | 127 | ||
| @@ -315,10 +319,28 @@ impl VkH264Decoder { | |||
| 315 | refs: &refs, | 319 | refs: &refs, |
| 316 | slices: &slices, | 320 | slices: &slices, |
| 317 | })?; | 321 | })?; |
| 318 | - let (y, uv) = session | 322 | + let out = match self.rgb { |
| 319 | - .h264 | 323 | + None => { |
| 320 | - .read_output(sps.coded_width, sps.coded_height)?; | 324 | + let (y, uv) = session |
| 321 | - let out = crop(&sps, &y, &uv); | 325 | + .h264 |
| 326 | + .read_output(sps.coded_width, sps.coded_height)?; | ||
| 327 | + Decoded::I420(crop(&sps, &y, &uv)) | ||
| 328 | + } | ||
| 329 | + Some(rgb) => { | ||
| 330 | + let (left, _, top, _) = sps.crop; | ||
| 331 | + let matrix = | ||
| 332 | + ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height) | ||
| 333 | + .matrix; | ||
| 334 | + let (w, h) = rgb_size(sps.width, sps.height, rgb.max_width); | ||
| 335 | + let data = session.h264.read_output_rgb( | ||
| 336 | + (left, top, sps.width, sps.height), | ||
| 337 | + (w, h), | ||
| 338 | + rgb.order == RgbOrder::Bgra, | ||
| 339 | + yuv_to_rgb(matrix).words(), | ||
| 340 | + )?; | ||
| 341 | + Decoded::Rgb(RgbPicture::new(data, w, h)) | ||
| 342 | + } | ||
| 343 | + }; | ||
| 322 | 344 | ||
| 323 | let picture = Picture { | 345 | let picture = Picture { |
| 324 | id: current.id, | 346 | id: current.id, |
crates/ec-hw/src/vkdec265.rsmodified+35 -11
| @@ -14,9 +14,12 @@ use ec_vk::{ | |||
| 14 | use crate::error::{Error, Result}; | 14 | use crate::error::{Error, Result}; |
| 15 | use crate::hevc_dpb::{ | 15 | use crate::hevc_dpb::{ |
| 16 | self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, | 16 | self, Dpb, Mark, is_bla_picture, is_leading_picture, is_rasl_picture, is_reference_picture, |
| 17 | - peek_pps_id, | 17 | + peek_pps_id, vui_colour_tags, |
| 18 | }; | 18 | }; |
| 19 | -use crate::picture::{I420, semi_planar_to_i420}; | 19 | +use ec_core::color::{ColorDescription, Tags}; |
| 20 | + | ||
| 21 | +use crate::hw::{RgbOrder, RgbOutput}; | ||
| 22 | +use crate::picture::{Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb}; | ||
| 20 | 23 | ||
| 21 | const MAX_SLOTS: u32 = 17; | 24 | const MAX_SLOTS: u32 = 17; |
| 22 | 25 | ||
| @@ -54,14 +57,15 @@ pub(crate) struct VkH265Decoder { | |||
| 54 | sps_map: Vec<Option<Sps>>, | 57 | sps_map: Vec<Option<Sps>>, |
| 55 | pps_map: Vec<Option<Pps>>, | 58 | pps_map: Vec<Option<Pps>>, |
| 56 | dpb: Dpb<u32>, | 59 | dpb: Dpb<u32>, |
| 57 | - outputs: HashMap<u32, I420>, | 60 | + outputs: HashMap<u32, Decoded>, |
| 58 | current: Option<Current>, | 61 | current: Option<Current>, |
| 59 | - ready: VecDeque<(i64, I420)>, | 62 | + ready: VecDeque<(i64, Decoded)>, |
| 60 | no_rasl_output: bool, | 63 | no_rasl_output: bool, |
| 64 | + rgb: Option<RgbOutput>, | ||
| 61 | } | 65 | } |
| 62 | 66 | ||
| 63 | impl VkH265Decoder { | 67 | impl VkH265Decoder { |
| 64 | - pub(crate) fn new() -> Result<Self> { | 68 | + pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> { |
| 65 | let gpu = crate::hw::vk_gpu() | 69 | let gpu = crate::hw::vk_gpu() |
| 66 | .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; | 70 | .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; |
| 67 | Ok(VkH265Decoder { | 71 | Ok(VkH265Decoder { |
| @@ -76,6 +80,7 @@ impl VkH265Decoder { | |||
| 76 | current: None, | 80 | current: None, |
| 77 | ready: VecDeque::new(), | 81 | ready: VecDeque::new(), |
| 78 | no_rasl_output: false, | 82 | no_rasl_output: false, |
| 83 | + rgb, | ||
| 79 | }) | 84 | }) |
| 80 | } | 85 | } |
| 81 | 86 | ||
| @@ -112,7 +117,7 @@ impl VkH265Decoder { | |||
| 112 | self.finish_picture() | 117 | self.finish_picture() |
| 113 | } | 118 | } |
| 114 | 119 | ||
| 115 | - pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { | 120 | + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { |
| 116 | self.ready.pop_front() | 121 | self.ready.pop_front() |
| 117 | } | 122 | } |
| 118 | 123 | ||
| @@ -336,12 +341,31 @@ impl VkH265Decoder { | |||
| 336 | refs: &refs, | 341 | refs: &refs, |
| 337 | slices: &slices, | 342 | slices: &slices, |
| 338 | })?; | 343 | })?; |
| 339 | - let (y, uv) = session.h265.read_output( | ||
| 340 | - sps.pic_width_in_luma_samples, | ||
| 341 | - sps.pic_height_in_luma_samples, | ||
| 342 | - )?; | ||
| 343 | if current.output { | 344 | if current.output { |
| 344 | - let frame = crop(&sps, &y, &uv)?; | 345 | + let frame = match self.rgb { |
| 346 | + None => { | ||
| 347 | + let (y, uv) = session.h265.read_output( | ||
| 348 | + sps.pic_width_in_luma_samples, | ||
| 349 | + sps.pic_height_in_luma_samples, | ||
| 350 | + )?; | ||
| 351 | + Decoded::I420(crop(&sps, &y, &uv)?) | ||
| 352 | + } | ||
| 353 | + Some(rgb) => { | ||
| 354 | + let (width, height) = sps.display_size(); | ||
| 355 | + let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32); | ||
| 356 | + let matrix = | ||
| 357 | + ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height) | ||
| 358 | + .matrix; | ||
| 359 | + let (w, h) = rgb_size(width, height, rgb.max_width); | ||
| 360 | + let data = session.h265.read_output_rgb( | ||
| 361 | + (origin.0, origin.1, width, height), | ||
| 362 | + (w, h), | ||
| 363 | + rgb.order == RgbOrder::Bgra, | ||
| 364 | + yuv_to_rgb(matrix).words(), | ||
| 365 | + )?; | ||
| 366 | + Decoded::Rgb(RgbPicture::new(data, w, h)) | ||
| 367 | + } | ||
| 368 | + }; | ||
| 345 | self.outputs.insert(current.slot, frame); | 369 | self.outputs.insert(current.slot, frame); |
| 346 | } | 370 | } |
| 347 | 371 | ||
crates/ec-hw/src/vkdec_av1.rsmodified+35 -14
| @@ -17,7 +17,10 @@ use ec_vk::{ | |||
| 17 | 17 | ||
| 18 | use crate::av1_refs::RefSlots; | 18 | use crate::av1_refs::RefSlots; |
| 19 | use crate::error::{Error, Result}; | 19 | use crate::error::{Error, Result}; |
| 20 | -use crate::picture::{I420, semi_planar_to_i420}; | 20 | +use ec_core::color::{ColorDescription, Tags}; |
| 21 | + | ||
| 22 | +use crate::hw::{RgbOrder, RgbOutput}; | ||
| 23 | +use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb}; | ||
| 21 | 24 | ||
| 22 | const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; | 25 | const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; |
| 23 | 26 | ||
| @@ -31,7 +34,7 @@ struct Session { | |||
| 31 | 34 | ||
| 32 | struct Reference { | 35 | struct Reference { |
| 33 | state: Av1RefSlot, | 36 | state: Av1RefSlot, |
| 34 | - picture: I420, | 37 | + picture: Decoded, |
| 35 | } | 38 | } |
| 36 | 39 | ||
| 37 | /// AV1 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. | 40 | /// AV1 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. |
| @@ -40,11 +43,12 @@ pub(crate) struct VkAv1Decoder { | |||
| 40 | parser: Av1Parser, | 43 | parser: Av1Parser, |
| 41 | session: Option<Session>, | 44 | session: Option<Session>, |
| 42 | refs: RefSlots<Rc<Reference>>, | 45 | refs: RefSlots<Rc<Reference>>, |
| 43 | - ready: VecDeque<(i64, I420)>, | 46 | + ready: VecDeque<(i64, Decoded)>, |
| 47 | + rgb: Option<RgbOutput>, | ||
| 44 | } | 48 | } |
| 45 | 49 | ||
| 46 | impl VkAv1Decoder { | 50 | impl VkAv1Decoder { |
| 47 | - pub(crate) fn new() -> Result<Self> { | 51 | + pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> { |
| 48 | let gpu = crate::hw::vk_gpu() | 52 | let gpu = crate::hw::vk_gpu() |
| 49 | .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?; | 53 | .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?; |
| 50 | Ok(VkAv1Decoder { | 54 | Ok(VkAv1Decoder { |
| @@ -53,6 +57,7 @@ impl VkAv1Decoder { | |||
| 53 | session: None, | 57 | session: None, |
| 54 | refs: RefSlots::new(), | 58 | refs: RefSlots::new(), |
| 55 | ready: VecDeque::new(), | 59 | ready: VecDeque::new(), |
| 60 | + rgb, | ||
| 56 | }) | 61 | }) |
| 57 | } | 62 | } |
| 58 | 63 | ||
| @@ -81,7 +86,7 @@ impl VkAv1Decoder { | |||
| 81 | Ok(()) | 86 | Ok(()) |
| 82 | } | 87 | } |
| 83 | 88 | ||
| 84 | - pub(crate) fn next_frame(&mut self) -> Option<(i64, I420)> { | 89 | + pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { |
| 85 | self.ready.pop_front() | 90 | self.ready.pop_front() |
| 86 | } | 91 | } |
| 87 | 92 | ||
| @@ -161,15 +166,31 @@ impl VkAv1Decoder { | |||
| 161 | if !(header.show_frame || header.refresh_frame_flags != 0) { | 166 | if !(header.show_frame || header.refresh_frame_flags != 0) { |
| 162 | return Ok(()); | 167 | return Ok(()); |
| 163 | } | 168 | } |
| 164 | - let (y, uv) = session.av1.read_output(width, height)?; | 169 | + let decoded = match self.rgb { |
| 165 | - let decoded = semi_planar_to_i420( | 170 | + None => { |
| 166 | - session.bit_depth, | 171 | + let (y, uv) = session.av1.read_output(width, height)?; |
| 167 | - &y, | 172 | + Decoded::I420(semi_planar_to_i420( |
| 168 | - &uv, | 173 | + session.bit_depth, |
| 169 | - width as usize, | 174 | + &y, |
| 170 | - (0, 0), | 175 | + &uv, |
| 171 | - (width, height), | 176 | + width as usize, |
| 172 | - )?; | 177 | + (0, 0), |
| 178 | + (width, height), | ||
| 179 | + )?) | ||
| 180 | + } | ||
| 181 | + Some(rgb) => { | ||
| 182 | + let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0); | ||
| 183 | + let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; | ||
| 184 | + let (w, h) = rgb_size(width, height, rgb.max_width); | ||
| 185 | + let data = session.av1.read_output_rgb( | ||
| 186 | + (0, 0, width, height), | ||
| 187 | + (w, h), | ||
| 188 | + rgb.order == RgbOrder::Bgra, | ||
| 189 | + yuv_to_rgb(matrix).words(), | ||
| 190 | + )?; | ||
| 191 | + Decoded::Rgb(RgbPicture::new(data, w, h)) | ||
| 192 | + } | ||
| 193 | + }; | ||
| 173 | let state = Av1RefSlot { | 194 | let state = Av1RefSlot { |
| 174 | slot: setup_slot, | 195 | slot: setup_slot, |
| 175 | frame_type: av1_frame_type(header.frame_type), | 196 | frame_type: av1_frame_type(header.frame_type), |
shims/vk-video-ffi/shaders/nv12_to_rgb.compadded+68 -0
| @@ -0,0 +1,68 @@ | |||
| 1 | +#version 450 | ||
| 2 | + | ||
| 3 | +layout(local_size_x = 8, local_size_y = 8) in; | ||
| 4 | + | ||
| 5 | +layout(std430, set = 0, binding = 0) readonly buffer Src { | ||
| 6 | + uint src[]; | ||
| 7 | +}; | ||
| 8 | + | ||
| 9 | +layout(std430, set = 0, binding = 1) writeonly buffer Dst { | ||
| 10 | + uint dst[]; | ||
| 11 | +}; | ||
| 12 | + | ||
| 13 | +layout(push_constant) uniform Push { | ||
| 14 | + uint w; | ||
| 15 | + uint h; | ||
| 16 | + uint out_w; | ||
| 17 | + uint out_h; | ||
| 18 | + uint bytes; | ||
| 19 | + uint bgra; | ||
| 20 | + int ky; | ||
| 21 | + int rv; | ||
| 22 | + int gu; | ||
| 23 | + int gv; | ||
| 24 | + int bu; | ||
| 25 | +} pc; | ||
| 26 | + | ||
| 27 | +uint byte_at(uint o) { | ||
| 28 | + return (src[o >> 2] >> ((o & 3u) * 8u)) & 255u; | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +uint sample_at(uint e) { | ||
| 32 | + return byte_at(e * pc.bytes + pc.bytes - 1u); | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +ivec3 rgb_at(uint x, uint y) { | ||
| 36 | + int yy = int(sample_at(y * pc.w + x)) - 16; | ||
| 37 | + uint c = pc.w * pc.h + (y / 2u) * pc.w + 2u * (x / 2u); | ||
| 38 | + int u = int(sample_at(c)) - 128; | ||
| 39 | + int v = int(sample_at(c + 1u)) - 128; | ||
| 40 | + int r = (pc.ky * yy + pc.rv * v + 128) >> 8; | ||
| 41 | + int g = (pc.ky * yy + pc.gu * u + pc.gv * v + 128) >> 8; | ||
| 42 | + int b = (pc.ky * yy + pc.bu * u + 128) >> 8; | ||
| 43 | + return clamp(ivec3(r, g, b), 0, 255); | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +void main() { | ||
| 47 | + uint ox = gl_GlobalInvocationID.x; | ||
| 48 | + uint oy = gl_GlobalInvocationID.y; | ||
| 49 | + if (ox >= pc.out_w || oy >= pc.out_h) { | ||
| 50 | + return; | ||
| 51 | + } | ||
| 52 | + uint x0 = ox * pc.w / pc.out_w; | ||
| 53 | + uint x1 = ((ox + 1u) * pc.w + pc.out_w - 1u) / pc.out_w; | ||
| 54 | + uint y0 = oy * pc.h / pc.out_h; | ||
| 55 | + uint y1 = ((oy + 1u) * pc.h + pc.out_h - 1u) / pc.out_h; | ||
| 56 | + uvec3 sum = uvec3(0u); | ||
| 57 | + for (uint y = y0; y < y1; ++y) { | ||
| 58 | + for (uint x = x0; x < x1; ++x) { | ||
| 59 | + sum += uvec3(rgb_at(x, y)); | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + uint n = (x1 - x0) * (y1 - y0); | ||
| 63 | + uvec3 c = (sum + uvec3(n / 2u)) / uvec3(n); | ||
| 64 | + uint px = pc.bgra != 0u | ||
| 65 | + ? (c.b | (c.g << 8) | (c.r << 16)) | ||
| 66 | + : (c.r | (c.g << 8) | (c.b << 16)); | ||
| 67 | + dst[oy * pc.out_w + ox] = px | 0xFF000000u; | ||
| 68 | +} | ||
shims/vk-video-ffi/shaders/nv12_to_rgb.spvadded+0 -0
Binary file changed
shims/vk-video-ffi/src/av1_decode.rsmodified+11 -0
| @@ -856,6 +856,17 @@ impl Av1DecodeSession { | |||
| 856 | pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { | 856 | pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { |
| 857 | self.dec.read_nv12(width, height) | 857 | self.dec.read_nv12(width, height) |
| 858 | } | 858 | } |
| 859 | + | ||
| 860 | + /// 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. | ||
| 861 | + pub fn read_output_rgb( | ||
| 862 | + &mut self, | ||
| 863 | + crop: (u32, u32, u32, u32), | ||
| 864 | + out: (u32, u32), | ||
| 865 | + bgra: bool, | ||
| 866 | + coeffs: [i32; 5], | ||
| 867 | + ) -> Result<Vec<u8>, Error> { | ||
| 868 | + self.dec.read_rgb(crop, out, bgra, coeffs) | ||
| 869 | + } | ||
| 859 | } | 870 | } |
| 860 | 871 | ||
| 861 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { | 872 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { |
shims/vk-video-ffi/src/h264_decode.rsmodified+11 -0
| @@ -460,6 +460,17 @@ impl H264DecodeSession { | |||
| 460 | pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { | 460 | pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { |
| 461 | self.dec.read_nv12(width, height) | 461 | self.dec.read_nv12(width, height) |
| 462 | } | 462 | } |
| 463 | + | ||
| 464 | + /// 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. | ||
| 465 | + pub fn read_output_rgb( | ||
| 466 | + &mut self, | ||
| 467 | + crop: (u32, u32, u32, u32), | ||
| 468 | + out: (u32, u32), | ||
| 469 | + bgra: bool, | ||
| 470 | + coeffs: [i32; 5], | ||
| 471 | + ) -> Result<Vec<u8>, Error> { | ||
| 472 | + self.dec.read_rgb(crop, out, bgra, coeffs) | ||
| 473 | + } | ||
| 463 | } | 474 | } |
| 464 | 475 | ||
| 465 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { | 476 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { |
shims/vk-video-ffi/src/h265_decode.rsmodified+11 -0
| @@ -697,6 +697,17 @@ impl H265DecodeSession { | |||
| 697 | pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { | 697 | pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>), Error> { |
| 698 | self.dec.read_nv12(width, height) | 698 | self.dec.read_nv12(width, height) |
| 699 | } | 699 | } |
| 700 | + | ||
| 701 | + /// 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. | ||
| 702 | + pub fn read_output_rgb( | ||
| 703 | + &mut self, | ||
| 704 | + crop: (u32, u32, u32, u32), | ||
| 705 | + out: (u32, u32), | ||
| 706 | + bgra: bool, | ||
| 707 | + coeffs: [i32; 5], | ||
| 708 | + ) -> Result<Vec<u8>, Error> { | ||
| 709 | + self.dec.read_rgb(crop, out, bgra, coeffs) | ||
| 710 | + } | ||
| 700 | } | 711 | } |
| 701 | 712 | ||
| 702 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { | 713 | fn query_caps(gpu: &Gpu, profile: &vk::VideoProfileInfoKHR) -> Result<Caps, Error> { |
shims/vk-video-ffi/src/lib.rsmodified+1 -0
| @@ -13,6 +13,7 @@ mod h264_encode; | |||
| 13 | mod h265_decode; | 13 | mod h265_decode; |
| 14 | mod h265_encode; | 14 | mod h265_encode; |
| 15 | mod rgb_convert; | 15 | mod rgb_convert; |
| 16 | +mod rgb_decode; | ||
| 16 | mod session; | 17 | mod session; |
| 17 | 18 | ||
| 18 | pub use av1_decode::{ | 19 | pub use av1_decode::{ |
shims/vk-video-ffi/src/rgb_decode.rsadded+181 -0
| @@ -0,0 +1,181 @@ | |||
| 1 | +use vulkanalia::prelude::v1_3::*; | ||
| 2 | + | ||
| 3 | +use crate::session::vk; | ||
| 4 | +use crate::{Error, Gpu}; | ||
| 5 | + | ||
| 6 | +const SPV: &[u8] = include_bytes!("../shaders/nv12_to_rgb.spv"); | ||
| 7 | + | ||
| 8 | +pub(crate) struct RgbPass { | ||
| 9 | + set_layout: vk::DescriptorSetLayout, | ||
| 10 | + pool: vk::DescriptorPool, | ||
| 11 | + set: vk::DescriptorSet, | ||
| 12 | + layout: vk::PipelineLayout, | ||
| 13 | + pipeline: vk::Pipeline, | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +pub(crate) struct Params { | ||
| 17 | + pub(crate) w: u32, | ||
| 18 | + pub(crate) h: u32, | ||
| 19 | + pub(crate) out: (u32, u32), | ||
| 20 | + pub(crate) bytes: u32, | ||
| 21 | + pub(crate) bgra: bool, | ||
| 22 | + pub(crate) coeffs: [i32; 5], | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +impl RgbPass { | ||
| 26 | + pub(crate) fn new( | ||
| 27 | + gpu: &Gpu, | ||
| 28 | + input: (vk::Buffer, u64), | ||
| 29 | + output: (vk::Buffer, u64), | ||
| 30 | + ) -> Result<Self, Error> { | ||
| 31 | + let d = gpu.device(); | ||
| 32 | + let bindings = [storage(0), storage(1)]; | ||
| 33 | + let set_info = vk::DescriptorSetLayoutCreateInfo::builder().bindings(&bindings); | ||
| 34 | + let set_layout = unsafe { | ||
| 35 | + vk( | ||
| 36 | + d.create_descriptor_set_layout(&set_info, None), | ||
| 37 | + "vkCreateDescriptorSetLayout", | ||
| 38 | + )? | ||
| 39 | + }; | ||
| 40 | + let push = vk::PushConstantRange::builder() | ||
| 41 | + .stage_flags(vk::ShaderStageFlags::COMPUTE) | ||
| 42 | + .offset(0) | ||
| 43 | + .size(44) | ||
| 44 | + .build(); | ||
| 45 | + let set_layouts = [set_layout]; | ||
| 46 | + let pushes = [push]; | ||
| 47 | + let layout_info = vk::PipelineLayoutCreateInfo::builder() | ||
| 48 | + .set_layouts(&set_layouts) | ||
| 49 | + .push_constant_ranges(&pushes); | ||
| 50 | + let layout = unsafe { | ||
| 51 | + vk( | ||
| 52 | + d.create_pipeline_layout(&layout_info, None), | ||
| 53 | + "vkCreatePipelineLayout", | ||
| 54 | + )? | ||
| 55 | + }; | ||
| 56 | + | ||
| 57 | + let words: Vec<u32> = SPV | ||
| 58 | + .chunks_exact(4) | ||
| 59 | + .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) | ||
| 60 | + .collect(); | ||
| 61 | + let module_info = vk::ShaderModuleCreateInfo::builder() | ||
| 62 | + .code_size(SPV.len()) | ||
| 63 | + .code(&words); | ||
| 64 | + let module = unsafe { | ||
| 65 | + vk( | ||
| 66 | + d.create_shader_module(&module_info, None), | ||
| 67 | + "vkCreateShaderModule", | ||
| 68 | + )? | ||
| 69 | + }; | ||
| 70 | + let stage = vk::PipelineShaderStageCreateInfo::builder() | ||
| 71 | + .stage(vk::ShaderStageFlags::COMPUTE) | ||
| 72 | + .module(module) | ||
| 73 | + .name(b"main\0"); | ||
| 74 | + let pipeline_info = vk::ComputePipelineCreateInfo::builder() | ||
| 75 | + .stage(stage) | ||
| 76 | + .layout(layout); | ||
| 77 | + let pipelines = unsafe { | ||
| 78 | + d.create_compute_pipelines(vk::PipelineCache::null(), &[pipeline_info], None) | ||
| 79 | + }; | ||
| 80 | + unsafe { d.destroy_shader_module(module, None) }; | ||
| 81 | + let pipeline = pipelines | ||
| 82 | + .map_err(|c| Error::Vk(c.as_raw(), "vkCreateComputePipelines"))? | ||
| 83 | + .0[0]; | ||
| 84 | + | ||
| 85 | + let sizes = [vk::DescriptorPoolSize { | ||
| 86 | + type_: vk::DescriptorType::STORAGE_BUFFER, | ||
| 87 | + descriptor_count: 2, | ||
| 88 | + }]; | ||
| 89 | + let pool_info = vk::DescriptorPoolCreateInfo::builder() | ||
| 90 | + .max_sets(1) | ||
| 91 | + .pool_sizes(&sizes); | ||
| 92 | + let pool = unsafe { | ||
| 93 | + vk( | ||
| 94 | + d.create_descriptor_pool(&pool_info, None), | ||
| 95 | + "vkCreateDescriptorPool", | ||
| 96 | + )? | ||
| 97 | + }; | ||
| 98 | + let alloc = vk::DescriptorSetAllocateInfo::builder() | ||
| 99 | + .descriptor_pool(pool) | ||
| 100 | + .set_layouts(&set_layouts); | ||
| 101 | + let set = unsafe { | ||
| 102 | + vk( | ||
| 103 | + d.allocate_descriptor_sets(&alloc), | ||
| 104 | + "vkAllocateDescriptorSets", | ||
| 105 | + )?[0] | ||
| 106 | + }; | ||
| 107 | + let infos = [ | ||
| 108 | + [vk::DescriptorBufferInfo { | ||
| 109 | + buffer: input.0, | ||
| 110 | + offset: 0, | ||
| 111 | + range: input.1, | ||
| 112 | + }], | ||
| 113 | + [vk::DescriptorBufferInfo { | ||
| 114 | + buffer: output.0, | ||
| 115 | + offset: 0, | ||
| 116 | + range: output.1, | ||
| 117 | + }], | ||
| 118 | + ]; | ||
| 119 | + let writes = [ | ||
| 120 | + vk::WriteDescriptorSet::builder() | ||
| 121 | + .dst_set(set) | ||
| 122 | + .dst_binding(0) | ||
| 123 | + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) | ||
| 124 | + .buffer_info(&infos[0]) | ||
| 125 | + .build(), | ||
| 126 | + vk::WriteDescriptorSet::builder() | ||
| 127 | + .dst_set(set) | ||
| 128 | + .dst_binding(1) | ||
| 129 | + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) | ||
| 130 | + .buffer_info(&infos[1]) | ||
| 131 | + .build(), | ||
| 132 | + ]; | ||
| 133 | + unsafe { d.update_descriptor_sets(&writes, &[] as &[vk::CopyDescriptorSet]) }; | ||
| 134 | + | ||
| 135 | + Ok(RgbPass { | ||
| 136 | + set_layout, | ||
| 137 | + pool, | ||
| 138 | + set, | ||
| 139 | + layout, | ||
| 140 | + pipeline, | ||
| 141 | + }) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + pub(crate) fn record(&self, d: &Device, cb: vk::CommandBuffer, p: &Params) { | ||
| 145 | + let words = [p.w, p.h, p.out.0, p.out.1, p.bytes, p.bgra as u32]; | ||
| 146 | + let mut push: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); | ||
| 147 | + push.extend(p.coeffs.iter().flat_map(|c| c.to_le_bytes())); | ||
| 148 | + let sets = [self.set]; | ||
| 149 | + unsafe { | ||
| 150 | + d.cmd_bind_pipeline(cb, vk::PipelineBindPoint::COMPUTE, self.pipeline); | ||
| 151 | + d.cmd_bind_descriptor_sets( | ||
| 152 | + cb, | ||
| 153 | + vk::PipelineBindPoint::COMPUTE, | ||
| 154 | + self.layout, | ||
| 155 | + 0, | ||
| 156 | + &sets, | ||
| 157 | + &[], | ||
| 158 | + ); | ||
| 159 | + d.cmd_push_constants(cb, self.layout, vk::ShaderStageFlags::COMPUTE, 0, &push); | ||
| 160 | + d.cmd_dispatch(cb, p.out.0.div_ceil(8), p.out.1.div_ceil(8), 1); | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + pub(crate) fn destroy(&self, d: &Device) { | ||
| 165 | + unsafe { | ||
| 166 | + d.destroy_descriptor_pool(self.pool, None); | ||
| 167 | + d.destroy_pipeline(self.pipeline, None); | ||
| 168 | + d.destroy_pipeline_layout(self.layout, None); | ||
| 169 | + d.destroy_descriptor_set_layout(self.set_layout, None); | ||
| 170 | + } | ||
| 171 | + } | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +fn storage(binding: u32) -> vk::DescriptorSetLayoutBinding { | ||
| 175 | + vk::DescriptorSetLayoutBinding::builder() | ||
| 176 | + .binding(binding) | ||
| 177 | + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) | ||
| 178 | + .descriptor_count(1) | ||
| 179 | + .stage_flags(vk::ShaderStageFlags::COMPUTE) | ||
| 180 | + .build() | ||
| 181 | +} | ||
shims/vk-video-ffi/src/session.rsmodified+132 -13
| @@ -5,6 +5,7 @@ use vulkanalia::vk::{ | |||
| 5 | }; | 5 | }; |
| 6 | 6 | ||
| 7 | use crate::rgb_convert::{Input, RgbConverter}; | 7 | use crate::rgb_convert::{Input, RgbConverter}; |
| 8 | +use crate::rgb_decode::{Params, RgbPass}; | ||
| 8 | use crate::{Error, Gpu, RateControl}; | 9 | use crate::{Error, Gpu, RateControl}; |
| 9 | 10 | ||
| 10 | pub(crate) const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM; | 11 | pub(crate) const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM; |
| @@ -120,6 +121,15 @@ pub(crate) fn copy_region( | |||
| 120 | aspect: vk::ImageAspectFlags, | 121 | aspect: vk::ImageAspectFlags, |
| 121 | width: u32, | 122 | width: u32, |
| 122 | height: u32, | 123 | height: u32, |
| 124 | +) -> vk::BufferImageCopy { | ||
| 125 | + copy_rect(offset, aspect, (0, 0), (width, height)) | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +pub(crate) fn copy_rect( | ||
| 129 | + offset: u64, | ||
| 130 | + aspect: vk::ImageAspectFlags, | ||
| 131 | + origin: (u32, u32), | ||
| 132 | + (width, height): (u32, u32), | ||
| 123 | ) -> vk::BufferImageCopy { | 133 | ) -> vk::BufferImageCopy { |
| 124 | vk::BufferImageCopy::builder() | 134 | vk::BufferImageCopy::builder() |
| 125 | .buffer_offset(offset) | 135 | .buffer_offset(offset) |
| @@ -129,6 +139,11 @@ pub(crate) fn copy_region( | |||
| 129 | base_array_layer: 0, | 139 | base_array_layer: 0, |
| 130 | layer_count: 1, | 140 | layer_count: 1, |
| 131 | }) | 141 | }) |
| 142 | + .image_offset(vk::Offset3D { | ||
| 143 | + x: origin.0 as i32, | ||
| 144 | + y: origin.1 as i32, | ||
| 145 | + z: 0, | ||
| 146 | + }) | ||
| 132 | .image_extent(vk::Extent3D { | 147 | .image_extent(vk::Extent3D { |
| 133 | width, | 148 | width, |
| 134 | height, | 149 | height, |
| @@ -906,6 +921,8 @@ pub(crate) struct Decoder { | |||
| 906 | pub(crate) output: Image, | 921 | pub(crate) output: Image, |
| 907 | pub(crate) bitstream: Buffer, | 922 | pub(crate) bitstream: Buffer, |
| 908 | readback: Buffer, | 923 | readback: Buffer, |
| 924 | + rgb_out: Buffer, | ||
| 925 | + rgb: Option<RgbPass>, | ||
| 909 | pub(crate) coded: bool, | 926 | pub(crate) coded: bool, |
| 910 | } | 927 | } |
| 911 | 928 | ||
| @@ -935,6 +952,8 @@ impl Decoder { | |||
| 935 | output: Default::default(), | 952 | output: Default::default(), |
| 936 | bitstream: Default::default(), | 953 | bitstream: Default::default(), |
| 937 | readback: Default::default(), | 954 | readback: Default::default(), |
| 955 | + rgb_out: Default::default(), | ||
| 956 | + rgb: None, | ||
| 938 | coded: false, | 957 | coded: false, |
| 939 | }; | 958 | }; |
| 940 | let mut list = vk::VideoProfileListInfoKHR::builder() | 959 | let mut list = vk::VideoProfileListInfoKHR::builder() |
| @@ -969,12 +988,25 @@ impl Decoder { | |||
| 969 | vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, | 988 | vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, |
| 970 | Some(&mut list), | 989 | Some(&mut list), |
| 971 | )?; | 990 | )?; |
| 991 | + let readback_size = max_extent.width as u64 * max_extent.height as u64 * 3 / 2 * bytes; | ||
| 972 | dec.readback = dec.vs.buffer( | 992 | dec.readback = dec.vs.buffer( |
| 973 | - max_extent.width as u64 * max_extent.height as u64 * 3 / 2 * bytes, | 993 | + readback_size, |
| 974 | - vk::BufferUsageFlags::TRANSFER_DST, | 994 | + vk::BufferUsageFlags::TRANSFER_DST | vk::BufferUsageFlags::STORAGE_BUFFER, |
| 975 | vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, | 995 | vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, |
| 976 | None, | 996 | None, |
| 977 | )?; | 997 | )?; |
| 998 | + let rgb_size = max_extent.width as u64 * max_extent.height as u64 * 4; | ||
| 999 | + dec.rgb_out = dec.vs.buffer( | ||
| 1000 | + rgb_size, | ||
| 1001 | + vk::BufferUsageFlags::STORAGE_BUFFER, | ||
| 1002 | + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, | ||
| 1003 | + None, | ||
| 1004 | + )?; | ||
| 1005 | + dec.rgb = Some(RgbPass::new( | ||
| 1006 | + &gpu, | ||
| 1007 | + (dec.readback.buffer, readback_size), | ||
| 1008 | + (dec.rgb_out.buffer, rgb_size), | ||
| 1009 | + )?); | ||
| 978 | 1010 | ||
| 979 | let d = gpu.device(); | 1011 | let d = gpu.device(); |
| 980 | let cb = dec.decode.cb; | 1012 | let cb = dec.decode.cb; |
| @@ -1047,8 +1079,6 @@ impl Decoder { | |||
| 1047 | } | 1079 | } |
| 1048 | let gpu = self.vs.gpu.clone(); | 1080 | let gpu = self.vs.gpu.clone(); |
| 1049 | let d = gpu.device(); | 1081 | let d = gpu.device(); |
| 1050 | - let cb = self.graphics.cb; | ||
| 1051 | - let image = self.output.image; | ||
| 1052 | let bytes = bytes_per_sample(self.vs.format); | 1082 | let bytes = bytes_per_sample(self.vs.format); |
| 1053 | let luma = width as usize * height as usize * bytes; | 1083 | let luma = width as usize * height as usize * bytes; |
| 1054 | let copies = [ | 1084 | let copies = [ |
| @@ -1056,6 +1086,99 @@ impl Decoder { | |||
| 1056 | copy_region(luma as u64, PLANE_1, width / 2, height / 2), | 1086 | copy_region(luma as u64, PLANE_1, width / 2, height / 2), |
| 1057 | ]; | 1087 | ]; |
| 1058 | self.graphics.begin()?; | 1088 | self.graphics.begin()?; |
| 1089 | + self.copy_to_readback(d, self.graphics.cb, &copies); | ||
| 1090 | + self.graphics.end()?; | ||
| 1091 | + self.graphics.submit()?; | ||
| 1092 | + let ptr = self | ||
| 1093 | + .readback | ||
| 1094 | + .ptr | ||
| 1095 | + .ok_or_else(|| Error::Invalid("readback buffer not mapped".into()))?; | ||
| 1096 | + let bytes = unsafe { std::slice::from_raw_parts(ptr, luma * 3 / 2) }; | ||
| 1097 | + Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec())) | ||
| 1098 | + } | ||
| 1099 | + | ||
| 1100 | + /// 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. | ||
| 1101 | + pub(crate) fn read_rgb( | ||
| 1102 | + &mut self, | ||
| 1103 | + crop: (u32, u32, u32, u32), | ||
| 1104 | + out: (u32, u32), | ||
| 1105 | + bgra: bool, | ||
| 1106 | + coeffs: [i32; 5], | ||
| 1107 | + ) -> Result<Vec<u8>, Error> { | ||
| 1108 | + let (x, y, width, height) = crop; | ||
| 1109 | + if !self.coded { | ||
| 1110 | + return Err(Error::Invalid("nothing decoded".into())); | ||
| 1111 | + } | ||
| 1112 | + if width == 0 | ||
| 1113 | + || height == 0 | ||
| 1114 | + || width % 2 != 0 | ||
| 1115 | + || height % 2 != 0 | ||
| 1116 | + || x % 2 != 0 | ||
| 1117 | + || y % 2 != 0 | ||
| 1118 | + || x + width > self.max_extent.width | ||
| 1119 | + || y + height > self.max_extent.height | ||
| 1120 | + || out.0 == 0 | ||
| 1121 | + || out.1 == 0 | ||
| 1122 | + || out.0 > width | ||
| 1123 | + || out.1 > height | ||
| 1124 | + { | ||
| 1125 | + return Err(Error::Invalid("RGB readback size".into())); | ||
| 1126 | + } | ||
| 1127 | + let pass = self | ||
| 1128 | + .rgb | ||
| 1129 | + .as_ref() | ||
| 1130 | + .ok_or_else(|| Error::Invalid("RGB readback not set up".into()))?; | ||
| 1131 | + let gpu = self.vs.gpu.clone(); | ||
| 1132 | + let d = gpu.device(); | ||
| 1133 | + let cb = self.graphics.cb; | ||
| 1134 | + let bytes = bytes_per_sample(self.vs.format); | ||
| 1135 | + let luma = width as usize * height as usize * bytes; | ||
| 1136 | + let copies = [ | ||
| 1137 | + copy_rect(0, PLANE_0, (x, y), (width, height)), | ||
| 1138 | + copy_rect(luma as u64, PLANE_1, (x / 2, y / 2), (width / 2, height / 2)), | ||
| 1139 | + ]; | ||
| 1140 | + self.graphics.begin()?; | ||
| 1141 | + self.copy_to_readback(d, cb, &copies); | ||
| 1142 | + let barrier = vk::BufferMemoryBarrier2::builder() | ||
| 1143 | + .src_stage_mask(vk::PipelineStageFlags2::COPY) | ||
| 1144 | + .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE) | ||
| 1145 | + .dst_stage_mask(vk::PipelineStageFlags2::COMPUTE_SHADER) | ||
| 1146 | + .dst_access_mask(vk::AccessFlags2::SHADER_STORAGE_READ) | ||
| 1147 | + .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) | ||
| 1148 | + .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) | ||
| 1149 | + .buffer(self.readback.buffer) | ||
| 1150 | + .offset(0) | ||
| 1151 | + .size(vk::WHOLE_SIZE) | ||
| 1152 | + .build(); | ||
| 1153 | + let barriers = [barrier]; | ||
| 1154 | + let dep = vk::DependencyInfo::builder().buffer_memory_barriers(&barriers); | ||
| 1155 | + unsafe { | ||
| 1156 | + d.cmd_pipeline_barrier2(cb, &dep); | ||
| 1157 | + } | ||
| 1158 | + pass.record( | ||
| 1159 | + d, | ||
| 1160 | + cb, | ||
| 1161 | + &Params { | ||
| 1162 | + w: width, | ||
| 1163 | + h: height, | ||
| 1164 | + out, | ||
| 1165 | + bytes: bytes as u32, | ||
| 1166 | + bgra, | ||
| 1167 | + coeffs, | ||
| 1168 | + }, | ||
| 1169 | + ); | ||
| 1170 | + self.graphics.end()?; | ||
| 1171 | + self.graphics.submit()?; | ||
| 1172 | + let ptr = self | ||
| 1173 | + .rgb_out | ||
| 1174 | + .ptr | ||
| 1175 | + .ok_or_else(|| Error::Invalid("RGB buffer not mapped".into()))?; | ||
| 1176 | + let len = out.0 as usize * out.1 as usize * 4; | ||
| 1177 | + Ok(unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()) | ||
| 1178 | + } | ||
| 1179 | + | ||
| 1180 | + fn copy_to_readback(&self, d: &Device, cb: vk::CommandBuffer, copies: &[vk::BufferImageCopy]) { | ||
| 1181 | + let image = self.output.image; | ||
| 1059 | unsafe { | 1182 | unsafe { |
| 1060 | barrier( | 1183 | barrier( |
| 1061 | d, | 1184 | d, |
| @@ -1077,7 +1200,7 @@ impl Decoder { | |||
| 1077 | image, | 1200 | image, |
| 1078 | vk::ImageLayout::TRANSFER_SRC_OPTIMAL, | 1201 | vk::ImageLayout::TRANSFER_SRC_OPTIMAL, |
| 1079 | self.readback.buffer, | 1202 | self.readback.buffer, |
| 1080 | - &copies, | 1203 | + copies, |
| 1081 | ); | 1204 | ); |
| 1082 | barrier( | 1205 | barrier( |
| 1083 | d, | 1206 | d, |
| @@ -1095,14 +1218,6 @@ impl Decoder { | |||
| 1095 | ), | 1218 | ), |
| 1096 | ); | 1219 | ); |
| 1097 | } | 1220 | } |
| 1098 | - self.graphics.end()?; | ||
| 1099 | - self.graphics.submit()?; | ||
| 1100 | - let ptr = self | ||
| 1101 | - .readback | ||
| 1102 | - .ptr | ||
| 1103 | - .ok_or_else(|| Error::Invalid("readback buffer not mapped".into()))?; | ||
| 1104 | - let bytes = unsafe { std::slice::from_raw_parts(ptr, luma * 3 / 2) }; | ||
| 1105 | - Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec())) | ||
| 1106 | } | 1221 | } |
| 1107 | } | 1222 | } |
| 1108 | 1223 | ||
| @@ -1118,5 +1233,9 @@ impl Drop for Decoder { | |||
| 1118 | } | 1233 | } |
| 1119 | self.bitstream.destroy(d); | 1234 | self.bitstream.destroy(d); |
| 1120 | self.readback.destroy(d); | 1235 | self.readback.destroy(d); |
| 1236 | + self.rgb_out.destroy(d); | ||
| 1237 | + if let Some(rgb) = &self.rgb { | ||
| 1238 | + rgb.destroy(d); | ||
| 1239 | + } | ||
| 1121 | } | 1240 | } |
| 1122 | } | 1241 | } |