diff --git a/crates/ec-hw/examples/hw_ten.rs b/crates/ec-hw/examples/hw_ten.rs new file mode 100644 index 00000000..3dca5a9c --- /dev/null +++ b/crates/ec-hw/examples/hw_ten.rs @@ -0,0 +1,141 @@ +use ec_hw::{ + Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420_16, + RateControlMode, +}; + +const WIDTH: u32 = 1280; +const HEIGHT: u32 = 720; +const FRAMES: u32 = 30; +const PEAK: f64 = 1023.0; + +fn main() { + let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into()); + let rates = [ + ("cqp", RateControlMode::ConstantQp { qp: 30 }), + ("cbr", RateControlMode::ConstantBitrate), + ]; + for codec in [EncCodec::H265, EncCodec::Av1] { + for (name, rate) in rates { + for backend in [Backend::Vk, Backend::Va] { + if let Err(e) = run(&dir, codec, name, rate, backend) { + println!("{codec:?} {name} {backend:?}: error: {e}"); + } + } + } + } +} + +fn run( + dir: &str, + codec: EncCodec, + name: &str, + rate: RateControlMode, + backend: Backend, +) -> ec_hw::Result<()> { + let config = EncoderConfig { + bitrate: 4_000_000, + rate_control: rate, + ..EncoderConfig::new(codec, WIDTH, HEIGHT).ten_bit() + }; + let mut encoder = match HwEncoder::open(config, Some(backend)) { + Ok(encoder) => encoder, + Err(e) => { + println!("{codec:?} {name} {backend:?}: no encoder: {e}"); + return Ok(()); + } + }; + let mut coded = Vec::with_capacity(FRAMES as usize); + let mut sources = Vec::with_capacity(FRAMES as usize); + for index in 0..FRAMES { + let frame = pattern(index); + let meta = FrameMetadata { + timestamp: index as i64, + force_keyframe: index == 0, + }; + coded.push(encoder.encode_16(&frame, meta)?); + sources.push(frame); + } + let stream: Vec = coded.iter().flat_map(|c| c.data.iter().copied()).collect(); + let stem = format!("{dir}/ten_{codec:?}_{name}_{backend:?}"); + std::fs::write(format!("{stem}.bin"), &stream).expect("write bitstream"); + + let mut decoder = HwDecoder::open_16(decode_codec(codec))?; + let mut decoded = Vec::new(); + for c in &coded { + decoder.decode(&c.data, c.timestamp)?; + while let Some(frame) = decoder.next_frame_16()? { + decoded.push(frame); + } + } + decoder.flush()?; + while let Some(frame) = decoder.next_frame_16()? { + decoded.push(frame); + } + + let mut yuv = Vec::new(); + for (_, frame) in &decoded { + for sample in frame.y.iter().chain(&frame.u).chain(&frame.v) { + yuv.extend_from_slice(&sample.to_le_bytes()); + } + } + std::fs::write(format!("{stem}_ours.yuv"), &yuv).expect("write decoded yuv"); + + let psnr: f64 = decoded + .iter() + .map(|(ts, frame)| psnr(&sources[*ts as usize], frame)) + .sum::() + / decoded.len().max(1) as f64; + println!( + "{codec:?} {name} {backend:?}: {} bytes, decoded {} frames, PSNR {psnr:.2} dB", + stream.len(), + decoded.len() + ); + Ok(()) +} + +fn decode_codec(codec: EncCodec) -> Codec { + match codec { + EncCodec::H264 => Codec::H264, + EncCodec::H265 => Codec::H265, + EncCodec::Av1 => Codec::Av1, + } +} + +fn pattern(index: u32) -> I420_16 { + let t = index as usize; + let (w, h) = (WIDTH as usize, HEIGHT as usize); + I420_16 { + y: plane(w, h, |x, y| x * 3 + y * 5 + t * 16), + u: plane(w / 2, h / 2, |x, y| x * 7 + y * 2 + t * 9), + v: plane(w / 2, h / 2, |x, y| x * 2 + y * 11 + t * 5 + 512), + width: WIDTH, + height: HEIGHT, + bit_depth: 10, + } +} + +fn plane(w: usize, h: usize, value: impl Fn(usize, usize) -> usize) -> Vec { + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + for col in 0..w { + out.push((value(col, row) & 0x3ff) as u16); + } + } + out +} + +fn psnr(a: &I420_16, b: &I420_16) -> f64 { + let mut sse = 0f64; + let mut n = 0usize; + for (x, y) in + a.y.iter() + .chain(&a.u) + .chain(&a.v) + .zip(b.y.iter().chain(&b.u).chain(&b.v)) + { + let d = f64::from(*x) - f64::from(*y); + sse += d * d; + n += 1; + } + 10.0 * (PEAK * PEAK * n as f64 / sse).log10() +} diff --git a/crates/ec-hw/src/frame.rs b/crates/ec-hw/src/frame.rs index 951e2bb2..94f173b2 100644 --- a/crates/ec-hw/src/frame.rs +++ b/crates/ec-hw/src/frame.rs @@ -7,7 +7,7 @@ use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010}; use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt}; use crate::error::{Error, Result}; -use crate::picture::{check_plane, fill_i420}; +use crate::picture::{fill_i420, fill_i420_16}; use crate::pool::PooledSurface; pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420}; @@ -192,68 +192,6 @@ impl std::fmt::Debug for Frame { } } -/// Copy NV12/P010 planes into `out`, after validating every plane against it. -fn fill_i420_16( - out: &mut I420_16, - bit_depth: u8, - y_plane: &[u8], - y_pitch: usize, - uv_plane: &[u8], - uv_pitch: usize, -) -> Result<()> { - let (w, h) = (out.width as usize, out.height as usize); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - let bytes = if bit_depth == 8 { 1 } else { 2 }; - check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; - check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; - let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)]; - match bit_depth { - 8 => { - for row in 0..h { - let src = row * y_pitch; - row_buf[..w].copy_from_slice(&y_plane[src..src + w]); - for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) { - *dst = u16::from(sample) << 2; - } - } - for row in 0..ch { - let src = row * uv_pitch; - let line = &mut row_buf[..cw * 2]; - line.copy_from_slice(&uv_plane[src..src + cw * 2]); - for col in 0..cw { - out.u[row * cw + col] = u16::from(line[col * 2]) << 2; - out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2; - } - } - } - _ => { - // P010 is 16-bit little endian with the sample in the top ten - // bits; the low six are zero padding. - for row in 0..h { - let src = row * y_pitch; - let line = &mut row_buf[..w * 2]; - line.copy_from_slice(&y_plane[src..src + w * 2]); - for col in 0..w { - out.y[row * w + col] = - u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6; - } - } - for row in 0..ch { - let src = row * uv_pitch; - let line = &mut row_buf[..cw * 4]; - line.copy_from_slice(&uv_plane[src..src + cw * 4]); - for col in 0..cw { - out.u[row * cw + col] = - u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6; - out.v[row * cw + col] = - u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6; - } - } - } - } - Ok(()) -} - /// Luma and chroma planes of a read-back NV12/P010 image, with their pitches. fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usize)> { let data: &[u8] = image.as_ref(); @@ -276,6 +214,7 @@ fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usi #[cfg(test)] mod tests { use super::*; + use crate::picture::check_plane; fn blank(w: u32, h: u32) -> I420 { I420 { diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 1d84309f..2b64abfc 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -7,7 +7,7 @@ use std::os::fd::BorrowedFd; use ec_vk::DmaBuf; use crate::error::{Error, Result}; -use crate::picture::{Decoded, I420, RgbPicture}; +use crate::picture::{Decoded, I420, I420_16, RgbPicture}; #[cfg(target_os = "linux")] use crate::picture::{rgb_size, yuv_to_rgb}; #[cfg(target_os = "linux")] @@ -278,6 +278,19 @@ impl VkEncoder { } } + fn encode_16( + &mut self, + frame: &I420_16, + force_keyframe: bool, + ) -> std::result::Result { + let (y, u, v) = (&frame.y, &frame.u, &frame.v); + match self { + VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())), + VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe), + VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe), + } + } + fn set_rate( &mut self, rate: ec_vk::RateControl, @@ -411,6 +424,22 @@ impl HwEncoder { } } + /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder. + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { + match &mut self.inner { + EncInner::Vk(enc) => { + let coded = enc.encode_16(frame, meta.force_keyframe)?; + Ok(CodedFrame { + data: coded.data, + timestamp: meta.timestamp, + is_keyframe: coded.keyframe, + }) + } + #[cfg(target_os = "linux")] + EncInner::Va(enc) => enc.encode_16(frame, meta), + } + } + /// Encode one packed RGB frame of the source size; it is box-downscaled to the encoder size. Vulkan does this and the NV12 conversion on the GPU, VA-API on the CPU. pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result { match &mut self.inner { @@ -459,12 +488,18 @@ fn open_backend(backend: Backend, config: EncoderConfig) -> Result { } fn open_vk(config: EncoderConfig) -> Result { - if config.bit_depth != 8 { + if config.bit_depth == 10 && config.codec == EncCodec::H264 { return Err(Error::unsupported( - "10-bit Vulkan Video encode", - "the Vulkan encoders are 8-bit", + "10-bit H.264 Vulkan Video encode", + "the driver offers no High 10 H.264 encode", )); } + if config.bit_depth != 8 && config.bit_depth != 10 { + return Err(Error::config(format!( + "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1", + config.bit_depth + ))); + } let gpu = vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?; let rate = vk_rate(&config); @@ -493,6 +528,7 @@ fn open_vk(config: EncoderConfig) -> Result { fps, gop_size, rate, + bit_depth: config.bit_depth, }, )?), EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new( @@ -503,6 +539,7 @@ fn open_vk(config: EncoderConfig) -> Result { fps, gop_size, rate, + bit_depth: config.bit_depth, }, )?), }) @@ -586,8 +623,9 @@ pub struct RgbOutput { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Mode { +pub(crate) enum Mode { I420, + I420_16, Rgb(RgbOutput), } @@ -612,16 +650,17 @@ impl HwDecoder { HwDecoder::open_mode(codec, Mode::Rgb(output)) } + /// Open a decoder for `codec` that hands out 10-bit I420 ([`HwDecoder::next_frame_16`]). 8-bit streams are widened to 10 bits. + pub fn open_16(codec: Codec) -> Result { + HwDecoder::open_mode(codec, Mode::I420_16) + } + 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(rgb).map(VkDecoder::H264), - Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265), - Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1), + Codec::H264 => VkH264Decoder::new(mode).map(VkDecoder::H264), + Codec::H265 => VkH265Decoder::new(mode).map(VkDecoder::H265), + Codec::Av1 => VkAv1Decoder::new(mode).map(VkDecoder::Av1), _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")), }; match vk { @@ -695,27 +734,45 @@ impl HwDecoder { result } - /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`]. + /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`] or [`HwDecoder::open_16`]. 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")); + if self.mode != Mode::I420 { + return Err(Error::config( + "next_frame on a decoder not opened as 8-bit I420", + )); } 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")), + Some(_) => Err(Error::config("non-I420 picture from an I420 decoder")), + } + } + + /// The next picture in display order, as 10-bit I420 with its timestamp. An error on a decoder not opened with [`HwDecoder::open_16`]. + pub fn next_frame_16(&mut self) -> Result> { + if self.mode != Mode::I420_16 { + return Err(Error::config( + "next_frame_16 on a decoder not opened with open_16", + )); + } + match self.pull()? { + None => Ok(None), + Some((ts, Decoded::I420_16(frame))) => Ok(Some((ts, frame))), + Some(_) => Err(Error::config("non-16-bit picture from a 16-bit decoder")), } } - /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder opened with [`HwDecoder::open`]. + /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. 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")); + if !matches!(self.mode, Mode::Rgb(_)) { + return Err(Error::config( + "next_rgb on a decoder not opened with 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")), + Some(_) => Err(Error::config("non-RGB picture from an RGB decoder")), } } @@ -731,10 +788,11 @@ impl HwDecoder { #[cfg(target_os = "linux")] DecInner::Va(d) => match d.next_frame() { Some(frame) => { - let i420 = frame.to_i420()?; let decoded = match self.mode { - Mode::I420 => Decoded::I420(i420), + Mode::I420 => Decoded::I420(frame.to_i420()?), + Mode::I420_16 => Decoded::I420_16(frame.to_i420_16()?), Mode::Rgb(output) => { + let i420 = frame.to_i420()?; let matrix = frame .colour .map(|c| c.description.matrix) diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs index bea704b4..f27a7538 100644 --- a/crates/ec-hw/src/picture.rs +++ b/crates/ec-hw/src/picture.rs @@ -62,6 +62,7 @@ impl RgbPicture { #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Decoded { I420(I420), + I420_16(I420_16), Rgb(RgbPicture), } @@ -170,6 +171,95 @@ pub(crate) fn semi_planar_to_i420( Ok(out) } +/// Copy NV12/P010 planes into `out`, after validating every plane against it. +pub(crate) fn fill_i420_16( + out: &mut I420_16, + bit_depth: u8, + y_plane: &[u8], + y_pitch: usize, + uv_plane: &[u8], + uv_pitch: usize, +) -> Result<()> { + let (w, h) = (out.width as usize, out.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let bytes = if bit_depth == 8 { 1 } else { 2 }; + check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; + check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; + let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)]; + match bit_depth { + 8 => { + for row in 0..h { + let src = row * y_pitch; + row_buf[..w].copy_from_slice(&y_plane[src..src + w]); + for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) { + *dst = u16::from(sample) << 2; + } + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 2]; + line.copy_from_slice(&uv_plane[src..src + cw * 2]); + for col in 0..cw { + out.u[row * cw + col] = u16::from(line[col * 2]) << 2; + out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2; + } + } + } + _ => { + // P010 is 16-bit little endian with the sample in the top ten + // bits; the low six are zero padding. + for row in 0..h { + let src = row * y_pitch; + let line = &mut row_buf[..w * 2]; + line.copy_from_slice(&y_plane[src..src + w * 2]); + for col in 0..w { + out.y[row * w + col] = + u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6; + } + } + for row in 0..ch { + let src = row * uv_pitch; + let line = &mut row_buf[..cw * 4]; + line.copy_from_slice(&uv_plane[src..src + cw * 4]); + for col in 0..cw { + out.u[row * cw + col] = + u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6; + out.v[row * cw + col] = + u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6; + } + } + } + } + Ok(()) +} + +pub(crate) fn semi_planar_to_i420_16( + bit_depth: u8, + y: &[u8], + uv: &[u8], + pitch: usize, + origin: (usize, usize), + size: (u32, u32), +) -> Result { + let bytes = if bit_depth == 8 { 1 } else { 2 }; + let pitch = pitch * bytes; + let (x, top) = (origin.0 * bytes, origin.1); + let y = y.get(top * pitch + x..).unwrap_or(&[]); + let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]); + let (width, height) = size; + let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2)); + let mut out = I420_16 { + y: vec![0; width as usize * height as usize], + u: vec![0; cw * ch], + v: vec![0; cw * ch], + width, + height, + bit_depth: 10, + }; + fill_i420_16(&mut out, bit_depth, y, pitch, uv, pitch)?; + Ok(out) +} + /// Copy NV12/P010 planes into `out`, after validating every plane against it. pub(crate) fn fill_i420( out: &mut I420, diff --git a/crates/ec-hw/src/types.rs b/crates/ec-hw/src/types.rs index 16b61468..e417c1b9 100644 --- a/crates/ec-hw/src/types.rs +++ b/crates/ec-hw/src/types.rs @@ -111,9 +111,8 @@ pub struct EncoderConfig { /// The colour description to write into the VUI, or `None` to leave it /// unsignalled (`video_signal_type_present_flag = 0`) as before. pub colour: Option, - /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). - /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or - /// straight from a 10-bit [`crate::Frame`]. + /// Luma bit depth: 8, or 10 for H.265 and AV1. A 10-bit encoder takes its + /// pixels through [`Encoder::encode_16`] or [`HwEncoder::encode_16`]. pub bit_depth: u8, } diff --git a/crates/ec-hw/src/vkdec264.rs b/crates/ec-hw/src/vkdec264.rs index 68f065f6..34ca8923 100644 --- a/crates/ec-hw/src/vkdec264.rs +++ b/crates/ec-hw/src/vkdec264.rs @@ -14,8 +14,10 @@ use ec_vk::{ use crate::dpb264::{self, Mark, PicInfo, Poc}; use crate::error::{Error, Result}; 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 crate::hw::{Mode, RgbOrder}; +use crate::picture::{ + Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, semi_planar_to_i420_16, yuv_to_rgb, +}; use ec_core::color::{ColorDescription, Tags}; const MAX_SLOTS: u32 = 17; @@ -60,11 +62,11 @@ pub(crate) struct VkH264Decoder { current: Option, ready: VecDeque<(i64, Decoded)>, rbsp: Vec, - rgb: Option, + mode: Mode, } impl VkH264Decoder { - pub(crate) fn new(rgb: Option) -> Result { + pub(crate) fn new(mode: Mode) -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; Ok(VkH264Decoder { @@ -78,7 +80,7 @@ impl VkH264Decoder { current: None, ready: VecDeque::new(), rbsp: Vec::new(), - rgb, + mode, }) } @@ -319,14 +321,28 @@ impl VkH264Decoder { refs: &refs, slices: &slices, })?; - let out = match self.rgb { - None => { + let out = match self.mode { + Mode::I420 => { let (y, uv) = session .h264 .read_output(sps.coded_width, sps.coded_height)?; Decoded::I420(crop(&sps, &y, &uv)) } - Some(rgb) => { + Mode::I420_16 => { + let (y, uv) = session + .h264 + .read_output(sps.coded_width, sps.coded_height)?; + let (left, _, top, _) = sps.crop; + Decoded::I420_16(semi_planar_to_i420_16( + 8, + &y, + &uv, + sps.coded_width as usize, + (left as usize, top as usize), + (sps.width, sps.height), + )?) + } + Mode::Rgb(rgb) => { let (left, _, top, _) = sps.crop; let matrix = ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height) diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs index 60de62d5..5dbf4731 100644 --- a/crates/ec-hw/src/vkdec265.rs +++ b/crates/ec-hw/src/vkdec265.rs @@ -18,8 +18,11 @@ use crate::hevc_dpb::{ }; 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}; +use crate::hw::{Mode, RgbOrder}; +use crate::picture::{ + Decoded, I420, I420_16, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, + yuv_to_rgb, +}; const MAX_SLOTS: u32 = 17; @@ -61,11 +64,11 @@ pub(crate) struct VkH265Decoder { current: Option, ready: VecDeque<(i64, Decoded)>, no_rasl_output: bool, - rgb: Option, + mode: Mode, } impl VkH265Decoder { - pub(crate) fn new(rgb: Option) -> Result { + pub(crate) fn new(mode: Mode) -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; Ok(VkH265Decoder { @@ -80,7 +83,7 @@ impl VkH265Decoder { current: None, ready: VecDeque::new(), no_rasl_output: false, - rgb, + mode, }) } @@ -342,15 +345,22 @@ impl VkH265Decoder { slices: &slices, })?; if current.output { - let frame = match self.rgb { - None => { + let frame = match self.mode { + Mode::I420 => { 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) => { + Mode::I420_16 => { + let (y, uv) = session.h265.read_output( + sps.pic_width_in_luma_samples, + sps.pic_height_in_luma_samples, + )?; + Decoded::I420_16(crop16(&sps, &y, &uv)?) + } + Mode::Rgb(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 = @@ -421,6 +431,20 @@ fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result { ) } +fn crop16(sps: &Sps, y: &[u8], uv: &[u8]) -> Result { + semi_planar_to_i420_16( + (8 + sps.bit_depth_luma_minus8) as u8, + y, + uv, + sps.pic_width_in_luma_samples as usize, + ( + 2 * sps.conf_win.left as usize, + 2 * sps.conf_win.top as usize, + ), + sps.display_size(), + ) +} + fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel { H265ProfileTierLevel { tier_flag: p.tier_flag, diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index f1ba8cc1..ecc3c303 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -19,8 +19,11 @@ use crate::av1_refs::RefSlots; use crate::error::{Error, Result}; 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}; +use crate::hw::{Mode, RgbOrder}; +use crate::picture::{ + Decoded, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, + yuv_to_rgb, +}; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; @@ -44,11 +47,11 @@ pub(crate) struct VkAv1Decoder { session: Option, refs: RefSlots>, ready: VecDeque<(i64, Decoded)>, - rgb: Option, + mode: Mode, } impl VkAv1Decoder { - pub(crate) fn new(rgb: Option) -> Result { + pub(crate) fn new(mode: Mode) -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?; Ok(VkAv1Decoder { @@ -57,7 +60,7 @@ impl VkAv1Decoder { session: None, refs: RefSlots::new(), ready: VecDeque::new(), - rgb, + mode, }) } @@ -166,8 +169,8 @@ impl VkAv1Decoder { if !(header.show_frame || header.refresh_frame_flags != 0) { return Ok(()); } - let decoded = match self.rgb { - None => { + let decoded = match self.mode { + Mode::I420 => { let (y, uv) = session.av1.read_output(width, height)?; Decoded::I420(semi_planar_to_i420( session.bit_depth, @@ -178,7 +181,18 @@ impl VkAv1Decoder { (width, height), )?) } - Some(rgb) => { + Mode::I420_16 => { + let (y, uv) = session.av1.read_output(width, height)?; + Decoded::I420_16(semi_planar_to_i420_16( + session.bit_depth, + &y, + &uv, + width as usize, + (0, 0), + (width, height), + )?) + } + Mode::Rgb(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); diff --git a/crates/ec-vk/examples/av1_encode.rs b/crates/ec-vk/examples/av1_encode.rs index 0a7c06bc..77ea138b 100644 --- a/crates/ec-vk/examples/av1_encode.rs +++ b/crates/ec-vk/examples/av1_encode.rs @@ -34,6 +34,7 @@ fn main() { }, None => RateControl::ConstantQp { qp: 26 }, }, + bit_depth: 8, }; let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder"); diff --git a/crates/ec-vk/examples/h265_encode.rs b/crates/ec-vk/examples/h265_encode.rs index d09b996c..f09c679b 100644 --- a/crates/ec-vk/examples/h265_encode.rs +++ b/crates/ec-vk/examples/h265_encode.rs @@ -33,6 +33,7 @@ fn main() { }, None => RateControl::ConstantQp { qp: 26 }, }, + bit_depth: 8, }; let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder"); let mut out = Vec::new(); diff --git a/crates/ec-vk/src/av1.rs b/crates/ec-vk/src/av1.rs index 9045936b..341c48a2 100644 --- a/crates/ec-vk/src/av1.rs +++ b/crates/ec-vk/src/av1.rs @@ -19,6 +19,8 @@ pub struct Av1EncoderConfig { pub gop_size: u32, /// Rate control. pub rate: RateControl, + /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`). + pub bit_depth: u8, } /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`]. @@ -32,6 +34,7 @@ pub struct Av1Encoder { order_hint: u8, reference: Option, uv: Vec, + uv16: Vec, } impl Av1Encoder { @@ -47,6 +50,7 @@ impl Av1Encoder { height: cfg.height, fps: cfg.fps, rate: cfg.rate, + bit_depth: cfg.bit_depth, }, )?; let sequence_header = session.sequence_header(); @@ -60,6 +64,7 @@ impl Av1Encoder { order_hint: 0, reference: None, uv: vec![0; cfg.width as usize * cfg.height as usize / 2], + uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], }) } @@ -84,6 +89,27 @@ impl Av1Encoder { Ok(self.finish(&pic, frame)) } + /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP. + pub fn encode_16( + &mut self, + y: &[u16], + u: &[u16], + v: &[u16], + force_keyframe: bool, + ) -> Result { + let chroma = self.width * self.height / 4; + if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { + return Err(Error::Invalid("I420 plane size".into())); + } + for (i, pair) in self.uv16.chunks_exact_mut(2).enumerate() { + pair[0] = u[i]; + pair[1] = v[i]; + } + let pic = self.next_picture(force_keyframe); + let frame = self.session.encode_16(y, &self.uv16, &pic)?; + Ok(self.finish(&pic, frame)) + } + /// Changes bitrate or frame rate; takes effect on the next frame. pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { Ok(self.session.set_rate(rate, fps)?) diff --git a/crates/ec-vk/src/h265.rs b/crates/ec-vk/src/h265.rs index d7916024..ee416044 100644 --- a/crates/ec-vk/src/h265.rs +++ b/crates/ec-vk/src/h265.rs @@ -17,6 +17,8 @@ pub struct H265EncoderConfig { pub gop_size: u32, /// Rate control. pub rate: RateControl, + /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`). + pub bit_depth: u8, } /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`]. @@ -30,6 +32,7 @@ pub struct H265Encoder { poc: i32, reference: Option, uv: Vec, + uv16: Vec, } impl H265Encoder { @@ -45,6 +48,7 @@ impl H265Encoder { height: cfg.height, fps: cfg.fps, rate: cfg.rate, + bit_depth: cfg.bit_depth, }, )?; let parameter_sets = session.parameter_sets()?; @@ -58,6 +62,7 @@ impl H265Encoder { poc: 0, reference: None, uv: vec![0; cfg.width as usize * cfg.height as usize / 2], + uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], }) } @@ -82,6 +87,27 @@ impl H265Encoder { Ok(self.finish(&pic, slice)) } + /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP. + pub fn encode_16( + &mut self, + y: &[u16], + u: &[u16], + v: &[u16], + force_keyframe: bool, + ) -> Result { + let chroma = self.width * self.height / 4; + if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { + return Err(Error::Invalid("I420 plane size".into())); + } + for (i, pair) in self.uv16.chunks_exact_mut(2).enumerate() { + pair[0] = u[i]; + pair[1] = v[i]; + } + let pic = self.next_picture(force_keyframe); + let slice = self.session.encode_16(y, &self.uv16, &pic)?; + Ok(self.finish(&pic, slice)) + } + /// Changes bitrate or frame rate; takes effect on the next frame. pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { Ok(self.session.set_rate(rate, fps)?) diff --git a/shims/vk-video-ffi/examples/dmabuf_smoke.rs b/shims/vk-video-ffi/examples/dmabuf_smoke.rs index 1546f071..b67026cc 100644 --- a/shims/vk-video-ffi/examples/dmabuf_smoke.rs +++ b/shims/vk-video-ffi/examples/dmabuf_smoke.rs @@ -82,6 +82,7 @@ impl Encode for H265EncodeSession { height: size.1, fps: FPS, rate: RATE, + bit_depth: 8, }; H265EncodeSession::new(gpu, &cfg) } @@ -115,6 +116,7 @@ impl Encode for Av1EncodeSession { height: size.1, fps: FPS, rate: RATE, + bit_depth: 8, }; Av1EncodeSession::new(gpu, &cfg) } diff --git a/shims/vk-video-ffi/src/av1_encode.rs b/shims/vk-video-ffi/src/av1_encode.rs index 7a83c985..2c15be1d 100644 --- a/shims/vk-video-ffi/src/av1_encode.rs +++ b/shims/vk-video-ffi/src/av1_encode.rs @@ -8,7 +8,7 @@ use crate::dmabuf::DmaBuf; use crate::rgb_convert::{Input, check_rgb}; use crate::session::{ DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, - picture_resource, validate_rate, video_caps, vk, zeroed, + component_bit_depth, picture_resource, validate_rate, video_caps, vk, zeroed, }; use crate::{Error, Gpu, RateControl}; @@ -27,6 +27,8 @@ pub struct Av1EncodeConfig { pub fps: (u32, u32), /// Rate control; ConstantQp qp is mapped to AV1 base_q_idx as qp * 5. pub rate: RateControl, + /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input). + pub bit_depth: u8, } /// One picture to encode. @@ -67,13 +69,14 @@ struct Profile { } impl Profile { - fn new() -> Box { + fn new(bit_depth: u8) -> Box { + let component = component_bit_depth(bit_depth); let mut p = Box::new(Profile { info: vk::VideoProfileInfoKHR::builder() .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_AV1) .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) - .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) - .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .luma_bit_depth(component) + .chroma_bit_depth(component) .build(), codec: vk::VideoEncodeAV1ProfileInfoKHR::builder() .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN) @@ -158,8 +161,11 @@ impl Av1EncodeSession { { return Err(Error::Unsupported("AV1 encode".into())); } - let profile = Profile::new(); - let caps = query_caps(gpu, &profile.info)?; + let profile = Profile::new(cfg.bit_depth); + let caps = query_caps(gpu, &profile.info).map_err(|e| match e { + Error::Vk(..) if cfg.bit_depth == 10 => Error::Unsupported("10-bit AV1 encode".into()), + e => e, + })?; if cfg.width > caps.max_extent.width || cfg.height > caps.max_extent.height { return Err(Error::Unsupported(format!( "AV1 encode {}x{}", @@ -203,11 +209,11 @@ impl Av1EncodeSession { (cfg.rate, cfg.fps), caps.size_align, )?; - let params = create_parameters(&enc.vs, extent, sb128)?; + let params = create_parameters(&enc.vs, extent, sb128, cfg.bit_depth)?; enc.vs.set_params(params); Ok(Av1EncodeSession { enc, - seq: sequence_header_obu(cfg.width, cfg.height, sb128), + seq: sequence_header_obu(cfg.width, cfg.height, sb128, cfg.bit_depth), slot_key: [false; DPB_SLOTS], ref_order_hint: [0; AV1_SLOTS], }) @@ -230,6 +236,18 @@ impl Av1EncodeSession { self.encode_uploaded(pic) } + /// Encodes one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session and returns its frame OBUs. + pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result, Error> { + if y.len() != self.enc.input.0 * self.enc.input.1 + || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 + { + return Err(Error::Invalid("P010 plane size".into())); + } + self.check(pic)?; + self.enc.upload(Input::P010 { y, uv })?; + self.encode_uploaded(pic) + } + /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU. pub fn encode_rgb( &mut self, @@ -430,9 +448,10 @@ fn create_parameters( vs: &VideoSession, extent: vk::Extent2D, sb128: bool, + bit_depth: u8, ) -> Result { let mut color = zeroed::(); - color.BitDepth = 8; + color.BitDepth = bit_depth; color.subsampling_x = 1; color.subsampling_y = 1; color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED; @@ -515,7 +534,7 @@ fn obu(kind: u8, payload: &[u8]) -> Vec { out } -fn sequence_header_obu(width: u32, height: u32, sb128: bool) -> Vec { +fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> Vec { let mut b = Bits(Vec::new()); b.put(0, 3); b.put(0, 1); @@ -547,17 +566,20 @@ fn sequence_header_obu(width: u32, height: u32, sb128: bool) -> Vec { b.put(0, 1); b.put(0, 1); b.put(0, 1); + b.put((bit_depth == 10) as u32, 1); b.put(0, 1); b.put(0, 1); b.put(0, 1); b.put(0, 2); b.put(0, 1); b.put(0, 1); - b.put(0, 1); obu(1, &b.finish()) } fn validate(cfg: &Av1EncodeConfig) -> Result<(), Error> { + if cfg.bit_depth != 8 && cfg.bit_depth != 10 { + return Err(Error::Invalid("AV1 bit depth".into())); + } if cfg.width == 0 || cfg.height == 0 || cfg.width % 8 != 0 || cfg.height % 8 != 0 { return Err(Error::Invalid( "size must be a non-zero multiple of 8".into(), diff --git a/shims/vk-video-ffi/src/h265_encode.rs b/shims/vk-video-ffi/src/h265_encode.rs index 374bc8c0..efb0da23 100644 --- a/shims/vk-video-ffi/src/h265_encode.rs +++ b/shims/vk-video-ffi/src/h265_encode.rs @@ -11,7 +11,7 @@ use crate::h264_encode::validate; use crate::rgb_convert::{Input, check_rgb}; use crate::session::{ DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align, - picture_resource, video_caps, vk, zeroed, + component_bit_depth, picture_resource, video_caps, vk, zeroed, }; use crate::{Error, Gpu, RateControl}; @@ -26,6 +26,8 @@ pub struct H265EncodeConfig { pub fps: (u32, u32), /// Rate control. pub rate: RateControl, + /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input). + pub bit_depth: u8, } /// One picture to encode. @@ -80,16 +82,17 @@ struct Profile { } impl Profile { - fn new() -> Box { + fn new(bit_depth: u8) -> Box { + let component = component_bit_depth(bit_depth); let mut p = Box::new(Profile { info: vk::VideoProfileInfoKHR::builder() .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H265) .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) - .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) - .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .luma_bit_depth(component) + .chroma_bit_depth(component) .build(), codec: vk::VideoEncodeH265ProfileInfoKHR::builder() - .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN) + .std_profile_idc(profile_idc(bit_depth)) .build(), usage: vk::VideoEncodeUsageInfoKHR::builder() .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING) @@ -161,6 +164,9 @@ impl H265EncodeSession { /// Creates a session with its DPB, buffers and parameter sets. pub fn new(gpu: &Gpu, cfg: &H265EncodeConfig) -> Result { validate(cfg.width, cfg.height, cfg.fps, cfg.rate)?; + if cfg.bit_depth != 8 && cfg.bit_depth != 10 { + return Err(Error::Invalid("H.265 bit depth".into())); + } let family = gpu .encode_family() .ok_or_else(|| Error::Unsupported("H.265 encode queue family".into()))?; @@ -171,8 +177,13 @@ impl H265EncodeSession { { return Err(Error::Unsupported("H.265 encode".into())); } - let profile = Profile::new(); - let caps = query_caps(gpu, &profile.info)?; + let profile = Profile::new(cfg.bit_depth); + let caps = query_caps(gpu, &profile.info).map_err(|e| match e { + Error::Vk(..) if cfg.bit_depth == 10 => { + Error::Unsupported("10-bit H.265 encode".into()) + } + e => e, + })?; let coding = coding(&caps, cfg)?; if coding.width > caps.max_extent.width || coding.height > caps.max_extent.height { return Err(Error::Unsupported(format!( @@ -259,6 +270,23 @@ impl H265EncodeSession { self.encode_uploaded(pic) } + /// Encodes one 10-bit picture (y: width*height, uv: interleaved CbCr width*height/2, samples in the low 10 bits) of a 10-bit session and returns its Annex-B slice NAL units. + pub fn encode_16( + &mut self, + y: &[u16], + uv: &[u16], + pic: &H265Picture, + ) -> Result, Error> { + if y.len() != self.enc.input.0 * self.enc.input.1 + || uv.len() != self.enc.input.0 * self.enc.input.1 / 2 + { + return Err(Error::Invalid("P010 plane size".into())); + } + self.check(pic)?; + self.enc.upload(Input::P010 { y, uv })?; + self.encode_uploaded(pic) + } + /// Encodes one packed RGB picture (src_width x src_height, row stride in bytes, BGRx or RGBx byte order), box-downscaled to the encoder size on the GPU. pub fn encode_rgb( &mut self, @@ -444,7 +472,7 @@ fn create_parameters( let cropped = c.width != cfg.width || c.height != cfg.height; let mut ptl = zeroed::(); - ptl.general_profile_idc = vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN; + ptl.general_profile_idc = profile_idc(cfg.bit_depth); ptl.general_level_idc = c.level; ptl.flags.set_general_progressive_source_flag(1); ptl.flags.set_general_frame_only_constraint_flag(1); @@ -475,6 +503,8 @@ fn create_parameters( sps.flags .set_sample_adaptive_offset_enabled_flag(c.sao as u32); sps.chroma_format_idc = vk::video::STD_VIDEO_H265_CHROMA_FORMAT_IDC_420; + sps.bit_depth_luma_minus8 = cfg.bit_depth - 8; + sps.bit_depth_chroma_minus8 = cfg.bit_depth - 8; sps.pic_width_in_luma_samples = c.width; sps.pic_height_in_luma_samples = c.height; sps.log2_max_pic_order_cnt_lsb_minus4 = 4; @@ -563,6 +593,14 @@ fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result { }) } +fn profile_idc(bit_depth: u8) -> vk::video::StdVideoH265ProfileIdc { + if bit_depth == 10 { + vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10 + } else { + vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN + } +} + fn level_for( width: u32, height: u32, diff --git a/shims/vk-video-ffi/src/rgb_convert.rs b/shims/vk-video-ffi/src/rgb_convert.rs index 539aefe9..2bc9cff8 100644 --- a/shims/vk-video-ffi/src/rgb_convert.rs +++ b/shims/vk-video-ffi/src/rgb_convert.rs @@ -11,6 +11,10 @@ pub(crate) enum Input<'a> { y: &'a [u8], uv: &'a [u8], }, + P010 { + y: &'a [u16], + uv: &'a [u16], + }, Rgb { data: &'a [u8], width: usize, @@ -30,7 +34,7 @@ pub(crate) enum Input<'a> { impl Input<'_> { pub(crate) fn bgr(&self) -> Option { match *self { - Input::Nv12 { .. } => None, + Input::Nv12 { .. } | Input::P010 { .. } => None, Input::Rgb { bgr, .. } => Some(bgr), #[cfg(target_os = "linux")] Input::DmaBuf { bgr, .. } => Some(bgr), @@ -39,7 +43,7 @@ impl Input<'_> { pub(crate) fn source_image(&self) -> Option { match *self { - Input::Nv12 { .. } | Input::Rgb { .. } => None, + Input::Nv12 { .. } | Input::P010 { .. } | Input::Rgb { .. } => None, #[cfg(target_os = "linux")] Input::DmaBuf { image, .. } => Some(image), } diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index 3499f1ec..10f60b46 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -260,6 +260,37 @@ pub(crate) fn fill_nv12( } } +pub(crate) fn fill_p010( + dst: &mut [u8], + y: &[u16], + uv: &[u16], + w: usize, + h: usize, + aw: usize, + ah: usize, +) { + let (y_dst, uv_dst) = dst.split_at_mut(aw * ah * 2); + for (r, row) in y_dst.chunks_exact_mut(aw * 2).enumerate() { + let src = &y[r.min(h - 1) * w..][..w]; + for (c, px) in row.chunks_exact_mut(2).enumerate() { + px.copy_from_slice(&p010_sample(src[c.min(w - 1)])); + } + } + for (r, row) in uv_dst.chunks_exact_mut(aw * 2).enumerate() { + let src = &uv[r.min(h / 2 - 1) * w..][..w]; + let pairs = w / 2 - 1; + for (c, pair) in row.chunks_exact_mut(4).enumerate() { + let p = c.min(pairs); + pair[..2].copy_from_slice(&p010_sample(src[2 * p])); + pair[2..].copy_from_slice(&p010_sample(src[2 * p + 1])); + } + } +} + +fn p010_sample(value: u16) -> [u8; 2] { + ((value & 0x3ff) << 6).to_le_bytes() +} + #[derive(Default)] pub(crate) struct Image { pub(crate) image: vk::Image, @@ -700,7 +731,8 @@ impl Encoder { bitstream: Default::default(), query: Default::default(), }; - let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2; + let bytes = bytes_per_sample(e.vs.format) as u64; + let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes; let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR; let mut list = vk::VideoProfileListInfoKHR::builder() .profiles(std::slice::from_ref(profile)) @@ -790,6 +822,19 @@ impl Encoder { pub(crate) fn upload(&mut self, input: Input) -> Result<(), Error> { let aw = self.extent.width as usize; let ah = self.extent.height as usize; + let bytes = bytes_per_sample(self.vs.format); + match input { + Input::Nv12 { .. } if bytes != 1 => { + return Err(Error::Invalid("8-bit planes for a 10-bit session".into())); + } + Input::P010 { .. } if bytes != 2 => { + return Err(Error::Invalid("10-bit planes for an 8-bit session".into())); + } + _ if bytes != 1 && input.bgr().is_some() => { + return Err(Error::Unsupported("RGB input at 10 bits".into())); + } + _ => {} + } let gpu = self.vs.gpu.clone(); match input { Input::Nv12 { y, uv } => { @@ -797,6 +842,11 @@ impl Encoder { unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) }; fill_nv12(staging, y, uv, self.input.0, self.input.1, aw, ah); } + Input::P010 { y, uv } => { + let staging = + unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3) }; + fill_p010(staging, y, uv, self.input.0, self.input.1, aw, ah); + } Input::Rgb { data, width, @@ -823,9 +873,10 @@ impl Encoder { let d = gpu.device(); let cb = self.upload.cb; + let luma = (aw * ah * bytes) as u64; let copies = [ copy_region(0, PLANE_0, aw as u32, ah as u32), - copy_region((aw * ah) as u64, PLANE_1, (aw / 2) as u32, (ah / 2) as u32), + copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32), ]; self.upload.begin()?; unsafe {