From ad62b2306bba3fa5c544a28f68453a47feacd67d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 15:18:46 +0300 Subject: [PATCH] S8: encoder analysis heuristics (mean_gradient, chroma offset, fast knobs, lambda) move to enc/analysis.rs --- crates/ec-h264/src/enc/analysis.rs | 141 ++++++++++++++++++++++++++++ crates/ec-h264/src/enc/mod.rs | 142 +---------------------------- 2 files changed, 144 insertions(+), 139 deletions(-) create mode 100644 crates/ec-h264/src/enc/analysis.rs diff --git a/crates/ec-h264/src/enc/analysis.rs b/crates/ec-h264/src/enc/analysis.rs new file mode 100644 index 00000000..dcf4e226 --- /dev/null +++ b/crates/ec-h264/src/enc/analysis.rs @@ -0,0 +1,141 @@ +use super::mb; +use super::mb::Source; + +/// Everything one band worker needs. +/// Mean absolute neighbour difference of one plane, horizontal and vertical +/// averaged, over the `w` by `h` samples at the top left of `plane`. +pub(super) fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 { + let (mut sum, mut n) = (0u64, 0u64); + for y in 0..h { + let row = &plane[y * stride..y * stride + w]; + for x in 1..w { + sum += u64::from(row[x].abs_diff(row[x - 1])); + n += 1; + } + if y > 0 { + let prev = &plane[(y - 1) * stride..(y - 1) * stride + w]; + for x in 0..w { + sum += u64::from(row[x].abs_diff(prev[x])); + n += 1; + } + } + } + if n == 0 { 0.0 } else { sum as f64 / n as f64 } +} + +/// `chroma_qp_index_offset` for a source, from how textured its chroma is +/// relative to its luma. +/// +/// A negative offset spends bits on chroma that luma would otherwise take. +/// That pays when the chroma planes are flat — screen capture, phone video, +/// anything with large constant-hue areas — because their few edges are what +/// the eye reads, and it loses on film, whose chroma carries as much detail as +/// its luma and whose luma is the better place for the same bits. The +/// separating statistic is the mean absolute sample gradient of the chroma +/// planes over that of luma, measured on the first source picture. +/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over +/// nine clips of the user's library, offset 0 against offset -2: +/// +/// ```text +/// chroma/luma gradient 0 -> -2 (dB) +/// 0.013 +0.019 +/// 0.092 +0.181 +/// 0.094 +0.228 +/// 0.098 +0.014 +/// 0.118 +0.081 +/// 0.122 +0.045 +/// 0.128 +0.065 +/// 0.286 +0.011 +/// 0.911 -0.158 +/// ``` +/// +/// Every clip whose chroma is flatter than its luma gains; the one film clip, +/// whose chroma gradient is nearly its luma's, loses. The threshold sits in +/// the middle of the gap the data leaves. +pub(super) fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w / 2, h / 2); + let luma = mean_gradient(&src.y, src.stride, w, h); + if luma <= 0.0 { + return 0; + } + let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch) + + mean_gradient(&src.v, src.c_stride, cw, ch)) + / 2.0; + if chroma / luma < CHROMA_FLAT_RATIO { + CHROMA_FLAT_QP_OFFSET + } else { + 0 + } +} + +/// Chroma is "flat" below this share of the luma gradient. +pub(super) const CHROMA_FLAT_RATIO: f64 = 0.5; + +/// The offset flat chroma is coded with. +pub(super) const CHROMA_FLAT_QP_OFFSET: i32 = -2; + +/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE` +/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as +/// sweep overrides. Read once per band, so they cost nothing per macroblock. +pub(super) fn fast_knobs() -> mb::FastKnobs { + let mut k = mb::FastKnobs::default(); + if let Some(g) = std::env::var("EC_H264_INTRA_GATE") + .ok() + .and_then(|v| v.parse().ok()) + { + k.intra_gate = g; + } + if let Ok(v) = std::env::var("EC_H264_SKIP_I8") { + k.skip_i8 = v != "0"; + } + if let Some(v) = std::env::var("EC_H264_ME_SUB") + .ok() + .and_then(|v| v.parse().ok()) + { + k.me_sub = v; + } + if let Ok(v) = std::env::var("EC_H264_ME_SATD") { + k.me_satd = v != "0"; + } + if let Some(v) = std::env::var("EC_H264_INTER_TX") + .ok() + .and_then(|v| v.parse().ok()) + { + k.inter_tx = v; + } + if let Ok(v) = std::env::var("EC_H264_LAZY_I16") { + k.lazy_i16 = v != "0"; + } + if let Some(v) = std::env::var("EC_H264_EARLY_SKIP") + .ok() + .and_then(|v| v.parse().ok()) + { + k.early_skip = v; + } + if let Some(v) = std::env::var("EC_H264_TX8_NZ") + .ok() + .and_then(|v| v.parse().ok()) + { + k.tx8_nz_limit = v; + } + if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") { + k.p_skip_i8 = v != "0"; + } + k +} + +/// Standard Lagrangian multiplier in the squared-error domain. +pub(crate) fn lambda_ssd(qp: i32) -> f64 { + 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() +} + +/// Lagrangian multiplier. Production uses the established byte-stable ladder; +/// the ablation feature can select the standard squared-error multiplier. +pub(super) fn lambda_for(qp: i32, standard: bool) -> f64 { + if standard { + lambda_ssd(qp) + } else { + (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0) + } +} diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 58c95232..f345ba64 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -20,6 +20,7 @@ //! once over the whole picture, across slice boundaries exactly as a decoder //! runs it. No `unsafe`, no shared mutable state at all. +mod analysis; mod cabac_enc; mod entropy; mod headers; @@ -41,6 +42,7 @@ use crate::transform::{LevelScale4x4, LevelScale8x8}; use entropy::EncEntropy; use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; +use analysis::{chroma_qp_offset_for_source, fast_knobs, lambda_for, lambda_ssd}; use mb::{MbEnc, Source, encode_mb}; use pool::BandPool; use rc::RateControl; @@ -512,80 +514,6 @@ impl Encoder { } } -/// Everything one band worker needs. -/// Mean absolute neighbour difference of one plane, horizontal and vertical -/// averaged, over the `w` by `h` samples at the top left of `plane`. -fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 { - let (mut sum, mut n) = (0u64, 0u64); - for y in 0..h { - let row = &plane[y * stride..y * stride + w]; - for x in 1..w { - sum += u64::from(row[x].abs_diff(row[x - 1])); - n += 1; - } - if y > 0 { - let prev = &plane[(y - 1) * stride..(y - 1) * stride + w]; - for x in 0..w { - sum += u64::from(row[x].abs_diff(prev[x])); - n += 1; - } - } - } - if n == 0 { 0.0 } else { sum as f64 / n as f64 } -} - -/// `chroma_qp_index_offset` for a source, from how textured its chroma is -/// relative to its luma. -/// -/// A negative offset spends bits on chroma that luma would otherwise take. -/// That pays when the chroma planes are flat — screen capture, phone video, -/// anything with large constant-hue areas — because their few edges are what -/// the eye reads, and it loses on film, whose chroma carries as much detail as -/// its luma and whose luma is the better place for the same bits. The -/// separating statistic is the mean absolute sample gradient of the chroma -/// planes over that of luma, measured on the first source picture. -/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over -/// nine clips of the user's library, offset 0 against offset -2: -/// -/// ```text -/// chroma/luma gradient 0 -> -2 (dB) -/// 0.013 +0.019 -/// 0.092 +0.181 -/// 0.094 +0.228 -/// 0.098 +0.014 -/// 0.118 +0.081 -/// 0.122 +0.045 -/// 0.128 +0.065 -/// 0.286 +0.011 -/// 0.911 -0.158 -/// ``` -/// -/// Every clip whose chroma is flatter than its luma gains; the one film clip, -/// whose chroma gradient is nearly its luma's, loses. The threshold sits in -/// the middle of the gap the data leaves. -fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 { - let (w, h) = (width as usize, height as usize); - let (cw, ch) = (w / 2, h / 2); - let luma = mean_gradient(&src.y, src.stride, w, h); - if luma <= 0.0 { - return 0; - } - let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch) - + mean_gradient(&src.v, src.c_stride, cw, ch)) - / 2.0; - if chroma / luma < CHROMA_FLAT_RATIO { - CHROMA_FLAT_QP_OFFSET - } else { - 0 - } -} - -/// Chroma is "flat" below this share of the luma gradient. -const CHROMA_FLAT_RATIO: f64 = 0.5; - -/// The offset flat chroma is coded with. -const CHROMA_FLAT_QP_OFFSET: i32 = -2; - /// What every band of one picture reads. The workers share it through an `Arc`. struct FrameShared { sps: Sps, @@ -740,71 +668,6 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { w.finish(job.slice_type == SliceType::P) } -/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE` -/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as -/// sweep overrides. Read once per band, so they cost nothing per macroblock. -fn fast_knobs() -> mb::FastKnobs { - let mut k = mb::FastKnobs::default(); - if let Some(g) = std::env::var("EC_H264_INTRA_GATE") - .ok() - .and_then(|v| v.parse().ok()) - { - k.intra_gate = g; - } - if let Ok(v) = std::env::var("EC_H264_SKIP_I8") { - k.skip_i8 = v != "0"; - } - if let Some(v) = std::env::var("EC_H264_ME_SUB") - .ok() - .and_then(|v| v.parse().ok()) - { - k.me_sub = v; - } - if let Ok(v) = std::env::var("EC_H264_ME_SATD") { - k.me_satd = v != "0"; - } - if let Some(v) = std::env::var("EC_H264_INTER_TX") - .ok() - .and_then(|v| v.parse().ok()) - { - k.inter_tx = v; - } - if let Ok(v) = std::env::var("EC_H264_LAZY_I16") { - k.lazy_i16 = v != "0"; - } - if let Some(v) = std::env::var("EC_H264_EARLY_SKIP") - .ok() - .and_then(|v| v.parse().ok()) - { - k.early_skip = v; - } - if let Some(v) = std::env::var("EC_H264_TX8_NZ") - .ok() - .and_then(|v| v.parse().ok()) - { - k.tx8_nz_limit = v; - } - if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") { - k.p_skip_i8 = v != "0"; - } - k -} - -/// Standard Lagrangian multiplier in the squared-error domain. -pub(crate) fn lambda_ssd(qp: i32) -> f64 { - 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() -} - -/// Lagrangian multiplier. Production uses the established byte-stable ladder; -/// the ablation feature can select the standard squared-error multiplier. -fn lambda_for(qp: i32, standard: bool) -> f64 { - if standard { - lambda_ssd(qp) - } else { - (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0) - } -} - /// Split `mb_h` macroblock rows into at most `n` contiguous bands. fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { let n = n.clamp(1, mb_h); @@ -927,6 +790,7 @@ fn rational_timing(fps: f64) -> (u32, u32) { #[cfg(test)] mod tests { use super::*; + use super::analysis::CHROMA_FLAT_QP_OFFSET; #[test] fn bands_cover_every_row_once() {