diff --git a/crates/ec-hw/src/enc/av1.rs b/crates/ec-hw/src/enc/av1.rs index 5bd8a5fc..74763153 100644 --- a/crates/ec-hw/src/enc/av1.rs +++ b/crates/ec-hw/src/enc/av1.rs @@ -49,7 +49,8 @@ pub(super) fn parameters( let context = encoder.context(); let (coded_w, coded_h) = encoder.coded_size(); let (width, height) = (config.width.max(1), config.height.max(1)); - let cqp = matches!(config.rate_control, RateControlMode::ConstantQp { .. }); + let cqp = config.rate_control.is_cqp(); + let ten_bit = config.bit_depth == 10; let level_idx = seq_level_idx(coded_w, coded_h, config.framerate); let mut seq = EncSequenceParameterBufferAV1 { @@ -59,8 +60,8 @@ pub(super) fn parameters( intra_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { - RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, + _ => config.bitrate, }, order_hint_bits_minus_1: (av1_headers::ORDER_HINT_BITS - 1) as u8, ..EncSequenceParameterBufferAV1::default() @@ -68,7 +69,7 @@ pub(super) fn parameters( seq.seq_fields = seq .seq_fields .enable_order_hint(1) - .bit_depth_minus8(0) + .bit_depth_minus8(if ten_bit { 2 } else { 0 }) .subsampling_x(1) .subsampling_y(1); out.push(param_buffer(context, &seq)?); @@ -84,7 +85,7 @@ pub(super) fn parameters( }; let base_qindex = match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 255) as u8, - RateControlMode::ConstantBitrate => 128, + _ => 128, }; // One reference, refreshed every picture: slot 0 holds the previous // reconstruction and every ref_frame_idx points at it. @@ -142,7 +143,7 @@ pub(super) fn parameters( height, seq_level_idx: level_idx, seq_tier: 0, - high_bitdepth: false, + high_bitdepth: ten_bit, colour: config.colour, }), out, diff --git a/crates/ec-hw/src/enc/h264.rs b/crates/ec-hw/src/enc/h264.rs index 5c142b1d..e96ea460 100644 --- a/crates/ec-hw/src/enc/h264.rs +++ b/crates/ec-hw/src/enc/h264.rs @@ -44,8 +44,8 @@ pub(super) fn parameters( intra_idr_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { - RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, + _ => config.bitrate, }, max_num_ref_frames: 1, picture_width_in_mbs: (coded_w / 16) as u16, @@ -84,7 +84,7 @@ pub(super) fn parameters( frame_num, pic_init_qp: match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, - RateControlMode::ConstantBitrate => 26, + _ => 26, }, ..EncPictureParameterBufferH264::default() }; diff --git a/crates/ec-hw/src/enc/hevc.rs b/crates/ec-hw/src/enc/hevc.rs index bfe5485e..6e1f96dc 100644 --- a/crates/ec-hw/src/enc/hevc.rs +++ b/crates/ec-hw/src/enc/hevc.rs @@ -50,8 +50,8 @@ pub(super) fn parameters( intra_idr_period: config.gop_size.max(1), ip_period: 1, bits_per_second: match config.rate_control { - RateControlMode::ConstantBitrate => config.bitrate, RateControlMode::ConstantQp { .. } => 0, + _ => config.bitrate, }, pic_width_in_luma_samples: coded_w as u16, pic_height_in_luma_samples: coded_h as u16, @@ -87,7 +87,7 @@ pub(super) fn parameters( collocated_ref_pic_index: 0xff, pic_init_qp: match config.rate_control { RateControlMode::ConstantQp { qp } => qp.clamp(1, 51) as u8, - RateControlMode::ConstantBitrate => 26, + _ => 26, }, nal_unit_type: if keyframe { NAL_IDR_W_RADL diff --git a/crates/ec-hw/src/enc/mod.rs b/crates/ec-hw/src/enc/mod.rs index c0bc0fbf..b5e3ccce 100644 --- a/crates/ec-hw/src/enc/mod.rs +++ b/crates/ec-hw/src/enc/mod.rs @@ -26,10 +26,10 @@ use ec_va::{ }; use crate::error::{Error, Result}; -use crate::frame::I420; +use crate::frame::{I420, I420_16}; use crate::params::enc::{ MISC_FRAME_RATE, MISC_HRD, MISC_RATE_CONTROL, PackedHeaderParameterBuffer, RateControl, - misc_bytes, + VA_RC_QVBR, misc_bytes, }; use crate::params::param_buffer; use crate::pool::{PooledSurface, SurfacePool}; @@ -60,6 +60,38 @@ pub enum RateControlMode { }, /// Constant bitrate, the driver picking quantisers to hold it. ConstantBitrate, + /// Variable bitrate: `bitrate` is the average asked for, and the driver + /// may spend up to 1.5x it inside the rate window. + VariableBitrate, + /// Quality-defined variable bitrate: the driver holds `quality` (a + /// quantiser-like target, lower is better quality) and treats `bitrate` + /// as the ceiling it may not exceed. + Qvbr { + /// The quality factor, in the codec's quantiser scale. + quality: u32, + }, +} + +impl RateControlMode { + /// The `VAConfigAttribRateControl` value this mode is configured with. + /// + /// The attribute is set at config creation, not per picture: a driver + /// that was configured for CQP ignores a bitrate handed to it later + /// (which is how the AV1 path measured CQP-only until 2026-09-07). + fn va_mode(self) -> u32 { + match self { + RateControlMode::ConstantQp { .. } => sys::VA_RC_CQP, + RateControlMode::ConstantBitrate => sys::VA_RC_CBR, + RateControlMode::VariableBitrate => sys::VA_RC_VBR, + RateControlMode::Qvbr { .. } => VA_RC_QVBR, + } + } + + /// True when the driver is told exactly which quantiser to use, so it has + /// nothing to back-annotate into the header this crate packs. + pub(crate) fn is_cqp(self) -> bool { + matches!(self, RateControlMode::ConstantQp { .. }) + } } /// What can be changed between frames without rebuilding the encoder. @@ -102,6 +134,10 @@ pub struct EncoderConfig { /// The colour description to write into the VUI, or `None` to leave it /// unsignalled (`video_signal_type_present_flag = 0`) as before. pub colour: Option, + /// Luma bit depth: 8, or 10 for AV1 (his own library is `yuv420p10le`). + /// A 10-bit encoder takes its pixels through [`Encoder::encode_16`] or + /// straight from a 10-bit [`crate::Frame`]. + pub bit_depth: u8, } /// H.265 E.2.1 / H.264 E.1.1 colour description code points for the VUI. @@ -135,9 +171,16 @@ impl EncoderConfig { rate_control: RateControlMode::ConstantBitrate, quality: 0, colour: None, + bit_depth: 8, } } + /// Encode at 10 bits (AV1 only); see [`EncoderConfig::bit_depth`]. + pub fn ten_bit(mut self) -> EncoderConfig { + self.bit_depth = 10; + self + } + /// Set the VUI colour description; H.265 E.2.1 / H.264 E.1.1 code points. pub fn colour( mut self, @@ -200,6 +243,19 @@ pub struct Encoder { impl Encoder { /// Build an encoder for `config` on `display`. pub fn new(display: &Arc, config: EncoderConfig) -> Result { + if config.bit_depth != 8 && config.bit_depth != 10 { + return Err(Error::config(format!( + "encoder bit depth {} : this crate encodes 8-bit, or 10-bit AV1", + config.bit_depth + ))); + } + if config.bit_depth == 10 && config.codec != EncCodec::Av1 { + // Not a driver refusal: H264High and HEVCMain are 8-bit profiles + // by definition, and this crate configures no other. + return Err(Error::config( + "10-bit encode is AV1 only here: the H.264 and H.265 profiles this crate configures (High, Main) are 8-bit", + )); + } let profile = match config.codec { // High is the profile every H.264 encoder on this driver reports and // the one a High-profile decoder expects; Main is a strict subset. @@ -217,6 +273,11 @@ impl Encoder { config.height.next_multiple_of(block), ); + let rt_format = if config.bit_depth == 10 { + sys::VA_RT_FORMAT_YUV420_10 + } else { + sys::VA_RT_FORMAT_YUV420 + }; let caps = CapReport::probe(display)?; let entry = caps.entry(profile, Entrypoint::EncSlice).ok_or_else(|| { Error::unsupported( @@ -255,15 +316,18 @@ impl Encoder { profile, Entrypoint::EncSlice, &[ - ConfigAttrib::rt_format(sys::VA_RT_FORMAT_YUV420), + ConfigAttrib::rt_format(rt_format), + ConfigAttrib { + type_: sys::VAConfigAttribRateControl, + value: config.rate_control.va_mode(), + }, ConfigAttrib { type_: sys::VAConfigAttribEncPackedHeaders, value: packed, }, ], )?; - let spec = SurfaceSpec::nv12(coded_size.0, coded_size.1) - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); + let spec = surface_spec(config.bit_depth, coded_size); // Input, reconstruction, one reference, and slack for the driver to // keep a submission in flight. let pool = SurfacePool::new(display, &spec, 8)?; @@ -309,6 +373,12 @@ impl Encoder { /// Encode one frame and return its coded bytes. pub fn encode(&mut self, frame: &I420, meta: FrameMetadata) -> Result { + if self.config.bit_depth != 8 { + return Err(Error::config(format!( + "encode: this encoder is configured for {} bits; call encode_16", + self.config.bit_depth + ))); + } if frame.width != self.config.width || frame.height != self.config.height { return Err(Error::config(format!( "encoder configured for {}x{} was given a {}x{} frame", @@ -323,6 +393,32 @@ impl Encoder { self.encode_surface(Arc::clone(input.surface()), meta) } + /// Encode one 10-bit frame; the [`Encoder::encode`] of a 10-bit encoder. + /// + /// Samples are 0..1023 in the low ten bits of each `u16`, as + /// [`crate::Frame::to_i420_16`] returns them, and are shifted into P010's + /// top ten bits on upload. + pub fn encode_16(&mut self, frame: &I420_16, meta: FrameMetadata) -> Result { + if self.config.bit_depth != 10 { + return Err(Error::config(format!( + "encode_16: this encoder is configured for {} bits; call encode", + self.config.bit_depth + ))); + } + if frame.width != self.config.width || frame.height != self.config.height { + return Err(Error::config(format!( + "encoder configured for {}x{} was given a {}x{} frame", + self.config.width, self.config.height, frame.width, frame.height + ))); + } + let input = self + .pool + .acquire() + .ok_or_else(|| Error::config("encode: every surface is still in use"))?; + self.upload_16(frame, &input)?; + self.encode_surface(Arc::clone(input.surface()), meta) + } + /// Encode a decoded frame's GPU surface directly: no `to_i420` read-back, /// no re-upload, just the decoder's picture handed straight to the /// encoder as its source. This is the path a decode-then-encode pipeline @@ -377,7 +473,9 @@ impl Encoder { "encode_frame: the frame was decoded on a different Display than this encoder", )); } - let source = if frame.bit_depth == 10 || frame.coded_size != self.coded_size { + let source = if frame.bit_depth != self.config.bit_depth + || frame.coded_size != self.coded_size + { self.vpp_into_pool(frame.surface(), frame.display_size)? } else { Arc::clone(frame.surface()) @@ -397,12 +495,11 @@ impl Encoder { display_size: (u32, u32), ) -> Result> { if self.vpp.is_none() { - let spec = SurfaceSpec::nv12(self.coded_size.0, self.coded_size.1) - .with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER); + let spec = surface_spec(self.config.bit_depth, self.coded_size); let display = self.context.display(); let surfaces = Surface::create_pool(display, &spec, 2)?; for s in &surfaces { - Self::fill_black(s, self.coded_size)?; + Self::fill_black(s, self.coded_size, self.config.bit_depth)?; } let vpp = Vpp::new( display, @@ -427,16 +524,26 @@ impl Encoder { /// one-time initialisation [`Encoder::vpp_into_pool`] gives its pool so a /// region copy's untouched padding reads the same deterministic value on /// every driver instead of whatever the fresh allocation contained. - fn fill_black(surface: &Arc, size: (u32, u32)) -> Result<()> { - let mut image = Image::create(surface.display(), sys::VA_FOURCC_NV12, size.0, size.1)?; + fn fill_black(surface: &Arc, size: (u32, u32), bit_depth: u8) -> Result<()> { + let mut image = Image::create(surface.display(), fourcc(bit_depth), size.0, size.1)?; { let mut mapped = image.map()?; - if let Some(y) = mapped.plane_mut(0) { - y.fill(16); - } - if let Some(uv) = mapped.plane_mut(1) { - uv.fill(128); - } + // P010 carries the sample in the top ten bits, so black is the + // 8-bit value shifted up by six, little endian. + let (luma, chroma) = (16u16 << 6, 128u16 << 6); + let mut plane = |index: usize, eight: u8, ten: u16| { + if let Some(p) = mapped.plane_mut(index) { + if bit_depth == 8 { + p.fill(eight); + } else { + for sample in p.chunks_exact_mut(2) { + sample.copy_from_slice(&ten.to_le_bytes()); + } + } + } + }; + plane(0, 16, luma); + plane(1, 128, chroma); } surface.write_from(&image, size.0, size.1)?; Ok(()) @@ -514,7 +621,7 @@ impl Encoder { if self.upload.is_none() { self.upload = Some(Image::create( surface.display(), - sys::VA_FOURCC_NV12, + fourcc(self.config.bit_depth), self.coded_size.0, self.coded_size.1, )?); @@ -558,23 +665,86 @@ impl Encoder { Ok(()) } + /// Upload one 10-bit frame into a surface as P010. + /// + /// The same reused image as [`Encoder::upload`], created P010 because the + /// encoder's surfaces are; samples move from the low ten bits of the + /// caller's `u16` into P010's top ten. + fn upload_16(&mut self, frame: &I420_16, surface: &Arc) -> Result<()> { + if self.upload.is_none() { + self.upload = Some(Image::create( + surface.display(), + fourcc(self.config.bit_depth), + self.coded_size.0, + self.coded_size.1, + )?); + } + let image = self + .upload + .as_mut() + .ok_or_else(|| Error::config("no upload image"))?; + let (w, h) = (frame.width as usize, frame.height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + { + let mut mapped = image.map()?; + let y_pitch = mapped.pitch(0).unwrap_or(0) as usize; + let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize; + if let Some(dst) = mapped.plane_mut(0) { + for row in 0..h { + let d = row * y_pitch; + if d + w * 2 > dst.len() { + break; + } + for col in 0..w { + let v = (frame.y[row * w + col] & 0x3ff) << 6; + dst[d + col * 2..d + col * 2 + 2].copy_from_slice(&v.to_le_bytes()); + } + } + } + if let Some(dst) = mapped.plane_mut(1) { + for row in 0..ch { + let d = row * uv_pitch; + if d + cw * 4 > dst.len() { + break; + } + for col in 0..cw { + let u = (frame.u[row * cw + col] & 0x3ff) << 6; + let v = (frame.v[row * cw + col] & 0x3ff) << 6; + dst[d + col * 4..d + col * 4 + 2].copy_from_slice(&u.to_le_bytes()); + dst[d + col * 4 + 2..d + col * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + } + } + } + surface.write_from(image, self.coded_size.0, self.coded_size.1)?; + Ok(()) + } + /// The misc parameter buffers that carry rate control, resent when tuned. fn rate_control_buffers(&mut self) -> Result> { if !self.tunings_dirty { return Ok(Vec::new()); } self.tunings_dirty = false; - let (initial_qp, min_qp, max_qp, bits) = match self.config.rate_control { - RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0), - RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate), + // VBR's `bits_per_second` is the peak, not the average: libva takes + // the average as `target_percentage` of it, so an average-rate ask + // becomes a 1.5x ceiling at 66%. + let (initial_qp, min_qp, max_qp, bits, target, quality) = match self.config.rate_control { + RateControlMode::ConstantQp { qp } => (qp, qp, qp, 0, 100, 0), + RateControlMode::ConstantBitrate => (0, 0, 0, self.tunings.bitrate, 100, 0), + RateControlMode::VariableBitrate => { + (0, 0, 0, self.tunings.bitrate.saturating_mul(3) / 2, 66, 0) + } + RateControlMode::Qvbr { quality } => (0, 0, 0, self.tunings.bitrate, 100, quality), }; let rc = RateControl { bits_per_second: bits, - target_percentage: 100, + target_percentage: target, window_size: 1000, initial_qp, min_qp, max_qp, + quality_factor: quality, }; let mut out = vec![Buffer::from_bytes( &self.context, @@ -654,6 +824,25 @@ impl Encoder { } } +/// The surface format an encoder of `bit_depth` works in. +fn surface_spec(bit_depth: u8, size: (u32, u32)) -> SurfaceSpec { + let spec = if bit_depth == 10 { + SurfaceSpec::p010(size.0, size.1) + } else { + SurfaceSpec::nv12(size.0, size.1) + }; + spec.with_usage_hint(sys::VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER) +} + +/// The image fourcc matching `bit_depth`. +fn fourcc(bit_depth: u8) -> u32 { + if bit_depth == 10 { + sys::VA_FOURCC_P010 + } else { + sys::VA_FOURCC_NV12 + } +} + /// Collect the bytes of a coded buffer's segment list. /// /// `VACodedBufferSegment` is a linked list in driver memory: `size`, `bit_offset`, diff --git a/crates/ec-hw/src/params/enc.rs b/crates/ec-hw/src/params/enc.rs index ce1fa07c..ce26c0bd 100644 --- a/crates/ec-hw/src/params/enc.rs +++ b/crates/ec-hw/src/params/enc.rs @@ -61,6 +61,11 @@ unsafe impl VaParam for PackedHeaderParameterBuffer { const TYPE: i32 = VAEncPackedHeaderParameterBufferType; } +/// `VA_RC_QVBR`, `va.h:1652`. Not in `ec_va::sys` because this is the only +/// crate that spends it; radeonsi advertises it in `VAConfigAttribRateControl` +/// (probed 0x416 = CQP|CBR|VBR|QVBR on mesa 26.1.8). +pub const VA_RC_QVBR: u32 = 0x0000_0400; + /// `VAEncMiscParameterRateControl`, `va.h:2492`. /// /// Built as words rather than as a struct because a misc parameter is submitted @@ -81,6 +86,8 @@ pub struct RateControl { pub min_qp: u32, /// Maximum quantiser. pub max_qp: u32, + /// QVBR target quality; ignored by every other mode. + pub quality_factor: u32, } impl RateControl { @@ -96,7 +103,7 @@ impl RateControl { 0, // rc_flags 0, // ICQ_quality_factor self.max_qp, - 0, // quality_factor + self.quality_factor, 0, // target_frame_size 0, 0, diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index bd64d4c8..02d7f7d3 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -15,7 +15,8 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use ec_hw::{ - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, RateControlMode, + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, + RateControlMode, }; use ec_va::Display; @@ -918,6 +919,275 @@ fn av1_encode_agrees_between_two_decoders() { } } +// --------------------------------------------------------------------------- +// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only +// encoder does not serve his files. +// --------------------------------------------------------------------------- + +/// Film B's native 10-bit crop from the real-library manifest: `(path, seek, +/// width, height, x, y)`, the same 1920x1024 window and 00:40:00 seek the +/// software gates use (`ec-av1`'s `native_gate_clips`). +fn ten_bit_film_clip() -> Option<(PathBuf, String, u32, u32, u32, u32)> { + let manifest = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv"); + let text = std::fs::read_to_string(manifest).ok()?; + for line in text.lines().skip(1) { + let f: Vec<&str> = line.split('\t').collect(); + if f.len() < 7 || f[2] != "av1" || f[5] != "yuv420p10le" || f[3] != "3840" { + continue; + } + let path = PathBuf::from(f[0]); + if !path.exists() { + continue; + } + let (nw, nh): (u32, u32) = (f[3].parse().ok()?, f[4].parse().ok()?); + let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); + return Some((path, "00:40:00".into(), cw, ch, (nw - cw) / 2 & !1, (nh - ch) / 2 & !1)); + } + None +} + +/// A 10-bit gradient with real dynamic range, used when the manifest has no +/// 10-bit film: 64..940 across the frame with a moving highlight, so the +/// stream is neither flat nor 8-bit content dressed up as 10. +fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let mut f = I420_16 { + y: vec![0; w * h], + u: vec![512; cw * ch], + v: vec![512; cw * ch], + width, + height, + bit_depth: 10, + }; + for y in 0..h { + for x in 0..w { + f.y[y * w + x] = (64 + x * 700 / w + y * 176 / h) as u16; + } + } + let (bx, by) = ((t as usize * 7) % (w - 64), (t as usize * 5) % (h - 64)); + for y in by..by + 64 { + for x in bx..bx + 64 { + f.y[y * w + x] = 940; + } + } + for y in by / 2..(by + 64) / 2 { + for x in bx / 2..(bx + 64) / 2 { + f.u[y * cw + x] = 360; + f.v[y * cw + x] = 960; + } + } + f +} + +/// Write 10-bit planes as a y4m so ffmpeg sees the same source the encoder did. +fn write_y4m_16(path: &Path, frames: &[I420_16], fps: (u32, u32)) -> bool { + use std::io::Write; + let Ok(file) = std::fs::File::create(path) else { + return false; + }; + let mut out = std::io::BufWriter::new(file); + let (w, h) = (frames[0].width, frames[0].height); + if write!(out, "YUV4MPEG2 W{w} H{h} F{}:{} Ip A1:1 C420p10\n", fps.0, fps.1).is_err() { + return false; + } + for f in frames { + if out.write_all(b"FRAME\n").is_err() { + return false; + } + for plane in [&f.y, &f.u, &f.v] { + let bytes: Vec = plane.iter().flat_map(|s| s.to_le_bytes()).collect(); + if out.write_all(&bytes).is_err() { + return false; + } + } + } + out.flush().is_ok() +} + +/// The 10-bit source the 10-bit gates encode, plus the y4m every reference +/// encoder and every PSNR reads: his own film when the manifest has it, +/// a synthetic 10-bit gradient otherwise. The label says which — a gate that +/// does not say what it exercised proves nothing about his library. +fn ten_bit_source(dir: &Path, frames: u32) -> Option<(String, PathBuf, Vec)> { + let y4m = dir.join("source-10bit.y4m"); + let _ = std::fs::remove_file(&y4m); + if let Some((path, seek, cw, ch, x, y)) = ten_bit_film_clip() { + let ok = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-y", "-ss", &seek, "-i"]) + .arg(&path) + .args([ + "-frames:v", + &frames.to_string(), + "-vf", + &format!("crop={cw}:{ch}:{x}:{y}"), + "-pix_fmt", + "yuv420p10le", + // y4m's 10-bit chroma formats are outside its official set. + "-strict", + "-1", + ]) + .arg(&y4m) + .status() + .is_ok_and(|s| s.success()); + if ok && let Some(planes) = raw_frames_16(&y4m, cw, ch, frames) { + return Some(("film B 10-bit native crop".into(), y4m, planes)); + } + eprintln!("film B 10-bit extraction failed; falling back to the synthetic gradient"); + } + let (w, h) = (1920u32, 1024u32); + let planes: Vec = (0..frames).map(|t| source_frame_16(w, h, t)).collect(); + write_y4m_16(&y4m, &planes, (24, 1)).then_some(("synthetic 10-bit gradient".into(), y4m, planes)) +} + +/// The same pictures as 10-bit planes, for the hardware encoder's own input. +fn raw_frames_16(y4m: &Path, width: u32, height: u32, frames: u32) -> Option> { + let out = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i"]) + .arg(y4m) + .args(["-pix_fmt", "yuv420p10le", "-f", "rawvideo", "-"]) + .stderr(Stdio::null()) + .output() + .ok()?; + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let frame_len = (w * h + 2 * cw * ch) * 2; + let read = |s: &[u8]| -> Vec { + s.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).collect() + }; + let mut pictures = Vec::new(); + for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) { + let (y, rest) = chunk.split_at(w * h * 2); + let (u, v) = rest.split_at(cw * ch * 2); + pictures.push(I420_16 { + y: read(y), + u: read(u), + v: read(v), + width, + height, + bit_depth: 10, + }); + } + (!pictures.is_empty()).then_some(pictures) +} + +/// What ffprobe calls the stream's pixel format — for an AV1 stream that is +/// libdav1d reporting the sequence header's `high_bitdepth`, read by a decoder +/// that shares no code with the writer above. +fn ffprobe_pix_fmt(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", "error", "-select_streams", "v:0", "-show_entries", + "stream=pix_fmt", "-of", "default=nw=1:nk=1", "-f", "obu", + ]) + .arg(path) + .output() + .ok()?; + Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) +} + +/// Encode 10-bit planes and return the bitstream. +fn encode_stream_16( + display: &Arc, + planes: &[I420_16], + qp: u32, + rate_control: RateControlMode, +) -> Result, ec_hw::Error> { + let (width, height) = (planes[0].width, planes[0].height); + let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); + config.gop_size = 60; + config.framerate = (24, 1); + config.rate_control = match rate_control { + RateControlMode::ConstantQp { .. } => RateControlMode::ConstantQp { qp }, + other => other, + }; + let mut encoder = Encoder::new(display, config)?; + let mut out = Vec::new(); + for (t, frame) in planes.iter().enumerate() { + let coded = encoder.encode_16( + frame, + FrameMetadata { timestamp: t as i64, force_keyframe: false }, + )?; + out.extend_from_slice(&coded.data); + } + Ok(out) +} + +/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of +/// the stream's bit depth. +/// +/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the +/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this +/// crate packs into the sequence header, and `ec-av1`'s own decode must +/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. +#[test] +fn av1_10bit_encode_agrees_between_two_decoders() { + let Some(display) = display() else { return }; + let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); + let _ = std::fs::create_dir_all(&dir); + let frames = 10u32; + let Some((label, y4m, planes)) = ten_bit_source(&dir, frames) else { + eprintln!("skipped: no 10-bit source could be built"); + return; + }; + let _ = y4m; + let (width, height) = (planes[0].width, planes[0].height); + let data = match encode_stream_16( + &display, + &planes, + 90, + RateControlMode::ConstantQp { qp: 90 }, + ) { + Ok(data) => data, + Err(e) => { + eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); + return; + } + }; + let path = dir.join("hw-10bit.obu"); + std::fs::write(&path, &data).expect("write the coded stream"); + + assert_eq!( + ffprobe_pix_fmt(&path).as_deref(), + Some("yuv420p10le"), + "the coded stream's sequence header does not say 10-bit" + ); + + let ours = ec_av1::stream::decode_stream(&data) + .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); + assert_eq!(ours.len(), planes.len(), "ec-av1 decoded {} of {frames} frames", ours.len()); + let peak = ours.iter().flat_map(|p| p.y.iter()).copied().max().unwrap_or(0); + assert!(peak > 255, "every decoded luma sample fits in 8 bits (peak {peak})"); + + let mut reference = + Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); + let mut worst = f64::INFINITY; + for (i, picture) in ours.iter().enumerate() { + let theirs = reference + .next(width, height) + .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); + let mine = Planes { + y: picture.y.clone(), + u: picture.u.clone(), + v: picture.v.clone(), + peak: 1023.0, + }; + let db = psnr(&mine, &theirs); + assert!(db.is_infinite(), "frame {i}: the two decoders disagree ({db:.2} dB)"); + let source = Planes::from_16bit(&planes[i]); + let fidelity = psnr(&mine, &source); + assert!(fidelity > 30.0, "frame {i}: coded {fidelity:.2} dB from the 10-bit source"); + worst = worst.min(fidelity); + } + println!( + "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ + yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ + sample, worst frame {worst:.2} dB from the source (10-bit domain)", + data.len() + ); +} + /// What the GPU's AV1 costs against software, on his own content. /// /// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen