10-bit AV1 hardware encode
Browse files at this commit98dcdcf06aff6924b3f13211870a639b3530313eParent: cb7efaf- feat
- 10-bit AV1 hardware encode
6 changed files +500 -33
- crates/ec-hw/src/enc/av1.rs +6 -5
- crates/ec-hw/src/enc/h264.rs +2 -2
- crates/ec-hw/src/enc/hevc.rs +2 -2
- crates/ec-hw/src/enc/mod.rs +211 -22
- crates/ec-hw/src/params/enc.rs +8 -1
- crates/ec-hw/tests/gpu.rs +271 -1
crates/ec-hw/src/enc/av1.rsmodified+6 -5
| @@ -49,7 +49,8 @@ pub(super) fn parameters( | ||
| 49 | 49 | let context = encoder.context(); |
| 50 | 50 | let (coded_w, coded_h) = encoder.coded_size(); |
| 51 | 51 | let (width, height) = (config.width.max(1), config.height.max(1)); |
| 52 | - let cqp = matches!(config.rate_control, RateControlMode::ConstantQp { .. }); | |
| 52 | + let cqp = config.rate_control.is_cqp(); | |
| 53 | + let ten_bit = config.bit_depth == 10; | |
| 53 | 54 | let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); |
| 54 | 55 | |
| 55 | 56 | let mut seq = EncSequenceParameterBufferAV1 { |
| @@ -59,8 +60,8 @@ pub(super) fn parameters( | ||
| 59 | 60 | intra_period: config.gop_size.max(1), |
| 60 | 61 | ip_period: 1, |
| 61 | 62 | bits_per_second: match config.rate_control { |
| 62 | - RateControlMode::ConstantBitrate => config.bitrate, | |
| 63 | 63 | RateControlMode::ConstantQp { .. } => 0, |
| 64 | + _ => config.bitrate, | |
| 64 | 65 | }, |
| 65 | 66 | order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, |
| 66 | 67 | ..EncSequenceParameterBufferAV1::default() |
| @@ -68,7 +69,7 @@ pub(super) fn parameters( | ||
| 68 | 69 | seq.seq_fields = seq |
| 69 | 70 | .seq_fields |
| 70 | 71 | .enable_order_hint(1) |
| 71 | - .bit_depth_minus8(0) | |
| 72 | + .bit_depth_minus8(if ten_bit { 2 } else { 0 }) | |
| 72 | 73 | .subsampling_x(1) |
| 73 | 74 | .subsampling_y(1); |
| 74 | 75 | out.push(param_buffer(context, &seq)?); |
| @@ -84,7 +85,7 @@ pub(super) fn parameters( | ||
| 84 | 85 | }; |
| 85 | 86 | let base_qindex = match config.rate_control { |
| 86 | 87 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, |
| 87 | - RateControlMode::ConstantBitrate => 128, | |
| 88 | + _ => 128, | |
| 88 | 89 | }; |
| 89 | 90 | // One reference, refreshed every picture: slot 0 holds the previous |
| 90 | 91 | // reconstruction and every ref_frame_idx points at it. |
| @@ -142,7 +143,7 @@ pub(super) fn parameters( | ||
| 142 | 143 | height, |
| 143 | 144 | seq_level_idx: level_idx, |
| 144 | 145 | seq_tier: 0, |
| 145 | - high_bitdepth: false, | |
| 146 | + high_bitdepth: ten_bit, | |
| 146 | 147 | colour: config.colour, |
| 147 | 148 | }), |
| 148 | 149 | out, |
crates/ec-hw/src/enc/h264.rsmodified+2 -2
| @@ -44,8 +44,8 @@ pub(super) fn parameters( | ||
| 44 | 44 | intra_idr_period: config.gop_size.max(1), |
| 45 | 45 | ip_period: 1, |
| 46 | 46 | bits_per_second: match config.rate_control { |
| 47 | - RateControlMode::ConstantBitrate => config.bitrate, | |
| 48 | 47 | RateControlMode::ConstantQp { .. } => 0, |
| 48 | + _ => config.bitrate, | |
| 49 | 49 | }, |
| 50 | 50 | max_num_ref_frames: 1, |
| 51 | 51 | picture_width_in_mbs: (coded_w / 16) as u16, |
| @@ -84,7 +84,7 @@ pub(super) fn parameters( | ||
| 84 | 84 | frame_num, |
| 85 | 85 | pic_init_qp: match config.rate_control { |
| 86 | 86 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, |
| 87 | - RateControlMode::ConstantBitrate => 26, | |
| 87 | + _ => 26, | |
| 88 | 88 | }, |
| 89 | 89 | ..EncPictureParameterBufferH264::default() |
| 90 | 90 | }; |
crates/ec-hw/src/enc/hevc.rsmodified+2 -2
| @@ -50,8 +50,8 @@ pub(super) fn parameters( | ||
| 50 | 50 | intra_idr_period: config.gop_size.max(1), |
| 51 | 51 | ip_period: 1, |
| 52 | 52 | bits_per_second: match config.rate_control { |
| 53 | - RateControlMode::ConstantBitrate => config.bitrate, | |
| 54 | 53 | RateControlMode::ConstantQp { .. } => 0, |
| 54 | + _ => config.bitrate, | |
| 55 | 55 | }, |
| 56 | 56 | pic_width_in_luma_samples: coded_w as u16, |
| 57 | 57 | pic_height_in_luma_samples: coded_h as u16, |
| @@ -87,7 +87,7 @@ pub(super) fn parameters( | ||
| 87 | 87 | collocated_ref_pic_index: 0xff, |
| 88 | 88 | pic_init_qp: match config.rate_control { |
| 89 | 89 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, |
| 90 | - RateControlMode::ConstantBitrate => 26, | |
| 90 | + _ => 26, | |
| 91 | 91 | }, |
| 92 | 92 | nal_unit_type: if keyframe { |
| 93 | 93 | NAL_IDR_W_RADL |
crates/ec-hw/src/enc/mod.rsmodified+211 -22
| @@ -26,10 +26,10 @@ use ec_va::{ | ||
| 26 | 26 | }; |
| 27 | 27 | |
| 28 | 28 | use crate::error::{Error, Result}; |
| 29 | -use crate::frame::I420; | |
| 29 | +use crate::frame::{I420, I420_16}; | |
| 30 | 30 | use crate::params::enc::{ |
| 31 | 31 | MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, |
| 32 | - misc_bytes, | |
| 32 | + VA_RC_QVBR, misc_bytes, | |
| 33 | 33 | }; |
| 34 | 34 | use crate::params::param_buffer; |
| 35 | 35 | use crate::pool::{PooledSurface, SurfacePool}; |
| @@ -60,6 +60,38 @@ pub enum RateControlMode { | ||
| 60 | 60 | }, |
| 61 | 61 | /// Constant bitrate, the driver picking quantisers to hold it. |
| 62 | 62 | ConstantBitrate, |
| 63 | + /// Variable bitrate: `bitrate` is the average asked for, and the driver | |
| 64 | + /// may spend up to 1.5x it inside the rate window. | |
| 65 | + VariableBitrate, | |
| 66 | + /// Quality-defined variable bitrate: the driver holds `quality` (a | |
| 67 | + /// quantiser-like target, lower is better quality) and treats `bitrate` | |
| 68 | + /// as the ceiling it may not exceed. | |
| 69 | + Qvbr { | |
| 70 | + /// The quality factor, in the codec's quantiser scale. | |
| 71 | + quality: u32, | |
| 72 | + }, | |
| 73 | +} | |
| 74 | + | |
| 75 | +impl RateControlMode { | |
| 76 | + /// The `VAConfigAttribRateControl` value this mode is configured with. | |
| 77 | + /// | |
| 78 | + /// The attribute is set at config creation, not per picture: a driver | |
| 79 | + /// that was configured for CQP ignores a bitrate handed to it later | |
| 80 | + /// (which is how the AV1 path measured CQP-only until 2026-09-07). | |
| 81 | + fn va_mode(self) -> u32 { | |
| 82 | + match self { | |
| 83 | + RateControlMode::ConstantQp { .. } => sys::VA_RC_CQP, | |
| 84 | + RateControlMode::ConstantBitrate => sys::VA_RC_CBR, | |
| 85 | + RateControlMode::VariableBitrate => sys::VA_RC_VBR, | |
| 86 | + RateControlMode::Qvbr { .. } => VA_RC_QVBR, | |
| 87 | + } | |
| 88 | + } | |
| 89 | + | |
| 90 | + /// True when the driver is told exactly which quantiser to use, so it has | |
| 91 | + /// nothing to back-annotate into the header this crate packs. | |
| 92 | + pub(crate) fn is_cqp(self) -> bool { | |
| 93 | + matches!(self, RateControlMode::ConstantQp { .. }) | |
| 94 | + } | |
| 63 | 95 | } |
| 64 | 96 | |
| 65 | 97 | /// What can be changed between frames without rebuilding the encoder. |
| @@ -102,6 +134,10 @@ pub struct EncoderConfig { | ||
| 102 | 134 | /// The colour description to write into the VUI, or `None` to leave it |
| 103 | 135 | /// unsignalled (`video_signal_type_present_flag = 0`) as before. |
| 104 | 136 | pub colour: Option<Colour>, |
| 137 | + /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). | |
| 138 | + /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or | |
| 139 | + /// straight from a 10-bit [`crate::Frame`]. | |
| 140 | + pub bit_depth: u8, | |
| 105 | 141 | } |
| 106 | 142 | |
| 107 | 143 | /// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. |
| @@ -135,9 +171,16 @@ impl EncoderConfig { | ||
| 135 | 171 | rate_control: RateControlMode::ConstantBitrate, |
| 136 | 172 | quality: 0, |
| 137 | 173 | colour: None, |
| 174 | + bit_depth: 8, | |
| 138 | 175 | } |
| 139 | 176 | } |
| 140 | 177 | |
| 178 | + /// Encode at 10 bits (AV1 only); see [`EncoderConfig::bit_depth`]. | |
| 179 | + pub fn ten_bit(mut self) -> EncoderConfig { | |
| 180 | + self.bit_depth = 10; | |
| 181 | + self | |
| 182 | + } | |
| 183 | + | |
| 141 | 184 | /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. |
| 142 | 185 | pub fn colour( |
| 143 | 186 | mut self, |
| @@ -200,6 +243,19 @@ pub struct Encoder { | ||
| 200 | 243 | impl Encoder { |
| 201 | 244 | /// Build an encoder for `config` on `display`. |
| 202 | 245 | pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> { |
| 246 | + if config.bit_depth != 8 && config.bit_depth != 10 { | |
| 247 | + return Err(Error::config(format!( | |
| 248 | + "encoder bit depth {} : this crate encodes 8-bit, or 10-bit AV1", | |
| 249 | + config.bit_depth | |
| 250 | + ))); | |
| 251 | + } | |
| 252 | + if config.bit_depth == 10 && config.codec != EncCodec::Av1 { | |
| 253 | + // Not a driver refusal: H264High and HEVCMain are 8-bit profiles | |
| 254 | + // by definition, and this crate configures no other. | |
| 255 | + return Err(Error::config( | |
| 256 | + "10-bit encode is AV1 only here: the H.264 and H.265 profiles this crate configures (High, Main) are 8-bit", | |
| 257 | + )); | |
| 258 | + } | |
| 203 | 259 | let profile = match config.codec { |
| 204 | 260 | // High is the profile every H.264 encoder on this driver reports and |
| 205 | 261 | // the one a High-profile decoder expects; Main is a strict subset. |
| @@ -217,6 +273,11 @@ impl Encoder { | ||
| 217 | 273 | config.height.next_multiple_of(block), |
| 218 | 274 | ); |
| 219 | 275 | |
| 276 | + let rt_format = if config.bit_depth == 10 { | |
| 277 | + sys::VA_RT_FORMAT_YUV420_10 | |
| 278 | + } else { | |
| 279 | + sys::VA_RT_FORMAT_YUV420 | |
| 280 | + }; | |
| 220 | 281 | let caps = CapReport::probe(display)?; |
| 221 | 282 | let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { |
| 222 | 283 | Error::unsupported( |
| @@ -255,15 +316,18 @@ impl Encoder { | ||
| 255 | 316 | profile, |
| 256 | 317 | Entrypoint::EncSlice, |
| 257 | 318 | &[ |
| 258 | - ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420), | |
| 319 | + ConfigAttrib::rt_format(rt_format), | |
| 320 | + ConfigAttrib { | |
| 321 | + type_: sys::VAConfigAttribRateControl, | |
| 322 | + value: config.rate_control.va_mode(), | |
| 323 | + }, | |
| 259 | 324 | ConfigAttrib { |
| 260 | 325 | type_: sys::VAConfigAttribEncPackedHeaders, |
| 261 | 326 | value: packed, |
| 262 | 327 | }, |
| 263 | 328 | ], |
| 264 | 329 | )?; |
| 265 | - let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1) | |
| 266 | - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); | |
| 330 | + let spec = surface_spec(config.bit_depth, coded_size); | |
| 267 | 331 | // Input, reconstruction, one reference, and slack for the driver to |
| 268 | 332 | // keep a submission in flight. |
| 269 | 333 | let pool = SurfacePool::new(display, &spec, 8)?; |
| @@ -309,6 +373,12 @@ impl Encoder { | ||
| 309 | 373 | |
| 310 | 374 | /// Encode one frame and return its coded bytes. |
| 311 | 375 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { |
| 376 | + if self.config.bit_depth != 8 { | |
| 377 | + return Err(Error::config(format!( | |
| 378 | + "encode: this encoder is configured for {} bits; call encode_16", | |
| 379 | + self.config.bit_depth | |
| 380 | + ))); | |
| 381 | + } | |
| 312 | 382 | if frame.width != self.config.width || frame.height != self.config.height { |
| 313 | 383 | return Err(Error::config(format!( |
| 314 | 384 | "encoder configured for {}x{} was given a {}x{} frame", |
| @@ -323,6 +393,32 @@ impl Encoder { | ||
| 323 | 393 | self.encode_surface(Arc::clone(input.surface()), meta) |
| 324 | 394 | } |
| 325 | 395 | |
| 396 | + /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder. | |
| 397 | + /// | |
| 398 | + /// Samples are 0..1023 in the low ten bits of each `u16`, as | |
| 399 | + /// [`crate::Frame::to_i420_16`] returns them, and are shifted into P010's | |
| 400 | + /// top ten bits on upload. | |
| 401 | + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { | |
| 402 | + if self.config.bit_depth != 10 { | |
| 403 | + return Err(Error::config(format!( | |
| 404 | + "encode_16: this encoder is configured for {} bits; call encode", | |
| 405 | + self.config.bit_depth | |
| 406 | + ))); | |
| 407 | + } | |
| 408 | + if frame.width != self.config.width || frame.height != self.config.height { | |
| 409 | + return Err(Error::config(format!( | |
| 410 | + "encoder configured for {}x{} was given a {}x{} frame", | |
| 411 | + self.config.width, self.config.height, frame.width, frame.height | |
| 412 | + ))); | |
| 413 | + } | |
| 414 | + let input = self | |
| 415 | + .pool | |
| 416 | + .acquire() | |
| 417 | + .ok_or_else(|| Error::config("encode: every surface is still in use"))?; | |
| 418 | + self.upload_16(frame, &input)?; | |
| 419 | + self.encode_surface(Arc::clone(input.surface()), meta) | |
| 420 | + } | |
| 421 | + | |
| 326 | 422 | /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, |
| 327 | 423 | /// no re-upload, just the decoder's picture handed straight to the |
| 328 | 424 | /// encoder as its source. This is the path a decode-then-encode pipeline |
| @@ -377,7 +473,9 @@ impl Encoder { | ||
| 377 | 473 | "encode_frame: the frame was decoded on a different Display than this encoder", |
| 378 | 474 | )); |
| 379 | 475 | } |
| 380 | - let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { | |
| 476 | + let source = if frame.bit_depth != self.config.bit_depth | |
| 477 | + || frame.coded_size != self.coded_size | |
| 478 | + { | |
| 381 | 479 | self.vpp_into_pool(frame.surface(), frame.display_size)? |
| 382 | 480 | } else { |
| 383 | 481 | Arc::clone(frame.surface()) |
| @@ -397,12 +495,11 @@ impl Encoder { | ||
| 397 | 495 | display_size: (u32, u32), |
| 398 | 496 | ) -> Result<Arc<Surface>> { |
| 399 | 497 | if self.vpp.is_none() { |
| 400 | - let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) | |
| 401 | - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); | |
| 498 | + let spec = surface_spec(self.config.bit_depth, self.coded_size); | |
| 402 | 499 | let display = self.context.display(); |
| 403 | 500 | let surfaces = Surface::create_pool(display, &spec, 2)?; |
| 404 | 501 | for s in &surfaces { |
| 405 | - Self::fill_black(s, self.coded_size)?; | |
| 502 | + Self::fill_black(s, self.coded_size, self.config.bit_depth)?; | |
| 406 | 503 | } |
| 407 | 504 | let vpp = Vpp::new( |
| 408 | 505 | display, |
| @@ -427,16 +524,26 @@ impl Encoder { | ||
| 427 | 524 | /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a |
| 428 | 525 | /// region copy's untouched padding reads the same deterministic value on |
| 429 | 526 | /// every driver instead of whatever the fresh allocation contained. |
| 430 | - fn fill_black(surface: &Arc<Surface>, size: (u32, u32)) -> Result<()> { | |
| 431 | - let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; | |
| 527 | + fn fill_black(surface: &Arc<Surface>, size: (u32, u32), bit_depth: u8) -> Result<()> { | |
| 528 | + let mut image = Image::create(surface.display(), fourcc(bit_depth), size.0, size.1)?; | |
| 432 | 529 | { |
| 433 | 530 | let mut mapped = image.map()?; |
| 434 | - if let Some(y) = mapped.plane_mut(0) { | |
| 435 | - y.fill(16); | |
| 436 | - } | |
| 437 | - if let Some(uv) = mapped.plane_mut(1) { | |
| 438 | - uv.fill(128); | |
| 439 | - } | |
| 531 | + // P010 carries the sample in the top ten bits, so black is the | |
| 532 | + // 8-bit value shifted up by six, little endian. | |
| 533 | + let (luma, chroma) = (16u16 << 6, 128u16 << 6); | |
| 534 | + let mut plane = |index: usize, eight: u8, ten: u16| { | |
| 535 | + if let Some(p) = mapped.plane_mut(index) { | |
| 536 | + if bit_depth == 8 { | |
| 537 | + p.fill(eight); | |
| 538 | + } else { | |
| 539 | + for sample in p.chunks_exact_mut(2) { | |
| 540 | + sample.copy_from_slice(&ten.to_le_bytes()); | |
| 541 | + } | |
| 542 | + } | |
| 543 | + } | |
| 544 | + }; | |
| 545 | + plane(0, 16, luma); | |
| 546 | + plane(1, 128, chroma); | |
| 440 | 547 | } |
| 441 | 548 | surface.write_from(&image, size.0, size.1)?; |
| 442 | 549 | Ok(()) |
| @@ -514,7 +621,7 @@ impl Encoder { | ||
| 514 | 621 | if self.upload.is_none() { |
| 515 | 622 | self.upload = Some(Image::create( |
| 516 | 623 | surface.display(), |
| 517 | - sys::VA_FOURCC_NV12, | |
| 624 | + fourcc(self.config.bit_depth), | |
| 518 | 625 | self.coded_size.0, |
| 519 | 626 | self.coded_size.1, |
| 520 | 627 | )?); |
| @@ -558,23 +665,86 @@ impl Encoder { | ||
| 558 | 665 | Ok(()) |
| 559 | 666 | } |
| 560 | 667 | |
| 668 | + /// Upload one 10-bit frame into a surface as P010. | |
| 669 | + /// | |
| 670 | + /// The same reused image as [`Encoder::upload`], created P010 because the | |
| 671 | + /// encoder's surfaces are; samples move from the low ten bits of the | |
| 672 | + /// caller's `u16` into P010's top ten. | |
| 673 | + fn upload_16(&mut self, frame: &I420_16, surface: &Arc<Surface>) -> Result<()> { | |
| 674 | + if self.upload.is_none() { | |
| 675 | + self.upload = Some(Image::create( | |
| 676 | + surface.display(), | |
| 677 | + fourcc(self.config.bit_depth), | |
| 678 | + self.coded_size.0, | |
| 679 | + self.coded_size.1, | |
| 680 | + )?); | |
| 681 | + } | |
| 682 | + let image = self | |
| 683 | + .upload | |
| 684 | + .as_mut() | |
| 685 | + .ok_or_else(|| Error::config("no upload image"))?; | |
| 686 | + let (w, h) = (frame.width as usize, frame.height as usize); | |
| 687 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 688 | + { | |
| 689 | + let mut mapped = image.map()?; | |
| 690 | + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; | |
| 691 | + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; | |
| 692 | + if let Some(dst) = mapped.plane_mut(0) { | |
| 693 | + for row in 0..h { | |
| 694 | + let d = row * y_pitch; | |
| 695 | + if d + w * 2 > dst.len() { | |
| 696 | + break; | |
| 697 | + } | |
| 698 | + for col in 0..w { | |
| 699 | + let v = (frame.y[row * w + col] & 0x3ff) << 6; | |
| 700 | + dst[d + col * 2..d + col * 2 + 2].copy_from_slice(&v.to_le_bytes()); | |
| 701 | + } | |
| 702 | + } | |
| 703 | + } | |
| 704 | + if let Some(dst) = mapped.plane_mut(1) { | |
| 705 | + for row in 0..ch { | |
| 706 | + let d = row * uv_pitch; | |
| 707 | + if d + cw * 4 > dst.len() { | |
| 708 | + break; | |
| 709 | + } | |
| 710 | + for col in 0..cw { | |
| 711 | + let u = (frame.u[row * cw + col] & 0x3ff) << 6; | |
| 712 | + let v = (frame.v[row * cw + col] & 0x3ff) << 6; | |
| 713 | + dst[d + col * 4..d + col * 4 + 2].copy_from_slice(&u.to_le_bytes()); | |
| 714 | + dst[d + col * 4 + 2..d + col * 4 + 4].copy_from_slice(&v.to_le_bytes()); | |
| 715 | + } | |
| 716 | + } | |
| 717 | + } | |
| 718 | + } | |
| 719 | + surface.write_from(image, self.coded_size.0, self.coded_size.1)?; | |
| 720 | + Ok(()) | |
| 721 | + } | |
| 722 | + | |
| 561 | 723 | /// The misc parameter buffers that carry rate control, resent when tuned. |
| 562 | 724 | fn rate_control_buffers(&mut self) -> Result<Vec<Buffer>> { |
| 563 | 725 | if !self.tunings_dirty { |
| 564 | 726 | return Ok(Vec::new()); |
| 565 | 727 | } |
| 566 | 728 | self.tunings_dirty = false; |
| 567 | - let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control { | |
| 568 | - RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0), | |
| 569 | - RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate), | |
| 729 | + // VBR's `bits_per_second` is the peak, not the average: libva takes | |
| 730 | + // the average as `target_percentage` of it, so an average-rate ask | |
| 731 | + // becomes a 1.5x ceiling at 66%. | |
| 732 | + let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control { | |
| 733 | + RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0), | |
| 734 | + RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate, 100, 0), | |
| 735 | + RateControlMode::VariableBitrate => { | |
| 736 | + (0, 0, 0, self.tunings.bitrate.saturating_mul(3) / 2, 66, 0) | |
| 737 | + } | |
| 738 | + RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), | |
| 570 | 739 | }; |
| 571 | 740 | let rc = RateControl { |
| 572 | 741 | bits_per_second: bits, |
| 573 | - target_percentage: 100, | |
| 742 | + target_percentage: target, | |
| 574 | 743 | window_size: 1000, |
| 575 | 744 | initial_qp, |
| 576 | 745 | min_qp, |
| 577 | 746 | max_qp, |
| 747 | + quality_factor: quality, | |
| 578 | 748 | }; |
| 579 | 749 | let mut out = vec![Buffer::from_bytes( |
| 580 | 750 | &self.context, |
| @@ -654,6 +824,25 @@ impl Encoder { | ||
| 654 | 824 | } |
| 655 | 825 | } |
| 656 | 826 | |
| 827 | +/// The surface format an encoder of `bit_depth` works in. | |
| 828 | +fn surface_spec(bit_depth: u8, size: (u32, u32)) -> SurfaceSpec { | |
| 829 | + let spec = if bit_depth == 10 { | |
| 830 | + SurfaceSpec::p010(size.0, size.1) | |
| 831 | + } else { | |
| 832 | + SurfaceSpec::nv12(size.0, size.1) | |
| 833 | + }; | |
| 834 | + spec.with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER) | |
| 835 | +} | |
| 836 | + | |
| 837 | +/// The image fourcc matching `bit_depth`. | |
| 838 | +fn fourcc(bit_depth: u8) -> u32 { | |
| 839 | + if bit_depth == 10 { | |
| 840 | + sys::VA_FOURCC_P010 | |
| 841 | + } else { | |
| 842 | + sys::VA_FOURCC_NV12 | |
| 843 | + } | |
| 844 | +} | |
| 845 | + | |
| 657 | 846 | /// Collect the bytes of a coded buffer's segment list. |
| 658 | 847 | /// |
| 659 | 848 | /// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, |
crates/ec-hw/src/params/enc.rsmodified+8 -1
| @@ -61,6 +61,11 @@ unsafe impl VaParam for PackedHeaderParameterBuffer { | ||
| 61 | 61 | const TYPE: i32 = VAEncPackedHeaderParameterBufferType; |
| 62 | 62 | } |
| 63 | 63 | |
| 64 | +/// `VA_RC_QVBR`, `va.h:1652`. Not in `ec_va::sys` because this is the only | |
| 65 | +/// crate that spends it; radeonsi advertises it in `VAConfigAttribRateControl` | |
| 66 | +/// (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8). | |
| 67 | +pub const VA_RC_QVBR: u32 = 0x0000_0400; | |
| 68 | + | |
| 64 | 69 | /// `VAEncMiscParameterRateControl`, `va.h:2492`. |
| 65 | 70 | /// |
| 66 | 71 | /// Built as words rather than as a struct because a misc parameter is submitted |
| @@ -81,6 +86,8 @@ pub struct RateControl { | ||
| 81 | 86 | pub min_qp: u32, |
| 82 | 87 | /// Maximum quantiser. |
| 83 | 88 | pub max_qp: u32, |
| 89 | + /// QVBR target quality; ignored by every other mode. | |
| 90 | + pub quality_factor: u32, | |
| 84 | 91 | } |
| 85 | 92 | |
| 86 | 93 | impl RateControl { |
| @@ -96,7 +103,7 @@ impl RateControl { | ||
| 96 | 103 | 0, // rc_flags |
| 97 | 104 | 0, // ICQ_quality_factor |
| 98 | 105 | self.max_qp, |
| 99 | - 0, // quality_factor | |
| 106 | + self.quality_factor, | |
| 100 | 107 | 0, // target_frame_size |
| 101 | 108 | 0, |
| 102 | 109 | 0, |
crates/ec-hw/tests/gpu.rsmodified+271 -1
| @@ -15,7 +15,8 @@ use std::sync::Arc; | ||
| 15 | 15 | use std::time::{Duration, Instant}; |
| 16 | 16 | |
| 17 | 17 | use ec_hw::{ |
| 18 | - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode, | |
| 18 | + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, | |
| 19 | + RateControlMode, | |
| 19 | 20 | }; |
| 20 | 21 | use ec_va::Display; |
| 21 | 22 | |
| @@ -918,6 +919,275 @@ fn av1_encode_agrees_between_two_decoders() { | ||
| 918 | 919 | } |
| 919 | 920 | } |
| 920 | 921 | |
| 922 | +// --------------------------------------------------------------------------- | |
| 923 | +// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only | |
| 924 | +// encoder does not serve his files. | |
| 925 | +// --------------------------------------------------------------------------- | |
| 926 | + | |
| 927 | +/// Film B's native 10-bit crop from the real-library manifest: `(path, seek, | |
| 928 | +/// width, height, x, y)`, the same 1920x1024 window and 00:40:00 seek the | |
| 929 | +/// software gates use (`ec-av1`'s `native_gate_clips`). | |
| 930 | +fn ten_bit_film_clip() -> Option<(PathBuf, String, u32, u32, u32, u32)> { | |
| 931 | + let manifest = | |
| 932 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); | |
| 933 | + let text = std::fs::read_to_string(manifest).ok()?; | |
| 934 | + for line in text.lines().skip(1) { | |
| 935 | + let f: Vec<&str> = line.split('\t').collect(); | |
| 936 | + if f.len() < 7 || f[2] != "av1" || f[5] != "yuv420p10le" || f[3] != "3840" { | |
| 937 | + continue; | |
| 938 | + } | |
| 939 | + let path = PathBuf::from(f[0]); | |
| 940 | + if !path.exists() { | |
| 941 | + continue; | |
| 942 | + } | |
| 943 | + let (nw, nh): (u32, u32) = (f[3].parse().ok()?, f[4].parse().ok()?); | |
| 944 | + let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); | |
| 945 | + return Some((path, "00:40:00".into(), cw, ch, (nw - cw) / 2 & !1, (nh - ch) / 2 & !1)); | |
| 946 | + } | |
| 947 | + None | |
| 948 | +} | |
| 949 | + | |
| 950 | +/// A 10-bit gradient with real dynamic range, used when the manifest has no | |
| 951 | +/// 10-bit film: 64..940 across the frame with a moving highlight, so the | |
| 952 | +/// stream is neither flat nor 8-bit content dressed up as 10. | |
| 953 | +fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { | |
| 954 | + let (w, h) = (width as usize, height as usize); | |
| 955 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 956 | + let mut f = I420_16 { | |
| 957 | + y: vec![0; w * h], | |
| 958 | + u: vec![512; cw * ch], | |
| 959 | + v: vec![512; cw * ch], | |
| 960 | + width, | |
| 961 | + height, | |
| 962 | + bit_depth: 10, | |
| 963 | + }; | |
| 964 | + for y in 0..h { | |
| 965 | + for x in 0..w { | |
| 966 | + f.y[y * w + x] = (64 + x * 700 / w + y * 176 / h) as u16; | |
| 967 | + } | |
| 968 | + } | |
| 969 | + let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); | |
| 970 | + for y in by..by + 64 { | |
| 971 | + for x in bx..bx + 64 { | |
| 972 | + f.y[y * w + x] = 940; | |
| 973 | + } | |
| 974 | + } | |
| 975 | + for y in by / 2..(by + 64) / 2 { | |
| 976 | + for x in bx / 2..(bx + 64) / 2 { | |
| 977 | + f.u[y * cw + x] = 360; | |
| 978 | + f.v[y * cw + x] = 960; | |
| 979 | + } | |
| 980 | + } | |
| 981 | + f | |
| 982 | +} | |
| 983 | + | |
| 984 | +/// Write 10-bit planes as a y4m so ffmpeg sees the same source the encoder did. | |
| 985 | +fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { | |
| 986 | + use std::io::Write; | |
| 987 | + let Ok(file) = std::fs::File::create(path) else { | |
| 988 | + return false; | |
| 989 | + }; | |
| 990 | + let mut out = std::io::BufWriter::new(file); | |
| 991 | + let (w, h) = (frames[0].width, frames[0].height); | |
| 992 | + if write!(out, "YUV4MPEG2 W{w} H{h} F{}:{} Ip A1:1 C420p10\n", fps.0, fps.1).is_err() { | |
| 993 | + return false; | |
| 994 | + } | |
| 995 | + for f in frames { | |
| 996 | + if out.write_all(b"FRAME\n").is_err() { | |
| 997 | + return false; | |
| 998 | + } | |
| 999 | + for plane in [&f.y, &f.u, &f.v] { | |
| 1000 | + let bytes: Vec<u8> = plane.iter().flat_map(|s| s.to_le_bytes()).collect(); | |
| 1001 | + if out.write_all(&bytes).is_err() { | |
| 1002 | + return false; | |
| 1003 | + } | |
| 1004 | + } | |
| 1005 | + } | |
| 1006 | + out.flush().is_ok() | |
| 1007 | +} | |
| 1008 | + | |
| 1009 | +/// The 10-bit source the 10-bit gates encode, plus the y4m every reference | |
| 1010 | +/// encoder and every PSNR reads: his own film when the manifest has it, | |
| 1011 | +/// a synthetic 10-bit gradient otherwise. The label says which — a gate that | |
| 1012 | +/// does not say what it exercised proves nothing about his library. | |
| 1013 | +fn ten_bit_source(dir: &Path, frames: u32) -> Option<(String, PathBuf, Vec<I420_16>)> { | |
| 1014 | + let y4m = dir.join("source-10bit.y4m"); | |
| 1015 | + let _ = std::fs::remove_file(&y4m); | |
| 1016 | + if let Some((path, seek, cw, ch, x, y)) = ten_bit_film_clip() { | |
| 1017 | + let ok = Command::new("ffmpeg") | |
| 1018 | + .args(["-nostdin", "-v", "error", "-y", "-ss", &seek, "-i"]) | |
| 1019 | + .arg(&path) | |
| 1020 | + .args([ | |
| 1021 | + "-frames:v", | |
| 1022 | + &frames.to_string(), | |
| 1023 | + "-vf", | |
| 1024 | + &format!("crop={cw}:{ch}:{x}:{y}"), | |
| 1025 | + "-pix_fmt", | |
| 1026 | + "yuv420p10le", | |
| 1027 | + // y4m's 10-bit chroma formats are outside its official set. | |
| 1028 | + "-strict", | |
| 1029 | + "-1", | |
| 1030 | + ]) | |
| 1031 | + .arg(&y4m) | |
| 1032 | + .status() | |
| 1033 | + .is_ok_and(|s| s.success()); | |
| 1034 | + if ok && let Some(planes) = raw_frames_16(&y4m, cw, ch, frames) { | |
| 1035 | + return Some(("film B 10-bit native crop".into(), y4m, planes)); | |
| 1036 | + } | |
| 1037 | + eprintln!("film B 10-bit extraction failed; falling back to the synthetic gradient"); | |
| 1038 | + } | |
| 1039 | + let (w, h) = (1920u32, 1024u32); | |
| 1040 | + let planes: Vec<I420_16> = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); | |
| 1041 | + write_y4m_16(&y4m, &planes, (24, 1)).then_some(("synthetic 10-bit gradient".into(), y4m, planes)) | |
| 1042 | +} | |
| 1043 | + | |
| 1044 | +/// The same pictures as 10-bit planes, for the hardware encoder's own input. | |
| 1045 | +fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option<Vec<I420_16>> { | |
| 1046 | + let out = Command::new("ffmpeg") | |
| 1047 | + .args(["-nostdin", "-v", "error", "-i"]) | |
| 1048 | + .arg(y4m) | |
| 1049 | + .args(["-pix_fmt", "yuv420p10le", "-f", "rawvideo", "-"]) | |
| 1050 | + .stderr(Stdio::null()) | |
| 1051 | + .output() | |
| 1052 | + .ok()?; | |
| 1053 | + let (w, h) = (width as usize, height as usize); | |
| 1054 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 1055 | + let frame_len = (w * h + 2 * cw * ch) * 2; | |
| 1056 | + let read = |s: &[u8]| -> Vec<u16> { | |
| 1057 | + s.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).collect() | |
| 1058 | + }; | |
| 1059 | + let mut pictures = Vec::new(); | |
| 1060 | + for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { | |
| 1061 | + let (y, rest) = chunk.split_at(w * h * 2); | |
| 1062 | + let (u, v) = rest.split_at(cw * ch * 2); | |
| 1063 | + pictures.push(I420_16 { | |
| 1064 | + y: read(y), | |
| 1065 | + u: read(u), | |
| 1066 | + v: read(v), | |
| 1067 | + width, | |
| 1068 | + height, | |
| 1069 | + bit_depth: 10, | |
| 1070 | + }); | |
| 1071 | + } | |
| 1072 | + (!pictures.is_empty()).then_some(pictures) | |
| 1073 | +} | |
| 1074 | + | |
| 1075 | +/// What ffprobe calls the stream's pixel format — for an AV1 stream that is | |
| 1076 | +/// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder | |
| 1077 | +/// that shares no code with the writer above. | |
| 1078 | +fn ffprobe_pix_fmt(path: &Path) -> Option<String> { | |
| 1079 | + let out = Command::new("ffprobe") | |
| 1080 | + .args([ | |
| 1081 | + "-v", "error", "-select_streams", "v:0", "-show_entries", | |
| 1082 | + "stream=pix_fmt", "-of", "default=nw=1:nk=1", "-f", "obu", | |
| 1083 | + ]) | |
| 1084 | + .arg(path) | |
| 1085 | + .output() | |
| 1086 | + .ok()?; | |
| 1087 | + Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) | |
| 1088 | +} | |
| 1089 | + | |
| 1090 | +/// Encode 10-bit planes and return the bitstream. | |
| 1091 | +fn encode_stream_16( | |
| 1092 | + display: &Arc<Display>, | |
| 1093 | + planes: &[I420_16], | |
| 1094 | + qp: u32, | |
| 1095 | + rate_control: RateControlMode, | |
| 1096 | +) -> Result<Vec<u8>, ec_hw::Error> { | |
| 1097 | + let (width, height) = (planes[0].width, planes[0].height); | |
| 1098 | + let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); | |
| 1099 | + config.gop_size = 60; | |
| 1100 | + config.framerate = (24, 1); | |
| 1101 | + config.rate_control = match rate_control { | |
| 1102 | + RateControlMode::ConstantQp { .. } => RateControlMode::ConstantQp { qp }, | |
| 1103 | + other => other, | |
| 1104 | + }; | |
| 1105 | + let mut encoder = Encoder::new(display, config)?; | |
| 1106 | + let mut out = Vec::new(); | |
| 1107 | + for (t, frame) in planes.iter().enumerate() { | |
| 1108 | + let coded = encoder.encode_16( | |
| 1109 | + frame, | |
| 1110 | + FrameMetadata { timestamp: t as i64, force_keyframe: false }, | |
| 1111 | + )?; | |
| 1112 | + out.extend_from_slice(&coded.data); | |
| 1113 | + } | |
| 1114 | + Ok(out) | |
| 1115 | +} | |
| 1116 | + | |
| 1117 | +/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of | |
| 1118 | +/// the stream's bit depth. | |
| 1119 | +/// | |
| 1120 | +/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the | |
| 1121 | +/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this | |
| 1122 | +/// crate packs into the sequence header, and `ec-av1`'s own decode must | |
| 1123 | +/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. | |
| 1124 | +#[test] | |
| 1125 | +fn av1_10bit_encode_agrees_between_two_decoders() { | |
| 1126 | + let Some(display) = display() else { return }; | |
| 1127 | + let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); | |
| 1128 | + let _ = std::fs::create_dir_all(&dir); | |
| 1129 | + let frames = 10u32; | |
| 1130 | + let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { | |
| 1131 | + eprintln!("skipped: no 10-bit source could be built"); | |
| 1132 | + return; | |
| 1133 | + }; | |
| 1134 | + let _ = y4m; | |
| 1135 | + let (width, height) = (planes[0].width, planes[0].height); | |
| 1136 | + let data = match encode_stream_16( | |
| 1137 | + &display, | |
| 1138 | + &planes, | |
| 1139 | + 90, | |
| 1140 | + RateControlMode::ConstantQp { qp: 90 }, | |
| 1141 | + ) { | |
| 1142 | + Ok(data) => data, | |
| 1143 | + Err(e) => { | |
| 1144 | + eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); | |
| 1145 | + return; | |
| 1146 | + } | |
| 1147 | + }; | |
| 1148 | + let path = dir.join("hw-10bit.obu"); | |
| 1149 | + std::fs::write(&path, &data).expect("write the coded stream"); | |
| 1150 | + | |
| 1151 | + assert_eq!( | |
| 1152 | + ffprobe_pix_fmt(&path).as_deref(), | |
| 1153 | + Some("yuv420p10le"), | |
| 1154 | + "the coded stream's sequence header does not say 10-bit" | |
| 1155 | + ); | |
| 1156 | + | |
| 1157 | + let ours = ec_av1::stream::decode_stream(&data) | |
| 1158 | + .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); | |
| 1159 | + assert_eq!(ours.len(), planes.len(), "ec-av1 decoded {} of {frames} frames", ours.len()); | |
| 1160 | + let peak = ours.iter().flat_map(|p| p.y.iter()).copied().max().unwrap_or(0); | |
| 1161 | + assert!(peak > 255, "every decoded luma sample fits in 8 bits (peak {peak})"); | |
| 1162 | + | |
| 1163 | + let mut reference = | |
| 1164 | + Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); | |
| 1165 | + let mut worst = f64::INFINITY; | |
| 1166 | + for (i, picture) in ours.iter().enumerate() { | |
| 1167 | + let theirs = reference | |
| 1168 | + .next(width, height) | |
| 1169 | + .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); | |
| 1170 | + let mine = Planes { | |
| 1171 | + y: picture.y.clone(), | |
| 1172 | + u: picture.u.clone(), | |
| 1173 | + v: picture.v.clone(), | |
| 1174 | + peak: 1023.0, | |
| 1175 | + }; | |
| 1176 | + let db = psnr(&mine, &theirs); | |
| 1177 | + assert!(db.is_infinite(), "frame {i}: the two decoders disagree ({db:.2} dB)"); | |
| 1178 | + let source = Planes::from_16bit(&planes[i]); | |
| 1179 | + let fidelity = psnr(&mine, &source); | |
| 1180 | + assert!(fidelity > 30.0, "frame {i}: coded {fidelity:.2} dB from the 10-bit source"); | |
| 1181 | + worst = worst.min(fidelity); | |
| 1182 | + } | |
| 1183 | + println!( | |
| 1184 | + "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ | |
| 1185 | + yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ | |
| 1186 | + sample, worst frame {worst:.2} dB from the source (10-bit domain)", | |
| 1187 | + data.len() | |
| 1188 | + ); | |
| 1189 | +} | |
| 1190 | + | |
| 921 | 1191 | /// What the GPU's AV1 costs against software, on his own content. |
| 922 | 1192 | /// |
| 923 | 1193 | /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen |