use crate::internal::bpg_bitstream::BitWriter;
use crate::internal::bpg_hevc_decode::hevc::sao::SaoMap;
use crate::cabac::CabacEncoder;
use crate::contexts::{Contexts, ctx};
pub const EO_OFFSETS: [(i32, i32, i32, i32); 4] =
[(-1, 0, 1, 0), (0, -1, 0, 1), (-1, -1, 1, 1), (1, -1, -1, 1)];
pub fn sao_c_max(bit_depth: u8) -> u32 {
(1u32 << (bit_depth.min(10) - 5)) - 1
}
pub fn sao_offset_scale(bit_depth: u8) -> i32 {
1i32 << bit_depth.saturating_sub(bit_depth.min(10))
}
#[derive(Default, Clone, Copy)]
pub struct EoStats {
pub sum: [i64; 5],
pub count: [u32; 5],
}
#[derive(Default, Clone, Copy)]
pub struct BoStats {
pub sum: [i64; 32],
pub count: [u32; 32],
}
fn offset_reduction(sum: i64, count: u32, applied_offset: i32) -> i64 {
let off = applied_offset as i64;
2 * off * sum - count as i64 * off * off
}
pub fn eo_offsets_and_reduction(stats: &EoStats, bit_depth: u8) -> ([i8; 4], i64) {
let c_max = sao_c_max(bit_depth) as i32;
let scale = sao_offset_scale(bit_depth);
let max_offset = c_max * scale;
let mut offsets = [0i8; 4];
let mut reduction = 0i64;
const CATS: [(usize, usize, i64); 4] = [(0, 0, 1), (1, 1, 1), (2, 3, -1), (3, 4, -1)];
for (out_idx, edge_idx, sign) in CATS {
let count = stats.count[edge_idx];
if count == 0 {
continue;
}
let mean = stats.sum[edge_idx] as f64 / count as f64;
let raw = sign as f64 * mean;
if raw <= 0.0 {
continue;
}
let mut off = raw.round() as i32;
off = off.clamp(0, max_offset);
if scale > 1 {
off = ((off + scale / 2) / scale) * scale;
off = off.clamp(0, max_offset);
}
if off == 0 {
continue;
}
let applied = sign * off as i64;
let sum = stats.sum[edge_idx];
let r = offset_reduction(sum, count, applied as i32);
if r > 0 {
reduction += r;
offsets[out_idx] = off as i8;
}
}
(offsets, reduction)
}
pub fn bo_offsets_and_reduction(stats: &BoStats, bit_depth: u8) -> (u8, [i8; 4], i64) {
let c_max = sao_c_max(bit_depth) as i32;
let scale = sao_offset_scale(bit_depth);
let max_offset = c_max * scale;
let mut best_pos = 0u8;
let mut best_offsets = [0i8; 4];
let mut best_reduction = 0i64;
for start in 0..32usize {
let mut offsets = [0i8; 4];
let mut reduction = 0i64;
for (i, off_slot) in offsets.iter_mut().enumerate() {
let band = (start + i) & 31;
let count = stats.count[band];
if count == 0 {
continue;
}
let mean = stats.sum[band] as f64 / count as f64;
let mut off = mean.round() as i32;
off = off.clamp(-max_offset, max_offset);
if scale > 1 {
off = if off >= 0 {
((off + scale / 2) / scale) * scale
} else {
-(((-off + scale / 2) / scale) * scale)
};
off = off.clamp(-max_offset, max_offset);
}
if off == 0 {
continue;
}
let r = offset_reduction(stats.sum[band], count, off);
if r > 0 {
*off_slot = off as i8;
reduction += r;
}
}
if reduction > best_reduction {
best_pos = start as u8;
best_offsets = offsets;
best_reduction = reduction;
}
}
(best_pos, best_offsets, best_reduction)
}
fn encode_tu_bypass(enc: &mut CabacEncoder, w: &mut BitWriter, value: u32, c_max: u32) {
let value = value.min(c_max);
for _ in 0..value {
enc.encode_bin_ep(w, 1);
}
if value < c_max {
enc.encode_bin_ep(w, 0);
}
}
fn encode_sao_type_idx(
enc: &mut CabacEncoder,
w: &mut BitWriter,
ctxs: &mut Contexts,
type_idx: u8,
) {
if type_idx == 0 {
enc.encode_bin(w, 0, ctxs.get(ctx::SAO_TYPE_IDX));
} else {
enc.encode_bin(w, 1, ctxs.get(ctx::SAO_TYPE_IDX));
enc.encode_bin_ep(w, (type_idx == 2) as u8);
}
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)]
pub fn write_sao(
enc: &mut CabacEncoder,
w: &mut BitWriter,
ctxs: &mut Contexts,
sao_map: &SaoMap,
x_ctb: u32,
y_ctb: u32,
left_merge_avail: bool,
up_merge_avail: bool,
slice_sao_luma: bool,
slice_sao_chroma: bool,
bit_depth: u8,
) {
let info = sao_map.get(x_ctb, y_ctb);
if left_merge_avail {
let merge_left = sao_map.get(x_ctb - 1, y_ctb) == info;
enc.encode_bin(w, merge_left as u8, ctxs.get(ctx::SAO_MERGE_FLAG));
if merge_left {
return;
}
}
if up_merge_avail {
let merge_up = sao_map.get(x_ctb, y_ctb - 1) == info;
enc.encode_bin(w, merge_up as u8, ctxs.get(ctx::SAO_MERGE_FLAG));
if merge_up {
return;
}
}
let c_max = sao_c_max(bit_depth);
let offset_scale = sao_offset_scale(bit_depth) as u32;
for c_idx in 0..3usize {
let should_write = (slice_sao_luma && c_idx == 0) || (slice_sao_chroma && c_idx > 0);
if !should_write {
continue;
}
if c_idx <= 1 {
encode_sao_type_idx(enc, w, ctxs, info.sao_type_idx[c_idx]);
}
let sao_type_idx = info.sao_type_idx[c_idx];
if sao_type_idx == 0 {
continue;
}
for &v in &info.sao_offset_val[c_idx] {
let abs = v.unsigned_abs() as u32 / offset_scale;
encode_tu_bypass(enc, w, abs, c_max);
}
if sao_type_idx == 1 {
for &v in &info.sao_offset_val[c_idx] {
if v != 0 {
enc.encode_bin_ep(w, (v < 0) as u8);
}
}
enc.encode_bins_ep(w, info.sao_band_position[c_idx] as u32, 5);
} else {
if c_idx <= 1 {
enc.encode_bins_ep(w, info.sao_eo_class[c_idx] as u32, 2);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bo_search_picks_best_consecutive_band_run() {
let mut stats = BoStats::default();
stats.sum[9] = 30;
stats.count[9] = 10;
stats.sum[10] = -40;
stats.count[10] = 10;
let (band_pos, offsets, reduction) = bo_offsets_and_reduction(&stats, 8);
assert_eq!(band_pos, 7);
assert_eq!(offsets, [0, 0, 3, -4]);
assert!(reduction > 0);
}
}