forge
Explore
Log in

Don't you dare go Hollow

Merge 10-bit Vk encode (H.265 Main10, AV1 10-bit) and 16-bit decode output; VP9 decoder takes the shared Mode

Browse files at this commit

59d3a02304c3b708d5155ac805d0df72aa8ff585Ahmet Kaan GümüşParent: 9777d9a82a0fd5
crates/ec-hw/examples/hw_ten.rsadded+141 -0
@@ -0,0 +1,141 @@
1+use ec_hw::{
2+ Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420_16,
3+ RateControlMode,
4+};
5+
6+const WIDTH: u32 = 1280;
7+const HEIGHT: u32 = 720;
8+const FRAMES: u32 = 30;
9+const PEAK: f64 = 1023.0;
10+
11+fn main() {
12+ let dir = std::env::args().nth(1).unwrap_or_else(|| ".".into());
13+ let rates = [
14+ ("cqp", RateControlMode::ConstantQp { qp: 30 }),
15+ ("cbr", RateControlMode::ConstantBitrate),
16+ ];
17+ for codec in [EncCodec::H265, EncCodec::Av1] {
18+ for (name, rate) in rates {
19+ for backend in [Backend::Vk, Backend::Va] {
20+ if let Err(e) = run(&dir, codec, name, rate, backend) {
21+ println!("{codec:?} {name} {backend:?}: error: {e}");
22+ }
23+ }
24+ }
25+ }
26+}
27+
28+fn run(
29+ dir: &str,
30+ codec: EncCodec,
31+ name: &str,
32+ rate: RateControlMode,
33+ backend: Backend,
34+) -> ec_hw::Result<()> {
35+ let config = EncoderConfig {
36+ bitrate: 4_000_000,
37+ rate_control: rate,
38+ ..EncoderConfig::new(codec, WIDTH, HEIGHT).ten_bit()
39+ };
40+ let mut encoder = match HwEncoder::open(config, Some(backend)) {
41+ Ok(encoder) => encoder,
42+ Err(e) => {
43+ println!("{codec:?} {name} {backend:?}: no encoder: {e}");
44+ return Ok(());
45+ }
46+ };
47+ let mut coded = Vec::with_capacity(FRAMES as usize);
48+ let mut sources = Vec::with_capacity(FRAMES as usize);
49+ for index in 0..FRAMES {
50+ let frame = pattern(index);
51+ let meta = FrameMetadata {
52+ timestamp: index as i64,
53+ force_keyframe: index == 0,
54+ };
55+ coded.push(encoder.encode_16(&frame, meta)?);
56+ sources.push(frame);
57+ }
58+ let stream: Vec<u8> = coded.iter().flat_map(|c| c.data.iter().copied()).collect();
59+ let stem = format!("{dir}/ten_{codec:?}_{name}_{backend:?}");
60+ std::fs::write(format!("{stem}.bin"), &stream).expect("write bitstream");
61+
62+ let mut decoder = HwDecoder::open_16(decode_codec(codec))?;
63+ let mut decoded = Vec::new();
64+ for c in &coded {
65+ decoder.decode(&c.data, c.timestamp)?;
66+ while let Some(frame) = decoder.next_frame_16()? {
67+ decoded.push(frame);
68+ }
69+ }
70+ decoder.flush()?;
71+ while let Some(frame) = decoder.next_frame_16()? {
72+ decoded.push(frame);
73+ }
74+
75+ let mut yuv = Vec::new();
76+ for (_, frame) in &decoded {
77+ for sample in frame.y.iter().chain(&frame.u).chain(&frame.v) {
78+ yuv.extend_from_slice(&sample.to_le_bytes());
79+ }
80+ }
81+ std::fs::write(format!("{stem}_ours.yuv"), &yuv).expect("write decoded yuv");
82+
83+ let psnr: f64 = decoded
84+ .iter()
85+ .map(|(ts, frame)| psnr(&sources[*ts as usize], frame))
86+ .sum::<f64>()
87+ / decoded.len().max(1) as f64;
88+ println!(
89+ "{codec:?} {name} {backend:?}: {} bytes, decoded {} frames, PSNR {psnr:.2} dB",
90+ stream.len(),
91+ decoded.len()
92+ );
93+ Ok(())
94+}
95+
96+fn decode_codec(codec: EncCodec) -> Codec {
97+ match codec {
98+ EncCodec::H264 => Codec::H264,
99+ EncCodec::H265 => Codec::H265,
100+ EncCodec::Av1 => Codec::Av1,
101+ }
102+}
103+
104+fn pattern(index: u32) -> I420_16 {
105+ let t = index as usize;
106+ let (w, h) = (WIDTH as usize, HEIGHT as usize);
107+ I420_16 {
108+ y: plane(w, h, |x, y| x * 3 + y * 5 + t * 16),
109+ u: plane(w / 2, h / 2, |x, y| x * 7 + y * 2 + t * 9),
110+ v: plane(w / 2, h / 2, |x, y| x * 2 + y * 11 + t * 5 + 512),
111+ width: WIDTH,
112+ height: HEIGHT,
113+ bit_depth: 10,
114+ }
115+}
116+
117+fn plane(w: usize, h: usize, value: impl Fn(usize, usize) -> usize) -> Vec<u16> {
118+ let mut out = Vec::with_capacity(w * h);
119+ for row in 0..h {
120+ for col in 0..w {
121+ out.push((value(col, row) & 0x3ff) as u16);
122+ }
123+ }
124+ out
125+}
126+
127+fn psnr(a: &I420_16, b: &I420_16) -> f64 {
128+ let mut sse = 0f64;
129+ let mut n = 0usize;
130+ for (x, y) in
131+ a.y.iter()
132+ .chain(&a.u)
133+ .chain(&a.v)
134+ .zip(b.y.iter().chain(&b.u).chain(&b.v))
135+ {
136+ let d = f64::from(*x) - f64::from(*y);
137+ sse += d * d;
138+ n += 1;
139+ }
140+ 10.0 * (PEAK * PEAK * n as f64 / sse).log10()
141+}
crates/ec-hw/src/frame.rsmodified+2 -63
@@ -7,7 +7,7 @@ use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010};
7 use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};7 use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};
8 8
9 use crate::error::{Error, Result};9 use crate::error::{Error, Result};
10-use crate::picture::{check_plane, fill_i420};10+use crate::picture::{fill_i420, fill_i420_16};
11 use crate::pool::PooledSurface;11 use crate::pool::PooledSurface;
12 12
13 pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};13 pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
@@ -192,68 +192,6 @@ impl std::fmt::Debug for Frame {
192 }192 }
193 }193 }
194 194
195-/// Copy NV12/P010 planes into `out`, after validating every plane against it.
196-fn fill_i420_16(
197- out: &mut I420_16,
198- bit_depth: u8,
199- y_plane: &[u8],
200- y_pitch: usize,
201- uv_plane: &[u8],
202- uv_pitch: usize,
203-) -> Result<()> {
204- let (w, h) = (out.width as usize, out.height as usize);
205- let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
206- let bytes = if bit_depth == 8 { 1 } else { 2 };
207- check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
208- check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
209- let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
210- match bit_depth {
211- 8 => {
212- for row in 0..h {
213- let src = row * y_pitch;
214- row_buf[..w].copy_from_slice(&y_plane[src..src + w]);
215- for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) {
216- *dst = u16::from(sample) << 2;
217- }
218- }
219- for row in 0..ch {
220- let src = row * uv_pitch;
221- let line = &mut row_buf[..cw * 2];
222- line.copy_from_slice(&uv_plane[src..src + cw * 2]);
223- for col in 0..cw {
224- out.u[row * cw + col] = u16::from(line[col * 2]) << 2;
225- out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2;
226- }
227- }
228- }
229- _ => {
230- // P010 is 16-bit little endian with the sample in the top ten
231- // bits; the low six are zero padding.
232- for row in 0..h {
233- let src = row * y_pitch;
234- let line = &mut row_buf[..w * 2];
235- line.copy_from_slice(&y_plane[src..src + w * 2]);
236- for col in 0..w {
237- out.y[row * w + col] =
238- u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6;
239- }
240- }
241- for row in 0..ch {
242- let src = row * uv_pitch;
243- let line = &mut row_buf[..cw * 4];
244- line.copy_from_slice(&uv_plane[src..src + cw * 4]);
245- for col in 0..cw {
246- out.u[row * cw + col] =
247- u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6;
248- out.v[row * cw + col] =
249- u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6;
250- }
251- }
252- }
253- }
254- Ok(())
255-}
256-
257 /// Luma and chroma planes of a read-back NV12/P010 image, with their pitches.195 /// Luma and chroma planes of a read-back NV12/P010 image, with their pitches.
258 fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usize)> {196 fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usize)> {
259 let data: &[u8] = image.as_ref();197 let data: &[u8] = image.as_ref();
@@ -276,6 +214,7 @@ fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usi
276 #[cfg(test)]214 #[cfg(test)]
277 mod tests {215 mod tests {
278 use super::*;216 use super::*;
217+ use crate::picture::check_plane;
279 218
280 fn blank(w: u32, h: u32) -> I420 {219 fn blank(w: u32, h: u32) -> I420 {
281 I420 {220 I420 {
crates/ec-hw/src/hw.rsmodified+81 -23
@@ -9,7 +9,7 @@ use ec_vk::DmaBuf;
9 use std::cell::RefCell;9 use std::cell::RefCell;
10 10
11 use crate::error::{Error, Result};11 use crate::error::{Error, Result};
12-use crate::picture::{Decoded, I420, RgbPicture};12+use crate::picture::{Decoded, I420, I420_16, RgbPicture};
13 #[cfg(target_os = "linux")]13 #[cfg(target_os = "linux")]
14 use crate::picture::{rgb_size, yuv_to_rgb};14 use crate::picture::{rgb_size, yuv_to_rgb};
15 #[cfg(target_os = "linux")]15 #[cfg(target_os = "linux")]
@@ -311,6 +311,19 @@ impl VkEncoder {
311 }311 }
312 }312 }
313 313
314+ fn encode_16(
315+ &mut self,
316+ frame: &I420_16,
317+ force_keyframe: bool,
318+ ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {
319+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
320+ match self {
321+ VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())),
322+ VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe),
323+ VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe),
324+ }
325+ }
326+
314 fn set_rate(327 fn set_rate(
315 &mut self,328 &mut self,
316 rate: ec_vk::RateControl,329 rate: ec_vk::RateControl,
@@ -449,6 +462,22 @@ impl HwEncoder {
449 }462 }
450 }463 }
451 464
465+ /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.
466+ pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
467+ match &mut self.inner {
468+ EncInner::Vk(enc) => {
469+ let coded = enc.encode_16(frame, meta.force_keyframe)?;
470+ Ok(CodedFrame {
471+ data: coded.data,
472+ timestamp: meta.timestamp,
473+ is_keyframe: coded.keyframe,
474+ })
475+ }
476+ #[cfg(target_os = "linux")]
477+ EncInner::Va(enc) => enc.encode_16(frame, meta),
478+ }
479+ }
480+
452 /// 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.481 /// 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.
453 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {482 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
454 match &mut self.inner {483 match &mut self.inner {
@@ -500,12 +529,18 @@ fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> {
500 529
501 fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {530 fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
502 vk_grace()?;531 vk_grace()?;
503- if config.bit_depth != 8 {532+ if config.bit_depth == 10 && config.codec == EncCodec::H264 {
504 return Err(Error::unsupported(533 return Err(Error::unsupported(
505- "10-bit Vulkan Video encode",534+ "10-bit H.264 Vulkan Video encode",
506- "the Vulkan encoders are 8-bit",535+ "the driver offers no High 10 H.264 encode",
507 ));536 ));
508 }537 }
538+ if config.bit_depth != 8 && config.bit_depth != 10 {
539+ return Err(Error::config(format!(
540+ "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1",
541+ config.bit_depth
542+ )));
543+ }
509 let gpu = vk_gpu()544 let gpu = vk_gpu()
510 .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?;545 .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?;
511 let rate = vk_rate(&config);546 let rate = vk_rate(&config);
@@ -534,6 +569,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
534 fps,569 fps,
535 gop_size,570 gop_size,
536 rate,571 rate,
572+ bit_depth: config.bit_depth,
537 },573 },
538 )?),574 )?),
539 EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(575 EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(
@@ -544,6 +580,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
544 fps,580 fps,
545 gop_size,581 gop_size,
546 rate,582 rate,
583+ bit_depth: config.bit_depth,
547 },584 },
548 )?),585 )?),
549 })586 })
@@ -631,8 +668,9 @@ pub struct RgbOutput {
631 }668 }
632 669
633 #[derive(Debug, Clone, Copy, PartialEq, Eq)]670 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
634-enum Mode {671+pub(crate) enum Mode {
635 I420,672 I420,
673+ I420_16,
636 Rgb(RgbOutput),674 Rgb(RgbOutput),
637 }675 }
638 676
@@ -658,18 +696,19 @@ impl HwDecoder {
658 HwDecoder::open_mode(codec, Mode::Rgb(output))696 HwDecoder::open_mode(codec, Mode::Rgb(output))
659 }697 }
660 698
699+ /// Open a decoder for `codec` that hands out 10-bit I420 ([`HwDecoder::next_frame_16`]). 8-bit streams are widened to 10 bits.
700+ pub fn open_16(codec: Codec) -> Result<HwDecoder> {
701+ HwDecoder::open_mode(codec, Mode::I420_16)
702+ }
703+
661 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {704 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {
662- let rgb = match mode {
663- Mode::I420 => None,
664- Mode::Rgb(output) => Some(output),
665- };
666 let mut reasons = Vec::new();705 let mut reasons = Vec::new();
667 let born_epoch = crate::reset::gpu_reset_epoch();706 let born_epoch = crate::reset::gpu_reset_epoch();
668 let vk = vk_grace().and_then(|()| match codec {707 let vk = vk_grace().and_then(|()| match codec {
669- Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264),708+ Codec::H264 => VkH264Decoder::new(mode).map(VkDecoder::H264),
670- Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265),709+ Codec::H265 => VkH265Decoder::new(mode).map(VkDecoder::H265),
671- Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1),710+ Codec::Av1 => VkAv1Decoder::new(mode).map(VkDecoder::Av1),
672- Codec::Vp9 => VkVp9Decoder::new(rgb).map(VkDecoder::Vp9),711+ Codec::Vp9 => VkVp9Decoder::new(mode).map(VkDecoder::Vp9),
673 });712 });
674 match vk {713 match vk {
675 Ok(inner) => {714 Ok(inner) => {
@@ -742,27 +781,45 @@ impl HwDecoder {
742 result781 result
743 }782 }
744 783
745- /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`].784+ /// 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`].
746 pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {785 pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {
747- if let Mode::Rgb(_) = self.mode {786+ if self.mode != Mode::I420 {
748- return Err(Error::config("next_frame on an RGB decoder; use next_rgb"));787+ return Err(Error::config(
788+ "next_frame on a decoder not opened as 8-bit I420",
789+ ));
749 }790 }
750 match self.pull()? {791 match self.pull()? {
751 None => Ok(None),792 None => Ok(None),
752 Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))),793 Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))),
753- Some((_, Decoded::Rgb(_))) => Err(Error::config("RGB picture from an I420 decoder")),794+ Some(_) => Err(Error::config("non-I420 picture from an I420 decoder")),
795+ }
796+ }
797+
798+ /// The next picture in display order, as 10-bit I420 with its timestamp. An error on a decoder not opened with [`HwDecoder::open_16`].
799+ pub fn next_frame_16(&mut self) -> Result<Option<(i64, I420_16)>> {
800+ if self.mode != Mode::I420_16 {
801+ return Err(Error::config(
802+ "next_frame_16 on a decoder not opened with open_16",
803+ ));
804+ }
805+ match self.pull()? {
806+ None => Ok(None),
807+ Some((ts, Decoded::I420_16(frame))) => Ok(Some((ts, frame))),
808+ Some(_) => Err(Error::config("non-16-bit picture from a 16-bit decoder")),
754 }809 }
755 }810 }
756 811
757- /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder opened with [`HwDecoder::open`].812+ /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].
758 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {813 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {
759- if let Mode::I420 = self.mode {814+ if !matches!(self.mode, Mode::Rgb(_)) {
760- return Err(Error::config("next_rgb on an I420 decoder; use open_rgb"));815+ return Err(Error::config(
816+ "next_rgb on a decoder not opened with open_rgb",
817+ ));
761 }818 }
762 match self.pull()? {819 match self.pull()? {
763 None => Ok(None),820 None => Ok(None),
764 Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))),821 Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))),
765- Some((_, Decoded::I420(_))) => Err(Error::config("I420 picture from an RGB decoder")),822+ Some(_) => Err(Error::config("non-RGB picture from an RGB decoder")),
766 }823 }
767 }824 }
768 825
@@ -779,10 +836,11 @@ impl HwDecoder {
779 #[cfg(target_os = "linux")]836 #[cfg(target_os = "linux")]
780 DecInner::Va(d) => match d.next_frame() {837 DecInner::Va(d) => match d.next_frame() {
781 Some(frame) => {838 Some(frame) => {
782- let i420 = frame.to_i420()?;
783 let decoded = match self.mode {839 let decoded = match self.mode {
784- Mode::I420 => Decoded::I420(i420),840+ Mode::I420 => Decoded::I420(frame.to_i420()?),
841+ Mode::I420_16 => Decoded::I420_16(frame.to_i420_16()?),
785 Mode::Rgb(output) => {842 Mode::Rgb(output) => {
843+ let i420 = frame.to_i420()?;
786 let matrix = frame844 let matrix = frame
787 .colour845 .colour
788 .map(|c| c.description.matrix)846 .map(|c| c.description.matrix)
crates/ec-hw/src/picture.rsmodified+90 -0
@@ -62,6 +62,7 @@ impl RgbPicture {
62 #[derive(Debug, Clone, PartialEq, Eq)]62 #[derive(Debug, Clone, PartialEq, Eq)]
63 pub(crate) enum Decoded {63 pub(crate) enum Decoded {
64 I420(I420),64 I420(I420),
65+ I420_16(I420_16),
65 Rgb(RgbPicture),66 Rgb(RgbPicture),
66 }67 }
67 68
@@ -170,6 +171,95 @@ pub(crate) fn semi_planar_to_i420(
170 Ok(out)171 Ok(out)
171 }172 }
172 173
174+/// Copy NV12/P010 planes into `out`, after validating every plane against it.
175+pub(crate) fn fill_i420_16(
176+ out: &mut I420_16,
177+ bit_depth: u8,
178+ y_plane: &[u8],
179+ y_pitch: usize,
180+ uv_plane: &[u8],
181+ uv_pitch: usize,
182+) -> Result<()> {
183+ let (w, h) = (out.width as usize, out.height as usize);
184+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
185+ let bytes = if bit_depth == 8 { 1 } else { 2 };
186+ check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
187+ check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
188+ let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
189+ match bit_depth {
190+ 8 => {
191+ for row in 0..h {
192+ let src = row * y_pitch;
193+ row_buf[..w].copy_from_slice(&y_plane[src..src + w]);
194+ for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) {
195+ *dst = u16::from(sample) << 2;
196+ }
197+ }
198+ for row in 0..ch {
199+ let src = row * uv_pitch;
200+ let line = &mut row_buf[..cw * 2];
201+ line.copy_from_slice(&uv_plane[src..src + cw * 2]);
202+ for col in 0..cw {
203+ out.u[row * cw + col] = u16::from(line[col * 2]) << 2;
204+ out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2;
205+ }
206+ }
207+ }
208+ _ => {
209+ // P010 is 16-bit little endian with the sample in the top ten
210+ // bits; the low six are zero padding.
211+ for row in 0..h {
212+ let src = row * y_pitch;
213+ let line = &mut row_buf[..w * 2];
214+ line.copy_from_slice(&y_plane[src..src + w * 2]);
215+ for col in 0..w {
216+ out.y[row * w + col] =
217+ u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6;
218+ }
219+ }
220+ for row in 0..ch {
221+ let src = row * uv_pitch;
222+ let line = &mut row_buf[..cw * 4];
223+ line.copy_from_slice(&uv_plane[src..src + cw * 4]);
224+ for col in 0..cw {
225+ out.u[row * cw + col] =
226+ u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6;
227+ out.v[row * cw + col] =
228+ u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6;
229+ }
230+ }
231+ }
232+ }
233+ Ok(())
234+}
235+
236+pub(crate) fn semi_planar_to_i420_16(
237+ bit_depth: u8,
238+ y: &[u8],
239+ uv: &[u8],
240+ pitch: usize,
241+ origin: (usize, usize),
242+ size: (u32, u32),
243+) -> Result<I420_16> {
244+ let bytes = if bit_depth == 8 { 1 } else { 2 };
245+ let pitch = pitch * bytes;
246+ let (x, top) = (origin.0 * bytes, origin.1);
247+ let y = y.get(top * pitch + x..).unwrap_or(&[]);
248+ let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]);
249+ let (width, height) = size;
250+ let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2));
251+ let mut out = I420_16 {
252+ y: vec![0; width as usize * height as usize],
253+ u: vec![0; cw * ch],
254+ v: vec![0; cw * ch],
255+ width,
256+ height,
257+ bit_depth: 10,
258+ };
259+ fill_i420_16(&mut out, bit_depth, y, pitch, uv, pitch)?;
260+ Ok(out)
261+}
262+
173 /// Copy NV12/P010 planes into `out`, after validating every plane against it.263 /// Copy NV12/P010 planes into `out`, after validating every plane against it.
174 pub(crate) fn fill_i420(264 pub(crate) fn fill_i420(
175 out: &mut I420,265 out: &mut I420,
crates/ec-hw/src/types.rsmodified+2 -3
@@ -111,9 +111,8 @@ pub struct EncoderConfig {
111 /// The colour description to write into the VUI, or `None` to leave it111 /// The colour description to write into the VUI, or `None` to leave it
112 /// unsignalled (`video_signal_type_present_flag = 0`) as before.112 /// unsignalled (`video_signal_type_present_flag = 0`) as before.
113 pub colour: Option<Colour>,113 pub colour: Option<Colour>,
114- /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`).114+ /// Luma bit depth: 8, or 10 for H.265 and AV1. A 10-bit encoder takes its
115- /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or115+ /// pixels through [`Encoder::encode_16`] or [`HwEncoder::encode_16`].
116- /// straight from a 10-bit [`crate::Frame`].
117 pub bit_depth: u8,116 pub bit_depth: u8,
118 }117 }
119 118
crates/ec-hw/src/vkdec264.rsmodified+24 -8
@@ -14,8 +14,10 @@ use ec_vk::{
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, vui_colour_tags};16 use crate::h264_common::{peek_pps_id, vui_colour_tags};
17-use crate::hw::{RgbOrder, RgbOutput};17+use crate::hw::{Mode, RgbOrder};
18-use crate::picture::{Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, yuv_to_rgb};18+use crate::picture::{
19+ Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, semi_planar_to_i420_16, yuv_to_rgb,
20+};
19 use ec_core::color::{ColorDescription, Tags};21 use ec_core::color::{ColorDescription, Tags};
20 22
21 const MAX_SLOTS: u32 = 17;23 const MAX_SLOTS: u32 = 17;
@@ -60,11 +62,11 @@ pub(crate) struct VkH264Decoder {
60 current: Option<Current>,62 current: Option<Current>,
61 ready: VecDeque<(i64, Decoded)>,63 ready: VecDeque<(i64, Decoded)>,
62 rbsp: Vec<u8>,64 rbsp: Vec<u8>,
63- rgb: Option<RgbOutput>,65+ mode: Mode,
64 }66 }
65 67
66 impl VkH264Decoder {68 impl VkH264Decoder {
67- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {69+ pub(crate) fn new(mode: Mode) -> Result<Self> {
68 let gpu = crate::hw::vk_gpu()70 let gpu = crate::hw::vk_gpu()
69 .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?;71 .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?;
70 Ok(VkH264Decoder {72 Ok(VkH264Decoder {
@@ -78,7 +80,7 @@ impl VkH264Decoder {
78 current: None,80 current: None,
79 ready: VecDeque::new(),81 ready: VecDeque::new(),
80 rbsp: Vec::new(),82 rbsp: Vec::new(),
81- rgb,83+ mode,
82 })84 })
83 }85 }
84 86
@@ -319,14 +321,28 @@ impl VkH264Decoder {
319 refs: &refs,321 refs: &refs,
320 slices: &slices,322 slices: &slices,
321 })?;323 })?;
322- let out = match self.rgb {324+ let out = match self.mode {
323- None => {325+ Mode::I420 => {
324 let (y, uv) = session326 let (y, uv) = session
325 .h264327 .h264
326 .read_output(sps.coded_width, sps.coded_height)?;328 .read_output(sps.coded_width, sps.coded_height)?;
327 Decoded::I420(crop(&sps, &y, &uv))329 Decoded::I420(crop(&sps, &y, &uv))
328 }330 }
329- Some(rgb) => {331+ Mode::I420_16 => {
332+ let (y, uv) = session
333+ .h264
334+ .read_output(sps.coded_width, sps.coded_height)?;
335+ let (left, _, top, _) = sps.crop;
336+ Decoded::I420_16(semi_planar_to_i420_16(
337+ 8,
338+ &y,
339+ &uv,
340+ sps.coded_width as usize,
341+ (left as usize, top as usize),
342+ (sps.width, sps.height),
343+ )?)
344+ }
345+ Mode::Rgb(rgb) => {
330 let (left, _, top, _) = sps.crop;346 let (left, _, top, _) = sps.crop;
331 let matrix =347 let matrix =
332 ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height)348 ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height)
crates/ec-hw/src/vkdec265.rsmodified+32 -8
@@ -18,8 +18,11 @@ use crate::hevc_dpb::{
18 };18 };
19 use ec_core::color::{ColorDescription, Tags};19 use ec_core::color::{ColorDescription, Tags};
20 20
21-use crate::hw::{RgbOrder, RgbOutput};21+use crate::hw::{Mode, RgbOrder};
22-use crate::picture::{Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb};22+use crate::picture::{
23+ Decoded, I420, I420_16, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16,
24+ yuv_to_rgb,
25+};
23 26
24 const MAX_SLOTS: u32 = 17;27 const MAX_SLOTS: u32 = 17;
25 28
@@ -61,11 +64,11 @@ pub(crate) struct VkH265Decoder {
61 current: Option<Current>,64 current: Option<Current>,
62 ready: VecDeque<(i64, Decoded)>,65 ready: VecDeque<(i64, Decoded)>,
63 no_rasl_output: bool,66 no_rasl_output: bool,
64- rgb: Option<RgbOutput>,67+ mode: Mode,
65 }68 }
66 69
67 impl VkH265Decoder {70 impl VkH265Decoder {
68- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {71+ pub(crate) fn new(mode: Mode) -> Result<Self> {
69 let gpu = crate::hw::vk_gpu()72 let gpu = crate::hw::vk_gpu()
70 .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?;73 .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?;
71 Ok(VkH265Decoder {74 Ok(VkH265Decoder {
@@ -80,7 +83,7 @@ impl VkH265Decoder {
80 current: None,83 current: None,
81 ready: VecDeque::new(),84 ready: VecDeque::new(),
82 no_rasl_output: false,85 no_rasl_output: false,
83- rgb,86+ mode,
84 })87 })
85 }88 }
86 89
@@ -342,15 +345,22 @@ impl VkH265Decoder {
342 slices: &slices,345 slices: &slices,
343 })?;346 })?;
344 if current.output {347 if current.output {
345- let frame = match self.rgb {348+ let frame = match self.mode {
346- None => {349+ Mode::I420 => {
347 let (y, uv) = session.h265.read_output(350 let (y, uv) = session.h265.read_output(
348 sps.pic_width_in_luma_samples,351 sps.pic_width_in_luma_samples,
349 sps.pic_height_in_luma_samples,352 sps.pic_height_in_luma_samples,
350 )?;353 )?;
351 Decoded::I420(crop(&sps, &y, &uv)?)354 Decoded::I420(crop(&sps, &y, &uv)?)
352 }355 }
353- Some(rgb) => {356+ Mode::I420_16 => {
357+ let (y, uv) = session.h265.read_output(
358+ sps.pic_width_in_luma_samples,
359+ sps.pic_height_in_luma_samples,
360+ )?;
361+ Decoded::I420_16(crop16(&sps, &y, &uv)?)
362+ }
363+ Mode::Rgb(rgb) => {
354 let (width, height) = sps.display_size();364 let (width, height) = sps.display_size();
355 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);365 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);
356 let matrix =366 let matrix =
@@ -421,6 +431,20 @@ fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result<I420> {
421 )431 )
422 }432 }
423 433
434+fn crop16(sps: &Sps, y: &[u8], uv: &[u8]) -> Result<I420_16> {
435+ semi_planar_to_i420_16(
436+ (8 + sps.bit_depth_luma_minus8) as u8,
437+ y,
438+ uv,
439+ sps.pic_width_in_luma_samples as usize,
440+ (
441+ 2 * sps.conf_win.left as usize,
442+ 2 * sps.conf_win.top as usize,
443+ ),
444+ sps.display_size(),
445+ )
446+}
447+
424 fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel {448 fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel {
425 H265ProfileTierLevel {449 H265ProfileTierLevel {
426 tier_flag: p.tier_flag,450 tier_flag: p.tier_flag,
crates/ec-hw/src/vkdec_av1.rsmodified+22 -8
@@ -19,8 +19,11 @@ use crate::ref_slots::RefSlots;
19 use crate::error::{Error, Result};19 use crate::error::{Error, Result};
20 use ec_core::color::{ColorDescription, Tags};20 use ec_core::color::{ColorDescription, Tags};
21 21
22-use crate::hw::{RgbOrder, RgbOutput};22+use crate::hw::{Mode, RgbOrder};
23-use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb};23+use crate::picture::{
24+ Decoded, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16,
25+ yuv_to_rgb,
26+};
24 27
25 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;28 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
26 29
@@ -44,11 +47,11 @@ pub(crate) struct VkAv1Decoder {
44 session: Option<Session>,47 session: Option<Session>,
45 refs: RefSlots<Rc<Reference>>,48 refs: RefSlots<Rc<Reference>>,
46 ready: VecDeque<(i64, Decoded)>,49 ready: VecDeque<(i64, Decoded)>,
47- rgb: Option<RgbOutput>,50+ mode: Mode,
48 }51 }
49 52
50 impl VkAv1Decoder {53 impl VkAv1Decoder {
51- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {54+ pub(crate) fn new(mode: Mode) -> Result<Self> {
52 let gpu = crate::hw::vk_gpu()55 let gpu = crate::hw::vk_gpu()
53 .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?;56 .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?;
54 Ok(VkAv1Decoder {57 Ok(VkAv1Decoder {
@@ -57,7 +60,7 @@ impl VkAv1Decoder {
57 session: None,60 session: None,
58 refs: RefSlots::new(),61 refs: RefSlots::new(),
59 ready: VecDeque::new(),62 ready: VecDeque::new(),
60- rgb,63+ mode,
61 })64 })
62 }65 }
63 66
@@ -166,8 +169,8 @@ impl VkAv1Decoder {
166 if !(header.show_frame || header.refresh_frame_flags != 0) {169 if !(header.show_frame || header.refresh_frame_flags != 0) {
167 return Ok(());170 return Ok(());
168 }171 }
169- let decoded = match self.rgb {172+ let decoded = match self.mode {
170- None => {173+ Mode::I420 => {
171 let (y, uv) = session.av1.read_output(width, height)?;174 let (y, uv) = session.av1.read_output(width, height)?;
172 Decoded::I420(semi_planar_to_i420(175 Decoded::I420(semi_planar_to_i420(
173 session.bit_depth,176 session.bit_depth,
@@ -178,7 +181,18 @@ impl VkAv1Decoder {
178 (width, height),181 (width, height),
179 )?)182 )?)
180 }183 }
181- Some(rgb) => {184+ Mode::I420_16 => {
185+ let (y, uv) = session.av1.read_output(width, height)?;
186+ Decoded::I420_16(semi_planar_to_i420_16(
187+ session.bit_depth,
188+ &y,
189+ &uv,
190+ width as usize,
191+ (0, 0),
192+ (width, height),
193+ )?)
194+ }
195+ Mode::Rgb(rgb) => {
182 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);196 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
183 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;197 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
184 let (w, h) = rgb_size(width, height, rgb.max_width);198 let (w, h) = rgb_size(width, height, rgb.max_width);
crates/ec-hw/src/vkdec_vp9.rsmodified+21 -8
@@ -14,8 +14,10 @@ use ec_vp9_syntax::{
14 };14 };
15 15
16 use crate::error::{Error, Result};16 use crate::error::{Error, Result};
17-use crate::hw::{RgbOrder, RgbOutput};17+use crate::hw::{Mode, RgbOrder};
18-use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb};18+use crate::picture::{
19+ Decoded, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb,
20+};
19 use crate::ref_slots::RefSlots;21 use crate::ref_slots::RefSlots;
20 22
21 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;23 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
@@ -49,11 +51,11 @@ pub(crate) struct VkVp9Decoder {
49 refs: RefSlots<Rc<Reference>>,51 refs: RefSlots<Rc<Reference>>,
50 previous: Option<PreviousFrame>,52 previous: Option<PreviousFrame>,
51 ready: VecDeque<(i64, Decoded)>,53 ready: VecDeque<(i64, Decoded)>,
52- rgb: Option<RgbOutput>,54+ mode: Mode,
53 }55 }
54 56
55 impl VkVp9Decoder {57 impl VkVp9Decoder {
56- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {58+ pub(crate) fn new(mode: Mode) -> Result<Self> {
57 let gpu = crate::hw::vk_gpu()59 let gpu = crate::hw::vk_gpu()
58 .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?;60 .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?;
59 Ok(VkVp9Decoder {61 Ok(VkVp9Decoder {
@@ -63,7 +65,7 @@ impl VkVp9Decoder {
63 refs: RefSlots::new(),65 refs: RefSlots::new(),
64 previous: None,66 previous: None,
65 ready: VecDeque::new(),67 ready: VecDeque::new(),
66- rgb,68+ mode,
67 })69 })
68 }70 }
69 71
@@ -155,8 +157,8 @@ impl VkVp9Decoder {
155 return Ok(());157 return Ok(());
156 }158 }
157 let (width, height) = (header.width, header.height);159 let (width, height) = (header.width, header.height);
158- let decoded = match self.rgb {160+ let decoded = match self.mode {
159- None => {161+ Mode::I420 => {
160 let (y, uv) = session.vp9.read_output(width, height)?;162 let (y, uv) = session.vp9.read_output(width, height)?;
161 Decoded::I420(semi_planar_to_i420(163 Decoded::I420(semi_planar_to_i420(
162 session.bit_depth,164 session.bit_depth,
@@ -167,7 +169,18 @@ impl VkVp9Decoder {
167 (width, height),169 (width, height),
168 )?)170 )?)
169 }171 }
170- Some(rgb) => {172+ Mode::I420_16 => {
173+ let (y, uv) = session.vp9.read_output(width, height)?;
174+ Decoded::I420_16(semi_planar_to_i420_16(
175+ session.bit_depth,
176+ &y,
177+ &uv,
178+ width as usize,
179+ (0, 0),
180+ (width, height),
181+ )?)
182+ }
183+ Mode::Rgb(rgb) => {
171 let codes = Tags::from_codes(184 let codes = Tags::from_codes(
172 u64::from(header.color_space.h273().map_or(2, |c| c.2)),185 u64::from(header.color_space.h273().map_or(2, |c| c.2)),
173 0,186 0,
crates/ec-vk/examples/av1_encode.rsmodified+1 -0
@@ -34,6 +34,7 @@ fn main() {
34 },34 },
35 None => RateControl::ConstantQp { qp: 26 },35 None => RateControl::ConstantQp { qp: 26 },
36 },36 },
37+ bit_depth: 8,
37 };38 };
38 let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder");39 let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder");
39 40
crates/ec-vk/examples/h265_encode.rsmodified+1 -0
@@ -33,6 +33,7 @@ fn main() {
33 },33 },
34 None => RateControl::ConstantQp { qp: 26 },34 None => RateControl::ConstantQp { qp: 26 },
35 },35 },
36+ bit_depth: 8,
36 };37 };
37 let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder");38 let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder");
38 let mut out = Vec::new();39 let mut out = Vec::new();
crates/ec-vk/src/av1.rsmodified+26 -0
@@ -19,6 +19,8 @@ pub struct Av1EncoderConfig {
19 pub gop_size: u32,19 pub gop_size: u32,
20 /// Rate control.20 /// Rate control.
21 pub rate: RateControl,21 pub rate: RateControl,
22+ /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
23+ pub bit_depth: u8,
22 }24 }
23 25
24 /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`].26 /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`].
@@ -32,6 +34,7 @@ pub struct Av1Encoder {
32 order_hint: u8,34 order_hint: u8,
33 reference: Option<Av1Ref>,35 reference: Option<Av1Ref>,
34 uv: Vec<u8>,36 uv: Vec<u8>,
37+ uv16: Vec<u16>,
35 }38 }
36 39
37 impl Av1Encoder {40 impl Av1Encoder {
@@ -47,6 +50,7 @@ impl Av1Encoder {
47 height: cfg.height,50 height: cfg.height,
48 fps: cfg.fps,51 fps: cfg.fps,
49 rate: cfg.rate,52 rate: cfg.rate,
53+ bit_depth: cfg.bit_depth,
50 },54 },
51 )?;55 )?;
52 let sequence_header = session.sequence_header();56 let sequence_header = session.sequence_header();
@@ -60,6 +64,7 @@ impl Av1Encoder {
60 order_hint: 0,64 order_hint: 0,
61 reference: None,65 reference: None,
62 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],66 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
67+ uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
63 })68 })
64 }69 }
65 70
@@ -84,6 +89,27 @@ impl Av1Encoder {
84 Ok(self.finish(&pic, frame))89 Ok(self.finish(&pic, frame))
85 }90 }
86 91
92+ /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it a KEY frame and restarts the GOP.
93+ pub fn encode_16(
94+ &mut self,
95+ y: &[u16],
96+ u: &[u16],
97+ v: &[u16],
98+ force_keyframe: bool,
99+ ) -> Result<CodedFrame, Error> {
100+ let chroma = self.width * self.height / 4;
101+ if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
102+ return Err(Error::Invalid("I420 plane size".into()));
103+ }
104+ for (i, pair) in self.uv16.chunks_exact_mut(2).enumerate() {
105+ pair[0] = u[i];
106+ pair[1] = v[i];
107+ }
108+ let pic = self.next_picture(force_keyframe);
109+ let frame = self.session.encode_16(y, &self.uv16, &pic)?;
110+ Ok(self.finish(&pic, frame))
111+ }
112+
87 /// Changes bitrate or frame rate; takes effect on the next frame.113 /// Changes bitrate or frame rate; takes effect on the next frame.
88 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {114 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
89 Ok(self.session.set_rate(rate, fps)?)115 Ok(self.session.set_rate(rate, fps)?)
crates/ec-vk/src/h265.rsmodified+26 -0
@@ -17,6 +17,8 @@ pub struct H265EncoderConfig {
17 pub gop_size: u32,17 pub gop_size: u32,
18 /// Rate control.18 /// Rate control.
19 pub rate: RateControl,19 pub rate: RateControl,
20+ /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
21+ pub bit_depth: u8,
20 }22 }
21 23
22 /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].24 /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].
@@ -30,6 +32,7 @@ pub struct H265Encoder {
30 poc: i32,32 poc: i32,
31 reference: Option<H265Ref>,33 reference: Option<H265Ref>,
32 uv: Vec<u8>,34 uv: Vec<u8>,
35+ uv16: Vec<u16>,
33 }36 }
34 37
35 impl H265Encoder {38 impl H265Encoder {
@@ -45,6 +48,7 @@ impl H265Encoder {
45 height: cfg.height,48 height: cfg.height,
46 fps: cfg.fps,49 fps: cfg.fps,
47 rate: cfg.rate,50 rate: cfg.rate,
51+ bit_depth: cfg.bit_depth,
48 },52 },
49 )?;53 )?;
50 let parameter_sets = session.parameter_sets()?;54 let parameter_sets = session.parameter_sets()?;
@@ -58,6 +62,7 @@ impl H265Encoder {
58 poc: 0,62 poc: 0,
59 reference: None,63 reference: None,
60 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],64 uv: vec![0; cfg.width as usize * cfg.height as usize / 2],
65+ uv16: vec![0; cfg.width as usize * cfg.height as usize / 2],
61 })66 })
62 }67 }
63 68
@@ -82,6 +87,27 @@ impl H265Encoder {
82 Ok(self.finish(&pic, slice))87 Ok(self.finish(&pic, slice))
83 }88 }
84 89
90+ /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP.
91+ pub fn encode_16(
92+ &mut self,
93+ y: &[u16],
94+ u: &[u16],
95+ v: &[u16],
96+ force_keyframe: bool,
97+ ) -> Result<CodedFrame, Error> {
98+ let chroma = self.width * self.height / 4;
99+ if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma {
100+ return Err(Error::Invalid("I420 plane size".into()));
101+ }
102+ for (i, pair) in self.uv16.chunks_exact_mut(2).enumerate() {
103+ pair[0] = u[i];
104+ pair[1] = v[i];
105+ }
106+ let pic = self.next_picture(force_keyframe);
107+ let slice = self.session.encode_16(y, &self.uv16, &pic)?;
108+ Ok(self.finish(&pic, slice))
109+ }
110+
85 /// Changes bitrate or frame rate; takes effect on the next frame.111 /// Changes bitrate or frame rate; takes effect on the next frame.
86 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {112 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
87 Ok(self.session.set_rate(rate, fps)?)113 Ok(self.session.set_rate(rate, fps)?)
shims/vk-video-ffi/examples/dmabuf_smoke.rsmodified+2 -0
@@ -82,6 +82,7 @@ impl Encode for H265EncodeSession {
82 height: size.1,82 height: size.1,
83 fps: FPS,83 fps: FPS,
84 rate: RATE,84 rate: RATE,
85+ bit_depth: 8,
85 };86 };
86 H265EncodeSession::new(gpu, &cfg)87 H265EncodeSession::new(gpu, &cfg)
87 }88 }
@@ -115,6 +116,7 @@ impl Encode for Av1EncodeSession {
115 height: size.1,116 height: size.1,
116 fps: FPS,117 fps: FPS,
117 rate: RATE,118 rate: RATE,
119+ bit_depth: 8,
118 };120 };
119 Av1EncodeSession::new(gpu, &cfg)121 Av1EncodeSession::new(gpu, &cfg)
120 }122 }
shims/vk-video-ffi/src/av1_encode.rsmodified+33 -11
@@ -8,7 +8,7 @@ use crate::dmabuf::DmaBuf;
8 use crate::rgb_convert::{Input, check_rgb};8 use crate::rgb_convert::{Input, check_rgb};
9 use crate::session::{9 use crate::session::{
10 DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession,10 DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession,
11- picture_resource, validate_rate, video_caps, vk, zeroed,11+ component_bit_depth, picture_resource, validate_rate, video_caps, vk, zeroed,
12 };12 };
13 use crate::{Error, Gpu, RateControl};13 use crate::{Error, Gpu, RateControl};
14 14
@@ -27,6 +27,8 @@ pub struct Av1EncodeConfig {
27 pub fps: (u32, u32),27 pub fps: (u32, u32),
28 /// Rate control; ConstantQp qp is mapped to AV1 base_q_idx as qp * 5.28 /// Rate control; ConstantQp qp is mapped to AV1 base_q_idx as qp * 5.
29 pub rate: RateControl,29 pub rate: RateControl,
30+ /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).
31+ pub bit_depth: u8,
30 }32 }
31 33
32 /// One picture to encode.34 /// One picture to encode.
@@ -67,13 +69,14 @@ struct Profile {
67 }69 }
68 70
69 impl Profile {71 impl Profile {
70- fn new() -> Box<Self> {72+ fn new(bit_depth: u8) -> Box<Self> {
73+ let component = component_bit_depth(bit_depth);
71 let mut p = Box::new(Profile {74 let mut p = Box::new(Profile {
72 info: vk::VideoProfileInfoKHR::builder()75 info: vk::VideoProfileInfoKHR::builder()
73 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_AV1)76 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_AV1)
74 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)77 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
75- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)78+ .luma_bit_depth(component)
76- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)79+ .chroma_bit_depth(component)
77 .build(),80 .build(),
78 codec: vk::VideoEncodeAV1ProfileInfoKHR::builder()81 codec: vk::VideoEncodeAV1ProfileInfoKHR::builder()
79 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN)82 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN)
@@ -158,8 +161,11 @@ impl Av1EncodeSession {
158 {161 {
159 return Err(Error::Unsupported("AV1 encode".into()));162 return Err(Error::Unsupported("AV1 encode".into()));
160 }163 }
161- let profile = Profile::new();164+ let profile = Profile::new(cfg.bit_depth);
162- let caps = query_caps(gpu, &profile.info)?;165+ let caps = query_caps(gpu, &profile.info).map_err(|e| match e {
166+ Error::Vk(..) if cfg.bit_depth == 10 => Error::Unsupported("10-bit AV1 encode".into()),
167+ e => e,
168+ })?;
163 if cfg.width > caps.max_extent.width || cfg.height > caps.max_extent.height {169 if cfg.width > caps.max_extent.width || cfg.height > caps.max_extent.height {
164 return Err(Error::Unsupported(format!(170 return Err(Error::Unsupported(format!(
165 "AV1 encode {}x{}",171 "AV1 encode {}x{}",
@@ -203,11 +209,11 @@ impl Av1EncodeSession {
203 (cfg.rate, cfg.fps),209 (cfg.rate, cfg.fps),
204 caps.size_align,210 caps.size_align,
205 )?;211 )?;
206- let params = create_parameters(&enc.vs, extent, sb128)?;212+ let params = create_parameters(&enc.vs, extent, sb128, cfg.bit_depth)?;
207 enc.vs.set_params(params);213 enc.vs.set_params(params);
208 Ok(Av1EncodeSession {214 Ok(Av1EncodeSession {
209 enc,215 enc,
210- seq: sequence_header_obu(cfg.width, cfg.height, sb128),216+ seq: sequence_header_obu(cfg.width, cfg.height, sb128, cfg.bit_depth),
211 slot_key: [false; DPB_SLOTS],217 slot_key: [false; DPB_SLOTS],
212 ref_order_hint: [0; AV1_SLOTS],218 ref_order_hint: [0; AV1_SLOTS],
213 })219 })
@@ -230,6 +236,18 @@ impl Av1EncodeSession {
230 self.encode_uploaded(pic)236 self.encode_uploaded(pic)
231 }237 }
232 238
239+ /// 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.
240+ pub fn encode_16(&mut self, y: &[u16], uv: &[u16], pic: &Av1Picture) -> Result<Vec<u8>, Error> {
241+ if y.len() != self.enc.input.0 * self.enc.input.1
242+ || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
243+ {
244+ return Err(Error::Invalid("P010 plane size".into()));
245+ }
246+ self.check(pic)?;
247+ self.enc.upload(Input::P010 { y, uv })?;
248+ self.encode_uploaded(pic)
249+ }
250+
233 /// 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.251 /// 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.
234 pub fn encode_rgb(252 pub fn encode_rgb(
235 &mut self,253 &mut self,
@@ -430,9 +448,10 @@ fn create_parameters(
430 vs: &VideoSession,448 vs: &VideoSession,
431 extent: vk::Extent2D,449 extent: vk::Extent2D,
432 sb128: bool,450 sb128: bool,
451+ bit_depth: u8,
433 ) -> Result<vk::VideoSessionParametersKHR, Error> {452 ) -> Result<vk::VideoSessionParametersKHR, Error> {
434 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();453 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();
435- color.BitDepth = 8;454+ color.BitDepth = bit_depth;
436 color.subsampling_x = 1;455 color.subsampling_x = 1;
437 color.subsampling_y = 1;456 color.subsampling_y = 1;
438 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;457 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;
@@ -515,7 +534,7 @@ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
515 out534 out
516 }535 }
517 536
518-fn sequence_header_obu(width: u32, height: u32, sb128: bool) -> Vec<u8> {537+fn sequence_header_obu(width: u32, height: u32, sb128: bool, bit_depth: u8) -> Vec<u8> {
519 let mut b = Bits(Vec::new());538 let mut b = Bits(Vec::new());
520 b.put(0, 3);539 b.put(0, 3);
521 b.put(0, 1);540 b.put(0, 1);
@@ -547,17 +566,20 @@ fn sequence_header_obu(width: u32, height: u32, sb128: bool) -> Vec<u8> {
547 b.put(0, 1);566 b.put(0, 1);
548 b.put(0, 1);567 b.put(0, 1);
549 b.put(0, 1);568 b.put(0, 1);
569+ b.put((bit_depth == 10) as u32, 1);
550 b.put(0, 1);570 b.put(0, 1);
551 b.put(0, 1);571 b.put(0, 1);
552 b.put(0, 1);572 b.put(0, 1);
553 b.put(0, 2);573 b.put(0, 2);
554 b.put(0, 1);574 b.put(0, 1);
555 b.put(0, 1);575 b.put(0, 1);
556- b.put(0, 1);
557 obu(1, &b.finish())576 obu(1, &b.finish())
558 }577 }
559 578
560 fn validate(cfg: &Av1EncodeConfig) -> Result<(), Error> {579 fn validate(cfg: &Av1EncodeConfig) -> Result<(), Error> {
580+ if cfg.bit_depth != 8 && cfg.bit_depth != 10 {
581+ return Err(Error::Invalid("AV1 bit depth".into()));
582+ }
561 if cfg.width == 0 || cfg.height == 0 || cfg.width % 8 != 0 || cfg.height % 8 != 0 {583 if cfg.width == 0 || cfg.height == 0 || cfg.width % 8 != 0 || cfg.height % 8 != 0 {
562 return Err(Error::Invalid(584 return Err(Error::Invalid(
563 "size must be a non-zero multiple of 8".into(),585 "size must be a non-zero multiple of 8".into(),
shims/vk-video-ffi/src/h265_encode.rsmodified+46 -8
@@ -11,7 +11,7 @@ use crate::h264_encode::validate;
11 use crate::rgb_convert::{Input, check_rgb};11 use crate::rgb_convert::{Input, check_rgb};
12 use crate::session::{12 use crate::session::{
13 DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align,13 DPB_SLOTS, Encoder, INITIAL_VIRTUAL_BUFFER_MS, VIRTUAL_BUFFER_MS, VideoSession, align,
14- picture_resource, video_caps, vk, zeroed,14+ component_bit_depth, picture_resource, video_caps, vk, zeroed,
15 };15 };
16 use crate::{Error, Gpu, RateControl};16 use crate::{Error, Gpu, RateControl};
17 17
@@ -26,6 +26,8 @@ pub struct H265EncodeConfig {
26 pub fps: (u32, u32),26 pub fps: (u32, u32),
27 /// Rate control.27 /// Rate control.
28 pub rate: RateControl,28 pub rate: RateControl,
29+ /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input).
30+ pub bit_depth: u8,
29 }31 }
30 32
31 /// One picture to encode.33 /// One picture to encode.
@@ -80,16 +82,17 @@ struct Profile {
80 }82 }
81 83
82 impl Profile {84 impl Profile {
83- fn new() -> Box<Self> {85+ fn new(bit_depth: u8) -> Box<Self> {
86+ let component = component_bit_depth(bit_depth);
84 let mut p = Box::new(Profile {87 let mut p = Box::new(Profile {
85 info: vk::VideoProfileInfoKHR::builder()88 info: vk::VideoProfileInfoKHR::builder()
86 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H265)89 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H265)
87 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)90 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
88- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)91+ .luma_bit_depth(component)
89- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)92+ .chroma_bit_depth(component)
90 .build(),93 .build(),
91 codec: vk::VideoEncodeH265ProfileInfoKHR::builder()94 codec: vk::VideoEncodeH265ProfileInfoKHR::builder()
92- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN)95+ .std_profile_idc(profile_idc(bit_depth))
93 .build(),96 .build(),
94 usage: vk::VideoEncodeUsageInfoKHR::builder()97 usage: vk::VideoEncodeUsageInfoKHR::builder()
95 .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING)98 .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING)
@@ -161,6 +164,9 @@ impl H265EncodeSession {
161 /// Creates a session with its DPB, buffers and parameter sets.164 /// Creates a session with its DPB, buffers and parameter sets.
162 pub fn new(gpu: &Gpu, cfg: &H265EncodeConfig) -> Result<Self, Error> {165 pub fn new(gpu: &Gpu, cfg: &H265EncodeConfig) -> Result<Self, Error> {
163 validate(cfg.width, cfg.height, cfg.fps, cfg.rate)?;166 validate(cfg.width, cfg.height, cfg.fps, cfg.rate)?;
167+ if cfg.bit_depth != 8 && cfg.bit_depth != 10 {
168+ return Err(Error::Invalid("H.265 bit depth".into()));
169+ }
164 let family = gpu170 let family = gpu
165 .encode_family()171 .encode_family()
166 .ok_or_else(|| Error::Unsupported("H.265 encode queue family".into()))?;172 .ok_or_else(|| Error::Unsupported("H.265 encode queue family".into()))?;
@@ -171,8 +177,13 @@ impl H265EncodeSession {
171 {177 {
172 return Err(Error::Unsupported("H.265 encode".into()));178 return Err(Error::Unsupported("H.265 encode".into()));
173 }179 }
174- let profile = Profile::new();180+ let profile = Profile::new(cfg.bit_depth);
175- let caps = query_caps(gpu, &profile.info)?;181+ let caps = query_caps(gpu, &profile.info).map_err(|e| match e {
182+ Error::Vk(..) if cfg.bit_depth == 10 => {
183+ Error::Unsupported("10-bit H.265 encode".into())
184+ }
185+ e => e,
186+ })?;
176 let coding = coding(&caps, cfg)?;187 let coding = coding(&caps, cfg)?;
177 if coding.width > caps.max_extent.width || coding.height > caps.max_extent.height {188 if coding.width > caps.max_extent.width || coding.height > caps.max_extent.height {
178 return Err(Error::Unsupported(format!(189 return Err(Error::Unsupported(format!(
@@ -259,6 +270,23 @@ impl H265EncodeSession {
259 self.encode_uploaded(pic)270 self.encode_uploaded(pic)
260 }271 }
261 272
273+ /// 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.
274+ pub fn encode_16(
275+ &mut self,
276+ y: &[u16],
277+ uv: &[u16],
278+ pic: &H265Picture,
279+ ) -> Result<Vec<u8>, Error> {
280+ if y.len() != self.enc.input.0 * self.enc.input.1
281+ || uv.len() != self.enc.input.0 * self.enc.input.1 / 2
282+ {
283+ return Err(Error::Invalid("P010 plane size".into()));
284+ }
285+ self.check(pic)?;
286+ self.enc.upload(Input::P010 { y, uv })?;
287+ self.encode_uploaded(pic)
288+ }
289+
262 /// 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.290 /// 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.
263 pub fn encode_rgb(291 pub fn encode_rgb(
264 &mut self,292 &mut self,
@@ -444,7 +472,7 @@ fn create_parameters(
444 let cropped = c.width != cfg.width || c.height != cfg.height;472 let cropped = c.width != cfg.width || c.height != cfg.height;
445 473
446 let mut ptl = zeroed::<vk::video::StdVideoH265ProfileTierLevel>();474 let mut ptl = zeroed::<vk::video::StdVideoH265ProfileTierLevel>();
447- ptl.general_profile_idc = vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN;475+ ptl.general_profile_idc = profile_idc(cfg.bit_depth);
448 ptl.general_level_idc = c.level;476 ptl.general_level_idc = c.level;
449 ptl.flags.set_general_progressive_source_flag(1);477 ptl.flags.set_general_progressive_source_flag(1);
450 ptl.flags.set_general_frame_only_constraint_flag(1);478 ptl.flags.set_general_frame_only_constraint_flag(1);
@@ -475,6 +503,8 @@ fn create_parameters(
475 sps.flags503 sps.flags
476 .set_sample_adaptive_offset_enabled_flag(c.sao as u32);504 .set_sample_adaptive_offset_enabled_flag(c.sao as u32);
477 sps.chroma_format_idc = vk::video::STD_VIDEO_H265_CHROMA_FORMAT_IDC_420;505 sps.chroma_format_idc = vk::video::STD_VIDEO_H265_CHROMA_FORMAT_IDC_420;
506+ sps.bit_depth_luma_minus8 = cfg.bit_depth - 8;
507+ sps.bit_depth_chroma_minus8 = cfg.bit_depth - 8;
478 sps.pic_width_in_luma_samples = c.width;508 sps.pic_width_in_luma_samples = c.width;
479 sps.pic_height_in_luma_samples = c.height;509 sps.pic_height_in_luma_samples = c.height;
480 sps.log2_max_pic_order_cnt_lsb_minus4 = 4;510 sps.log2_max_pic_order_cnt_lsb_minus4 = 4;
@@ -563,6 +593,14 @@ fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result<Coding, Error> {
563 })593 })
564 }594 }
565 595
596+fn profile_idc(bit_depth: u8) -> vk::video::StdVideoH265ProfileIdc {
597+ if bit_depth == 10 {
598+ vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10
599+ } else {
600+ vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN
601+ }
602+}
603+
566 fn level_for(604 fn level_for(
567 width: u32,605 width: u32,
568 height: u32,606 height: u32,
shims/vk-video-ffi/src/rgb_convert.rsmodified+6 -2
@@ -11,6 +11,10 @@ pub(crate) enum Input<'a> {
11 y: &'a [u8],11 y: &'a [u8],
12 uv: &'a [u8],12 uv: &'a [u8],
13 },13 },
14+ P010 {
15+ y: &'a [u16],
16+ uv: &'a [u16],
17+ },
14 Rgb {18 Rgb {
15 data: &'a [u8],19 data: &'a [u8],
16 width: usize,20 width: usize,
@@ -30,7 +34,7 @@ pub(crate) enum Input<'a> {
30 impl Input<'_> {34 impl Input<'_> {
31 pub(crate) fn bgr(&self) -> Option<bool> {35 pub(crate) fn bgr(&self) -> Option<bool> {
32 match *self {36 match *self {
33- Input::Nv12 { .. } => None,37+ Input::Nv12 { .. } | Input::P010 { .. } => None,
34 Input::Rgb { bgr, .. } => Some(bgr),38 Input::Rgb { bgr, .. } => Some(bgr),
35 #[cfg(target_os = "linux")]39 #[cfg(target_os = "linux")]
36 Input::DmaBuf { bgr, .. } => Some(bgr),40 Input::DmaBuf { bgr, .. } => Some(bgr),
@@ -39,7 +43,7 @@ impl Input<'_> {
39 43
40 pub(crate) fn source_image(&self) -> Option<vk::Image> {44 pub(crate) fn source_image(&self) -> Option<vk::Image> {
41 match *self {45 match *self {
42- Input::Nv12 { .. } | Input::Rgb { .. } => None,46+ Input::Nv12 { .. } | Input::P010 { .. } | Input::Rgb { .. } => None,
43 #[cfg(target_os = "linux")]47 #[cfg(target_os = "linux")]
44 Input::DmaBuf { image, .. } => Some(image),48 Input::DmaBuf { image, .. } => Some(image),
45 }49 }
shims/vk-video-ffi/src/session.rsmodified+53 -2
@@ -268,6 +268,37 @@ pub(crate) fn fill_nv12(
268 }268 }
269 }269 }
270 270
271+pub(crate) fn fill_p010(
272+ dst: &mut [u8],
273+ y: &[u16],
274+ uv: &[u16],
275+ w: usize,
276+ h: usize,
277+ aw: usize,
278+ ah: usize,
279+) {
280+ let (y_dst, uv_dst) = dst.split_at_mut(aw * ah * 2);
281+ for (r, row) in y_dst.chunks_exact_mut(aw * 2).enumerate() {
282+ let src = &y[r.min(h - 1) * w..][..w];
283+ for (c, px) in row.chunks_exact_mut(2).enumerate() {
284+ px.copy_from_slice(&p010_sample(src[c.min(w - 1)]));
285+ }
286+ }
287+ for (r, row) in uv_dst.chunks_exact_mut(aw * 2).enumerate() {
288+ let src = &uv[r.min(h / 2 - 1) * w..][..w];
289+ let pairs = w / 2 - 1;
290+ for (c, pair) in row.chunks_exact_mut(4).enumerate() {
291+ let p = c.min(pairs);
292+ pair[..2].copy_from_slice(&p010_sample(src[2 * p]));
293+ pair[2..].copy_from_slice(&p010_sample(src[2 * p + 1]));
294+ }
295+ }
296+}
297+
298+fn p010_sample(value: u16) -> [u8; 2] {
299+ ((value & 0x3ff) << 6).to_le_bytes()
300+}
301+
271 #[derive(Default)]302 #[derive(Default)]
272 pub(crate) struct Image {303 pub(crate) struct Image {
273 pub(crate) image: vk::Image,304 pub(crate) image: vk::Image,
@@ -708,7 +739,8 @@ impl Encoder {
708 bitstream: Default::default(),739 bitstream: Default::default(),
709 query: Default::default(),740 query: Default::default(),
710 };741 };
711- let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2;742+ let bytes = bytes_per_sample(e.vs.format) as u64;
743+ let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
712 let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;744 let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
713 let mut list = vk::VideoProfileListInfoKHR::builder()745 let mut list = vk::VideoProfileListInfoKHR::builder()
714 .profiles(std::slice::from_ref(profile))746 .profiles(std::slice::from_ref(profile))
@@ -798,6 +830,19 @@ impl Encoder {
798 pub(crate) fn upload(&mut self, input: Input) -> Result<(), Error> {830 pub(crate) fn upload(&mut self, input: Input) -> Result<(), Error> {
799 let aw = self.extent.width as usize;831 let aw = self.extent.width as usize;
800 let ah = self.extent.height as usize;832 let ah = self.extent.height as usize;
833+ let bytes = bytes_per_sample(self.vs.format);
834+ match input {
835+ Input::Nv12 { .. } if bytes != 1 => {
836+ return Err(Error::Invalid("8-bit planes for a 10-bit session".into()));
837+ }
838+ Input::P010 { .. } if bytes != 2 => {
839+ return Err(Error::Invalid("10-bit planes for an 8-bit session".into()));
840+ }
841+ _ if bytes != 1 && input.bgr().is_some() => {
842+ return Err(Error::Unsupported("RGB input at 10 bits".into()));
843+ }
844+ _ => {}
845+ }
801 let gpu = self.vs.gpu.clone();846 let gpu = self.vs.gpu.clone();
802 match input {847 match input {
803 Input::Nv12 { y, uv } => {848 Input::Nv12 { y, uv } => {
@@ -805,6 +850,11 @@ impl Encoder {
805 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };850 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };
806 fill_nv12(staging, y, uv, self.input.0, self.input.1, aw, ah);851 fill_nv12(staging, y, uv, self.input.0, self.input.1, aw, ah);
807 }852 }
853+ Input::P010 { y, uv } => {
854+ let staging =
855+ unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3) };
856+ fill_p010(staging, y, uv, self.input.0, self.input.1, aw, ah);
857+ }
808 Input::Rgb {858 Input::Rgb {
809 data,859 data,
810 width,860 width,
@@ -831,9 +881,10 @@ impl Encoder {
831 881
832 let d = gpu.device();882 let d = gpu.device();
833 let cb = self.upload.cb;883 let cb = self.upload.cb;
884+ let luma = (aw * ah * bytes) as u64;
834 let copies = [885 let copies = [
835 copy_region(0, PLANE_0, aw as u32, ah as u32),886 copy_region(0, PLANE_0, aw as u32, ah as u32),
836- copy_region((aw * ah) as u64, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),887+ copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
837 ];888 ];
838 self.upload.begin()?;889 self.upload.begin()?;
839 unsafe {890 unsafe {