Merge branch 'lane-hwav1p010' (bc5dfe9c): 10-bit hardware AV1 encode and CBR/VBR/QVBR rate control
Browse files at this commit8 changed files +895 -35
- 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 +231 -24
- crates/ec-hw/src/lib.rs +6 -0
- crates/ec-hw/src/params/enc.rs +8 -1
- crates/ec-hw/tests/gpu.rs +547 -1
- tools/ec-bench/src/main.rs +93 -0
crates/ec-hw/src/enc/av1.rsmodified+6 -5
| @@ -49,7 +49,8 @@ pub(super) fn parameters( | |||
| 49 | let context = encoder.context(); | 49 | let context = encoder.context(); |
| 50 | let (coded_w, coded_h) = encoder.coded_size(); | 50 | let (coded_w, coded_h) = encoder.coded_size(); |
| 51 | let (width, height) = (config.width.max(1), config.height.max(1)); | 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 | let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); | 54 | let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); |
| 54 | 55 | ||
| 55 | let mut seq = EncSequenceParameterBufferAV1 { | 56 | let mut seq = EncSequenceParameterBufferAV1 { |
| @@ -59,8 +60,8 @@ pub(super) fn parameters( | |||
| 59 | intra_period: config.gop_size.max(1), | 60 | intra_period: config.gop_size.max(1), |
| 60 | ip_period: 1, | 61 | ip_period: 1, |
| 61 | bits_per_second: match config.rate_control { | 62 | bits_per_second: match config.rate_control { |
| 62 | - RateControlMode::ConstantBitrate => config.bitrate, | ||
| 63 | RateControlMode::ConstantQp { .. } => 0, | 63 | RateControlMode::ConstantQp { .. } => 0, |
| 64 | + _ => config.bitrate, | ||
| 64 | }, | 65 | }, |
| 65 | order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, | 66 | order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, |
| 66 | ..EncSequenceParameterBufferAV1::default() | 67 | ..EncSequenceParameterBufferAV1::default() |
| @@ -68,7 +69,7 @@ pub(super) fn parameters( | |||
| 68 | seq.seq_fields = seq | 69 | seq.seq_fields = seq |
| 69 | .seq_fields | 70 | .seq_fields |
| 70 | .enable_order_hint(1) | 71 | .enable_order_hint(1) |
| 71 | - .bit_depth_minus8(0) | 72 | + .bit_depth_minus8(if ten_bit { 2 } else { 0 }) |
| 72 | .subsampling_x(1) | 73 | .subsampling_x(1) |
| 73 | .subsampling_y(1); | 74 | .subsampling_y(1); |
| 74 | out.push(param_buffer(context, &seq)?); | 75 | out.push(param_buffer(context, &seq)?); |
| @@ -84,7 +85,7 @@ pub(super) fn parameters( | |||
| 84 | }; | 85 | }; |
| 85 | let base_qindex = match config.rate_control { | 86 | let base_qindex = match config.rate_control { |
| 86 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, | 87 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, |
| 87 | - RateControlMode::ConstantBitrate => 128, | 88 | + _ => 128, |
| 88 | }; | 89 | }; |
| 89 | // One reference, refreshed every picture: slot 0 holds the previous | 90 | // One reference, refreshed every picture: slot 0 holds the previous |
| 90 | // reconstruction and every ref_frame_idx points at it. | 91 | // reconstruction and every ref_frame_idx points at it. |
| @@ -142,7 +143,7 @@ pub(super) fn parameters( | |||
| 142 | height, | 143 | height, |
| 143 | seq_level_idx: level_idx, | 144 | seq_level_idx: level_idx, |
| 144 | seq_tier: 0, | 145 | seq_tier: 0, |
| 145 | - high_bitdepth: false, | 146 | + high_bitdepth: ten_bit, |
| 146 | colour: config.colour, | 147 | colour: config.colour, |
| 147 | }), | 148 | }), |
| 148 | out, | 149 | out, |
crates/ec-hw/src/enc/h264.rsmodified+2 -2
| @@ -44,8 +44,8 @@ pub(super) fn parameters( | |||
| 44 | intra_idr_period: config.gop_size.max(1), | 44 | intra_idr_period: config.gop_size.max(1), |
| 45 | ip_period: 1, | 45 | ip_period: 1, |
| 46 | bits_per_second: match config.rate_control { | 46 | bits_per_second: match config.rate_control { |
| 47 | - RateControlMode::ConstantBitrate => config.bitrate, | ||
| 48 | RateControlMode::ConstantQp { .. } => 0, | 47 | RateControlMode::ConstantQp { .. } => 0, |
| 48 | + _ => config.bitrate, | ||
| 49 | }, | 49 | }, |
| 50 | max_num_ref_frames: 1, | 50 | max_num_ref_frames: 1, |
| 51 | picture_width_in_mbs: (coded_w / 16) as u16, | 51 | picture_width_in_mbs: (coded_w / 16) as u16, |
| @@ -84,7 +84,7 @@ pub(super) fn parameters( | |||
| 84 | frame_num, | 84 | frame_num, |
| 85 | pic_init_qp: match config.rate_control { | 85 | pic_init_qp: match config.rate_control { |
| 86 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, | 86 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, |
| 87 | - RateControlMode::ConstantBitrate => 26, | 87 | + _ => 26, |
| 88 | }, | 88 | }, |
| 89 | ..EncPictureParameterBufferH264::default() | 89 | ..EncPictureParameterBufferH264::default() |
| 90 | }; | 90 | }; |
crates/ec-hw/src/enc/hevc.rsmodified+2 -2
| @@ -50,8 +50,8 @@ pub(super) fn parameters( | |||
| 50 | intra_idr_period: config.gop_size.max(1), | 50 | intra_idr_period: config.gop_size.max(1), |
| 51 | ip_period: 1, | 51 | ip_period: 1, |
| 52 | bits_per_second: match config.rate_control { | 52 | bits_per_second: match config.rate_control { |
| 53 | - RateControlMode::ConstantBitrate => config.bitrate, | ||
| 54 | RateControlMode::ConstantQp { .. } => 0, | 53 | RateControlMode::ConstantQp { .. } => 0, |
| 54 | + _ => config.bitrate, | ||
| 55 | }, | 55 | }, |
| 56 | pic_width_in_luma_samples: coded_w as u16, | 56 | pic_width_in_luma_samples: coded_w as u16, |
| 57 | pic_height_in_luma_samples: coded_h as u16, | 57 | pic_height_in_luma_samples: coded_h as u16, |
| @@ -87,7 +87,7 @@ pub(super) fn parameters( | |||
| 87 | collocated_ref_pic_index: 0xff, | 87 | collocated_ref_pic_index: 0xff, |
| 88 | pic_init_qp: match config.rate_control { | 88 | pic_init_qp: match config.rate_control { |
| 89 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, | 89 | RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, |
| 90 | - RateControlMode::ConstantBitrate => 26, | 90 | + _ => 26, |
| 91 | }, | 91 | }, |
| 92 | nal_unit_type: if keyframe { | 92 | nal_unit_type: if keyframe { |
| 93 | NAL_IDR_W_RADL | 93 | NAL_IDR_W_RADL |
crates/ec-hw/src/enc/mod.rsmodified+231 -24
| @@ -16,6 +16,20 @@ | |||
| 16 | //! driver composes no headers of its own from thin air: it parses the | 16 | //! driver composes no headers of its own from thin air: it parses the |
| 17 | //! sequence and frame header OBUs this crate packs (see `enc::headers::av1`) | 17 | //! sequence and frame header OBUs this crate packs (see `enc::headers::av1`) |
| 18 | //! and writes the stream's headers from them. | 18 | //! and writes the stream's headers from them. |
| 19 | +//! | ||
| 20 | +//! AV1 encodes at 8 or 10 bits ([`EncoderConfig::bit_depth`]); 10-bit is the | ||
| 21 | +//! depth his own library is stored at, and `gpu.rs`'s | ||
| 22 | +//! `av1_10bit_encode_agrees_between_two_decoders` proves a 10-bit stream out | ||
| 23 | +//! of this path decodes identically through `ec-av1` and libdav1d with | ||
| 24 | +//! ffprobe reading `yuv420p10le` out of the sequence header. | ||
| 25 | +//! | ||
| 26 | +//! # Rate control | ||
| 27 | +//! | ||
| 28 | +//! [`RateControlMode`] is not advisory: it is set as | ||
| 29 | +//! `VAConfigAttribRateControl` when the VA config is created, so an encoder | ||
| 30 | +//! built for CQP ignores a bitrate handed to it later. CQP, CBR, VBR and QVBR | ||
| 31 | +//! are all measured by `gpu.rs`'s `av1_encode_rate_control_lands`, which | ||
| 32 | +//! prints what each mode delivered against what it was asked for. | ||
| 19 | 33 | ||
| 20 | use std::sync::Arc; | 34 | use std::sync::Arc; |
| 21 | 35 | ||
| @@ -26,10 +40,10 @@ use ec_va::{ | |||
| 26 | }; | 40 | }; |
| 27 | 41 | ||
| 28 | use crate::error::{Error, Result}; | 42 | use crate::error::{Error, Result}; |
| 29 | -use crate::frame::I420; | 43 | +use crate::frame::{I420, I420_16}; |
| 30 | use crate::params::enc::{ | 44 | use crate::params::enc::{ |
| 31 | MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, | 45 | MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, |
| 32 | - misc_bytes, | 46 | + VA_RC_QVBR, misc_bytes, |
| 33 | }; | 47 | }; |
| 34 | use crate::params::param_buffer; | 48 | use crate::params::param_buffer; |
| 35 | use crate::pool::{PooledSurface, SurfacePool}; | 49 | use crate::pool::{PooledSurface, SurfacePool}; |
| @@ -60,6 +74,38 @@ pub enum RateControlMode { | |||
| 60 | }, | 74 | }, |
| 61 | /// Constant bitrate, the driver picking quantisers to hold it. | 75 | /// Constant bitrate, the driver picking quantisers to hold it. |
| 62 | ConstantBitrate, | 76 | ConstantBitrate, |
| 77 | + /// Variable bitrate: `bitrate` is the average asked for, and the driver | ||
| 78 | + /// may spend up to 1.5x it inside the rate window. | ||
| 79 | + VariableBitrate, | ||
| 80 | + /// Quality-defined variable bitrate: the driver holds `quality` (a | ||
| 81 | + /// quantiser-like target, lower is better quality) and treats `bitrate` | ||
| 82 | + /// as the ceiling it may not exceed. | ||
| 83 | + Qvbr { | ||
| 84 | + /// The quality factor, in the codec's quantiser scale. | ||
| 85 | + quality: u32, | ||
| 86 | + }, | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +impl RateControlMode { | ||
| 90 | + /// The `VAConfigAttribRateControl` value this mode is configured with. | ||
| 91 | + /// | ||
| 92 | + /// The attribute is set at config creation, not per picture: a driver | ||
| 93 | + /// that was configured for CQP ignores a bitrate handed to it later | ||
| 94 | + /// (which is how the AV1 path measured CQP-only until 2026-09-07). | ||
| 95 | + fn va_mode(self) -> u32 { | ||
| 96 | + match self { | ||
| 97 | + RateControlMode::ConstantQp { .. } => sys::VA_RC_CQP, | ||
| 98 | + RateControlMode::ConstantBitrate => sys::VA_RC_CBR, | ||
| 99 | + RateControlMode::VariableBitrate => sys::VA_RC_VBR, | ||
| 100 | + RateControlMode::Qvbr { .. } => VA_RC_QVBR, | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// True when the driver is told exactly which quantiser to use, so it has | ||
| 105 | + /// nothing to back-annotate into the header this crate packs. | ||
| 106 | + pub(crate) fn is_cqp(self) -> bool { | ||
| 107 | + matches!(self, RateControlMode::ConstantQp { .. }) | ||
| 108 | + } | ||
| 63 | } | 109 | } |
| 64 | 110 | ||
| 65 | /// What can be changed between frames without rebuilding the encoder. | 111 | /// What can be changed between frames without rebuilding the encoder. |
| @@ -102,6 +148,10 @@ pub struct EncoderConfig { | |||
| 102 | /// The colour description to write into the VUI, or `None` to leave it | 148 | /// The colour description to write into the VUI, or `None` to leave it |
| 103 | /// unsignalled (`video_signal_type_present_flag = 0`) as before. | 149 | /// unsignalled (`video_signal_type_present_flag = 0`) as before. |
| 104 | pub colour: Option<Colour>, | 150 | pub colour: Option<Colour>, |
| 151 | + /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). | ||
| 152 | + /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or | ||
| 153 | + /// straight from a 10-bit [`crate::Frame`]. | ||
| 154 | + pub bit_depth: u8, | ||
| 105 | } | 155 | } |
| 106 | 156 | ||
| 107 | /// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. | 157 | /// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. |
| @@ -135,9 +185,16 @@ impl EncoderConfig { | |||
| 135 | rate_control: RateControlMode::ConstantBitrate, | 185 | rate_control: RateControlMode::ConstantBitrate, |
| 136 | quality: 0, | 186 | quality: 0, |
| 137 | colour: None, | 187 | colour: None, |
| 188 | + bit_depth: 8, | ||
| 138 | } | 189 | } |
| 139 | } | 190 | } |
| 140 | 191 | ||
| 192 | + /// Encode at 10 bits (AV1 only); see [`EncoderConfig::bit_depth`]. | ||
| 193 | + pub fn ten_bit(mut self) -> EncoderConfig { | ||
| 194 | + self.bit_depth = 10; | ||
| 195 | + self | ||
| 196 | + } | ||
| 197 | + | ||
| 141 | /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. | 198 | /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. |
| 142 | pub fn colour( | 199 | pub fn colour( |
| 143 | mut self, | 200 | mut self, |
| @@ -200,6 +257,19 @@ pub struct Encoder { | |||
| 200 | impl Encoder { | 257 | impl Encoder { |
| 201 | /// Build an encoder for `config` on `display`. | 258 | /// Build an encoder for `config` on `display`. |
| 202 | pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> { | 259 | pub fn new(display: &Arc<Display>, config: EncoderConfig) -> Result<Encoder> { |
| 260 | + if config.bit_depth != 8 && config.bit_depth != 10 { | ||
| 261 | + return Err(Error::config(format!( | ||
| 262 | + "encoder bit depth {} : this crate encodes 8-bit, or 10-bit AV1", | ||
| 263 | + config.bit_depth | ||
| 264 | + ))); | ||
| 265 | + } | ||
| 266 | + if config.bit_depth == 10 && config.codec != EncCodec::Av1 { | ||
| 267 | + // Not a driver refusal: H264High and HEVCMain are 8-bit profiles | ||
| 268 | + // by definition, and this crate configures no other. | ||
| 269 | + return Err(Error::config( | ||
| 270 | + "10-bit encode is AV1 only here: the H.264 and H.265 profiles this crate configures (High, Main) are 8-bit", | ||
| 271 | + )); | ||
| 272 | + } | ||
| 203 | let profile = match config.codec { | 273 | let profile = match config.codec { |
| 204 | // High is the profile every H.264 encoder on this driver reports and | 274 | // High is the profile every H.264 encoder on this driver reports and |
| 205 | // the one a High-profile decoder expects; Main is a strict subset. | 275 | // the one a High-profile decoder expects; Main is a strict subset. |
| @@ -217,6 +287,11 @@ impl Encoder { | |||
| 217 | config.height.next_multiple_of(block), | 287 | config.height.next_multiple_of(block), |
| 218 | ); | 288 | ); |
| 219 | 289 | ||
| 290 | + let rt_format = if config.bit_depth == 10 { | ||
| 291 | + sys::VA_RT_FORMAT_YUV420_10 | ||
| 292 | + } else { | ||
| 293 | + sys::VA_RT_FORMAT_YUV420 | ||
| 294 | + }; | ||
| 220 | let caps = CapReport::probe(display)?; | 295 | let caps = CapReport::probe(display)?; |
| 221 | let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { | 296 | let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { |
| 222 | Error::unsupported( | 297 | Error::unsupported( |
| @@ -255,15 +330,18 @@ impl Encoder { | |||
| 255 | profile, | 330 | profile, |
| 256 | Entrypoint::EncSlice, | 331 | Entrypoint::EncSlice, |
| 257 | &[ | 332 | &[ |
| 258 | - ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420), | 333 | + ConfigAttrib::rt_format(rt_format), |
| 334 | + ConfigAttrib { | ||
| 335 | + type_: sys::VAConfigAttribRateControl, | ||
| 336 | + value: config.rate_control.va_mode(), | ||
| 337 | + }, | ||
| 259 | ConfigAttrib { | 338 | ConfigAttrib { |
| 260 | type_: sys::VAConfigAttribEncPackedHeaders, | 339 | type_: sys::VAConfigAttribEncPackedHeaders, |
| 261 | value: packed, | 340 | value: packed, |
| 262 | }, | 341 | }, |
| 263 | ], | 342 | ], |
| 264 | )?; | 343 | )?; |
| 265 | - let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1) | 344 | + let spec = surface_spec(config.bit_depth, coded_size); |
| 266 | - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); | ||
| 267 | // Input, reconstruction, one reference, and slack for the driver to | 345 | // Input, reconstruction, one reference, and slack for the driver to |
| 268 | // keep a submission in flight. | 346 | // keep a submission in flight. |
| 269 | let pool = SurfacePool::new(display, &spec, 8)?; | 347 | let pool = SurfacePool::new(display, &spec, 8)?; |
| @@ -309,6 +387,12 @@ impl Encoder { | |||
| 309 | 387 | ||
| 310 | /// Encode one frame and return its coded bytes. | 388 | /// Encode one frame and return its coded bytes. |
| 311 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { | 389 | pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result<CodedFrame> { |
| 390 | + if self.config.bit_depth != 8 { | ||
| 391 | + return Err(Error::config(format!( | ||
| 392 | + "encode: this encoder is configured for {} bits; call encode_16", | ||
| 393 | + self.config.bit_depth | ||
| 394 | + ))); | ||
| 395 | + } | ||
| 312 | if frame.width != self.config.width || frame.height != self.config.height { | 396 | if frame.width != self.config.width || frame.height != self.config.height { |
| 313 | return Err(Error::config(format!( | 397 | return Err(Error::config(format!( |
| 314 | "encoder configured for {}x{} was given a {}x{} frame", | 398 | "encoder configured for {}x{} was given a {}x{} frame", |
| @@ -323,6 +407,32 @@ impl Encoder { | |||
| 323 | self.encode_surface(Arc::clone(input.surface()), meta) | 407 | self.encode_surface(Arc::clone(input.surface()), meta) |
| 324 | } | 408 | } |
| 325 | 409 | ||
| 410 | + /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder. | ||
| 411 | + /// | ||
| 412 | + /// Samples are 0..1023 in the low ten bits of each `u16`, as | ||
| 413 | + /// [`crate::Frame::to_i420_16`] returns them, and are shifted into P010's | ||
| 414 | + /// top ten bits on upload. | ||
| 415 | + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result<CodedFrame> { | ||
| 416 | + if self.config.bit_depth != 10 { | ||
| 417 | + return Err(Error::config(format!( | ||
| 418 | + "encode_16: this encoder is configured for {} bits; call encode", | ||
| 419 | + self.config.bit_depth | ||
| 420 | + ))); | ||
| 421 | + } | ||
| 422 | + if frame.width != self.config.width || frame.height != self.config.height { | ||
| 423 | + return Err(Error::config(format!( | ||
| 424 | + "encoder configured for {}x{} was given a {}x{} frame", | ||
| 425 | + self.config.width, self.config.height, frame.width, frame.height | ||
| 426 | + ))); | ||
| 427 | + } | ||
| 428 | + let input = self | ||
| 429 | + .pool | ||
| 430 | + .acquire() | ||
| 431 | + .ok_or_else(|| Error::config("encode: every surface is still in use"))?; | ||
| 432 | + self.upload_16(frame, &input)?; | ||
| 433 | + self.encode_surface(Arc::clone(input.surface()), meta) | ||
| 434 | + } | ||
| 435 | + | ||
| 326 | /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, | 436 | /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, |
| 327 | /// no re-upload, just the decoder's picture handed straight to the | 437 | /// no re-upload, just the decoder's picture handed straight to the |
| 328 | /// encoder as its source. This is the path a decode-then-encode pipeline | 438 | /// encoder as its source. This is the path a decode-then-encode pipeline |
| @@ -377,7 +487,9 @@ impl Encoder { | |||
| 377 | "encode_frame: the frame was decoded on a different Display than this encoder", | 487 | "encode_frame: the frame was decoded on a different Display than this encoder", |
| 378 | )); | 488 | )); |
| 379 | } | 489 | } |
| 380 | - let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { | 490 | + let source = if frame.bit_depth != self.config.bit_depth |
| 491 | + || frame.coded_size != self.coded_size | ||
| 492 | + { | ||
| 381 | self.vpp_into_pool(frame.surface(), frame.display_size)? | 493 | self.vpp_into_pool(frame.surface(), frame.display_size)? |
| 382 | } else { | 494 | } else { |
| 383 | Arc::clone(frame.surface()) | 495 | Arc::clone(frame.surface()) |
| @@ -397,12 +509,11 @@ impl Encoder { | |||
| 397 | display_size: (u32, u32), | 509 | display_size: (u32, u32), |
| 398 | ) -> Result<Arc<Surface>> { | 510 | ) -> Result<Arc<Surface>> { |
| 399 | if self.vpp.is_none() { | 511 | if self.vpp.is_none() { |
| 400 | - let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) | 512 | + let spec = surface_spec(self.config.bit_depth, self.coded_size); |
| 401 | - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); | ||
| 402 | let display = self.context.display(); | 513 | let display = self.context.display(); |
| 403 | let surfaces = Surface::create_pool(display, &spec, 2)?; | 514 | let surfaces = Surface::create_pool(display, &spec, 2)?; |
| 404 | for s in &surfaces { | 515 | for s in &surfaces { |
| 405 | - Self::fill_black(s, self.coded_size)?; | 516 | + Self::fill_black(s, self.coded_size, self.config.bit_depth)?; |
| 406 | } | 517 | } |
| 407 | let vpp = Vpp::new( | 518 | let vpp = Vpp::new( |
| 408 | display, | 519 | display, |
| @@ -427,16 +538,26 @@ impl Encoder { | |||
| 427 | /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a | 538 | /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a |
| 428 | /// region copy's untouched padding reads the same deterministic value on | 539 | /// region copy's untouched padding reads the same deterministic value on |
| 429 | /// every driver instead of whatever the fresh allocation contained. | 540 | /// every driver instead of whatever the fresh allocation contained. |
| 430 | - fn fill_black(surface: &Arc<Surface>, size: (u32, u32)) -> Result<()> { | 541 | + fn fill_black(surface: &Arc<Surface>, size: (u32, u32), bit_depth: u8) -> Result<()> { |
| 431 | - let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; | 542 | + let mut image = Image::create(surface.display(), fourcc(bit_depth), size.0, size.1)?; |
| 432 | { | 543 | { |
| 433 | let mut mapped = image.map()?; | 544 | let mut mapped = image.map()?; |
| 434 | - if let Some(y) = mapped.plane_mut(0) { | 545 | + // P010 carries the sample in the top ten bits, so black is the |
| 435 | - y.fill(16); | 546 | + // 8-bit value shifted up by six, little endian. |
| 436 | - } | 547 | + let (luma, chroma) = (16u16 << 6, 128u16 << 6); |
| 437 | - if let Some(uv) = mapped.plane_mut(1) { | 548 | + let mut plane = |index: usize, eight: u8, ten: u16| { |
| 438 | - uv.fill(128); | 549 | + if let Some(p) = mapped.plane_mut(index) { |
| 439 | - } | 550 | + if bit_depth == 8 { |
| 551 | + p.fill(eight); | ||
| 552 | + } else { | ||
| 553 | + for sample in p.chunks_exact_mut(2) { | ||
| 554 | + sample.copy_from_slice(&ten.to_le_bytes()); | ||
| 555 | + } | ||
| 556 | + } | ||
| 557 | + } | ||
| 558 | + }; | ||
| 559 | + plane(0, 16, luma); | ||
| 560 | + plane(1, 128, chroma); | ||
| 440 | } | 561 | } |
| 441 | surface.write_from(&image, size.0, size.1)?; | 562 | surface.write_from(&image, size.0, size.1)?; |
| 442 | Ok(()) | 563 | Ok(()) |
| @@ -514,7 +635,7 @@ impl Encoder { | |||
| 514 | if self.upload.is_none() { | 635 | if self.upload.is_none() { |
| 515 | self.upload = Some(Image::create( | 636 | self.upload = Some(Image::create( |
| 516 | surface.display(), | 637 | surface.display(), |
| 517 | - sys::VA_FOURCC_NV12, | 638 | + fourcc(self.config.bit_depth), |
| 518 | self.coded_size.0, | 639 | self.coded_size.0, |
| 519 | self.coded_size.1, | 640 | self.coded_size.1, |
| 520 | )?); | 641 | )?); |
| @@ -558,23 +679,86 @@ impl Encoder { | |||
| 558 | Ok(()) | 679 | Ok(()) |
| 559 | } | 680 | } |
| 560 | 681 | ||
| 682 | + /// Upload one 10-bit frame into a surface as P010. | ||
| 683 | + /// | ||
| 684 | + /// The same reused image as [`Encoder::upload`], created P010 because the | ||
| 685 | + /// encoder's surfaces are; samples move from the low ten bits of the | ||
| 686 | + /// caller's `u16` into P010's top ten. | ||
| 687 | + fn upload_16(&mut self, frame: &I420_16, surface: &Arc<Surface>) -> Result<()> { | ||
| 688 | + if self.upload.is_none() { | ||
| 689 | + self.upload = Some(Image::create( | ||
| 690 | + surface.display(), | ||
| 691 | + fourcc(self.config.bit_depth), | ||
| 692 | + self.coded_size.0, | ||
| 693 | + self.coded_size.1, | ||
| 694 | + )?); | ||
| 695 | + } | ||
| 696 | + let image = self | ||
| 697 | + .upload | ||
| 698 | + .as_mut() | ||
| 699 | + .ok_or_else(|| Error::config("no upload image"))?; | ||
| 700 | + let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 701 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | ||
| 702 | + { | ||
| 703 | + let mut mapped = image.map()?; | ||
| 704 | + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; | ||
| 705 | + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; | ||
| 706 | + if let Some(dst) = mapped.plane_mut(0) { | ||
| 707 | + for row in 0..h { | ||
| 708 | + let d = row * y_pitch; | ||
| 709 | + if d + w * 2 > dst.len() { | ||
| 710 | + break; | ||
| 711 | + } | ||
| 712 | + for col in 0..w { | ||
| 713 | + let v = (frame.y[row * w + col] & 0x3ff) << 6; | ||
| 714 | + dst[d + col * 2..d + col * 2 + 2].copy_from_slice(&v.to_le_bytes()); | ||
| 715 | + } | ||
| 716 | + } | ||
| 717 | + } | ||
| 718 | + if let Some(dst) = mapped.plane_mut(1) { | ||
| 719 | + for row in 0..ch { | ||
| 720 | + let d = row * uv_pitch; | ||
| 721 | + if d + cw * 4 > dst.len() { | ||
| 722 | + break; | ||
| 723 | + } | ||
| 724 | + for col in 0..cw { | ||
| 725 | + let u = (frame.u[row * cw + col] & 0x3ff) << 6; | ||
| 726 | + let v = (frame.v[row * cw + col] & 0x3ff) << 6; | ||
| 727 | + dst[d + col * 4..d + col * 4 + 2].copy_from_slice(&u.to_le_bytes()); | ||
| 728 | + dst[d + col * 4 + 2..d + col * 4 + 4].copy_from_slice(&v.to_le_bytes()); | ||
| 729 | + } | ||
| 730 | + } | ||
| 731 | + } | ||
| 732 | + } | ||
| 733 | + surface.write_from(image, self.coded_size.0, self.coded_size.1)?; | ||
| 734 | + Ok(()) | ||
| 735 | + } | ||
| 736 | + | ||
| 561 | /// The misc parameter buffers that carry rate control, resent when tuned. | 737 | /// The misc parameter buffers that carry rate control, resent when tuned. |
| 562 | fn rate_control_buffers(&mut self) -> Result<Vec<Buffer>> { | 738 | fn rate_control_buffers(&mut self) -> Result<Vec<Buffer>> { |
| 563 | if !self.tunings_dirty { | 739 | if !self.tunings_dirty { |
| 564 | return Ok(Vec::new()); | 740 | return Ok(Vec::new()); |
| 565 | } | 741 | } |
| 566 | self.tunings_dirty = false; | 742 | self.tunings_dirty = false; |
| 567 | - let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control { | 743 | + // VBR's `bits_per_second` is the peak, not the average: libva takes |
| 568 | - RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0), | 744 | + // the average as `target_percentage` of it, so an average-rate ask |
| 569 | - RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate), | 745 | + // becomes a 1.5x ceiling at 66%. |
| 746 | + let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control { | ||
| 747 | + RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0), | ||
| 748 | + RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate, 100, 0), | ||
| 749 | + RateControlMode::VariableBitrate => { | ||
| 750 | + (0, 0, 0, self.tunings.bitrate.saturating_mul(3) / 2, 66, 0) | ||
| 751 | + } | ||
| 752 | + RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), | ||
| 570 | }; | 753 | }; |
| 571 | let rc = RateControl { | 754 | let rc = RateControl { |
| 572 | bits_per_second: bits, | 755 | bits_per_second: bits, |
| 573 | - target_percentage: 100, | 756 | + target_percentage: target, |
| 574 | window_size: 1000, | 757 | window_size: 1000, |
| 575 | initial_qp, | 758 | initial_qp, |
| 576 | min_qp, | 759 | min_qp, |
| 577 | max_qp, | 760 | max_qp, |
| 761 | + quality_factor: quality, | ||
| 578 | }; | 762 | }; |
| 579 | let mut out = vec![Buffer::from_bytes( | 763 | let mut out = vec![Buffer::from_bytes( |
| 580 | &self.context, | 764 | &self.context, |
| @@ -591,9 +775,13 @@ impl Encoder { | |||
| 591 | &misc_bytes(MISC_FRAME_RATE, &fr.words()), | 775 | &misc_bytes(MISC_FRAME_RATE, &fr.words()), |
| 592 | )?); | 776 | )?); |
| 593 | if bits > 0 { | 777 | if bits > 0 { |
| 778 | + // One rate window of buffer, three quarters full to start, which | ||
| 779 | + // is what ffmpeg's vaapi encoder asks for: a two-window buffer | ||
| 780 | + // let radeonsi's AV1 CBR undershoot the ask by 20% where ffmpeg's | ||
| 781 | + // own av1_vaapi undershot by 8% on the same clip (measured). | ||
| 594 | let hrd = crate::params::enc::Hrd { | 782 | let hrd = crate::params::enc::Hrd { |
| 595 | - initial_buffer_fullness: bits, | 783 | + initial_buffer_fullness: bits / 4 * 3, |
| 596 | - buffer_size: bits * 2, | 784 | + buffer_size: bits, |
| 597 | }; | 785 | }; |
| 598 | out.push(Buffer::from_bytes( | 786 | out.push(Buffer::from_bytes( |
| 599 | &self.context, | 787 | &self.context, |
| @@ -654,6 +842,25 @@ impl Encoder { | |||
| 654 | } | 842 | } |
| 655 | } | 843 | } |
| 656 | 844 | ||
| 845 | +/// The surface format an encoder of `bit_depth` works in. | ||
| 846 | +fn surface_spec(bit_depth: u8, size: (u32, u32)) -> SurfaceSpec { | ||
| 847 | + let spec = if bit_depth == 10 { | ||
| 848 | + SurfaceSpec::p010(size.0, size.1) | ||
| 849 | + } else { | ||
| 850 | + SurfaceSpec::nv12(size.0, size.1) | ||
| 851 | + }; | ||
| 852 | + spec.with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER) | ||
| 853 | +} | ||
| 854 | + | ||
| 855 | +/// The image fourcc matching `bit_depth`. | ||
| 856 | +fn fourcc(bit_depth: u8) -> u32 { | ||
| 857 | + if bit_depth == 10 { | ||
| 858 | + sys::VA_FOURCC_P010 | ||
| 859 | + } else { | ||
| 860 | + sys::VA_FOURCC_NV12 | ||
| 861 | + } | ||
| 862 | +} | ||
| 863 | + | ||
| 657 | /// Collect the bytes of a coded buffer's segment list. | 864 | /// Collect the bytes of a coded buffer's segment list. |
| 658 | /// | 865 | /// |
| 659 | /// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, | 866 | /// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, |
crates/ec-hw/src/lib.rsmodified+6 -0
| @@ -25,6 +25,12 @@ | |||
| 25 | //! call [`Frame::to_i420_16`] instead — that is the lossless path that keeps | 25 | //! call [`Frame::to_i420_16`] instead — that is the lossless path that keeps |
| 26 | //! all ten bits. | 26 | //! all ten bits. |
| 27 | //! | 27 | //! |
| 28 | +//! Encoding is 10-bit too, for AV1: `EncoderConfig::ten_bit()` allocates P010 | ||
| 29 | +//! surfaces and takes its pixels through [`Encoder::encode_16`] (or straight | ||
| 30 | +//! from a 10-bit [`Frame`], with no conversion at all). H.264 and H.265 stay | ||
| 31 | +//! 8-bit here, because High and Main — the profiles this crate configures — | ||
| 32 | +//! are 8-bit profiles. | ||
| 33 | +//! | ||
| 28 | //! # Shape | 34 | //! # Shape |
| 29 | //! | 35 | //! |
| 30 | //! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked | 36 | //! * [`params`] — the `#[repr(C)]` codec parameter buffers, each checked |
crates/ec-hw/src/params/enc.rsmodified+8 -1
| @@ -61,6 +61,11 @@ unsafe impl VaParam for PackedHeaderParameterBuffer { | |||
| 61 | const TYPE: i32 = VAEncPackedHeaderParameterBufferType; | 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 | /// `VAEncMiscParameterRateControl`, `va.h:2492`. | 69 | /// `VAEncMiscParameterRateControl`, `va.h:2492`. |
| 65 | /// | 70 | /// |
| 66 | /// Built as words rather than as a struct because a misc parameter is submitted | 71 | /// Built as words rather than as a struct because a misc parameter is submitted |
| @@ -81,6 +86,8 @@ pub struct RateControl { | |||
| 81 | pub min_qp: u32, | 86 | pub min_qp: u32, |
| 82 | /// Maximum quantiser. | 87 | /// Maximum quantiser. |
| 83 | pub max_qp: u32, | 88 | pub max_qp: u32, |
| 89 | + /// QVBR target quality; ignored by every other mode. | ||
| 90 | + pub quality_factor: u32, | ||
| 84 | } | 91 | } |
| 85 | 92 | ||
| 86 | impl RateControl { | 93 | impl RateControl { |
| @@ -96,7 +103,7 @@ impl RateControl { | |||
| 96 | 0, // rc_flags | 103 | 0, // rc_flags |
| 97 | 0, // ICQ_quality_factor | 104 | 0, // ICQ_quality_factor |
| 98 | self.max_qp, | 105 | self.max_qp, |
| 99 | - 0, // quality_factor | 106 | + self.quality_factor, |
| 100 | 0, // target_frame_size | 107 | 0, // target_frame_size |
| 101 | 0, | 108 | 0, |
| 102 | 0, | 109 | 0, |
crates/ec-hw/tests/gpu.rsmodified+547 -1
| @@ -15,7 +15,8 @@ use std::sync::Arc; | |||
| 15 | use std::time::{Duration, Instant}; | 15 | use std::time::{Duration, Instant}; |
| 16 | 16 | ||
| 17 | use ec_hw::{ | 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 | use ec_va::Display; | 21 | use ec_va::Display; |
| 21 | 22 | ||
| @@ -918,6 +919,535 @@ 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 | + // The two refusals this depth added, exercised rather than asserted in | ||
| 1158 | + // prose: 10-bit H.265 (High and Main are 8-bit profiles, so this crate | ||
| 1159 | + // never asks the driver), and 8-bit pixels handed to a 10-bit encoder. | ||
| 1160 | + let ten_bit_hevc = EncoderConfig::new(EncCodec::H265, width, height).ten_bit(); | ||
| 1161 | + assert!( | ||
| 1162 | + Encoder::new(&display, ten_bit_hevc).is_err(), | ||
| 1163 | + "a 10-bit HEVC encoder was built out of an 8-bit profile" | ||
| 1164 | + ); | ||
| 1165 | + let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); | ||
| 1166 | + config.rate_control = RateControlMode::ConstantQp { qp: 90 }; | ||
| 1167 | + let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); | ||
| 1168 | + assert!( | ||
| 1169 | + ten.encode(&source_frame(width, height, 0), FrameMetadata::default()).is_err(), | ||
| 1170 | + "8-bit pixels went into a 10-bit encoder" | ||
| 1171 | + ); | ||
| 1172 | + | ||
| 1173 | + let ours = ec_av1::stream::decode_stream(&data) | ||
| 1174 | + .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); | ||
| 1175 | + assert_eq!(ours.len(), planes.len(), "ec-av1 decoded {} of {frames} frames", ours.len()); | ||
| 1176 | + let peak = ours.iter().flat_map(|p| p.y.iter()).copied().max().unwrap_or(0); | ||
| 1177 | + assert!(peak > 255, "every decoded luma sample fits in 8 bits (peak {peak})"); | ||
| 1178 | + | ||
| 1179 | + let mut reference = | ||
| 1180 | + Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); | ||
| 1181 | + let mut worst = f64::INFINITY; | ||
| 1182 | + for (i, picture) in ours.iter().enumerate() { | ||
| 1183 | + let theirs = reference | ||
| 1184 | + .next(width, height) | ||
| 1185 | + .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); | ||
| 1186 | + let mine = Planes { | ||
| 1187 | + y: picture.y.clone(), | ||
| 1188 | + u: picture.u.clone(), | ||
| 1189 | + v: picture.v.clone(), | ||
| 1190 | + peak: 1023.0, | ||
| 1191 | + }; | ||
| 1192 | + let db = psnr(&mine, &theirs); | ||
| 1193 | + assert!(db.is_infinite(), "frame {i}: the two decoders disagree ({db:.2} dB)"); | ||
| 1194 | + let source = Planes::from_16bit(&planes[i]); | ||
| 1195 | + let fidelity = psnr(&mine, &source); | ||
| 1196 | + assert!(fidelity > 30.0, "frame {i}: coded {fidelity:.2} dB from the 10-bit source"); | ||
| 1197 | + worst = worst.min(fidelity); | ||
| 1198 | + } | ||
| 1199 | + println!( | ||
| 1200 | + "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ | ||
| 1201 | + yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ | ||
| 1202 | + sample, worst frame {worst:.2} dB from the source (10-bit domain)", | ||
| 1203 | + data.len() | ||
| 1204 | + ); | ||
| 1205 | +} | ||
| 1206 | + | ||
| 1207 | +/// Rate control: does an asked-for bitrate come back? | ||
| 1208 | +/// | ||
| 1209 | +/// CQP was the only mode the AV1 path had ever measured, because the config | ||
| 1210 | +/// was created without a `VAConfigAttribRateControl` at all — a driver | ||
| 1211 | +/// configured for CQP ignores a bitrate handed to it later. With the attribute | ||
| 1212 | +/// set, three targets are encoded in each of CBR and VBR on his own 1080p | ||
| 1213 | +/// content and the delivered rate is compared with the ask; the table is | ||
| 1214 | +/// printed either way, including the pixel format and the mode, so the row | ||
| 1215 | +/// says what it exercised. | ||
| 1216 | +#[test] | ||
| 1217 | +fn av1_encode_rate_control_lands() { | ||
| 1218 | + let Some(display) = display() else { return }; | ||
| 1219 | + let clips = real_clips(); | ||
| 1220 | + let Some((label, source)) = clips.into_iter().next() else { | ||
| 1221 | + eprintln!("skipped: no real-library manifest"); | ||
| 1222 | + return; | ||
| 1223 | + }; | ||
| 1224 | + let dir = std::env::temp_dir().join("ec-hw-av1-rc"); | ||
| 1225 | + let _ = std::fs::create_dir_all(&dir); | ||
| 1226 | + let (width, height, frames, fps) = (1920u32, 1080u32, 60u32, 30u32); | ||
| 1227 | + let y4m = dir.join("rc-source.y4m"); | ||
| 1228 | + if !extract_y4m(&source, &y4m, width, height, frames) { | ||
| 1229 | + eprintln!("skipped {label}: extraction failed"); | ||
| 1230 | + return; | ||
| 1231 | + } | ||
| 1232 | + let Some(planes) = raw_frames(&y4m, width, height, frames) else { | ||
| 1233 | + eprintln!("skipped {label}: no frames extracted"); | ||
| 1234 | + return; | ||
| 1235 | + }; | ||
| 1236 | + | ||
| 1237 | + println!("AV1 rate control on {label}, {width}x{height} yuv420p, {} frames at {fps} fps:", planes.len()); | ||
| 1238 | + // QVBR is quality-defined: `bitrate` is a ceiling it may not exceed, not | ||
| 1239 | + // a target it must reach, so asking it to land on the number would be | ||
| 1240 | + // asking for the wrong thing. | ||
| 1241 | + enum Ask { | ||
| 1242 | + Within(f64), | ||
| 1243 | + Ceiling, | ||
| 1244 | + } | ||
| 1245 | + for (mode_name, mode, ask) in [ | ||
| 1246 | + ("CBR", RateControlMode::ConstantBitrate, Ask::Within(0.15)), | ||
| 1247 | + ("VBR", RateControlMode::VariableBitrate, Ask::Within(0.25)), | ||
| 1248 | + ("QVBR", RateControlMode::Qvbr { quality: 100 }, Ask::Ceiling), | ||
| 1249 | + ] { | ||
| 1250 | + let mut table: Vec<(u32, f64, f64)> = Vec::new(); | ||
| 1251 | + for target in [2_000_000u32, 6_000_000, 12_000_000] { | ||
| 1252 | + let mut config = EncoderConfig::new(EncCodec::Av1, width, height); | ||
| 1253 | + config.framerate = (fps, 1); | ||
| 1254 | + config.gop_size = 60; | ||
| 1255 | + config.bitrate = target; | ||
| 1256 | + config.rate_control = mode; | ||
| 1257 | + let mut encoder = match Encoder::new(&display, config) { | ||
| 1258 | + Ok(encoder) => encoder, | ||
| 1259 | + Err(e) => { | ||
| 1260 | + // A mode the driver does not advertise refuses at config | ||
| 1261 | + // creation; that is the driver's answer, printed as one. | ||
| 1262 | + eprintln!(" {mode_name}: refused by the driver ({e})"); | ||
| 1263 | + break; | ||
| 1264 | + } | ||
| 1265 | + }; | ||
| 1266 | + let mut bytes = Vec::new(); | ||
| 1267 | + for (i, frame) in planes.iter().enumerate() { | ||
| 1268 | + match encoder.encode( | ||
| 1269 | + frame, | ||
| 1270 | + FrameMetadata { timestamp: i as i64, force_keyframe: false }, | ||
| 1271 | + ) { | ||
| 1272 | + Ok(coded) => bytes.extend_from_slice(&coded.data), | ||
| 1273 | + Err(e) => panic!("{mode_name} at {target} bps: encode failed ({e})"), | ||
| 1274 | + } | ||
| 1275 | + } | ||
| 1276 | + let path = dir.join(format!("{mode_name}-{target}.obu")); | ||
| 1277 | + std::fs::write(&path, &bytes).expect("write"); | ||
| 1278 | + let delivered = | ||
| 1279 | + bytes.len() as f64 * 8.0 * f64::from(fps) / f64::from(planes.len() as u32); | ||
| 1280 | + let db = ffmpeg_psnr_at(&path, &y4m, fps).unwrap_or(f64::NAN); | ||
| 1281 | + println!( | ||
| 1282 | + " {mode_name} target {:>5} kbps -> delivered {:>6.0} kbps ({:+.1}%), {db:.2} dB", | ||
| 1283 | + target / 1000, | ||
| 1284 | + delivered / 1000.0, | ||
| 1285 | + (delivered / f64::from(target) - 1.0) * 100.0 | ||
| 1286 | + ); | ||
| 1287 | + table.push((target, delivered, db)); | ||
| 1288 | + } | ||
| 1289 | + if table.len() < 3 { | ||
| 1290 | + continue; | ||
| 1291 | + } | ||
| 1292 | + match ask { | ||
| 1293 | + Ask::Within(tolerance) => { | ||
| 1294 | + for &(target, delivered, _) in &table { | ||
| 1295 | + let error = delivered / f64::from(target) - 1.0; | ||
| 1296 | + assert!( | ||
| 1297 | + error.abs() <= tolerance, | ||
| 1298 | + "{mode_name} at {target} bps delivered {delivered:.0} bps ({:+.1}%), \ | ||
| 1299 | + outside +/-{:.0}%", | ||
| 1300 | + error * 100.0, | ||
| 1301 | + tolerance * 100.0 | ||
| 1302 | + ); | ||
| 1303 | + } | ||
| 1304 | + for pair in table.windows(2) { | ||
| 1305 | + assert!( | ||
| 1306 | + pair[1].2 > pair[0].2, | ||
| 1307 | + "{mode_name}: PSNR is not monotone in the target ({:?} then {:?})", | ||
| 1308 | + pair[0], | ||
| 1309 | + pair[1] | ||
| 1310 | + ); | ||
| 1311 | + } | ||
| 1312 | + } | ||
| 1313 | + Ask::Ceiling => { | ||
| 1314 | + for &(target, delivered, _) in &table { | ||
| 1315 | + assert!( | ||
| 1316 | + delivered <= f64::from(target) * 1.1, | ||
| 1317 | + "{mode_name} at a {target} bps ceiling delivered {delivered:.0} bps" | ||
| 1318 | + ); | ||
| 1319 | + } | ||
| 1320 | + } | ||
| 1321 | + } | ||
| 1322 | + } | ||
| 1323 | +} | ||
| 1324 | + | ||
| 1325 | +/// [`ffmpeg_psnr`] with the rate pinned to `fps` on both inputs. | ||
| 1326 | +fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option<f64> { | ||
| 1327 | + let rate = fps.to_string(); | ||
| 1328 | + let out = Command::new("ffmpeg") | ||
| 1329 | + .args(["-nostdin", "-v", "info", "-f", "obu", "-r", &rate]) | ||
| 1330 | + .arg("-i") | ||
| 1331 | + .arg(coded) | ||
| 1332 | + .args(["-r", &rate]) | ||
| 1333 | + .arg("-i") | ||
| 1334 | + .arg(source) | ||
| 1335 | + .args(["-lavfi", "psnr", "-f", "null", "-"]) | ||
| 1336 | + .output() | ||
| 1337 | + .ok()?; | ||
| 1338 | + let text = String::from_utf8_lossy(&out.stderr); | ||
| 1339 | + let field = text.split("average:").nth(1)?; | ||
| 1340 | + field.split_whitespace().next()?.parse::<f64>().ok().filter(|v| v.is_finite()) | ||
| 1341 | +} | ||
| 1342 | + | ||
| 1343 | +/// What the GPU's 10-bit AV1 costs against 10-bit software, on his own film. | ||
| 1344 | +/// | ||
| 1345 | +/// The same shape as the 8-bit row, at film B's native 1920x1024 crop and | ||
| 1346 | +/// entirely in the 10-bit domain: no arm ever sees an 8-bit sample, so the | ||
| 1347 | +/// comparison is encoder against encoder rather than depth against depth. | ||
| 1348 | +/// Skips when the manifest has no 10-bit film -- a synthetic gradient would | ||
| 1349 | +/// be a BD-rate number about a gradient. | ||
| 1350 | +#[test] | ||
| 1351 | +fn av1_10bit_bd_row_vs_software() { | ||
| 1352 | + let Some(display) = display() else { return }; | ||
| 1353 | + let dir = std::env::temp_dir().join("ec-hw-av1-10bit-bd"); | ||
| 1354 | + let _ = std::fs::create_dir_all(&dir); | ||
| 1355 | + let frames = 12u32; | ||
| 1356 | + let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { | ||
| 1357 | + eprintln!("skipped: no 10-bit source could be built"); | ||
| 1358 | + return; | ||
| 1359 | + }; | ||
| 1360 | + if !label.starts_with("film") { | ||
| 1361 | + eprintln!("skipped: no 10-bit film in the real-library manifest ({label})"); | ||
| 1362 | + return; | ||
| 1363 | + } | ||
| 1364 | + let (width, height) = (planes[0].width, planes[0].height); | ||
| 1365 | + let coded = planes.len() as u32; | ||
| 1366 | + | ||
| 1367 | + let mut ours = Vec::new(); | ||
| 1368 | + for qp in [180u32, 140, 100, 60] { | ||
| 1369 | + let data = match encode_stream_16( | ||
| 1370 | + &display, | ||
| 1371 | + &planes, | ||
| 1372 | + qp, | ||
| 1373 | + RateControlMode::ConstantQp { qp }, | ||
| 1374 | + ) { | ||
| 1375 | + Ok(data) => data, | ||
| 1376 | + Err(e) => { | ||
| 1377 | + eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); | ||
| 1378 | + return; | ||
| 1379 | + } | ||
| 1380 | + }; | ||
| 1381 | + let path = dir.join(format!("hw10-{qp}.obu")); | ||
| 1382 | + std::fs::write(&path, &data).expect("write"); | ||
| 1383 | + if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { | ||
| 1384 | + ours.push((data.len() as f64 * 8.0 / f64::from(coded), db)); | ||
| 1385 | + } | ||
| 1386 | + } | ||
| 1387 | + let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] | ||
| 1388 | + .iter() | ||
| 1389 | + .filter_map(|q| { | ||
| 1390 | + software_point( | ||
| 1391 | + &dir, | ||
| 1392 | + &y4m, | ||
| 1393 | + "film-B-10bit", | ||
| 1394 | + "librav1e", | ||
| 1395 | + &[ | ||
| 1396 | + "-pix_fmt", "yuv420p10le", | ||
| 1397 | + "-rav1e-params", &format!("speed=6:quantizer={q}"), | ||
| 1398 | + "-g", "60", | ||
| 1399 | + ], | ||
| 1400 | + *q, | ||
| 1401 | + coded, | ||
| 1402 | + ) | ||
| 1403 | + }) | ||
| 1404 | + .collect(); | ||
| 1405 | + let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] | ||
| 1406 | + .iter() | ||
| 1407 | + .filter_map(|crf| { | ||
| 1408 | + software_point( | ||
| 1409 | + &dir, | ||
| 1410 | + &y4m, | ||
| 1411 | + "film-B-10bit", | ||
| 1412 | + "libaom-av1", | ||
| 1413 | + &[ | ||
| 1414 | + "-pix_fmt", "yuv420p10le", | ||
| 1415 | + "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60", | ||
| 1416 | + ], | ||
| 1417 | + *crf, | ||
| 1418 | + coded, | ||
| 1419 | + ) | ||
| 1420 | + }) | ||
| 1421 | + .collect(); | ||
| 1422 | + | ||
| 1423 | + println!("10-bit BD row: {label}, {width}x{height} yuv420p10le, {coded} frames"); | ||
| 1424 | + for (name, ladder) in [ | ||
| 1425 | + ("hw AV1 10-bit", &ours), | ||
| 1426 | + ("librav1e 10-bit", &rav1e), | ||
| 1427 | + ("libaom 10-bit", &libaom), | ||
| 1428 | + ] { | ||
| 1429 | + println!(" {name}: {ladder:?}"); | ||
| 1430 | + for pair in ladder.windows(2) { | ||
| 1431 | + assert!( | ||
| 1432 | + pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, | ||
| 1433 | + "{name}: ladder is not monotone at {pair:?}" | ||
| 1434 | + ); | ||
| 1435 | + } | ||
| 1436 | + } | ||
| 1437 | + if ours.len() >= 3 && rav1e.len() >= 3 { | ||
| 1438 | + println!( | ||
| 1439 | + " BD-rate: hw AV1 10-bit vs librav1e speed 6 10-bit: {:+.1}%", | ||
| 1440 | + bd_rate(&rav1e, &ours) * 100.0 | ||
| 1441 | + ); | ||
| 1442 | + } | ||
| 1443 | + if ours.len() >= 3 && libaom.len() >= 3 { | ||
| 1444 | + println!( | ||
| 1445 | + " BD-rate: hw AV1 10-bit vs libaom cpu-used 6 10-bit: {:+.1}%", | ||
| 1446 | + bd_rate(&libaom, &ours) * 100.0 | ||
| 1447 | + ); | ||
| 1448 | + } | ||
| 1449 | +} | ||
| 1450 | + | ||
| 921 | /// What the GPU's AV1 costs against software, on his own content. | 1451 | /// What the GPU's AV1 costs against software, on his own content. |
| 922 | /// | 1452 | /// |
| 923 | /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen | 1453 | /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen |
| @@ -1247,6 +1777,22 @@ fn av1_encode_speed() { | |||
| 1247 | } | 1777 | } |
| 1248 | } | 1778 | } |
| 1249 | } | 1779 | } |
| 1780 | + // 10-bit at the size his own films are in: the depth his library is | ||
| 1781 | + // actually stored at, so the fps that matters for a real export. | ||
| 1782 | + let planes: Vec<I420_16> = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); | ||
| 1783 | + let start = Instant::now(); | ||
| 1784 | + match encode_stream_16(&display, &planes, 90, RateControlMode::ConstantQp { qp: 90 }) { | ||
| 1785 | + Ok(data) => { | ||
| 1786 | + let secs = start.elapsed().as_secs_f64(); | ||
| 1787 | + println!( | ||
| 1788 | + "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", | ||
| 1789 | + planes.len() as f64 / secs, | ||
| 1790 | + planes.len(), | ||
| 1791 | + data.len() * 8 / planes.len() / 1000 | ||
| 1792 | + ); | ||
| 1793 | + } | ||
| 1794 | + Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), | ||
| 1795 | + } | ||
| 1250 | } | 1796 | } |
| 1251 | 1797 | ||
| 1252 | // --------------------------------------------------------------------------- | 1798 | // --------------------------------------------------------------------------- |
tools/ec-bench/src/main.rsmodified+93 -0
| @@ -43,6 +43,7 @@ fn main() { | |||
| 43 | bench_h265_encode(&mut rows); | 43 | bench_h265_encode(&mut rows); |
| 44 | bench_av1_encode(&mut rows); | 44 | bench_av1_encode(&mut rows); |
| 45 | bench_hw_av1_encode(&mut rows); | 45 | bench_hw_av1_encode(&mut rows); |
| 46 | + bench_hw_av1_encode_10bit(&mut rows); | ||
| 46 | bench_audio_decode(&mut rows); | 47 | bench_audio_decode(&mut rows); |
| 47 | bench_audio_encode(&mut rows); | 48 | bench_audio_encode(&mut rows); |
| 48 | bench_truehd(&mut rows); | 49 | bench_truehd(&mut rows); |
| @@ -400,6 +401,98 @@ fn bench_hw_av1_encode(rows: &mut Vec<Row>) { | |||
| 400 | }); | 401 | }); |
| 401 | } | 402 | } |
| 402 | 403 | ||
| 404 | +/// The same row at 10 bits, which is the depth his own AV1 library is stored | ||
| 405 | +/// at (`yuv420p10le`, both films). Skips as a row when there is no VA device, | ||
| 406 | +/// no AV1 encode entrypoint, or no source to read. | ||
| 407 | +fn bench_hw_av1_encode_10bit(rows: &mut Vec<Row>) { | ||
| 408 | + let Some(src) = real_video("av1").or_else(|| real_video("hevc")).or_else(|| real_video("h264")) | ||
| 409 | + else { | ||
| 410 | + rows.push(missing("ec-hw av1 10-bit", "encode")); | ||
| 411 | + return; | ||
| 412 | + }; | ||
| 413 | + let display = match ec_va::Display::open() { | ||
| 414 | + Ok(display) => display, | ||
| 415 | + Err(e) => { | ||
| 416 | + rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("no VA display ({e})"))); | ||
| 417 | + return; | ||
| 418 | + } | ||
| 419 | + }; | ||
| 420 | + let (w, h) = (1920u32, 1080u32); | ||
| 421 | + let raw = extract_yuv420p10(&src, w, h, 30); | ||
| 422 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | ||
| 423 | + let frame_len = ((w * h + 2 * cw * ch) * 2) as usize; | ||
| 424 | + let n = (raw.len() / frame_len) as u32; | ||
| 425 | + if n == 0 { | ||
| 426 | + rows.push(missing("ec-hw av1 10-bit", "encode")); | ||
| 427 | + return; | ||
| 428 | + } | ||
| 429 | + let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h).ten_bit(); | ||
| 430 | + cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; | ||
| 431 | + let mut enc = match ec_hw::Encoder::new(&display, cfg) { | ||
| 432 | + Ok(enc) => enc, | ||
| 433 | + Err(e) => { | ||
| 434 | + rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("driver refused ({e})"))); | ||
| 435 | + return; | ||
| 436 | + } | ||
| 437 | + }; | ||
| 438 | + let read = |s: &[u8]| -> Vec<u16> { | ||
| 439 | + s.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).collect() | ||
| 440 | + }; | ||
| 441 | + let start = Instant::now(); | ||
| 442 | + let mut coded = 0usize; | ||
| 443 | + for (i, frame) in raw.chunks_exact(frame_len).enumerate() { | ||
| 444 | + let (y, rest) = frame.split_at((w * h * 2) as usize); | ||
| 445 | + let (u, v) = rest.split_at(rest.len() / 2); | ||
| 446 | + let picture = ec_hw::I420_16 { | ||
| 447 | + y: read(y), | ||
| 448 | + u: read(u), | ||
| 449 | + v: read(v), | ||
| 450 | + width: w, | ||
| 451 | + height: h, | ||
| 452 | + bit_depth: 10, | ||
| 453 | + }; | ||
| 454 | + let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false }; | ||
| 455 | + match enc.encode_16(&picture, meta) { | ||
| 456 | + Ok(out) => coded += out.data.len(), | ||
| 457 | + Err(e) => { | ||
| 458 | + rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("encode failed ({e})"))); | ||
| 459 | + return; | ||
| 460 | + } | ||
| 461 | + } | ||
| 462 | + } | ||
| 463 | + let wall = start.elapsed().as_secs_f64(); | ||
| 464 | + let media_s = f64::from(n) / 30.0; | ||
| 465 | + rows.push(Row { | ||
| 466 | + component: "ec-hw av1 10-bit", | ||
| 467 | + direction: "encode", | ||
| 468 | + content: format!("{w}x{h} yuv420p10le, {n} frames from 00:01:00, CQP 120, {} kB", coded / 1000), | ||
| 469 | + media: format!("{media_s:.1}s"), | ||
| 470 | + wall_ms: wall * 1000.0, | ||
| 471 | + rtf: (wall > 0.0).then_some(media_s / wall), | ||
| 472 | + }); | ||
| 473 | +} | ||
| 474 | + | ||
| 475 | +/// `extract_yuv420p` at ten bits, planar 16-bit little endian, seeked a | ||
| 476 | +/// minute in: frame 0 of a film is its black leader, and a black leader codes | ||
| 477 | +/// to nothing and benchmarks nothing. | ||
| 478 | +fn extract_yuv420p10(src: &Path, w: u32, h: u32, n: u32) -> Vec<u8> { | ||
| 479 | + let out = Command::new("ffmpeg") | ||
| 480 | + .args(["-v", "error", "-ss", "60", "-i"]) | ||
| 481 | + .arg(src) | ||
| 482 | + .args([ | ||
| 483 | + "-vf", &format!("scale={w}:{h}"), | ||
| 484 | + "-frames:v", &n.to_string(), | ||
| 485 | + "-pix_fmt", "yuv420p10le", | ||
| 486 | + "-f", "rawvideo", "-", | ||
| 487 | + ]) | ||
| 488 | + .output() | ||
| 489 | + .expect("ffmpeg extract yuv420p10le"); | ||
| 490 | + if !out.status.success() { | ||
| 491 | + return Vec::new(); | ||
| 492 | + } | ||
| 493 | + out.stdout | ||
| 494 | +} | ||
| 495 | + | ||
| 403 | // --------------------------------------------------------------------------- | 496 | // --------------------------------------------------------------------------- |
| 404 | // av1: encode only -- same shape as h265. | 497 | // av1: encode only -- same shape as h265. |
| 405 | // --------------------------------------------------------------------------- | 498 | // --------------------------------------------------------------------------- |