//! H.264 encoder over Vulkan Video: IDR and P pictures, one reference, I420 in. #![forbid(unsafe_code)] #![deny(missing_docs)] use std::collections::VecDeque; use history::History; use vk_video_ffi::{H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, LOG2_MAX_FRAME_NUM}; mod av1; mod h265; mod history; pub use av1::{Av1Encoder, Av1EncoderConfig}; pub use h265::{H265Encoder, H265EncoderConfig}; #[cfg(windows)] pub use vk_video_ffi::{D3d11Pool, D3d11Texture, d3d11_importable, windows}; #[cfg(target_os = "linux")] pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers}; pub use vk_video_ffi::{ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Colour, Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264Profile, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, H265ShortTermRefPicSet, H265Sps, H265Vps, RateControl, ScalingLists, Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, }; /// Encoder settings. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct H264EncoderConfig { /// 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, /// H.264 profile. pub profile: H264Profile, /// `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, } /// One coded frame, Annex-B. Keyframes carry SPS and PPS before the slice. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CodedFrame { /// Annex-B bytes. pub data: Vec, /// True when the frame is an IDR picture. pub keyframe: bool, /// True when the frame references an acknowledged older picture instead of the previous one. pub recovery: bool, /// Submission index of the frame, the handle [`Av1Encoder::ack`] takes. pub id: u64, } #[derive(Debug, Clone, Copy, Default)] pub(crate) struct Meta { pub(crate) keyframe: bool, pub(crate) recovery: bool, pub(crate) id: u64, } #[derive(Default)] pub(crate) struct Flight(VecDeque); impl Flight { pub(crate) fn push(&mut self, meta: Meta) { self.0.push_back(meta); } pub(crate) fn pop(&mut self) -> Meta { self.0.pop_front().unwrap_or_default() } } pub(crate) fn last_frame( first: Option, rest: Vec, ) -> Result { rest.into_iter() .last() .or(first) .ok_or_else(|| Error::Invalid("no coded frame".into())) } /// H.264 encoder: GOP, frame_num, POC and DPB slot bookkeeping over [`H264EncodeSession`]. pub struct H264Encoder { session: H264EncodeSession, parameter_sets: Vec, width: usize, height: usize, gop_size: u32, position: u32, frame_num: u32, poc: i32, idr_pic_id: u16, history: History<(u32, i32)>, uv: Vec, flight: Flight, } impl H264Encoder { /// Opens an encoder session on `gpu`. pub fn new(gpu: &Gpu, cfg: H264EncoderConfig) -> Result { if cfg.gop_size == 0 { return Err(Error::Invalid("gop_size is zero".into())); } let session = H264EncodeSession::new( gpu, &H264EncodeConfig { width: cfg.width, height: cfg.height, fps: cfg.fps, rate: cfg.rate, profile: cfg.profile, level: cfg.level, colour: cfg.colour, quality: cfg.quality, }, )?; let parameter_sets = session.parameter_sets()?; Ok(H264Encoder { session, parameter_sets, width: cfg.width as usize, height: cfg.height as usize, gop_size: cfg.gop_size, position: 0, frame_num: 0, poc: 0, idr_pic_id: 0, history: History::new(), uv: 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)?; Ok(out.map(|bytes| self.coded(bytes))) } /// 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) } /// Waits for every submitted frame and returns them in order. pub fn flush(&mut self) -> Result, Error> { let bytes = self.session.flush()?; Ok(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)?; Ok(out.map(|bytes| self.coded(bytes))) } /// 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)?; Ok(out.map(|bytes| self.coded(bytes))) } /// 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)?; Ok(out.map(|bytes| self.coded(bytes))) } /// 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) -> H264Picture { let step = self .history .next(force_keyframe || self.position >= self.gop_size); if step.key { self.frame_num = 0; self.poc = 0; } else { self.frame_num = (self.frame_num + 1) % (1 << LOG2_MAX_FRAME_NUM); self.poc += 2; } let pic = H264Picture { idr: step.key, idr_pic_id: self.idr_pic_id, frame_num: self.frame_num, poc: self.poc, slot: step.slot, reference: step.reference.map(|(slot, (frame_num, poc))| H264Ref { slot, frame_num, poc }), }; self.history.store(&step, (self.frame_num, self.poc)); self.position = if step.key { 1 } else { self.position + 1 }; if step.key { self.idr_pic_id = self.idr_pic_id.wrapping_add(1); } self.flight.push(Meta { keyframe: step.key, recovery: step.recovery, id: step.id, }); pic } /// 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) -> CodedFrame { let meta = self.flight.pop(); let data = if meta.keyframe { [self.parameter_sets.as_slice(), bytes.as_slice()].concat() } else { bytes }; CodedFrame { data, keyframe: meta.keyframe, recovery: meta.recovery, id: meta.id, } } }