edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·00c1b3f·Tahinli·2 months ago·1999 commits
| 1 | //! Hardware encoding: H.264, HEVC, and AV1 behind an explicit opt-in. |
| 2 | //! |
| 3 | //! One frame in, one coded frame out. The GOP is IDR-then-P with a single |
| 4 | //! reference, which is what this GPU advertises (`VAConfigAttribEncMaxRefFrames` |
| 5 | //! reports one list-0 reference for HEVC) and what an editor's export wants: |
| 6 | //! no reordering, so a coded frame comes back in the call that fed it. |
| 7 | //! |
| 8 | //! # AV1 |
| 9 | //! |
| 10 | //! AV1 encoding is off unless [`EncoderConfig::allow_av1`] is set, and never |
| 11 | //! reachable from an "auto" codec choice. The reason is on the record rather |
| 12 | //! than theoretical: an AV1 encode submission on this driver generation took |
| 13 | //! the GPU down hard enough to need a reset. The path is built, typed and |
| 14 | //! probed; turning it on is a caller's explicit decision. |
| 15 | |
| 16 | use std::sync::Arc; |
| 17 | |
| 18 | use ec_va::caps::{Entrypoint, Profile}; |
| 19 | use ec_va::{ |
| 20 | Buffer, CapReport, Config, ConfigAttrib, Context, Display, Image, MappedBuffer, Picture, |
| 21 | Surface, SurfaceSpec, Vpp, sys, |
| 22 | }; |
| 23 | |
| 24 | use crate::error::{Error, Result}; |
| 25 | use crate::frame::I420; |
| 26 | use crate::params::enc::{ |
| 27 | MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, |
| 28 | misc_bytes, |
| 29 | }; |
| 30 | use crate::params::param_buffer; |
| 31 | use crate::pool::{PooledSurface, SurfacePool}; |
| 32 | |
| 33 | mod av1; |
| 34 | mod h264; |
| 35 | mod headers; |
| 36 | mod hevc; |
| 37 | |
| 38 | /// The codecs this crate encodes in hardware. |
| 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 40 | pub enum EncCodec { |
| 41 | /// H.264 / AVC, High profile. |
| 42 | H264, |
| 43 | /// H.265 / HEVC, Main profile. |
| 44 | H265, |
| 45 | /// AV1 Profile 0 — opt-in only, see the module docs. |
| 46 | Av1, |
| 47 | } |
| 48 | |
| 49 | /// How the driver should spend bits. |
| 50 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 51 | pub enum RateControlMode { |
| 52 | /// Constant quantiser: `qp` for every picture, bitrate ignored. |
| 53 | ConstantQp { |
| 54 | /// The quantiser, 0..51 for H.264/HEVC, 0..255 for AV1. |
| 55 | qp: u32, |
| 56 | }, |
| 57 | /// Constant bitrate, the driver picking quantisers to hold it. |
| 58 | ConstantBitrate, |
| 59 | } |
| 60 | |
| 61 | /// What can be changed between frames without rebuilding the encoder. |
| 62 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 63 | pub struct Tunings { |
| 64 | /// Target bitrate in bits per second. |
| 65 | pub bitrate: u32, |
| 66 | /// Frame rate as `(numerator, denominator)`. |
| 67 | pub framerate: (u32, u32), |
| 68 | } |
| 69 | |
| 70 | /// Per-frame instructions from the caller. |
| 71 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 72 | pub struct FrameMetadata { |
| 73 | /// Presentation timestamp, carried through to the coded frame. |
| 74 | pub timestamp: i64, |
| 75 | /// Start a new GOP with this frame. |
| 76 | pub force_keyframe: bool, |
| 77 | } |
| 78 | |
| 79 | /// How an encoder is set up. |
| 80 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 81 | pub struct EncoderConfig { |
| 82 | /// Which codec. |
| 83 | pub codec: EncCodec, |
| 84 | /// Displayed width; the coded size is rounded up for the codec's blocks. |
| 85 | pub width: u32, |
| 86 | /// Displayed height. |
| 87 | pub height: u32, |
| 88 | /// Frame rate as `(numerator, denominator)`. |
| 89 | pub framerate: (u32, u32), |
| 90 | /// Target bitrate in bits per second. |
| 91 | pub bitrate: u32, |
| 92 | /// Pictures per GOP; the first of each is an IDR / key frame. |
| 93 | pub gop_size: u32, |
| 94 | /// Rate control mode. |
| 95 | pub rate_control: RateControlMode, |
| 96 | /// Driver quality/speed level, 1 (best quality) upwards; 0 = driver default. |
| 97 | pub quality: u32, |
| 98 | /// Permit AV1 encoding. Without it, [`EncCodec::Av1`] is refused. |
| 99 | pub allow_av1: bool, |
| 100 | /// The colour description to write into the VUI, or `None` to leave it |
| 101 | /// unsignalled (`video_signal_type_present_flag = 0`) as before. |
| 102 | pub colour: Option<Colour>, |
| 103 | } |
| 104 | |
| 105 | /// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. |
| 106 | /// |
| 107 | /// Carried verbatim into `colour_primaries`, `transfer_characteristics` and |
| 108 | /// `matrix_coeffs` — this crate does not interpret them, so a caller wanting |
| 109 | /// BT.2020/PQ passes `(9, 16, 9)`, BT.709 SDR `(1, 1, 1)`, and so on (H.273 |
| 110 | /// tables 2/3/4). |
| 111 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 112 | pub struct Colour { |
| 113 | /// `colour_primaries`. |
| 114 | pub primaries: u8, |
| 115 | /// `transfer_characteristics`. |
| 116 | pub transfer: u8, |
| 117 | /// `matrix_coeffs`. |
| 118 | pub matrix: u8, |
| 119 | /// `video_full_range_flag`. |
| 120 | pub full_range: bool, |
| 121 | } |
| 122 | |
| 123 | impl EncoderConfig { |
| 124 | /// A configuration with sensible defaults for `codec` at `width x height`. |
| 125 | pub fn new(codec: EncCodec, width: u32, height: u32) -> EncoderConfig { |
| 126 | EncoderConfig { |
| 127 | codec, |
| 128 | width, |
| 129 | height, |
| 130 | framerate: (30, 1), |
| 131 | bitrate: 8_000_000, |
| 132 | gop_size: 60, |
| 133 | rate_control: RateControlMode::ConstantBitrate, |
| 134 | quality: 0, |
| 135 | allow_av1: false, |
| 136 | colour: None, |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. |
| 141 | pub fn colour( |
| 142 | mut self, |
| 143 | primaries: u8, |
| 144 | transfer: u8, |
| 145 | matrix: u8, |
| 146 | full_range: bool, |
| 147 | ) -> EncoderConfig { |
| 148 | self.colour = Some(Colour { |
| 149 | primaries, |
| 150 | transfer, |
| 151 | matrix, |
| 152 | full_range, |
| 153 | }); |
| 154 | self |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// One coded picture. |
| 159 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 160 | pub struct CodedFrame { |
| 161 | /// The bitstream: an Annex B access unit for H.264/HEVC, an OBU sequence |
| 162 | /// for AV1. |
| 163 | pub data: Vec<u8>, |
| 164 | /// The timestamp the caller supplied with the source frame. |
| 165 | pub timestamp: i64, |
| 166 | /// True for an IDR / key frame. |
| 167 | pub is_keyframe: bool, |
| 168 | } |
| 169 | |
| 170 | /// A hardware encoder. |
| 171 | pub struct Encoder { |
| 172 | config: EncoderConfig, |
| 173 | context: Arc<Context>, |
| 174 | pool: SurfacePool, |
| 175 | coded_size: (u32, u32), |
| 176 | /// The reconstruction of the previous picture, the single reference. |
| 177 | reference: Option<Arc<PooledSurface>>, |
| 178 | /// Pictures coded since the last key frame. |
| 179 | gop_position: u32, |
| 180 | /// Pictures coded in total, which drives frame_num and order hints. |
| 181 | coded: u64, |
| 182 | tunings: Tunings, |
| 183 | /// Set when the rate control parameters have to be resent. |
| 184 | tunings_dirty: bool, |
| 185 | profile: Profile, |
| 186 | /// An upload image, reused across frames. |
| 187 | upload: Option<Image>, |
| 188 | /// P010 -> NV12 GPU-resident conversion pipeline for [`Encoder::encode_frame`] |
| 189 | /// on a 10-bit source; built lazily, since most encoders never see one. |
| 190 | vpp: Option<Vpp>, |
| 191 | /// The small pool [`Encoder::vpp`] converts into, round-robined rather |
| 192 | /// than pool-acquired: each conversion is fully synced before this |
| 193 | /// encoder's own picture submission returns, so two surfaces are enough |
| 194 | /// to never hand out one still in flight. |
| 195 | vpp_surfaces: Vec<Arc<Surface>>, |
| 196 | vpp_next: usize, |
| 197 | } |
| 198 | |
| 199 | impl Encoder { |
| 200 | /// Build an encoder for `config` on `display`. |
| 201 | pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> { |
| 202 | if config.codec == EncCodec::Av1 && !config.allow_av1 { |
| 203 | return Err(Error::unsupported( |
| 204 | "AV1 hardware encoding", |
| 205 | "it is opt-in (EncoderConfig::allow_av1) after a GPU recovery incident", |
| 206 | )); |
| 207 | } |
| 208 | let profile = match config.codec { |
| 209 | // High is the profile every H.264 encoder on this driver reports and |
| 210 | // the one a High-profile decoder expects; Main is a strict subset. |
| 211 | EncCodec::H264 => Profile::H264High, |
| 212 | EncCodec::H265 => Profile::HEVCMain, |
| 213 | EncCodec::Av1 => Profile::AV1Profile0, |
| 214 | }; |
| 215 | let block = match config.codec { |
| 216 | EncCodec::H264 => 16, |
| 217 | EncCodec::H265 => 32, |
| 218 | EncCodec::Av1 => 64, |
| 219 | }; |
| 220 | let coded_size = ( |
| 221 | config.width.next_multiple_of(block), |
| 222 | config.height.next_multiple_of(block), |
| 223 | ); |
| 224 | |
| 225 | let caps = CapReport::probe(display)?; |
| 226 | let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { |
| 227 | Error::unsupported( |
| 228 | format!("{profile:?} encode"), |
| 229 | "the driver advertises no EncSlice entrypoint for this profile", |
| 230 | ) |
| 231 | })?; |
| 232 | if let Some(surfaces) = &entry.surfaces |
| 233 | && !surfaces.allows(coded_size.0, coded_size.1) |
| 234 | { |
| 235 | // The minimum encode size is a driver fact, not a guess: radeonsi |
| 236 | // refuses anything under 96x32 for H.264 and 384x128 for HEVC. |
| 237 | return Err(Error::unsupported( |
| 238 | format!("{}x{} {profile:?} encode", coded_size.0, coded_size.1), |
| 239 | format!( |
| 240 | "the driver accepts {:?}..{:?} x {:?}..{:?}", |
| 241 | surfaces.min_width, |
| 242 | surfaces.max_width, |
| 243 | surfaces.min_height, |
| 244 | surfaces.max_height |
| 245 | ), |
| 246 | )); |
| 247 | } |
| 248 | |
| 249 | // The packed-header attribute is not decoration: a config that does not |
| 250 | // ask for them gets a driver that writes its own headers and silently |
| 251 | // ignores the application's (measured on radeonsi — the parameter sets |
| 252 | // went in, the slice header did not, and every P picture came back |
| 253 | // missing its `byte_alignment()`). |
| 254 | let packed = entry.packed_headers |
| 255 | & (sys::VA_ENC_PACKED_HEADER_SEQUENCE |
| 256 | | sys::VA_ENC_PACKED_HEADER_PICTURE |
| 257 | | sys::VA_ENC_PACKED_HEADER_SLICE); |
| 258 | let config_id = Config::new( |
| 259 | display, |
| 260 | profile, |
| 261 | Entrypoint::EncSlice, |
| 262 | &[ |
| 263 | ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420), |
| 264 | ConfigAttrib { |
| 265 | type_: sys::VAConfigAttribEncPackedHeaders, |
| 266 | value: packed, |
| 267 | }, |
| 268 | ], |
| 269 | )?; |
| 270 | let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1) |
| 271 | .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); |
| 272 | // Input, reconstruction, one reference, and slack for the driver to |
| 273 | // keep a submission in flight. |
| 274 | let pool = SurfacePool::new(display, &spec, 8)?; |
| 275 | let context = Context::new( |
| 276 | &config_id, |
| 277 | coded_size.0, |
| 278 | coded_size.1, |
| 279 | sys::VA_PROGRESSIVE, |
| 280 | pool.targets(), |
| 281 | )?; |
| 282 | |
| 283 | Ok(Encoder { |
| 284 | tunings: Tunings { |
| 285 | bitrate: config.bitrate, |
| 286 | framerate: config.framerate, |
| 287 | }, |
| 288 | config, |
| 289 | context, |
| 290 | pool, |
| 291 | coded_size, |
| 292 | reference: None, |
| 293 | gop_position: 0, |
| 294 | coded: 0, |
| 295 | tunings_dirty: true, |
| 296 | profile, |
| 297 | upload: None, |
| 298 | vpp: None, |
| 299 | vpp_surfaces: Vec::new(), |
| 300 | vpp_next: 0, |
| 301 | }) |
| 302 | } |
| 303 | |
| 304 | /// The coded (block-aligned) size the driver works at. |
| 305 | pub fn coded_size(&self) -> (u32, u32) { |
| 306 | self.coded_size |
| 307 | } |
| 308 | |
| 309 | /// Change bitrate or frame rate; takes effect on the next frame. |
| 310 | pub fn tune(&mut self, tunings: Tunings) { |
| 311 | self.tunings = tunings; |
| 312 | self.tunings_dirty = true; |
| 313 | } |
| 314 | |
| 315 | /// Encode one frame and return its coded bytes. |
| 316 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { |
| 317 | if frame.width != self.config.width || frame.height != self.config.height { |
| 318 | return Err(Error::config(format!( |
| 319 | "encoder configured for {}x{} was given a {}x{} frame", |
| 320 | self.config.width, self.config.height, frame.width, frame.height |
| 321 | ))); |
| 322 | } |
| 323 | let input = self |
| 324 | .pool |
| 325 | .acquire() |
| 326 | .ok_or_else(|| Error::config("encode: every surface is still in use"))?; |
| 327 | self.upload(frame, &input)?; |
| 328 | self.encode_surface(Arc::clone(input.surface()), meta) |
| 329 | } |
| 330 | |
| 331 | /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, |
| 332 | /// no re-upload, just the decoder's picture handed straight to the |
| 333 | /// encoder as its source. This is the path a decode-then-encode pipeline |
| 334 | /// (e.g. a transcode) wants — the alternative is a full frame through |
| 335 | /// system memory and back for no reason. |
| 336 | /// |
| 337 | /// A 10-bit (P010) source is also zero-copy through the driver's own |
| 338 | /// video-processing pipeline: [`Encoder`] keeps a small VPP-owned NV12 |
| 339 | /// surface pool (built lazily, on the first 10-bit frame) and converts |
| 340 | /// into it on the GPU (`VAProfileNone`/`VAEntrypointVideoProc`) before |
| 341 | /// submitting exactly as for an 8-bit source — still no read-back to |
| 342 | /// system memory. Every profile this crate encodes (`H264High`, |
| 343 | /// `HEVCMain`) is itself 8-bit, so the low two bits are truncated the |
| 344 | /// same way [`Frame::to_i420`]'s CPU path truncates them (VPP's rounding |
| 345 | /// may differ by a code point; see `gpu.rs`'s PSNR comparison of the two |
| 346 | /// paths for the measured difference) — call [`Frame::to_i420_16`] |
| 347 | /// instead if the extra precision must survive encoding. |
| 348 | /// |
| 349 | /// Refused, rather than silently working around, when: |
| 350 | /// - `frame` was decoded on a different [`ec_va::Display`]: a surface id |
| 351 | /// only means anything on the display that created it. |
| 352 | /// - `frame`'s bit depth is neither 8 nor 10: no profile this crate |
| 353 | /// encodes, and no VPP conversion this crate builds, has a destination |
| 354 | /// for a 12-bit source. |
| 355 | /// |
| 356 | /// A `frame` whose coded size does not match this encoder's (a common |
| 357 | /// case: HEVC block-rounds to 32, so a 3840x2160 source's 2160 stays |
| 358 | /// unrounded while the encoder's coded height becomes 2176) is not |
| 359 | /// refused — it goes through the same VPP pool a 10-bit source uses, |
| 360 | /// placed by explicit region rather than a whole-surface convert: only |
| 361 | /// `frame.display_size` is read from the source and written into the |
| 362 | /// destination at `(0, 0)`, so the padding rows/columns beyond it are |
| 363 | /// never touched by the copy. Those padding pixels are still fed to the |
| 364 | /// encoder as part of the coded surface, so the pool is painted black |
| 365 | /// once, on creation, rather than left as whatever the driver's fresh |
| 366 | /// allocation happened to contain. |
| 367 | pub fn encode_frame( |
| 368 | &mut self, |
| 369 | frame: &crate::frame::Frame, |
| 370 | meta: FrameMetadata, |
| 371 | ) -> Result<CodedFrame> { |
| 372 | if frame.bit_depth != 8 && frame.bit_depth != 10 { |
| 373 | return Err(Error::unsupported( |
| 374 | format!("encode_frame of a {}-bit source", frame.bit_depth), |
| 375 | "H264High and HEVCMain, the only profiles this crate encodes, are 8-bit, and \ |
| 376 | the VPP conversion this crate builds only reads P010 (10-bit); decode to I420 \ |
| 377 | with Frame::to_i420 and call Encoder::encode instead", |
| 378 | )); |
| 379 | } |
| 380 | if !Arc::ptr_eq(frame.surface().display(), self.context.display()) { |
| 381 | return Err(Error::config( |
| 382 | "encode_frame: the frame was decoded on a different Display than this encoder", |
| 383 | )); |
| 384 | } |
| 385 | let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { |
| 386 | self.vpp_into_pool(frame.surface(), frame.display_size)? |
| 387 | } else { |
| 388 | Arc::clone(frame.surface()) |
| 389 | }; |
| 390 | self.encode_surface(source, meta) |
| 391 | } |
| 392 | |
| 393 | /// Place a source surface's visible rect into this encoder's coded size, |
| 394 | /// in NV12, on the GPU: a whole-surface convert when the source is |
| 395 | /// already the encoder's coded size (the common 10-bit case), a region |
| 396 | /// copy/convert otherwise. Builds the VPP pipeline and its two-surface |
| 397 | /// pool on first use, painting the pool black so any padding beyond |
| 398 | /// `display_size` a region copy never touches is deterministic. |
| 399 | fn vpp_into_pool( |
| 400 | &mut self, |
| 401 | source: &Arc<Surface>, |
| 402 | display_size: (u32, u32), |
| 403 | ) -> Result<Arc<Surface>> { |
| 404 | if self.vpp.is_none() { |
| 405 | let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) |
| 406 | .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); |
| 407 | let display = self.context.display(); |
| 408 | let surfaces = Surface::create_pool(display, &spec, 2)?; |
| 409 | for s in &surfaces { |
| 410 | Self::fill_black(s, self.coded_size)?; |
| 411 | } |
| 412 | let vpp = Vpp::new( |
| 413 | display, |
| 414 | sys::VA_RT_FORMAT_YUV420 | sys::VA_RT_FORMAT_YUV420_10, |
| 415 | &surfaces, |
| 416 | )?; |
| 417 | self.vpp_surfaces = surfaces; |
| 418 | self.vpp = Some(vpp); |
| 419 | } |
| 420 | let dest = Arc::clone(&self.vpp_surfaces[self.vpp_next]); |
| 421 | self.vpp_next = (self.vpp_next + 1) % self.vpp_surfaces.len(); |
| 422 | let vpp = self.vpp.as_ref().expect("just built above if it was None"); |
| 423 | if display_size == self.coded_size { |
| 424 | Ok(vpp.convert(source, dest)?) |
| 425 | } else { |
| 426 | let rect = (0, 0, display_size.0, display_size.1); |
| 427 | Ok(vpp.convert_region(source, rect, dest, rect)?) |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | /// Paint an NV12 surface black (Y=16, chroma=128, TV-range neutral): the |
| 432 | /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a |
| 433 | /// region copy's untouched padding reads the same deterministic value on |
| 434 | /// every driver instead of whatever the fresh allocation contained. |
| 435 | fn fill_black(surface: &Arc<Surface>, size: (u32, u32)) -> Result<()> { |
| 436 | let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; |
| 437 | { |
| 438 | let mut mapped = image.map()?; |
| 439 | if let Some(y) = mapped.plane_mut(0) { |
| 440 | y.fill(16); |
| 441 | } |
| 442 | if let Some(uv) = mapped.plane_mut(1) { |
| 443 | uv.fill(128); |
| 444 | } |
| 445 | } |
| 446 | surface.write_from(&image, size.0, size.1)?; |
| 447 | Ok(()) |
| 448 | } |
| 449 | |
| 450 | /// Shared submission path for [`Encoder::encode`] and |
| 451 | /// [`Encoder::encode_frame`]: everything after the source surface is |
| 452 | /// settled. |
| 453 | fn encode_surface(&mut self, source: Arc<Surface>, meta: FrameMetadata) -> Result<CodedFrame> { |
| 454 | let keyframe = meta.force_keyframe |
| 455 | || self.reference.is_none() |
| 456 | || self.gop_position >= self.config.gop_size.max(1); |
| 457 | |
| 458 | let recon = self |
| 459 | .pool |
| 460 | .acquire() |
| 461 | .ok_or_else(|| Error::config("encode: no surface for the reconstruction"))?; |
| 462 | |
| 463 | // 6 bits per pixel of headroom: an intra frame at a low quantiser is the |
| 464 | // worst case, and a coded buffer that overflows loses the picture. |
| 465 | let coded_size = (self.coded_size.0 * self.coded_size.1 * 3 / 4).max(1 << 20); |
| 466 | let coded_buf = Buffer::allocate(&self.context, sys::VAEncCodedBufferType, coded_size)?; |
| 467 | let coded_id = coded_buf.id(); |
| 468 | |
| 469 | let mut buffers = Vec::new(); |
| 470 | match self.config.codec { |
| 471 | EncCodec::H264 => h264::parameters(self, &recon, coded_id, keyframe, &mut buffers)?, |
| 472 | EncCodec::H265 => hevc::parameters(self, &recon, coded_id, keyframe, &mut buffers)?, |
| 473 | EncCodec::Av1 => av1::parameters(self, &recon, coded_id, keyframe, &mut buffers)?, |
| 474 | } |
| 475 | buffers.extend(self.rate_control_buffers()?); |
| 476 | buffers.push(coded_buf); |
| 477 | |
| 478 | let mut picture = Picture::new(&self.context, source) |
| 479 | .begin()? |
| 480 | .render_all(buffers)? |
| 481 | .end()? |
| 482 | .sync()?; |
| 483 | |
| 484 | let data = { |
| 485 | let coded = picture |
| 486 | .buffers_mut() |
| 487 | .iter_mut() |
| 488 | .find(|b| b.buffer_type() == sys::VAEncCodedBufferType) |
| 489 | .ok_or_else(|| Error::config("the coded buffer vanished from the picture"))?; |
| 490 | let mapped = coded.map()?; |
| 491 | coded_bytes(&mapped)? |
| 492 | }; |
| 493 | |
| 494 | self.reference = Some(recon); |
| 495 | self.coded += 1; |
| 496 | self.gop_position = if keyframe { 1 } else { self.gop_position + 1 }; |
| 497 | Ok(CodedFrame { |
| 498 | data, |
| 499 | timestamp: meta.timestamp, |
| 500 | is_keyframe: keyframe, |
| 501 | }) |
| 502 | } |
| 503 | |
| 504 | /// Upload one frame into a surface as NV12. |
| 505 | /// |
| 506 | /// One image is created per encoder and reused: `vaCreateImage` per frame |
| 507 | /// would be an allocation per frame, which is exactly the shape of the |
| 508 | /// per-frame cost this crate exists to remove. |
| 509 | fn upload(&mut self, frame: &I420, surface: &Arc<Surface>) -> Result<()> { |
| 510 | if self.upload.is_none() { |
| 511 | self.upload = Some(Image::create( |
| 512 | surface.display(), |
| 513 | sys::VA_FOURCC_NV12, |
| 514 | self.coded_size.0, |
| 515 | self.coded_size.1, |
| 516 | )?); |
| 517 | } |
| 518 | let image = self |
| 519 | .upload |
| 520 | .as_mut() |
| 521 | .ok_or_else(|| Error::config("no upload image"))?; |
| 522 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 523 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 524 | { |
| 525 | let mut mapped = image.map()?; |
| 526 | let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; |
| 527 | let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; |
| 528 | // The two planes are written in turn because a mapping hands out one |
| 529 | // mutable plane at a time; the loops are the interleave `i420_to_nv12` |
| 530 | // does for callers that own both buffers. |
| 531 | if let Some(dst) = mapped.plane_mut(0) { |
| 532 | for row in 0..h { |
| 533 | let (s, d) = (row * w, row * y_pitch); |
| 534 | if d + w > dst.len() { |
| 535 | break; |
| 536 | } |
| 537 | dst[d..d + w].copy_from_slice(&frame.y[s..s + w]); |
| 538 | } |
| 539 | } |
| 540 | if let Some(dst) = mapped.plane_mut(1) { |
| 541 | for row in 0..ch { |
| 542 | let d = row * uv_pitch; |
| 543 | if d + cw * 2 > dst.len() { |
| 544 | break; |
| 545 | } |
| 546 | for col in 0..cw { |
| 547 | dst[d + col * 2] = frame.u[row * cw + col]; |
| 548 | dst[d + col * 2 + 1] = frame.v[row * cw + col]; |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | surface.write_from(image, self.coded_size.0, self.coded_size.1)?; |
| 554 | Ok(()) |
| 555 | } |
| 556 | |
| 557 | /// The misc parameter buffers that carry rate control, resent when tuned. |
| 558 | fn rate_control_buffers(&mut self) -> Result<Vec<Buffer>> { |
| 559 | if !self.tunings_dirty { |
| 560 | return Ok(Vec::new()); |
| 561 | } |
| 562 | self.tunings_dirty = false; |
| 563 | let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control { |
| 564 | RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0), |
| 565 | RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate), |
| 566 | }; |
| 567 | let rc = RateControl { |
| 568 | bits_per_second: bits, |
| 569 | target_percentage: 100, |
| 570 | window_size: 1000, |
| 571 | initial_qp, |
| 572 | min_qp, |
| 573 | max_qp, |
| 574 | }; |
| 575 | let mut out = vec![Buffer::from_bytes( |
| 576 | &self.context, |
| 577 | sys::VAEncMiscParameterBufferType, |
| 578 | &misc_bytes(MISC_RATE_CONTROL, &rc.words()), |
| 579 | )?]; |
| 580 | let fr = crate::params::enc::FrameRate { |
| 581 | num: self.tunings.framerate.0.max(1), |
| 582 | den: self.tunings.framerate.1.max(1), |
| 583 | }; |
| 584 | out.push(Buffer::from_bytes( |
| 585 | &self.context, |
| 586 | sys::VAEncMiscParameterBufferType, |
| 587 | &misc_bytes(MISC_FRAME_RATE, &fr.words()), |
| 588 | )?); |
| 589 | if bits > 0 { |
| 590 | let hrd = crate::params::enc::Hrd { |
| 591 | initial_buffer_fullness: bits, |
| 592 | buffer_size: bits * 2, |
| 593 | }; |
| 594 | out.push(Buffer::from_bytes( |
| 595 | &self.context, |
| 596 | sys::VAEncMiscParameterBufferType, |
| 597 | &misc_bytes(MISC_HRD, &hrd.words()), |
| 598 | )?); |
| 599 | } |
| 600 | Ok(out) |
| 601 | } |
| 602 | |
| 603 | /// Submit one packed header: its parameter buffer, then its bytes. |
| 604 | /// |
| 605 | /// Both go in the same picture, in this order, which is what the driver |
| 606 | /// reads them in (`va.h:2446`). |
| 607 | pub(crate) fn push_packed( |
| 608 | &self, |
| 609 | packed: &headers::Packed, |
| 610 | out: &mut Vec<Buffer>, |
| 611 | ) -> Result<()> { |
| 612 | let param = PackedHeaderParameterBuffer { |
| 613 | type_: packed.kind, |
| 614 | bit_length: packed.bits, |
| 615 | has_emulation_bytes: 1, |
| 616 | ..PackedHeaderParameterBuffer::default() |
| 617 | }; |
| 618 | out.push(param_buffer(&self.context, ¶m)?); |
| 619 | out.push(Buffer::from_bytes( |
| 620 | &self.context, |
| 621 | sys::VAEncPackedHeaderDataBufferType, |
| 622 | &packed.bytes, |
| 623 | )?); |
| 624 | Ok(()) |
| 625 | } |
| 626 | |
| 627 | pub(crate) fn context(&self) -> &Arc<Context> { |
| 628 | &self.context |
| 629 | } |
| 630 | |
| 631 | pub(crate) fn config(&self) -> &EncoderConfig { |
| 632 | &self.config |
| 633 | } |
| 634 | |
| 635 | pub(crate) fn reference(&self) -> Option<&Arc<PooledSurface>> { |
| 636 | self.reference.as_ref() |
| 637 | } |
| 638 | |
| 639 | pub(crate) fn coded_count(&self) -> u64 { |
| 640 | self.coded |
| 641 | } |
| 642 | |
| 643 | pub(crate) fn gop_position(&self) -> u32 { |
| 644 | self.gop_position |
| 645 | } |
| 646 | |
| 647 | /// The VA profile this encoder was configured with. |
| 648 | pub fn profile(&self) -> Profile { |
| 649 | self.profile |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | /// Collect the bytes of a coded buffer's segment list. |
| 654 | /// |
| 655 | /// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, |
| 656 | /// `status`, a `buf` pointer to that segment's bytes and a `next` pointer. There |
| 657 | /// is no safe way to express that in `ec-va`, so this is one of the crate's two |
| 658 | /// unsafe functions. |
| 659 | fn coded_bytes(mapped: &MappedBuffer<'_>) -> Result<Vec<u8>> { |
| 660 | // Field offsets from `crates/ec-hw/abi-probe.c`: size=0 bit_offset=4 |
| 661 | // status=8 reserved=12 buf=16 next=24, total 48 bytes, align 8. |
| 662 | const BUF_OFFSET: usize = 16; |
| 663 | const NEXT_OFFSET: usize = 24; |
| 664 | let mut out = Vec::new(); |
| 665 | // SAFETY: the mapping is a VACodedBufferSegment as libva defines it |
| 666 | // (va.h:3940); the pointer is valid for the guard's lifetime. |
| 667 | let mut segment = unsafe { mapped.as_ptr() }; |
| 668 | // A driver returning a cyclic list would otherwise hang the export; 4096 |
| 669 | // segments is far beyond any real picture. |
| 670 | for _ in 0..4096 { |
| 671 | if segment.is_null() { |
| 672 | break; |
| 673 | } |
| 674 | // SAFETY: `segment` points at a 48-byte segment header the driver |
| 675 | // wrote; every field is read at its probed offset with an unaligned |
| 676 | // read, and `buf` points at `size` bytes of coded data that stay valid |
| 677 | // until the buffer is unmapped (i.e. for this guard's lifetime). |
| 678 | let (size, data, next) = unsafe { |
| 679 | let size = segment.cast::<u32>().read_unaligned() as usize; |
| 680 | let data = segment.add(BUF_OFFSET).cast::<*const u8>().read_unaligned(); |
| 681 | let next = segment.add(NEXT_OFFSET).cast::<*mut u8>().read_unaligned(); |
| 682 | (size, data, next) |
| 683 | }; |
| 684 | if data.is_null() || size == 0 { |
| 685 | break; |
| 686 | } |
| 687 | // SAFETY: as above — `data` is valid for `size` bytes. |
| 688 | out.extend_from_slice(unsafe { std::slice::from_raw_parts(data, size) }); |
| 689 | segment = next; |
| 690 | } |
| 691 | if out.is_empty() { |
| 692 | return Err(Error::config("the encoder produced an empty coded buffer")); |
| 693 | } |
| 694 | Ok(out) |
| 695 | } |