use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref}; #[cfg(windows)] use crate::D3d11Texture; #[cfg(target_os = "linux")] use crate::DmaBuf; use crate::history::History; use crate::{CodedFrame, Colour, Error, Flight, Gpu, Meta, RateControl, last_frame}; /// H.265 encoder settings. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct H265EncoderConfig { /// Width in luma samples, even. pub width: u32, /// Height in luma samples, even. pub height: u32, /// Frame rate as numerator and denominator. pub fps: (u32, u32), /// Frames from one IDR to the next, at least 1. pub gop_size: u32, /// Rate control. pub rate: RateControl, /// Luma and chroma bit depth: 8, or 10 for Main 10 (`encode_16`). pub bit_depth: u8, /// `general_level_idc`, clamped to the driver maximum. pub level: u8, /// Colour description for the VUI, or none. pub colour: Option, /// Speed/quality trade-off as in ec-hw's `EncoderConfig::quality`: 0 for the default level, 1 for the driver's best, each step up one level faster. pub quality: u32, } /// H.265 encoder: GOP, POC and DPB slot bookkeeping over [`H265EncodeSession`]. pub struct H265Encoder { session: H265EncodeSession, parameter_sets: Vec, width: usize, height: usize, gop_size: u32, position: u32, poc: i32, history: History, uv: Vec, uv16: Vec, flight: Flight, } impl H265Encoder { /// Opens an encoder session on `gpu`. pub fn new(gpu: &Gpu, cfg: H265EncoderConfig) -> Result { if cfg.gop_size == 0 { return Err(Error::Invalid("gop_size is zero".into())); } let session = H265EncodeSession::new( gpu, &H265EncodeConfig { width: cfg.width, height: cfg.height, fps: cfg.fps, rate: cfg.rate, bit_depth: cfg.bit_depth, level: cfg.level, colour: cfg.colour, quality: cfg.quality, }, )?; let parameter_sets = session.parameter_sets()?; Ok(H265Encoder { session, parameter_sets, width: cfg.width as usize, height: cfg.height as usize, gop_size: cfg.gop_size, position: 0, poc: 0, history: History::new(), uv: vec![0; cfg.width as usize * cfg.height as usize / 2], uv16: vec![0; cfg.width as usize * cfg.height as usize / 2], flight: Flight::default(), }) } /// Submits one I420 frame without waiting; returns the oldest frame once a second one is queued. pub fn submit( &mut self, y: &[u8], u: &[u8], v: &[u8], force_keyframe: bool, ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); } for (i, pair) in self.uv.chunks_exact_mut(2).enumerate() { pair[0] = u[i]; pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); let out = self.session.submit(y, &self.uv, &pic)?; out.map(|bytes| self.coded(bytes)).transpose() } /// Encodes one I420 frame; `force_keyframe` makes it an IDR and restarts the GOP. pub fn encode( &mut self, y: &[u8], u: &[u8], v: &[u8], force_keyframe: bool, ) -> Result { let first = self.submit(y, u, v, force_keyframe)?; let rest = self.flush()?; last_frame(first, rest) } /// Submits one 10-bit I420 frame of a 10-bit encoder without waiting. pub fn submit_16( &mut self, y: &[u16], u: &[u16], v: &[u16], force_keyframe: bool, ) -> Result, Error> { let chroma = self.width * self.height / 4; if y.len() != self.width * self.height || u.len() != chroma || v.len() != chroma { return Err(Error::Invalid("I420 plane size".into())); } for (i, pair) in self.uv16.chunks_exact_mut(2).enumerate() { pair[0] = u[i]; pair[1] = v[i]; } let pic = self.next_picture(force_keyframe); let out = self.session.submit_16(y, &self.uv16, &pic)?; out.map(|bytes| self.coded(bytes)).transpose() } /// Encodes one 10-bit I420 frame of a 10-bit encoder; `force_keyframe` makes it IDR and restarts the GOP. pub fn encode_16( &mut self, y: &[u16], u: &[u16], v: &[u16], force_keyframe: bool, ) -> Result { let first = self.submit_16(y, u, v, force_keyframe)?; let rest = self.flush()?; last_frame(first, rest) } /// Waits for every submitted frame and returns them in order. pub fn flush(&mut self) -> Result, Error> { let bytes = self.session.flush()?; bytes.into_iter().map(|b| self.coded(b)).collect() } /// Changes bitrate or frame rate; takes effect on the next frame. pub fn set_rate(&mut self, rate: RateControl, fps: (u32, u32)) -> Result<(), Error> { Ok(self.session.set_rate(rate, fps)?) } /// Submits one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes) without waiting. pub fn submit_rgb( &mut self, rgb: &[u8], src_width: u32, src_height: u32, stride_bytes: u32, bgr: bool, force_keyframe: bool, ) -> Result, Error> { let pic = self.next_picture(force_keyframe); let out = self .session .submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, &pic)?; out.map(|bytes| self.coded(bytes)).transpose() } /// Encodes one packed RGB frame (src_width x src_height, BGRx if `bgr`, else RGBx; row stride in bytes), box-downscaled to the encoder size on the GPU. pub fn encode_rgb( &mut self, rgb: &[u8], src_width: u32, src_height: u32, stride_bytes: u32, bgr: bool, force_keyframe: bool, ) -> Result { let first = self.submit_rgb(rgb, src_width, src_height, stride_bytes, bgr, force_keyframe)?; let rest = self.flush()?; last_frame(first, rest) } /// Submits one shared D3D11 texture of the source size without waiting. #[cfg(windows)] pub fn submit_d3d11( &mut self, src: &D3d11Texture<'_>, force_keyframe: bool, ) -> Result, Error> { let pic = self.next_picture(force_keyframe); let out = self.session.submit_d3d11(src, &pic)?; out.map(|bytes| self.coded(bytes)).transpose() } /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU. #[cfg(windows)] pub fn encode_d3d11( &mut self, src: &D3d11Texture<'_>, force_keyframe: bool, ) -> Result { let first = self.submit_d3d11(src, force_keyframe)?; let rest = self.flush()?; last_frame(first, rest) } /// Submits one DMA-BUF frame of the source size without waiting. #[cfg(target_os = "linux")] pub fn submit_dmabuf( &mut self, src: &DmaBuf<'_>, force_keyframe: bool, ) -> Result, Error> { let pic = self.next_picture(force_keyframe); let out = self.session.submit_dmabuf(src, &pic)?; out.map(|bytes| self.coded(bytes)).transpose() } /// Encodes one DMA-BUF frame of the source size (BGRx if `bgr`, else RGBx), box-downscaled to the encoder size on the GPU. #[cfg(target_os = "linux")] pub fn encode_dmabuf( &mut self, src: &DmaBuf<'_>, force_keyframe: bool, ) -> Result { let first = self.submit_dmabuf(src, force_keyframe)?; let rest = self.flush()?; last_frame(first, rest) } fn next_picture(&mut self, force_keyframe: bool) -> H265Picture { let step = self .history .next(force_keyframe || self.position >= self.gop_size); self.poc = if step.key { 0 } else { self.poc + 1 }; let reference = step.reference.map(|(slot, _)| slot as usize); let keep = std::array::from_fn(|i| { self.history.slots[i] .filter(|_| i != step.slot as usize && Some(i) != reference) .map(|h| h.data) }); self.history.store(&step, self.poc); self.position = if step.key { 1 } else { self.position + 1 }; self.flight.push(Meta { keyframe: step.key, recovery: step.recovery, id: step.id, }); H265Picture { idr: step.key, poc: self.poc, slot: step.slot, reference: step.reference.map(|(slot, poc)| H265Ref { slot, poc }), keep, } } /// The receiver decoded every frame up to `id` ([`CodedFrame::id`]); a recovery frame may reference one while it stays in the DPB. pub fn ack(&mut self, id: u64) { self.history.ack(id); } /// Make the next frame reference the newest acknowledged frame still held, or an IDR when none is. pub fn recover(&mut self) { self.history.arm(); } fn coded(&mut self, bytes: Vec) -> Result { let meta = self.flight.pop()?; let data = if meta.keyframe { [self.parameter_sets.as_slice(), bytes.as_slice()].concat() } else { bytes }; Ok(CodedFrame { data, keyframe: meta.keyframe, recovery: meta.recovery, id: meta.id, }) } }