//! The encode seats, on [`ec_hw::HwEncoder`]: H.264 (Main profile), HEVC and AV1. //! //! Pixels the caller holds are packed I420 and go through [`ec_hw::EncodeInput::I420`] //! (or `I420_16` for 10-bit). A picture the decoder left on the GPU arrives as a //! DRM-PRIME descriptor ([`DmaFrame`]) and goes through [`ec_hw::EncodeInput::DmaBufYuv`], //! which the encoder imports and caches itself. The backend, Vulkan or VA-API, is the //! one [`ec_hw::HwEncoder::open`] picks. use std::collections::VecDeque; use std::os::fd::{AsFd, BorrowedFd}; use ec_hw::{ Backend, DmaBufFormat, DmaBufPlane, DmaBufYuvFrame, EncCodec, EncodeInput, EncoderConfig, FrameMetadata, H264Profile, HwEncoder, I420, I420_16, RateControlMode, }; use engine::hw::DmaFrame; use engine::hwproc::SeatRate; /// `DRM_FORMAT_NV12`, which is also `VA_FOURCC_NV12`: the four characters. const FOURCC_NV12: u32 = u32::from_le_bytes(*b"NV12"); /// `DRM_FORMAT_P010`, which is also `VA_FOURCC_P010`. const FOURCC_P010: u32 = u32::from_le_bytes(*b"P010"); /// One hardware encode session on `ec_hw`. pub(crate) struct EcEncSession { encoder: HwEncoder, /// Display size: what is encoded. width: usize, height: usize, timestamp: i64, /// Access units the encoder has finished but the caller has not taken yet, /// in encode order (which is display order: no B-frames). ready: VecDeque>, /// The access unit currently handed out, kept alive until the next call. out: Vec, } /// The `open` arguments, for any of the three codecs. pub(crate) struct EcOpen { pub codec: EncCodec, pub width: u32, pub height: u32, pub fps_num: u32, pub fps_den: u32, pub rate: SeatRate, /// Every picture an IDR: what a proxy is coded with (see `gop_limit`). pub intra_only: bool, /// Pictures between key frames; `None` is `gop_limit`'s. pub gop: Option, /// Colour description for the VUI as `(primaries, transfer, matrix, full)`. pub colour: Option<(u8, u8, u8, bool)>, /// HEVC Main10: pictures go through [`EcEncSession::encode16_owned`]. pub ten_bit: bool, } impl EcEncSession { pub(crate) fn open(req: EcOpen) -> Option { let EcOpen { codec, width, height, fps_num, fps_den, rate, intra_only, gop, colour, ten_bit, } = req; // NV12 chroma is half resolution, so odd dimensions have no packing; // radeonsi refuses encode contexts below 64x64 (measured). if width < 64 || height < 64 || !width.is_multiple_of(2) || !height.is_multiple_of(2) { return None; } // The HEVC entrypoint's own floor: the same driver that takes a // 128x128 H.264 context answers `VaError(19)` to an HEVC one below // 384x384 (measured 2026-08-13 on radeonsi). if codec == EncCodec::H265 && (width < 384 || height < 384) { return None; } if fps_num == 0 || fps_den == 0 || rate == SeatRate::Bitrate(0) { return None; } let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32; let mut config = EncoderConfig::new(codec, width, height); config.framerate = (framerate, 1); if let SeatRate::Bitrate(bitrate) = rate { config.bitrate = u32::try_from(bitrate).unwrap_or(u32::MAX); } config.gop_size = gop.unwrap_or_else(|| match (codec, intra_only) { (EncCodec::H265, false) => framerate, _ => u32::from(crate::gop_limit(framerate, intra_only)), }); config.rate_control = match (codec, rate) { (EncCodec::Av1, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp: qp.min(51) * 255 / 51 }, (_, SeatRate::ConstantQp(qp)) => RateControlMode::ConstantQp { qp }, // Constant quality at 128 of 255, the AV1 rate control measured. (EncCodec::Av1, SeatRate::Bitrate(_)) => RateControlMode::ConstantQp { qp: 128 }, (_, SeatRate::Bitrate(_)) => RateControlMode::ConstantBitrate, }; if codec == EncCodec::H264 { // Main, not the High default: the seat's tests pin the profile. config = config.h264_profile(H264Profile::Main); } if let Some((p, t, m, full)) = colour { config = config.colour(p, t, m, full); } if ten_bit { config = config.ten_bit(); } let encoder = HwEncoder::open(config, None).ok()?; Some(Self { encoder, width: width as usize, height: height as usize, timestamp: 0, ready: VecDeque::new(), out: Vec::new(), }) } pub(crate) fn encode16_owned( &mut self, mut y: Vec, mut u: Vec, mut v: Vec, force_keyframe: bool, ) -> Result<(), String> { let (w, h) = (self.width, self.height); let (cw, ch) = (w / 2, h / 2); if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { return Err("encode input is not a packed I420 frame".into()); } y.truncate(w * h); u.truncate(cw * ch); v.truncate(cw * ch); let picture = I420_16 { y, u, v, width: w as u32, height: h as u32, bit_depth: 10, }; let meta = self.meta(force_keyframe); if let Some(coded) = self .encoder .submit(EncodeInput::I420_16(&picture), meta) .map_err(|e| e.to_string())? { self.ready.push_back(coded.data); } Ok(()) } pub(crate) fn flush(&mut self) -> Result<(), String> { for coded in self.encoder.flush().map_err(|e| e.to_string())? { self.ready.push_back(coded.data); } Ok(()) } /// The size a DMA-BUF picture must be described at, or `None` when the /// backend takes no DMA-BUF input (VA-API). pub(crate) fn coded_size(&self) -> Option<(u32, u32)> { match self.encoder.backend() { Backend::Vk => Some((self.width as u32, self.height as u32)), Backend::Va => None, } } /// Codes one packed I420 picture (`y`, `u`, `v` at the session's size) and /// queues the access unit it finishes. pub(crate) fn encode( &mut self, y: &[u8], u: &[u8], v: &[u8], force_keyframe: bool, ) -> Result<(), String> { let (w, h) = (self.width, self.height); let (cw, ch) = (w / 2, h / 2); if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { return Err("encode input is not a packed I420 frame".into()); } let picture = I420 { y: y[..w * h].to_vec(), u: u[..cw * ch].to_vec(), v: v[..cw * ch].to_vec(), width: w as u32, height: h as u32, }; let meta = self.meta(force_keyframe); if let Some(coded) = self .encoder .submit(EncodeInput::I420(&picture), meta) .map_err(|e| e.to_string())? { self.ready.push_back(coded.data); } Ok(()) } /// Codes one picture the decoder left on the GPU, read in place. /// /// The descriptors stay owned by `frame`; the encoder duplicates them on import. pub(crate) fn encode_dma(&mut self, frame: &DmaFrame, force_keyframe: bool) -> Result<(), String> { let format = match (frame.desc.fourcc, frame.fds.len()) { (FOURCC_NV12, 1 | 2) => DmaBufFormat::Nv12, (FOURCC_P010, 1 | 2) => DmaBufFormat::P010, _ => return Err("DMA-BUF is not an NV12 or P010 picture on the GPU".into()), }; let fds: Vec = frame.fds.iter().map(|fd| fd.as_fd()).collect(); let desc = &frame.desc; let chroma_fd = if fds.len() == 2 { 1 } else { 0 }; let input = DmaBufYuvFrame { fds: &fds, planes: [ DmaBufPlane { fd: 0, offset: desc.offset[0], pitch: desc.stride[0], }, DmaBufPlane { fd: chroma_fd, offset: desc.offset[1], pitch: desc.stride[1], }, ], width: self.width as u32, height: self.height as u32, modifier: desc.modifier, format, }; let meta = self.meta(force_keyframe); if let Some(coded) = self .encoder .submit(EncodeInput::DmaBufYuv(&input), meta) .map_err(|e| e.to_string())? { self.ready.push_back(coded.data); } Ok(()) } fn meta(&mut self, force_keyframe: bool) -> FrameMetadata { let meta = FrameMetadata { timestamp: self.timestamp, force_keyframe, }; self.timestamp += 1; meta } /// The oldest finished access unit, or `None` when the encoder has nothing /// queued. It stays valid until the next call on this session. pub(crate) fn next_au(&mut self) -> Option<&[u8]> { let au = self.ready.pop_front()?; self.out = au; Some(&self.out) } }