use crate::Effort;
use crate::encoder::Source;
pub const CELL_LOG2: u8 = 5;
const CELL: u32 = 1 << CELL_LOG2;
pub const NUM_CLASSES: usize = 7;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RegionClass {
#[default]
Flat,
Gradient,
ChromaCritical,
Noisy,
Texture,
DirectionalEdge,
TextLike,
}
impl RegionClass {
#[inline]
pub fn index(self) -> usize {
self as usize
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct CellAnalysis {
pub class: RegionClass,
pub variance: u32,
pub edge_density_q8: u16,
pub flat_ratio_q8: u16,
pub orient_entropy_q8: u16,
pub dir_dominance_q8: u16,
pub noise: u16,
pub chroma_activity: u16,
pub luma_mean: u16,
pub cb_mean: u16,
pub cr_mean: u16,
pub global_contrast_q8: u16,
pub center_surround_q8: u16,
pub importance_q8: u16,
}
pub struct AnalysisMaps {
cells_x: u32,
cells_y: u32,
cells: Vec<CellAnalysis>,
frame_mean_log2var: f32,
frame_min_log2var: f32,
frame_max_log2var: f32,
frame_mean_activity: f32,
autovar_chroma_weight: f32,
autovar_avg_adj: f32,
autovar_avg_adj_final: f32,
}
pub struct AqOffsetMap {
cells_x: u32,
cells_y: u32,
cell_log2: u8,
offsets: Vec<i8>,
}
#[derive(Clone, Copy, Debug)]
pub struct SearchPolicy {
pub angular_prune: Option<bool>,
pub allow_early_term: bool,
pub luma_rd_bias: i8,
pub chroma_rd_bias: i8,
pub force_leaf: bool,
pub prefer_split: bool,
pub force_split: bool,
pub rmd_prune_factor: Option<f64>,
}
pub const INERT: SearchPolicy = SearchPolicy {
angular_prune: None,
allow_early_term: true,
luma_rd_bias: 0,
chroma_rd_bias: 0,
force_leaf: false,
prefer_split: false,
force_split: false,
rmd_prune_factor: None,
};
pub fn external_aq_map_requested() -> bool {
std::env::var("BPG_AQ_OFFSET_MAP")
.ok()
.map(|s| !s.trim().is_empty() && s.trim() != "0")
.unwrap_or(false)
}
pub fn load_external_aq_offset_map(width: u32, height: u32, qg_log2: u8) -> Option<AqOffsetMap> {
let path = std::env::var("BPG_AQ_OFFSET_MAP").ok()?;
let path = path.trim();
if path.is_empty() || path == "0" {
return None;
}
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(err) => {
eprintln!("BPG_AQ_OFFSET_MAP: could not read {path}: {err}");
return None;
}
};
let cell = 1u32 << qg_log2;
let cells_x = width.div_ceil(cell).max(1);
let cells_y = height.div_ceil(cell).max(1);
let mut offsets = vec![0i8; (cells_x * cells_y) as usize];
let mut used = 0u32;
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut fields = line
.split(|c: char| c == ',' || c.is_ascii_whitespace())
.filter(|s| !s.is_empty());
let Some(x) = fields.next().and_then(|s| s.parse::<i32>().ok()) else {
continue;
};
let Some(y) = fields.next().and_then(|s| s.parse::<i32>().ok()) else {
continue;
};
let Some(offset) = fields.next().and_then(|s| s.parse::<i32>().ok()) else {
continue;
};
if x < 0 || y < 0 {
continue;
}
let cx = ((x as u32) >> qg_log2).min(cells_x.saturating_sub(1));
let cy = ((y as u32) >> qg_log2).min(cells_y.saturating_sub(1));
offsets[(cy * cells_x + cx) as usize] = offset.clamp(-12, 12) as i8;
used += 1;
}
if used == 0 {
eprintln!("BPG_AQ_OFFSET_MAP: no usable x,y,offset rows in {path}");
None
} else {
Some(AqOffsetMap {
cells_x,
cells_y,
cell_log2: qg_log2,
offsets,
})
}
}
const FLAT_VAR: u32 = 12; const FLAT_EDGE_Q8: u16 = 13; const GRAD_EDGE_Q8: u16 = 26; const EDGE_DENSE_Q8: u16 = 38; const TEXT_EDGE_Q8: u16 = 64; const DIR_DOMINANT_Q8: u16 = 128; const AXIS_ALIGNED_Q8: u16 = 160; const LOW_ENTROPY_Q8: u16 = 110; const HIGH_ENTROPY_Q8: u16 = 150; const TEXTURE_VAR: u32 = 64;
const NOISE_HI: u16 = 7;
const CHROMA_HI: u16 = 96;
pub fn analyze(width: u32, height: u32, bit_depth: u8, cat: u8, src: Source<'_>) -> AnalysisMaps {
let cells_x = width.div_ceil(CELL).max(1);
let cells_y = height.div_ceil(CELL).max(1);
let mut cells = Vec::with_capacity((cells_x * cells_y) as usize);
let shift = (bit_depth - 8) as u32;
let luma_stride = width as usize;
let lum = |x: i64, y: i64| -> i32 {
let sx = x.clamp(0, width as i64 - 1) as usize;
let sy = y.clamp(0, height as i64 - 1) as usize;
(src.y[sy * luma_stride + sx] >> shift) as i32
};
let (cw, ch) = chroma_dims(width, height, cat);
let (cell_cw, cell_ch) = chroma_cell_size(cat);
for cy in 0..cells_y {
for cx in 0..cells_x {
let x0 = (cx * CELL) as i64;
let y0 = (cy * CELL) as i64;
cells.push(analyze_cell(
x0, y0, width, height, &lum, src, cat, cw, ch, cx, cy, cell_cw, cell_ch, shift,
));
}
}
fill_contextual_features(&mut cells, cells_x, cells_y);
let autovar_chroma_weight = autovar_chroma_weight(cat);
let (
frame_mean_log2var,
frame_min_log2var,
frame_max_log2var,
frame_mean_activity,
autovar_avg_adj,
autovar_avg_adj_final,
) = if cells.is_empty() {
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
} else {
let n = cells.len() as f32;
let mut sum_lv = 0.0f32;
let mut sum_act = 0.0f32;
let mut min_lv = f32::INFINITY;
let mut max_lv = f32::NEG_INFINITY;
let mut sum_adj = 0.0f32;
let mut sum_adj_pow2 = 0.0f32;
for c in &cells {
let lv = ((1 + c.variance) as f32).log2();
sum_lv += lv;
sum_act += combined_activity(c.variance, c.chroma_activity);
min_lv = min_lv.min(lv);
max_lv = max_lv.max(lv);
let adj = autovar_qp_adj0(c.variance, c.chroma_activity, autovar_chroma_weight);
sum_adj += adj;
sum_adj_pow2 += adj * adj;
}
let avg_adj = sum_adj / n;
let avg_adj_pow2 = sum_adj_pow2 / n;
let avg_adj_final = avg_adj - 0.5 * (avg_adj_pow2 - AUTOVAR_MODE_TWO_CONST) / avg_adj;
(
sum_lv / n,
min_lv,
max_lv,
sum_act / n,
avg_adj,
avg_adj_final,
)
};
AnalysisMaps {
cells_x,
cells_y,
cells,
frame_mean_log2var,
frame_min_log2var,
frame_max_log2var,
frame_mean_activity,
autovar_chroma_weight,
autovar_avg_adj,
autovar_avg_adj_final,
}
}
fn fill_contextual_features(cells: &mut [CellAnalysis], cells_x: u32, cells_y: u32) {
let n = cells.len().max(1) as i64;
let (mut sy, mut scb, mut scr) = (0i64, 0i64, 0i64);
for c in cells.iter() {
sy += c.luma_mean as i64;
scb += c.cb_mean as i64;
scr += c.cr_mean as i64;
}
let (gy, gcb, gcr) = (sy / n, scb / n, scr / n);
let cx_n = cells_x as usize;
let cy_n = cells_y as usize;
let mean_of = |c: &CellAnalysis| (c.luma_mean as i64, c.cb_mean as i64, c.cr_mean as i64);
for gy_idx in 0..cy_n {
for gx_idx in 0..cx_n {
let i = gy_idx * cx_n + gx_idx;
let (ly, lcb, lcr) = mean_of(&cells[i]);
let global = (ly - gy).abs() + (lcb - gcb).abs() + (lcr - gcr).abs();
let (mut ny, mut ncb, mut ncr, mut cnt) = (0i64, 0i64, 0i64, 0i64);
for dy in -1i64..=1 {
for dx in -1i64..=1 {
if dx == 0 && dy == 0 {
continue;
}
let nx = gx_idx as i64 + dx;
let nyi = gy_idx as i64 + dy;
if nx < 0 || nyi < 0 || nx >= cx_n as i64 || nyi >= cy_n as i64 {
continue;
}
let (vy, vcb, vcr) = mean_of(&cells[nyi as usize * cx_n + nx as usize]);
ny += vy;
ncb += vcb;
ncr += vcr;
cnt += 1;
}
}
let surround = if cnt > 0 {
((ly - ny / cnt).abs() + (lcb - ncb / cnt).abs() + (lcr - ncr / cnt).abs()) as i64
} else {
0
};
let to_q8 = |v: i64| -> u16 { (v * 2).clamp(0, 256) as u16 };
cells[i].global_contrast_q8 = to_q8(global);
cells[i].center_surround_q8 = to_q8(surround);
cells[i].importance_q8 = compute_importance(&cells[i]);
}
}
}
pub fn aq_qp_offset(importance_q8: u16) -> i32 {
let t = (importance_q8.min(256) as f64) / 256.0;
(1.0 + (1.0 - t) * 7.0).round() as i32 }
pub const VAR_AQ_CLAMP: f32 = 8.0;
pub const CHROMA_AQ_WEIGHT: f32 = 0.35;
#[inline]
fn combined_activity(luma_var: u32, chroma_activity: u16) -> f32 {
let luma = ((1 + luma_var) as f32).log2();
let chroma = ((1 + chroma_activity as u32) as f32).log2();
luma + CHROMA_AQ_WEIGHT * chroma
}
pub fn aq_qp_offset_variance(
variance: u32,
frame_mean_log2var: f32,
strength: f32,
perceptual: bool,
clamp: f32,
) -> i32 {
let log2var = ((1 + variance) as f32).log2();
let mut adj = strength * (log2var - frame_mean_log2var);
if !perceptual {
adj = -adj;
}
adj.round().clamp(-clamp, clamp) as i32
}
pub fn aq_qp_offset_chroma(
luma_var: u32,
chroma_activity: u16,
frame_mean_activity: f32,
strength: f32,
clamp: f32,
) -> i32 {
let activity = combined_activity(luma_var, chroma_activity);
let adj = strength * (activity - frame_mean_activity);
adj.round().clamp(-clamp, clamp) as i32
}
pub fn aq_qp_offset_positive(
luma_var: u32,
frame_min_log2var: f32,
frame_max_log2var: f32,
clamp: f32,
) -> i32 {
let log2var = ((1 + luma_var) as f32).log2();
let span = frame_max_log2var - frame_min_log2var;
let rank = if span <= f32::EPSILON {
0.0
} else {
((log2var - frame_min_log2var) / span).clamp(0.0, 1.0)
};
(1.0 + 7.0 * rank).round().clamp(1.0, clamp.max(1.0)) as i32
}
pub const AUTOVAR_MODE_TWO_CONST: f32 = 11.0;
fn autovar_chroma_weight(cat: u8) -> f32 {
match cat {
0 => 0.0,
1 => 64.0,
2 => 128.0,
_ => 256.0,
}
}
#[inline]
fn autovar_qp_adj0(luma_var: u32, chroma_activity: u16, chroma_weight: f32) -> f32 {
let energy = 256.0 * luma_var as f32 + chroma_weight * chroma_activity as f32;
(energy + 1.0).powf(0.1)
}
pub fn aq_qp_offset_autovar(
qp_adj0: f32,
avg_adj: f32,
avg_adj_final: f32,
strength: f32,
biased: bool,
clamp: f32,
) -> i32 {
if avg_adj <= 0.0 || qp_adj0 <= 0.0 {
return 0; }
let mut adj = strength * avg_adj * (qp_adj0 - avg_adj_final);
if biased {
adj += strength * (1.0 - AUTOVAR_MODE_TWO_CONST / (qp_adj0 * qp_adj0));
}
adj.round().clamp(-clamp, clamp) as i32
}
fn compute_importance(c: &CellAnalysis) -> u16 {
let edge = c.edge_density_q8 as i32;
let dir_bonus = match c.class {
RegionClass::DirectionalEdge | RegionClass::TextLike => 96,
RegionClass::Texture => 32,
_ => 0,
};
let contrast = c.global_contrast_q8.max(c.center_surround_q8) as i32;
let noise_pen = if c.noise as i32 >= NOISE_HI as i32 {
96
} else {
0
};
(edge / 2 + contrast + dir_bonus - noise_pen).clamp(0, 256) as u16
}
#[allow(clippy::too_many_arguments)]
fn analyze_cell(
x0: i64,
y0: i64,
width: u32,
height: u32,
lum: &impl Fn(i64, i64) -> i32,
src: Source<'_>,
cat: u8,
cw: u32,
ch: u32,
cx: u32,
cy: u32,
cell_cw: u32,
cell_ch: u32,
shift: u32,
) -> CellAnalysis {
let x1 = (x0 + CELL as i64).min(width as i64);
let y1 = (y0 + CELL as i64).min(height as i64);
let n = ((x1 - x0) * (y1 - y0)).max(1) as i64;
let mut sum: i64 = 0;
let mut sum_sq: i64 = 0;
let mut edge_count: i64 = 0;
let mut flat_count: i64 = 0;
let mut noise_sum: i64 = 0;
let mut weak_count: i64 = 0;
let mut dir = [0i64; 4];
for y in y0..y1 {
for x in x0..x1 {
let c = lum(x, y);
sum += c as i64;
sum_sq += (c * c) as i64;
let tl = lum(x - 1, y - 1);
let tc = lum(x, y - 1);
let tr = lum(x + 1, y - 1);
let ml = lum(x - 1, y);
let mr = lum(x + 1, y);
let bl = lum(x - 1, y + 1);
let bc = lum(x, y + 1);
let br = lum(x + 1, y + 1);
let gx = (tr + 2 * mr + br) - (tl + 2 * ml + bl);
let gy = (bl + 2 * bc + br) - (tl + 2 * tc + tr);
let grad = gx.abs() + gy.abs();
if grad > EDGE_GRAD {
edge_count += 1;
let ax = gx.abs();
let ay = gy.abs();
let bin = if ax >= 2 * ay {
0
} else if ay >= 2 * ax {
1
} else if (gx > 0) == (gy > 0) {
2
} else {
3
};
dir[bin] += 1;
}
if grad < FLAT_GRAD {
flat_count += 1;
}
if grad < WEAK_GRAD {
let box_mean = (tl + tc + tr + ml + c + mr + bl + bc + br) / 9;
noise_sum += (c - box_mean).abs() as i64;
weak_count += 1;
}
}
}
let mean = sum / n;
let variance = ((sum_sq / n) - mean * mean).max(0) as u32;
let edge_density_q8 = ((edge_count * 256) / n) as u16;
let flat_ratio_q8 = ((flat_count * 256) / n) as u16;
let noise = if weak_count > 0 {
(noise_sum / weak_count) as u16
} else {
0
};
let edge_total = dir.iter().sum::<i64>().max(1);
let dir_max = *dir.iter().max().unwrap();
let dir_dominance_q8 = ((dir_max * 256) / edge_total) as u16;
let axis_aligned_q8 = (((dir[0] + dir[1]) * 256) / edge_total) as u16;
let orient_entropy_q8 = entropy4_q8(&dir, edge_total);
let (chroma_activity, cb_mean, cr_mean) =
chroma_cell_activity(src, cat, cw, ch, cx, cy, cell_cw, cell_ch, shift);
let class = classify(
variance,
edge_density_q8,
orient_entropy_q8,
dir_dominance_q8,
axis_aligned_q8,
noise,
chroma_activity,
);
CellAnalysis {
class,
variance,
edge_density_q8,
flat_ratio_q8,
orient_entropy_q8,
dir_dominance_q8,
noise,
chroma_activity,
luma_mean: mean as u16,
cb_mean,
cr_mean,
global_contrast_q8: 0,
center_surround_q8: 0,
importance_q8: 0,
}
}
const EDGE_GRAD: i32 = 48;
const FLAT_GRAD: i32 = 12;
const WEAK_GRAD: i32 = 24;
fn entropy4_q8(dir: &[i64; 4], total: i64) -> u16 {
if total <= 0 {
return 0;
}
let t = total as f64;
let mut h = 0.0f64;
for &c in dir {
if c > 0 {
let p = c as f64 / t;
h -= p * p.log2();
}
}
((h / 2.0) * 256.0).round().clamp(0.0, 256.0) as u16
}
#[allow(clippy::too_many_arguments)]
fn classify(
variance: u32,
edge_density_q8: u16,
orient_entropy_q8: u16,
dir_dominance_q8: u16,
axis_aligned_q8: u16,
noise: u16,
chroma_activity: u16,
) -> RegionClass {
if edge_density_q8 >= TEXT_EDGE_Q8
&& orient_entropy_q8 < LOW_ENTROPY_Q8
&& axis_aligned_q8 >= AXIS_ALIGNED_Q8
&& noise < NOISE_HI
{
return RegionClass::TextLike;
}
if edge_density_q8 >= EDGE_DENSE_Q8 && dir_dominance_q8 >= DIR_DOMINANT_Q8 {
return RegionClass::DirectionalEdge;
}
if noise >= NOISE_HI && variance < TEXTURE_VAR {
return RegionClass::Noisy;
}
if variance >= TEXTURE_VAR && orient_entropy_q8 >= HIGH_ENTROPY_Q8 {
return RegionClass::Texture;
}
if variance < FLAT_VAR && edge_density_q8 < FLAT_EDGE_Q8 {
return RegionClass::Flat;
}
if edge_density_q8 < GRAD_EDGE_Q8 {
return RegionClass::Gradient;
}
if chroma_activity >= CHROMA_HI {
return RegionClass::ChromaCritical;
}
RegionClass::Texture
}
impl AnalysisMaps {
pub fn empty() -> AnalysisMaps {
AnalysisMaps {
cells_x: 0,
cells_y: 0,
cells: Vec::new(),
frame_mean_log2var: 0.0,
frame_min_log2var: 0.0,
frame_max_log2var: 0.0,
frame_mean_activity: 0.0,
autovar_chroma_weight: 0.0,
autovar_avg_adj: 0.0,
autovar_avg_adj_final: 0.0,
}
}
pub fn policy_at(&self, x0: u32, y0: u32, log2_size: u8, effort: Effort) -> SearchPolicy {
crate::effort::template(effort).resolve_policy(
self.region_class_at(x0, y0, log2_size),
self.importance_at(x0, y0, log2_size),
)
}
fn fold_cells<T: Copy>(
&self,
x0: u32,
y0: u32,
log2_size: u8,
init: T,
f: impl Fn(T, &CellAnalysis) -> T,
) -> T {
if self.cells.is_empty() {
return init;
}
let size = 1u32 << log2_size;
let cx0 = x0 >> CELL_LOG2;
let cy0 = y0 >> CELL_LOG2;
let cx1 = ((x0 + size - 1) >> CELL_LOG2).min(self.cells_x - 1);
let cy1 = ((y0 + size - 1) >> CELL_LOG2).min(self.cells_y - 1);
let mut acc = init;
for cy in cy0..=cy1 {
for cx in cx0..=cx1 {
acc = f(acc, &self.cells[(cy * self.cells_x + cx) as usize]);
}
}
acc
}
pub fn region_class_at(&self, x0: u32, y0: u32, log2_size: u8) -> RegionClass {
self.fold_cells(x0, y0, log2_size, RegionClass::Flat, |best, c| {
if c.class.index() > best.index() {
c.class
} else {
best
}
})
}
pub fn importance_at(&self, x0: u32, y0: u32, log2_size: u8) -> u16 {
self.fold_cells(x0, y0, log2_size, 0u16, |best, c| best.max(c.importance_q8))
}
pub fn variance_at(&self, x0: u32, y0: u32) -> u32 {
if self.cells.is_empty() {
return 0;
}
let cx = (x0 / CELL).min(self.cells_x - 1);
let cy = (y0 / CELL).min(self.cells_y - 1);
self.cells[(cy * self.cells_x + cx) as usize].variance
}
pub fn chroma_activity_at(&self, x0: u32, y0: u32) -> u16 {
if self.cells.is_empty() {
return 0;
}
let cx = (x0 / CELL).min(self.cells_x - 1);
let cy = (y0 / CELL).min(self.cells_y - 1);
self.cells[(cy * self.cells_x + cx) as usize].chroma_activity
}
pub fn frame_mean_log2var(&self) -> f32 {
self.frame_mean_log2var
}
pub fn frame_mean_log2activity(&self) -> f32 {
self.frame_mean_activity
}
pub fn autovar_qp_adj0_at(&self, x0: u32, y0: u32) -> f32 {
if self.cells.is_empty() {
return 1.0;
}
let cx = (x0 / CELL).min(self.cells_x - 1);
let cy = (y0 / CELL).min(self.cells_y - 1);
let c = &self.cells[(cy * self.cells_x + cx) as usize];
autovar_qp_adj0(c.variance, c.chroma_activity, self.autovar_chroma_weight)
}
pub fn autovar_avg_adj(&self) -> f32 {
self.autovar_avg_adj
}
pub fn autovar_avg_adj_final(&self) -> f32 {
self.autovar_avg_adj_final
}
pub fn frame_min_log2var(&self) -> f32 {
self.frame_min_log2var
}
pub fn frame_max_log2var(&self) -> f32 {
self.frame_max_log2var
}
pub fn class_counts(&self) -> [u64; NUM_CLASSES] {
let mut h = [0u64; NUM_CLASSES];
for c in &self.cells {
h[c.class.index()] += 1;
}
h
}
}
impl AqOffsetMap {
pub fn offset_at(&self, x0: u32, y0: u32) -> i32 {
let cx = (x0 >> self.cell_log2).min(self.cells_x.saturating_sub(1));
let cy = (y0 >> self.cell_log2).min(self.cells_y.saturating_sub(1));
self.offsets[(cy * self.cells_x + cx) as usize] as i32
}
pub fn from_qg_activity(
cells_x: u32,
cells_y: u32,
activity: &[f64],
strength: f32,
clamp: u8,
) -> AqOffsetMap {
let n = activity.len();
let logs: Vec<f32> = activity
.iter()
.map(|&a| (1.0 + a.max(0.0)).ln() as f32)
.collect();
let mean = if n == 0 {
0.0
} else {
logs.iter().sum::<f32>() / n as f32
};
let cl = clamp.max(1) as f32;
let offsets = logs
.iter()
.map(|&lv| (strength * (lv - mean)).round().clamp(-cl, cl) as i8)
.collect();
AqOffsetMap {
cells_x,
cells_y,
cell_log2: CELL_LOG2,
offsets,
}
}
}
pub struct FineAqGrid {
cells_x: u32,
cells_y: u32,
luma_var: Vec<u32>,
chroma_act: Vec<u16>,
frame_mean_log2var: f32,
frame_min_log2var: f32,
frame_max_log2var: f32,
frame_mean_activity: f32,
autovar_chroma_weight: f32,
autovar_avg_adj: f32,
autovar_avg_adj_final: f32,
}
pub const FINE_CELL_LOG2: u8 = 4;
const FINE_CELL: u32 = 1 << FINE_CELL_LOG2;
pub fn analyze_fine(
width: u32,
height: u32,
bit_depth: u8,
cat: u8,
src: Source<'_>,
) -> FineAqGrid {
let cells_x = width.div_ceil(FINE_CELL).max(1);
let cells_y = height.div_ceil(FINE_CELL).max(1);
let n_cells = (cells_x * cells_y) as usize;
let mut luma_var = Vec::with_capacity(n_cells);
let mut chroma_act = Vec::with_capacity(n_cells);
let shift = (bit_depth - 8) as u32;
let luma_stride = width as usize;
let (cw, ch) = chroma_dims(width, height, cat);
let (cell_cw, cell_ch) = match cat {
0 => (0, 0),
1 => (FINE_CELL / 2, FINE_CELL / 2),
2 => (FINE_CELL / 2, FINE_CELL),
_ => (FINE_CELL, FINE_CELL),
};
let var_of = |plane: &[u16], stride: usize, x0: u32, y0: u32, x1: u32, y1: u32| -> i64 {
let n = ((x1 - x0) * (y1 - y0)) as i64;
let mut sum = 0i64;
let mut sum_sq = 0i64;
for y in y0..y1 {
for x in x0..x1 {
let v = (plane[y as usize * stride + x as usize] >> shift) as i64;
sum += v;
sum_sq += v * v;
}
}
let mean = sum / n;
((sum_sq / n) - mean * mean).max(0)
};
for cy in 0..cells_y {
for cx in 0..cells_x {
let x0 = cx * FINE_CELL;
let y0 = cy * FINE_CELL;
let x1 = (x0 + FINE_CELL).min(width);
let y1 = (y0 + FINE_CELL).min(height);
luma_var.push(var_of(src.y, luma_stride, x0, y0, x1, y1) as u32);
let act = if cat == 0 {
0
} else {
let cx0 = cx * cell_cw;
let cy0 = cy * cell_ch;
let cx1 = (cx0 + cell_cw).min(cw);
let cy1 = (cy0 + cell_ch).min(ch);
if cx1 <= cx0 || cy1 <= cy0 {
0
} else {
let v_cb = var_of(src.cb, cw as usize, cx0, cy0, cx1, cy1);
let v_cr = var_of(src.cr, cw as usize, cx0, cy0, cx1, cy1);
(v_cb + v_cr).min(u16::MAX as i64) as u16
}
};
chroma_act.push(act);
}
}
let autovar_chroma_weight = autovar_chroma_weight(cat);
let n = luma_var.len().max(1) as f32;
let mut sum_lv = 0.0f32;
let mut sum_act = 0.0f32;
let mut min_lv = f32::INFINITY;
let mut max_lv = f32::NEG_INFINITY;
let mut sum_adj = 0.0f32;
let mut sum_adj_pow2 = 0.0f32;
for (&v, &c) in luma_var.iter().zip(&chroma_act) {
let lv = ((1 + v) as f32).log2();
sum_lv += lv;
sum_act += combined_activity(v, c);
min_lv = min_lv.min(lv);
max_lv = max_lv.max(lv);
let adj = autovar_qp_adj0(v, c, autovar_chroma_weight);
sum_adj += adj;
sum_adj_pow2 += adj * adj;
}
let avg_adj = sum_adj / n;
let avg_adj_pow2 = sum_adj_pow2 / n;
let avg_adj_final = avg_adj - 0.5 * (avg_adj_pow2 - AUTOVAR_MODE_TWO_CONST) / avg_adj;
FineAqGrid {
cells_x,
cells_y,
luma_var,
chroma_act,
frame_mean_log2var: sum_lv / n,
frame_min_log2var: min_lv,
frame_max_log2var: max_lv,
frame_mean_activity: sum_act / n,
autovar_chroma_weight,
autovar_avg_adj: avg_adj,
autovar_avg_adj_final: avg_adj_final,
}
}
impl FineAqGrid {
#[inline]
fn cell_idx(&self, x0: u32, y0: u32) -> usize {
let cx = (x0 >> FINE_CELL_LOG2).min(self.cells_x - 1);
let cy = (y0 >> FINE_CELL_LOG2).min(self.cells_y - 1);
(cy * self.cells_x + cx) as usize
}
pub fn variance_at(&self, x0: u32, y0: u32) -> u32 {
self.luma_var[self.cell_idx(x0, y0)]
}
pub fn chroma_activity_at(&self, x0: u32, y0: u32) -> u16 {
self.chroma_act[self.cell_idx(x0, y0)]
}
pub fn frame_mean_log2var(&self) -> f32 {
self.frame_mean_log2var
}
pub fn frame_min_log2var(&self) -> f32 {
self.frame_min_log2var
}
pub fn frame_max_log2var(&self) -> f32 {
self.frame_max_log2var
}
pub fn frame_mean_log2activity(&self) -> f32 {
self.frame_mean_activity
}
pub fn autovar_qp_adj0_at(&self, x0: u32, y0: u32) -> f32 {
let i = self.cell_idx(x0, y0);
autovar_qp_adj0(
self.luma_var[i],
self.chroma_act[i],
self.autovar_chroma_weight,
)
}
pub fn autovar_avg_adj(&self) -> f32 {
self.autovar_avg_adj
}
pub fn autovar_avg_adj_final(&self) -> f32 {
self.autovar_avg_adj_final
}
}
fn chroma_dims(width: u32, height: u32, cat: u8) -> (u32, u32) {
match cat {
0 => (0, 0),
1 => (width.div_ceil(2), height.div_ceil(2)),
2 => (width.div_ceil(2), height),
_ => (width, height),
}
}
fn chroma_cell_size(cat: u8) -> (u32, u32) {
match cat {
0 => (0, 0),
1 => (CELL / 2, CELL / 2),
2 => (CELL / 2, CELL),
_ => (CELL, CELL),
}
}
#[allow(clippy::too_many_arguments)]
fn chroma_cell_activity(
src: Source<'_>,
cat: u8,
cw: u32,
ch: u32,
cx: u32,
cy: u32,
cell_cw: u32,
cell_ch: u32,
shift: u32,
) -> (u16, u16, u16) {
if cat == 0 {
return (0, 128, 128);
}
let stride = cw as usize;
let x0 = cx * cell_cw;
let y0 = cy * cell_ch;
let x1 = (x0 + cell_cw).min(cw);
let y1 = (y0 + cell_ch).min(ch);
if x1 <= x0 || y1 <= y0 {
return (0, 0, 0);
}
let n = ((x1 - x0) * (y1 - y0)) as i64;
let _ = cat;
let stat_of = |plane: &[u16]| -> (i64, i64) {
let mut sum = 0i64;
let mut sum_sq = 0i64;
for y in y0..y1 {
for x in x0..x1 {
let v = (plane[y as usize * stride + x as usize] >> shift) as i64;
sum += v;
sum_sq += v * v;
}
}
let mean = sum / n;
(((sum_sq / n) - mean * mean).max(0), mean)
};
let (v_cb, m_cb) = stat_of(src.cb);
let (v_cr, m_cr) = stat_of(src.cr);
let act = (v_cb + v_cr).min(u16::MAX as i64) as u16;
(act, m_cb as u16, m_cr as u16)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_flat_vs_edges() {
let (w, h) = (128usize, 64usize);
let mut y = vec![0u16; w * h];
for r in 0..h {
for c in 0..w {
y[r * w + c] = if c < w / 2 {
128
} else if c % 2 == 0 {
16
} else {
235
};
}
}
let gray = vec![128u16; w * h];
let src = Source {
y: &y,
cb: &gray,
cr: &gray,
};
let maps = analyze(w as u32, h as u32, 8, 3, src);
let counts = maps.class_counts();
assert_eq!(
counts.iter().sum::<u64>(),
4 * 2,
"8 cells over a 128x64 pic"
);
assert!(counts[RegionClass::Flat.index()] >= 1, "flat left half");
let structured: u64 = counts.iter().sum::<u64>() - counts[RegionClass::Flat.index()];
assert!(structured >= 1, "edges on the right half: {counts:?}");
}
#[test]
fn autovar_offsets_signs_and_bias() {
let (w, h) = (128usize, 64usize);
let mut y = vec![0u16; w * h];
for r in 0..h {
for c in 0..w {
y[r * w + c] = if c < w / 2 {
128
} else if c % 2 == 0 {
16
} else {
235
};
}
}
let gray = vec![128u16; w * h];
let src = Source {
y: &y,
cb: &gray,
cr: &gray,
};
let maps = analyze(w as u32, h as u32, 8, 3, src);
let (avg, avg_final) = (maps.autovar_avg_adj(), maps.autovar_avg_adj_final());
assert!(avg >= 1.0, "qp_adj0 >= 1 per cell, so avg_adj >= 1: {avg}");
let flat = maps.autovar_qp_adj0_at(0, 0);
let busy = maps.autovar_qp_adj0_at(96, 0);
assert!(flat < busy, "flat {flat} vs striped {busy}");
let clamp = 20.0;
let off = |adj0: f32, biased: bool, s: f32| {
aq_qp_offset_autovar(adj0, avg, avg_final, s, biased, clamp)
};
assert!(off(busy, false, 1.0) > 0, "high-energy cell must get +QP");
assert!(off(flat, false, 1.0) < 0, "flat cell must get -QP");
for biased in [false, true] {
assert!(off(flat, biased, 1.0) <= off((flat + busy) / 2.0, biased, 1.0));
assert!(off((flat + busy) / 2.0, biased, 1.0) <= off(busy, biased, 1.0));
}
assert!(
off(flat, true, 1.0) < off(flat, false, 1.0),
"dark/flat bias must lower flat-cell QP further: biased {} vs {}",
off(flat, true, 1.0),
off(flat, false, 1.0)
);
for adj0 in [flat, busy] {
assert_eq!(off(adj0, false, 0.0), 0);
assert_eq!(off(adj0, true, 0.0), 0);
}
assert_eq!(aq_qp_offset_autovar(1.0, 0.0, 0.0, 1.0, true, clamp), 0);
}
#[test]
fn placebo_gets_inert_policy() {
let y = vec![128u16; 64 * 64];
let src = Source {
y: &y,
cb: &y,
cr: &y,
};
let maps = analyze(64, 64, 8, 3, src);
let p = maps.policy_at(0, 0, 5, Effort::Placebo);
assert!(p.angular_prune.is_none() && p.allow_early_term);
assert_eq!((p.luma_rd_bias, p.chroma_rd_bias), (0, 0));
assert!(!p.force_leaf && p.rmd_prune_factor.is_none());
let p = maps.policy_at(0, 0, 5, Effort::Fast);
assert_eq!(p.angular_prune, Some(true));
}
}