use crate::cabac::{CabacEstimator, ContextModel};
use crate::contexts::{Contexts, ctx};
pub(super) fn rd_lambda(qp: i32) -> f64 {
let base = 0.57f64 * 2f64.powf((qp as f64 - 12.0) / 3.0);
base * super::env::lambda_scale()
}
#[inline]
pub(super) fn x265_sad_lambda(qp: i32, bit_depth: u8) -> f64 {
let depth_scale = 1u32 << bit_depth.saturating_sub(8);
2f64.powf(qp as f64 / 6.0 - 2.0) * f64::from(depth_scale)
}
#[inline]
pub(super) fn x265_sad_lambda_q8(qp: i32, bit_depth: u8) -> u64 {
(256.0 * x265_sad_lambda(qp, bit_depth)).floor() as u64
}
#[inline]
pub(super) fn x265_rd_sad_cost(sad: u32, bits: u32, qp: i32, bit_depth: u8) -> u64 {
sad as u64 + ((bits as u64 * x265_sad_lambda_q8(qp, bit_depth) + 128) >> 8)
}
pub(super) fn split_flag_bits(ctxs: &Contexts, log2_size: u8, is_split: bool) -> u64 {
let ci = ctx::SPLIT_TRANSFORM_FLAG + (5usize.saturating_sub(log2_size as usize)).min(2);
ctxs.models[ci].entropy_bits(is_split as u8) as u64
}
#[inline]
pub(super) fn entropy_bits(model: &ContextModel, bin: u8) -> u64 {
model.entropy_bits(bin) as u64
}
pub(super) fn luma_mode_bits(ctxs: &Contexts, mpm_u8: [u8; 3], mode: u8) -> u64 {
let prev = &ctxs.models[ctx::PREV_INTRA_LUMA_PRED_FLAG];
let bypass = CabacEstimator::SCALE;
match mpm_u8.iter().position(|&m| m == mode) {
Some(0) => entropy_bits(prev, 1) + bypass,
Some(_) => entropy_bits(prev, 1) + 2 * bypass,
None => entropy_bits(prev, 0) + 5 * bypass,
}
}
pub(super) fn x265_rmd_luma_mode_bits_no_carry(ctxs: &Contexts, mpm_u8: [u8; 3], mode: u8) -> u32 {
x265_rmd_luma_mode_bits_with_carry(ctxs, mpm_u8, mode, 0)
}
pub(super) fn x265_rmd_luma_mode_bits_with_carry(
ctxs: &Contexts,
mpm_u8: [u8; 3],
mode: u8,
carry: u32,
) -> u32 {
let prev = &ctxs.models[ctx::PREV_INTRA_LUMA_PRED_FLAG];
let carry = carry & 32767;
match mpm_u8.iter().position(|&m| m == mode) {
Some(0) => ((entropy_bits(prev, 1) as u32 + carry) >> 15) + 1,
Some(_) => ((entropy_bits(prev, 1) as u32 + carry) >> 15) + 2,
None => ((entropy_bits(prev, 0) as u32 + carry) >> 15) + 5,
}
}
pub(super) fn x265_rmd_luma_mode_carry_representatives(ctxs: &Contexts) -> [u32; 4] {
let prev = &ctxs.models[ctx::PREV_INTRA_LUMA_PRED_FLAG];
[
0,
carry_transition(entropy_bits(prev, 0) as u32),
carry_transition(entropy_bits(prev, 1) as u32),
32767,
]
}
#[inline]
fn carry_transition(bits: u32) -> u32 {
let low = bits & 32767;
if low == 0 { 0 } else { 32768 - low }
}
pub(super) fn part_mode_bits(ctxs: &Contexts, part_nxn: bool) -> u64 {
entropy_bits(&ctxs.models[ctx::PART_MODE], (!part_nxn) as u8)
}
pub(super) fn chroma_dm_bits(ctxs: &Contexts, cat: u8) -> u64 {
if cat == 0 {
0
} else {
entropy_bits(&ctxs.models[ctx::INTRA_CHROMA_PRED_MODE], 0)
}
}