forge
Explore
Log in

Don't you dare go Hollow

vk: 10-bit H.265 Main10 and AV1 encode from P010, Vulkan 10-bit decode output; ec-hw encode_16 and HwDecoder::open_16/next_frame_16

Browse files at this commit

82a0fd510bb85ae93b4c474b1f558dfa024f16f1Ahmet Kaan GümüşParent: abe484f
Shim: P010 input plane upload, Main 10 / high_bitdepth parameter sets, encode_16 on H.265 and AV1 sessions; RGB and DMA-BUF input refused at 10 bits; 10-bit caps query maps to Unsupported.
ec-vk: bit_depth in H265/Av1 encoder configs, encode_16.
ec-hw: EncoderConfig.bit_depth 10 on Vulkan (H.264 stays Unsupported), HwEncoder::encode_16; Mode::I420_16 decode output for Vulkan and VA-API, shared fill_i420_16 in picture.rs.
examples/hw_ten: 30-frame 1280x720 round trip, PSNR and VA comparison.
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};
77 use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};
88
99 use crate::error::{Error, Result};
10-use crate::picture::{check_plane, fill_i420};
10+use crate::picture::{fill_i420, fill_i420_16};
1111 use crate::pool::PooledSurface;
1212
1313 pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
@@ -192,68 +192,6 @@ impl std::fmt::Debug for Frame {
192192 }
193193 }
194194
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-
257195 /// Luma and chroma planes of a read-back NV12/P010 image, with their pitches.
258196 fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usize)> {
259197 let data: &[u8] = image.as_ref();
@@ -276,6 +214,7 @@ fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usi
276214 #[cfg(test)]
277215 mod tests {
278216 use super::*;
217+ use crate::picture::check_plane;
279218
280219 fn blank(w: u32, h: u32) -> I420 {
281220 I420 {
crates/ec-hw/src/hw.rsmodified+80 -22
@@ -7,7 +7,7 @@ use std::os::fd::BorrowedFd;
77 use ec_vk::DmaBuf;
88
99 use crate::error::{Error, Result};
10-use crate::picture::{Decoded, I420, RgbPicture};
10+use crate::picture::{Decoded, I420, I420_16, RgbPicture};
1111 #[cfg(target_os = "linux")]
1212 use crate::picture::{rgb_size, yuv_to_rgb};
1313 #[cfg(target_os = "linux")]
@@ -278,6 +278,19 @@ impl VkEncoder {
278278 }
279279 }
280280
281+ fn encode_16(
282+ &mut self,
283+ frame: &I420_16,
284+ force_keyframe: bool,
285+ ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {
286+ let (y, u, v) = (&frame.y, &frame.u, &frame.v);
287+ match self {
288+ VkEncoder::H264(_) => Err(ec_vk::Error::Unsupported("10-bit H.264 encode".into())),
289+ VkEncoder::H265(e) => e.encode_16(y, u, v, force_keyframe),
290+ VkEncoder::Av1(e) => e.encode_16(y, u, v, force_keyframe),
291+ }
292+ }
293+
281294 fn set_rate(
282295 &mut self,
283296 rate: ec_vk::RateControl,
@@ -411,6 +424,22 @@ impl HwEncoder {
411424 }
412425 }
413426
427+ /// Encode one 10-bit frame of a 10-bit encoder (H.265 and AV1), the [`HwEncoder::encode`] of a 10-bit encoder.
428+ pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> {
429+ match &mut self.inner {
430+ EncInner::Vk(enc) => {
431+ let coded = enc.encode_16(frame, meta.force_keyframe)?;
432+ Ok(CodedFrame {
433+ data: coded.data,
434+ timestamp: meta.timestamp,
435+ is_keyframe: coded.keyframe,
436+ })
437+ }
438+ #[cfg(target_os = "linux")]
439+ EncInner::Va(enc) => enc.encode_16(frame, meta),
440+ }
441+ }
442+
414443 /// 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.
415444 pub fn encode_rgb(&mut self, frame: &RgbFrame, meta: FrameMetadata) -> Result<CodedFrame> {
416445 match &mut self.inner {
@@ -459,12 +488,18 @@ fn open_backend(backend: Backend, config: EncoderConfig) -> Result<EncInner> {
459488 }
460489
461490 fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
462- if config.bit_depth != 8 {
491+ if config.bit_depth == 10 && config.codec == EncCodec::H264 {
463492 return Err(Error::unsupported(
464- "10-bit Vulkan Video encode",
465- "the Vulkan encoders are 8-bit",
493+ "10-bit H.264 Vulkan Video encode",
494+ "the driver offers no High 10 H.264 encode",
466495 ));
467496 }
497+ if config.bit_depth != 8 && config.bit_depth != 10 {
498+ return Err(Error::config(format!(
499+ "encoder bit depth {}: Vulkan encodes 8-bit, or 10-bit H.265 and AV1",
500+ config.bit_depth
501+ )));
502+ }
468503 let gpu = vk_gpu()
469504 .ok_or_else(|| Error::unsupported("Vulkan Video encode", "no Vulkan Video device"))?;
470505 let rate = vk_rate(&config);
@@ -493,6 +528,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
493528 fps,
494529 gop_size,
495530 rate,
531+ bit_depth: config.bit_depth,
496532 },
497533 )?),
498534 EncCodec::Av1 => VkEncoder::Av1(ec_vk::Av1Encoder::new(
@@ -503,6 +539,7 @@ fn open_vk(config: EncoderConfig) -> Result<VkEncoder> {
503539 fps,
504540 gop_size,
505541 rate,
542+ bit_depth: config.bit_depth,
506543 },
507544 )?),
508545 })
@@ -586,8 +623,9 @@ pub struct RgbOutput {
586623 }
587624
588625 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
589-enum Mode {
626+pub(crate) enum Mode {
590627 I420,
628+ I420_16,
591629 Rgb(RgbOutput),
592630 }
593631
@@ -612,16 +650,17 @@ impl HwDecoder {
612650 HwDecoder::open_mode(codec, Mode::Rgb(output))
613651 }
614652
653+ /// Open a decoder for `codec` that hands out 10-bit I420 ([`HwDecoder::next_frame_16`]). 8-bit streams are widened to 10 bits.
654+ pub fn open_16(codec: Codec) -> Result<HwDecoder> {
655+ HwDecoder::open_mode(codec, Mode::I420_16)
656+ }
657+
615658 fn open_mode(codec: Codec, mode: Mode) -> Result<HwDecoder> {
616- let rgb = match mode {
617- Mode::I420 => None,
618- Mode::Rgb(output) => Some(output),
619- };
620659 let mut reasons = Vec::new();
621660 let vk = match codec {
622- Codec::H264 => VkH264Decoder::new(rgb).map(VkDecoder::H264),
623- Codec::H265 => VkH265Decoder::new(rgb).map(VkDecoder::H265),
624- Codec::Av1 => VkAv1Decoder::new(rgb).map(VkDecoder::Av1),
661+ Codec::H264 => VkH264Decoder::new(mode).map(VkDecoder::H264),
662+ Codec::H265 => VkH265Decoder::new(mode).map(VkDecoder::H265),
663+ Codec::Av1 => VkAv1Decoder::new(mode).map(VkDecoder::Av1),
625664 _ => Err(Error::unsupported("Vulkan Video decode", "H.264, H.265 and AV1 only")),
626665 };
627666 match vk {
@@ -695,27 +734,45 @@ impl HwDecoder {
695734 result
696735 }
697736
698- /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`].
737+ /// 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`].
699738 pub fn next_frame(&mut self) -> Result<Option<(i64, I420)>> {
700- if let Mode::Rgb(_) = self.mode {
701- return Err(Error::config("next_frame on an RGB decoder; use next_rgb"));
739+ if self.mode != Mode::I420 {
740+ return Err(Error::config(
741+ "next_frame on a decoder not opened as 8-bit I420",
742+ ));
702743 }
703744 match self.pull()? {
704745 None => Ok(None),
705746 Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))),
706- Some((_, Decoded::Rgb(_))) => Err(Error::config("RGB picture from an I420 decoder")),
747+ Some(_) => Err(Error::config("non-I420 picture from an I420 decoder")),
748+ }
749+ }
750+
751+ /// The next picture in display order, as 10-bit I420 with its timestamp. An error on a decoder not opened with [`HwDecoder::open_16`].
752+ pub fn next_frame_16(&mut self) -> Result<Option<(i64, I420_16)>> {
753+ if self.mode != Mode::I420_16 {
754+ return Err(Error::config(
755+ "next_frame_16 on a decoder not opened with open_16",
756+ ));
757+ }
758+ match self.pull()? {
759+ None => Ok(None),
760+ Some((ts, Decoded::I420_16(frame))) => Ok(Some((ts, frame))),
761+ Some(_) => Err(Error::config("non-16-bit picture from a 16-bit decoder")),
707762 }
708763 }
709764
710- /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder opened with [`HwDecoder::open`].
765+ /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`].
711766 pub fn next_rgb(&mut self) -> Result<Option<(i64, RgbPicture)>> {
712- if let Mode::I420 = self.mode {
713- return Err(Error::config("next_rgb on an I420 decoder; use open_rgb"));
767+ if !matches!(self.mode, Mode::Rgb(_)) {
768+ return Err(Error::config(
769+ "next_rgb on a decoder not opened with open_rgb",
770+ ));
714771 }
715772 match self.pull()? {
716773 None => Ok(None),
717774 Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))),
718- Some((_, Decoded::I420(_))) => Err(Error::config("I420 picture from an RGB decoder")),
775+ Some(_) => Err(Error::config("non-RGB picture from an RGB decoder")),
719776 }
720777 }
721778
@@ -731,10 +788,11 @@ impl HwDecoder {
731788 #[cfg(target_os = "linux")]
732789 DecInner::Va(d) => match d.next_frame() {
733790 Some(frame) => {
734- let i420 = frame.to_i420()?;
735791 let decoded = match self.mode {
736- Mode::I420 => Decoded::I420(i420),
792+ Mode::I420 => Decoded::I420(frame.to_i420()?),
793+ Mode::I420_16 => Decoded::I420_16(frame.to_i420_16()?),
737794 Mode::Rgb(output) => {
795+ let i420 = frame.to_i420()?;
738796 let matrix = frame
739797 .colour
740798 .map(|c| c.description.matrix)
crates/ec-hw/src/picture.rsmodified+90 -0
@@ -62,6 +62,7 @@ impl RgbPicture {
6262 #[derive(Debug, Clone, PartialEq, Eq)]
6363 pub(crate) enum Decoded {
6464 I420(I420),
65+ I420_16(I420_16),
6566 Rgb(RgbPicture),
6667 }
6768
@@ -170,6 +171,95 @@ pub(crate) fn semi_planar_to_i420(
170171 Ok(out)
171172 }
172173
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+
173263 /// Copy NV12/P010 planes into `out`, after validating every plane against it.
174264 pub(crate) fn fill_i420(
175265 out: &mut I420,
crates/ec-hw/src/types.rsmodified+2 -3
@@ -111,9 +111,8 @@ pub struct EncoderConfig {
111111 /// The colour description to write into the VUI, or `None` to leave it
112112 /// unsignalled (`video_signal_type_present_flag = 0`) as before.
113113 pub colour: Option<Colour>,
114- /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`).
115- /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or
116- /// straight from a 10-bit [`crate::Frame`].
114+ /// Luma bit depth: 8, or 10 for H.265 and AV1. A 10-bit encoder takes its
115+ /// pixels through [`Encoder::encode_16`] or [`HwEncoder::encode_16`].
117116 pub bit_depth: u8,
118117 }
119118
crates/ec-hw/src/vkdec264.rsmodified+24 -8
@@ -14,8 +14,10 @@ use ec_vk::{
1414 use crate::dpb264::{self, Mark, PicInfo, Poc};
1515 use crate::error::{Error, Result};
1616 use crate::h264_common::{peek_pps_id, vui_colour_tags};
17-use crate::hw::{RgbOrder, RgbOutput};
18-use crate::picture::{Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, yuv_to_rgb};
17+use crate::hw::{Mode, RgbOrder};
18+use crate::picture::{
19+ Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, semi_planar_to_i420_16, yuv_to_rgb,
20+};
1921 use ec_core::color::{ColorDescription, Tags};
2022
2123 const MAX_SLOTS: u32 = 17;
@@ -60,11 +62,11 @@ pub(crate) struct VkH264Decoder {
6062 current: Option<Current>,
6163 ready: VecDeque<(i64, Decoded)>,
6264 rbsp: Vec<u8>,
63- rgb: Option<RgbOutput>,
65+ mode: Mode,
6466 }
6567
6668 impl VkH264Decoder {
67- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {
69+ pub(crate) fn new(mode: Mode) -> Result<Self> {
6870 let gpu = crate::hw::vk_gpu()
6971 .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?;
7072 Ok(VkH264Decoder {
@@ -78,7 +80,7 @@ impl VkH264Decoder {
7880 current: None,
7981 ready: VecDeque::new(),
8082 rbsp: Vec::new(),
81- rgb,
83+ mode,
8284 })
8385 }
8486
@@ -319,14 +321,28 @@ impl VkH264Decoder {
319321 refs: &refs,
320322 slices: &slices,
321323 })?;
322- let out = match self.rgb {
323- None => {
324+ let out = match self.mode {
325+ Mode::I420 => {
324326 let (y, uv) = session
325327 .h264
326328 .read_output(sps.coded_width, sps.coded_height)?;
327329 Decoded::I420(crop(&sps, &y, &uv))
328330 }
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) => {
330346 let (left, _, top, _) = sps.crop;
331347 let matrix =
332348 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::{
1818 };
1919 use ec_core::color::{ColorDescription, Tags};
2020
21-use crate::hw::{RgbOrder, RgbOutput};
22-use crate::picture::{Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb};
21+use crate::hw::{Mode, RgbOrder};
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+};
2326
2427 const MAX_SLOTS: u32 = 17;
2528
@@ -61,11 +64,11 @@ pub(crate) struct VkH265Decoder {
6164 current: Option<Current>,
6265 ready: VecDeque<(i64, Decoded)>,
6366 no_rasl_output: bool,
64- rgb: Option<RgbOutput>,
67+ mode: Mode,
6568 }
6669
6770 impl VkH265Decoder {
68- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {
71+ pub(crate) fn new(mode: Mode) -> Result<Self> {
6972 let gpu = crate::hw::vk_gpu()
7073 .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?;
7174 Ok(VkH265Decoder {
@@ -80,7 +83,7 @@ impl VkH265Decoder {
8083 current: None,
8184 ready: VecDeque::new(),
8285 no_rasl_output: false,
83- rgb,
86+ mode,
8487 })
8588 }
8689
@@ -342,15 +345,22 @@ impl VkH265Decoder {
342345 slices: &slices,
343346 })?;
344347 if current.output {
345- let frame = match self.rgb {
346- None => {
348+ let frame = match self.mode {
349+ Mode::I420 => {
347350 let (y, uv) = session.h265.read_output(
348351 sps.pic_width_in_luma_samples,
349352 sps.pic_height_in_luma_samples,
350353 )?;
351354 Decoded::I420(crop(&sps, &y, &uv)?)
352355 }
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) => {
354364 let (width, height) = sps.display_size();
355365 let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32);
356366 let matrix =
@@ -421,6 +431,20 @@ fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result<I420> {
421431 )
422432 }
423433
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+
424448 fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel {
425449 H265ProfileTierLevel {
426450 tier_flag: p.tier_flag,
crates/ec-hw/src/vkdec_av1.rsmodified+22 -8
@@ -19,8 +19,11 @@ use crate::av1_refs::RefSlots;
1919 use crate::error::{Error, Result};
2020 use ec_core::color::{ColorDescription, Tags};
2121
22-use crate::hw::{RgbOrder, RgbOutput};
23-use crate::picture::{Decoded, RgbPicture, rgb_size, semi_planar_to_i420, yuv_to_rgb};
22+use crate::hw::{Mode, RgbOrder};
23+use crate::picture::{
24+ Decoded, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16,
25+ yuv_to_rgb,
26+};
2427
2528 const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
2629
@@ -44,11 +47,11 @@ pub(crate) struct VkAv1Decoder {
4447 session: Option<Session>,
4548 refs: RefSlots<Rc<Reference>>,
4649 ready: VecDeque<(i64, Decoded)>,
47- rgb: Option<RgbOutput>,
50+ mode: Mode,
4851 }
4952
5053 impl VkAv1Decoder {
51- pub(crate) fn new(rgb: Option<RgbOutput>) -> Result<Self> {
54+ pub(crate) fn new(mode: Mode) -> Result<Self> {
5255 let gpu = crate::hw::vk_gpu()
5356 .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?;
5457 Ok(VkAv1Decoder {
@@ -57,7 +60,7 @@ impl VkAv1Decoder {
5760 session: None,
5861 refs: RefSlots::new(),
5962 ready: VecDeque::new(),
60- rgb,
63+ mode,
6164 })
6265 }
6366
@@ -166,8 +169,8 @@ impl VkAv1Decoder {
166169 if !(header.show_frame || header.refresh_frame_flags != 0) {
167170 return Ok(());
168171 }
169- let decoded = match self.rgb {
170- None => {
172+ let decoded = match self.mode {
173+ Mode::I420 => {
171174 let (y, uv) = session.av1.read_output(width, height)?;
172175 Decoded::I420(semi_planar_to_i420(
173176 session.bit_depth,
@@ -178,7 +181,18 @@ impl VkAv1Decoder {
178181 (width, height),
179182 )?)
180183 }
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) => {
182196 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
183197 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
184198 let (w, h) = rgb_size(width, height, rgb.max_width);
crates/ec-vk/examples/av1_encode.rsmodified+1 -0
@@ -34,6 +34,7 @@ fn main() {
3434 },
3535 None => RateControl::ConstantQp { qp: 26 },
3636 },
37+ bit_depth: 8,
3738 };
3839 let mut encoder = Av1Encoder::new(&gpu, cfg).expect("create encoder");
3940
crates/ec-vk/examples/h265_encode.rsmodified+1 -0
@@ -33,6 +33,7 @@ fn main() {
3333 },
3434 None => RateControl::ConstantQp { qp: 26 },
3535 },
36+ bit_depth: 8,
3637 };
3738 let mut encoder = H265Encoder::new(&gpu, cfg).expect("create encoder");
3839 let mut out = Vec::new();
crates/ec-vk/src/av1.rsmodified+26 -0
@@ -19,6 +19,8 @@ pub struct Av1EncoderConfig {
1919 pub gop_size: u32,
2020 /// Rate control.
2121 pub rate: RateControl,
22+ /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
23+ pub bit_depth: u8,
2224 }
2325
2426 /// AV1 encoder: order hint, DPB slot and LAST reference bookkeeping over [`Av1EncodeSession`].
@@ -32,6 +34,7 @@ pub struct Av1Encoder {
3234 order_hint: u8,
3335 reference: Option<Av1Ref>,
3436 uv: Vec<u8>,
37+ uv16: Vec<u16>,
3538 }
3639
3740 impl Av1Encoder {
@@ -47,6 +50,7 @@ impl Av1Encoder {
4750 height: cfg.height,
4851 fps: cfg.fps,
4952 rate: cfg.rate,
53+ bit_depth: cfg.bit_depth,
5054 },
5155 )?;
5256 let sequence_header = session.sequence_header();
@@ -60,6 +64,7 @@ impl Av1Encoder {
6064 order_hint: 0,
6165 reference: None,
6266 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],
6368 })
6469 }
6570
@@ -84,6 +89,27 @@ impl Av1Encoder {
8489 Ok(self.finish(&pic, frame))
8590 }
8691
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+
87113 /// Changes bitrate or frame rate; takes effect on the next frame.
88114 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
89115 Ok(self.session.set_rate(rate, fps)?)
crates/ec-vk/src/h265.rsmodified+26 -0
@@ -17,6 +17,8 @@ pub struct H265EncoderConfig {
1717 pub gop_size: u32,
1818 /// Rate control.
1919 pub rate: RateControl,
20+ /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`).
21+ pub bit_depth: u8,
2022 }
2123
2224 /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`].
@@ -30,6 +32,7 @@ pub struct H265Encoder {
3032 poc: i32,
3133 reference: Option<H265Ref>,
3234 uv: Vec<u8>,
35+ uv16: Vec<u16>,
3336 }
3437
3538 impl H265Encoder {
@@ -45,6 +48,7 @@ impl H265Encoder {
4548 height: cfg.height,
4649 fps: cfg.fps,
4750 rate: cfg.rate,
51+ bit_depth: cfg.bit_depth,
4852 },
4953 )?;
5054 let parameter_sets = session.parameter_sets()?;
@@ -58,6 +62,7 @@ impl H265Encoder {
5862 poc: 0,
5963 reference: None,
6064 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],
6166 })
6267 }
6368
@@ -82,6 +87,27 @@ impl H265Encoder {
8287 Ok(self.finish(&pic, slice))
8388 }
8489
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+
85111 /// Changes bitrate or frame rate; takes effect on the next frame.
86112 pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> {
87113 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 {
8282 height: size.1,
8383 fps: FPS,
8484 rate: RATE,
85+ bit_depth: 8,
8586 };
8687 H265EncodeSession::new(gpu, &cfg)
8788 }
@@ -115,6 +116,7 @@ impl Encode for Av1EncodeSession {
115116 height: size.1,
116117 fps: FPS,
117118 rate: RATE,
119+ bit_depth: 8,
118120 };
119121 Av1EncodeSession::new(gpu, &cfg)
120122 }
shims/vk-video-ffi/src/av1_encode.rsmodified+33 -11
@@ -8,7 +8,7 @@ use crate::dmabuf::DmaBuf;
88 use crate::rgb_convert::{Input, check_rgb};
99 use crate::session::{
1010 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,
1212 };
1313 use crate::{Error, Gpu, RateControl};
1414
@@ -27,6 +27,8 @@ pub struct Av1EncodeConfig {
2727 pub fps: (u32, u32),
2828 /// Rate control; ConstantQp qp is mapped to AV1 base_q_idx as qp * 5.
2929 pub rate: RateControl,
30+ /// Luma and chroma bit depth: 8 or 10 (Main profile, NV12 or P010 input).
31+ pub bit_depth: u8,
3032 }
3133
3234 /// One picture to encode.
@@ -67,13 +69,14 @@ struct Profile {
6769 }
6870
6971 impl Profile {
70- fn new() -> Box<Self> {
72+ fn new(bit_depth: u8) -> Box<Self> {
73+ let component = component_bit_depth(bit_depth);
7174 let mut p = Box::new(Profile {
7275 info: vk::VideoProfileInfoKHR::builder()
7376 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_AV1)
7477 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
75- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
76- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
78+ .luma_bit_depth(component)
79+ .chroma_bit_depth(component)
7780 .build(),
7881 codec: vk::VideoEncodeAV1ProfileInfoKHR::builder()
7982 .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN)
@@ -158,8 +161,11 @@ impl Av1EncodeSession {
158161 {
159162 return Err(Error::Unsupported("AV1 encode".into()));
160163 }
161- let profile = Profile::new();
162- let caps = query_caps(gpu, &profile.info)?;
164+ let profile = Profile::new(cfg.bit_depth);
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+ })?;
163169 if cfg.width > caps.max_extent.width || cfg.height > caps.max_extent.height {
164170 return Err(Error::Unsupported(format!(
165171 "AV1 encode {}x{}",
@@ -203,11 +209,11 @@ impl Av1EncodeSession {
203209 (cfg.rate, cfg.fps),
204210 caps.size_align,
205211 )?;
206- let params = create_parameters(&enc.vs, extent, sb128)?;
212+ let params = create_parameters(&enc.vs, extent, sb128, cfg.bit_depth)?;
207213 enc.vs.set_params(params);
208214 Ok(Av1EncodeSession {
209215 enc,
210- seq: sequence_header_obu(cfg.width, cfg.height, sb128),
216+ seq: sequence_header_obu(cfg.width, cfg.height, sb128, cfg.bit_depth),
211217 slot_key: [false; DPB_SLOTS],
212218 ref_order_hint: [0; AV1_SLOTS],
213219 })
@@ -230,6 +236,18 @@ impl Av1EncodeSession {
230236 self.encode_uploaded(pic)
231237 }
232238
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+
233251 /// 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.
234252 pub fn encode_rgb(
235253 &mut self,
@@ -430,9 +448,10 @@ fn create_parameters(
430448 vs: &VideoSession,
431449 extent: vk::Extent2D,
432450 sb128: bool,
451+ bit_depth: u8,
433452 ) -> Result<vk::VideoSessionParametersKHR, Error> {
434453 let mut color = zeroed::<vk::video::StdVideoAV1ColorConfig>();
435- color.BitDepth = 8;
454+ color.BitDepth = bit_depth;
436455 color.subsampling_x = 1;
437456 color.subsampling_y = 1;
438457 color.color_primaries = vk::video::STD_VIDEO_AV1_COLOR_PRIMARIES_UNSPECIFIED;
@@ -515,7 +534,7 @@ fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
515534 out
516535 }
517536
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> {
519538 let mut b = Bits(Vec::new());
520539 b.put(0, 3);
521540 b.put(0, 1);
@@ -547,17 +566,20 @@ fn sequence_header_obu(width: u32, height: u32, sb128: bool) -> Vec<u8> {
547566 b.put(0, 1);
548567 b.put(0, 1);
549568 b.put(0, 1);
569+ b.put((bit_depth == 10) as u32, 1);
550570 b.put(0, 1);
551571 b.put(0, 1);
552572 b.put(0, 1);
553573 b.put(0, 2);
554574 b.put(0, 1);
555575 b.put(0, 1);
556- b.put(0, 1);
557576 obu(1, &b.finish())
558577 }
559578
560579 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+ }
561583 if cfg.width == 0 || cfg.height == 0 || cfg.width % 8 != 0 || cfg.height % 8 != 0 {
562584 return Err(Error::Invalid(
563585 "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;
1111 use crate::rgb_convert::{Input, check_rgb};
1212 use crate::session::{
1313 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,
1515 };
1616 use crate::{Error, Gpu, RateControl};
1717
@@ -26,6 +26,8 @@ pub struct H265EncodeConfig {
2626 pub fps: (u32, u32),
2727 /// Rate control.
2828 pub rate: RateControl,
29+ /// Luma and chroma bit depth: 8 (Main, NV12 input) or 10 (Main 10, P010 input).
30+ pub bit_depth: u8,
2931 }
3032
3133 /// One picture to encode.
@@ -80,16 +82,17 @@ struct Profile {
8082 }
8183
8284 impl Profile {
83- fn new() -> Box<Self> {
85+ fn new(bit_depth: u8) -> Box<Self> {
86+ let component = component_bit_depth(bit_depth);
8487 let mut p = Box::new(Profile {
8588 info: vk::VideoProfileInfoKHR::builder()
8689 .video_codec_operation(vk::VideoCodecOperationFlagsKHR::ENCODE_H265)
8790 .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420)
88- .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
89- .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8)
91+ .luma_bit_depth(component)
92+ .chroma_bit_depth(component)
9093 .build(),
9194 codec: vk::VideoEncodeH265ProfileInfoKHR::builder()
92- .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN)
95+ .std_profile_idc(profile_idc(bit_depth))
9396 .build(),
9497 usage: vk::VideoEncodeUsageInfoKHR::builder()
9598 .video_usage_hints(vk::VideoEncodeUsageFlagsKHR::STREAMING)
@@ -161,6 +164,9 @@ impl H265EncodeSession {
161164 /// Creates a session with its DPB, buffers and parameter sets.
162165 pub fn new(gpu: &Gpu, cfg: &H265EncodeConfig) -> Result<Self, Error> {
163166 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+ }
164170 let family = gpu
165171 .encode_family()
166172 .ok_or_else(|| Error::Unsupported("H.265 encode queue family".into()))?;
@@ -171,8 +177,13 @@ impl H265EncodeSession {
171177 {
172178 return Err(Error::Unsupported("H.265 encode".into()));
173179 }
174- let profile = Profile::new();
175- let caps = query_caps(gpu, &profile.info)?;
180+ let profile = Profile::new(cfg.bit_depth);
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+ })?;
176187 let coding = coding(&caps, cfg)?;
177188 if coding.width > caps.max_extent.width || coding.height > caps.max_extent.height {
178189 return Err(Error::Unsupported(format!(
@@ -259,6 +270,23 @@ impl H265EncodeSession {
259270 self.encode_uploaded(pic)
260271 }
261272
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+
262290 /// 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.
263291 pub fn encode_rgb(
264292 &mut self,
@@ -444,7 +472,7 @@ fn create_parameters(
444472 let cropped = c.width != cfg.width || c.height != cfg.height;
445473
446474 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);
448476 ptl.general_level_idc = c.level;
449477 ptl.flags.set_general_progressive_source_flag(1);
450478 ptl.flags.set_general_frame_only_constraint_flag(1);
@@ -475,6 +503,8 @@ fn create_parameters(
475503 sps.flags
476504 .set_sample_adaptive_offset_enabled_flag(c.sao as u32);
477505 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;
478508 sps.pic_width_in_luma_samples = c.width;
479509 sps.pic_height_in_luma_samples = c.height;
480510 sps.log2_max_pic_order_cnt_lsb_minus4 = 4;
@@ -563,6 +593,14 @@ fn coding(caps: &Caps, cfg: &H265EncodeConfig) -> Result<Coding, Error> {
563593 })
564594 }
565595
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+
566604 fn level_for(
567605 width: u32,
568606 height: u32,
shims/vk-video-ffi/src/rgb_convert.rsmodified+6 -2
@@ -11,6 +11,10 @@ pub(crate) enum Input<'a> {
1111 y: &'a [u8],
1212 uv: &'a [u8],
1313 },
14+ P010 {
15+ y: &'a [u16],
16+ uv: &'a [u16],
17+ },
1418 Rgb {
1519 data: &'a [u8],
1620 width: usize,
@@ -30,7 +34,7 @@ pub(crate) enum Input<'a> {
3034 impl Input<'_> {
3135 pub(crate) fn bgr(&self) -> Option<bool> {
3236 match *self {
33- Input::Nv12 { .. } => None,
37+ Input::Nv12 { .. } | Input::P010 { .. } => None,
3438 Input::Rgb { bgr, .. } => Some(bgr),
3539 #[cfg(target_os = "linux")]
3640 Input::DmaBuf { bgr, .. } => Some(bgr),
@@ -39,7 +43,7 @@ impl Input<'_> {
3943
4044 pub(crate) fn source_image(&self) -> Option<vk::Image> {
4145 match *self {
42- Input::Nv12 { .. } | Input::Rgb { .. } => None,
46+ Input::Nv12 { .. } | Input::P010 { .. } | Input::Rgb { .. } => None,
4347 #[cfg(target_os = "linux")]
4448 Input::DmaBuf { image, .. } => Some(image),
4549 }
shims/vk-video-ffi/src/session.rsmodified+53 -2
@@ -260,6 +260,37 @@ pub(crate) fn fill_nv12(
260260 }
261261 }
262262
263+pub(crate) fn fill_p010(
264+ dst: &mut [u8],
265+ y: &[u16],
266+ uv: &[u16],
267+ w: usize,
268+ h: usize,
269+ aw: usize,
270+ ah: usize,
271+) {
272+ let (y_dst, uv_dst) = dst.split_at_mut(aw * ah * 2);
273+ for (r, row) in y_dst.chunks_exact_mut(aw * 2).enumerate() {
274+ let src = &y[r.min(h - 1) * w..][..w];
275+ for (c, px) in row.chunks_exact_mut(2).enumerate() {
276+ px.copy_from_slice(&p010_sample(src[c.min(w - 1)]));
277+ }
278+ }
279+ for (r, row) in uv_dst.chunks_exact_mut(aw * 2).enumerate() {
280+ let src = &uv[r.min(h / 2 - 1) * w..][..w];
281+ let pairs = w / 2 - 1;
282+ for (c, pair) in row.chunks_exact_mut(4).enumerate() {
283+ let p = c.min(pairs);
284+ pair[..2].copy_from_slice(&p010_sample(src[2 * p]));
285+ pair[2..].copy_from_slice(&p010_sample(src[2 * p + 1]));
286+ }
287+ }
288+}
289+
290+fn p010_sample(value: u16) -> [u8; 2] {
291+ ((value & 0x3ff) << 6).to_le_bytes()
292+}
293+
263294 #[derive(Default)]
264295 pub(crate) struct Image {
265296 pub(crate) image: vk::Image,
@@ -700,7 +731,8 @@ impl Encoder {
700731 bitstream: Default::default(),
701732 query: Default::default(),
702733 };
703- let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2;
734+ let bytes = bytes_per_sample(e.vs.format) as u64;
735+ let frame_bytes = extent.width as u64 * extent.height as u64 * 3 / 2 * bytes;
704736 let usage = vk::ImageUsageFlags::VIDEO_ENCODE_DPB_KHR;
705737 let mut list = vk::VideoProfileListInfoKHR::builder()
706738 .profiles(std::slice::from_ref(profile))
@@ -790,6 +822,19 @@ impl Encoder {
790822 pub(crate) fn upload(&mut self, input: Input) -> Result<(), Error> {
791823 let aw = self.extent.width as usize;
792824 let ah = self.extent.height as usize;
825+ let bytes = bytes_per_sample(self.vs.format);
826+ match input {
827+ Input::Nv12 { .. } if bytes != 1 => {
828+ return Err(Error::Invalid("8-bit planes for a 10-bit session".into()));
829+ }
830+ Input::P010 { .. } if bytes != 2 => {
831+ return Err(Error::Invalid("10-bit planes for an 8-bit session".into()));
832+ }
833+ _ if bytes != 1 && input.bgr().is_some() => {
834+ return Err(Error::Unsupported("RGB input at 10 bits".into()));
835+ }
836+ _ => {}
837+ }
793838 let gpu = self.vs.gpu.clone();
794839 match input {
795840 Input::Nv12 { y, uv } => {
@@ -797,6 +842,11 @@ impl Encoder {
797842 unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3 / 2) };
798843 fill_nv12(staging, y, uv, self.input.0, self.input.1, aw, ah);
799844 }
845+ Input::P010 { y, uv } => {
846+ let staging =
847+ unsafe { std::slice::from_raw_parts_mut(self.staging_ptr()?, aw * ah * 3) };
848+ fill_p010(staging, y, uv, self.input.0, self.input.1, aw, ah);
849+ }
800850 Input::Rgb {
801851 data,
802852 width,
@@ -823,9 +873,10 @@ impl Encoder {
823873
824874 let d = gpu.device();
825875 let cb = self.upload.cb;
876+ let luma = (aw * ah * bytes) as u64;
826877 let copies = [
827878 copy_region(0, PLANE_0, aw as u32, ah as u32),
828- copy_region((aw * ah) as u64, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
879+ copy_region(luma, PLANE_1, (aw / 2) as u32, (ah / 2) as u32),
829880 ];
830881 self.upload.begin()?;
831882 unsafe {