use crate::dsp::lossless_common::{WEBP_UINT64_MAX, vp8l_prefix_encode};
use crate::dsp::lossless_enc::vp8l_vector_mismatch;
use crate::enc::backward_references_cost_enc::vp8l_backward_references_trace_backwards;
use crate::enc::histogram_enc::{
VP8LHistogram, vp8l_allocate_histogram, vp8l_histogram_create, vp8l_histogram_estimate_bits,
vp8l_histogram_init,
};
use crate::enc::webp_enc::{webp_encoding_set_error, webp_report_progress};
use crate::utils::color_cache_utils::{
VP8LColorCache, vp8l_color_cache_clear, vp8l_color_cache_contains, vp8l_color_cache_get_index,
vp8l_color_cache_init, vp8l_color_cache_insert, vp8l_color_cache_lookup, vp8l_color_cache_set,
vp8l_hash_pix,
};
use crate::utils::utils::webp_safe_malloc;
use crate::webp::encode::{WebPEncodingError, WebPPicture};
use crate::webp::format_constants::{NUM_LENGTH_CODES, NUM_LITERAL_CODES};
#[must_use]
pub(crate) fn safe_malloc_test(nmemb: u64, size: usize) -> bool {
webp_safe_malloc::<()>(nmemb, size).is_some()
}
#[must_use]
pub(crate) fn try_filled<T: Clone>(count: usize, value: T) -> Option<Vec<T>> {
let mut buffer = Vec::new();
buffer.try_reserve_exact(count).ok()?;
buffer.resize(count, value);
Some(buffer)
}
#[inline]
pub(crate) fn to_index(value: i32) -> usize {
usize::try_from(value).expect("a C index or count is not negative")
}
pub(crate) fn split_pair<T>(slice: &mut [T], shared: usize, mutable: usize) -> (&T, &mut T) {
assert_ne!(shared, mutable, "the two elements differ");
if shared < mutable {
let (low, high) = slice.split_at_mut(mutable);
(&low[shared], &mut high[0])
} else {
let (low, high) = slice.split_at_mut(shared);
(&high[0], &mut low[mutable])
}
}
pub(crate) fn split_two<T>(slice: &mut [T], a: usize, b: usize) -> (&mut T, &mut T) {
assert_ne!(a, b, "the two elements differ");
if a < b {
let (low, high) = slice.split_at_mut(b);
(&mut low[a], &mut high[0])
} else {
let (low, high) = slice.split_at_mut(a);
(&mut high[0], &mut low[b])
}
}
pub const MAX_COLOR_CACHE_BITS: i32 = 10;
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Mode(pub u32);
#[expect(non_upper_case_globals, reason = "C enumerator names")]
impl Mode {
pub const kLiteral: Self = Self(0);
pub const kCacheIdx: Self = Self(1);
pub const kCopy: Self = Self(2);
pub const kNone: Self = Self(3);
}
#[expect(
clippy::cast_possible_truncation,
reason = "the enumerators fit uint8_t, as the C assignment assumes"
)]
const fn mode_byte(mode: Mode) -> u8 {
mode.0 as u8
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PixOrCopy {
pub mode: u8,
pub len: u16,
pub argb_or_distance: u32,
}
impl PixOrCopy {
pub const C_SIZE: usize = 8;
}
#[must_use]
#[inline]
pub fn pix_or_copy_create_copy(distance: u32, len: u16) -> PixOrCopy {
PixOrCopy {
mode: mode_byte(Mode::kCopy),
argb_or_distance: distance,
len,
}
}
#[must_use]
#[inline]
pub fn pix_or_copy_create_cache_idx(idx: i32) -> PixOrCopy {
debug_assert!(idx >= 0);
debug_assert!(idx < (1 << MAX_COLOR_CACHE_BITS));
PixOrCopy {
mode: mode_byte(Mode::kCacheIdx),
argb_or_distance: idx.cast_unsigned(),
len: 1,
}
}
#[must_use]
#[inline]
pub fn pix_or_copy_create_literal(argb: u32) -> PixOrCopy {
PixOrCopy {
mode: mode_byte(Mode::kLiteral),
argb_or_distance: argb,
len: 1,
}
}
#[must_use]
#[inline]
pub fn pix_or_copy_is_literal(p: &PixOrCopy) -> bool {
p.mode == mode_byte(Mode::kLiteral)
}
#[must_use]
#[inline]
pub fn pix_or_copy_is_cache_idx(p: &PixOrCopy) -> bool {
p.mode == mode_byte(Mode::kCacheIdx)
}
#[must_use]
#[inline]
pub fn pix_or_copy_is_copy(p: &PixOrCopy) -> bool {
p.mode == mode_byte(Mode::kCopy)
}
#[must_use]
#[inline]
pub fn pix_or_copy_literal(p: &PixOrCopy, component: i32) -> u32 {
debug_assert_eq!(p.mode, mode_byte(Mode::kLiteral));
(p.argb_or_distance >> (component * 8)) & 0xff
}
#[must_use]
#[inline]
pub fn pix_or_copy_length(p: &PixOrCopy) -> u32 {
u32::from(p.len)
}
#[must_use]
#[inline]
pub fn pix_or_copy_cache_idx(p: &PixOrCopy) -> u32 {
debug_assert_eq!(p.mode, mode_byte(Mode::kCacheIdx));
debug_assert!(p.argb_or_distance < (1_u32 << MAX_COLOR_CACHE_BITS));
p.argb_or_distance
}
#[must_use]
#[inline]
pub fn pix_or_copy_distance(p: &PixOrCopy) -> u32 {
debug_assert_eq!(p.mode, mode_byte(Mode::kCopy));
p.argb_or_distance
}
pub const HASH_BITS: i32 = 18;
pub const HASH_SIZE: i32 = 1 << HASH_BITS;
pub const MAX_LENGTH_BITS: i32 = 12;
pub const WINDOW_SIZE_BITS: i32 = 20;
pub const MAX_LENGTH: i32 = (1 << MAX_LENGTH_BITS) - 1;
const _: () = assert!(
MAX_LENGTH_BITS + WINDOW_SIZE_BITS <= 32,
"MAX_LENGTH_BITS + WINDOW_SIZE_BITS > 32"
);
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VP8LHashChain {
pub offset_length: Vec<u32>,
pub size: i32,
}
#[must_use]
#[inline]
pub fn vp8l_hash_chain_find_offset(p: &VP8LHashChain, base_position: i32) -> i32 {
(p.offset_length[to_index(base_position)] >> MAX_LENGTH_BITS).cast_signed()
}
#[must_use]
#[inline]
pub fn vp8l_hash_chain_find_length(p: &VP8LHashChain, base_position: i32) -> i32 {
(p.offset_length[to_index(base_position)] & ((1_u32 << MAX_LENGTH_BITS) - 1)).cast_signed()
}
#[must_use]
#[inline]
pub fn vp8l_hash_chain_find_copy(p: &VP8LHashChain, base_position: i32) -> (i32, i32) {
(
vp8l_hash_chain_find_offset(p, base_position),
vp8l_hash_chain_find_length(p, base_position),
)
}
pub const MAX_REFS_BLOCK_PER_IMAGE: i32 = 16;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PixOrCopyBlock {
pub start: Vec<PixOrCopy>,
pub size: i32,
}
impl PixOrCopyBlock {
pub const C_SIZE: usize = 3 * size_of::<usize>();
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VP8LBackwardRefs {
pub block_size: i32,
pub error: bool,
pub refs: Vec<PixOrCopyBlock>,
pub free_blocks: Vec<PixOrCopyBlock>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VP8LRefsCursor {
pub cur_pos: usize,
pub cur_block: usize,
pub last_pos: usize,
pub ok: bool,
}
impl VP8LRefsCursor {
#[must_use]
pub fn get<'r>(&self, refs: &'r VP8LBackwardRefs) -> &'r PixOrCopy {
&refs.refs[self.cur_block].start[self.cur_pos]
}
pub fn get_mut<'r>(&self, refs: &'r mut VP8LBackwardRefs) -> &'r mut PixOrCopy {
&mut refs.refs[self.cur_block].start[self.cur_pos]
}
}
#[must_use]
#[inline]
pub fn vp8l_refs_cursor_ok(c: &VP8LRefsCursor) -> bool {
c.ok
}
#[inline]
pub fn vp8l_refs_cursor_next(c: &mut VP8LRefsCursor, refs: &VP8LBackwardRefs) {
debug_assert!(vp8l_refs_cursor_ok(c));
c.cur_pos += 1;
if c.cur_pos == c.last_pos {
vp8l_refs_cursor_next_block(c, refs);
}
}
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VP8LLZ77Type(pub u32);
#[expect(non_upper_case_globals, reason = "C enumerator names")]
impl VP8LLZ77Type {
pub const kLZ77Standard: Self = Self(1);
pub const kLZ77RLE: Self = Self(2);
pub const kLZ77Box: Self = Self(4);
}
const MIN_BLOCK_SIZE: i32 = 256;
const WINDOW_SIZE: i32 = (1 << WINDOW_SIZE_BITS) - 120;
const MIN_LENGTH: i32 = 4;
static PLANE_TO_CODE_LUT: [u8; 128] = [
96, 73, 55, 39, 23, 13, 5, 1, 255, 255, 255, 255, 255, 255, 255, 255, 101, 78, 58, 42, 26, 16,
8, 2, 0, 3, 9, 17, 27, 43, 59, 79, 102, 86, 62, 46, 32, 20, 10, 6, 4, 7, 11, 21, 33, 47, 63,
87, 105, 90, 70, 52, 37, 28, 18, 14, 12, 15, 19, 29, 38, 53, 71, 91, 110, 99, 82, 66, 48, 35,
30, 24, 22, 25, 31, 36, 49, 67, 83, 100, 115, 108, 94, 76, 64, 50, 44, 40, 34, 41, 45, 51, 65,
77, 95, 109, 118, 113, 103, 92, 80, 68, 60, 56, 54, 57, 61, 69, 81, 93, 104, 114, 119, 116,
111, 106, 97, 88, 84, 74, 72, 75, 85, 89, 98, 107, 112, 117,
];
#[must_use]
pub fn vp8l_distance_to_plane_code(xsize: i32, dist: i32) -> i32 {
let yoffset = dist / xsize;
let xoffset = dist - yoffset * xsize;
if xoffset <= 8 && yoffset < 8 {
i32::from(PLANE_TO_CODE_LUT[to_index(yoffset * 16 + 8 - xoffset)]) + 1
} else if xoffset > xsize - 8 && yoffset < 7 {
i32::from(PLANE_TO_CODE_LUT[to_index((yoffset + 1) * 16 + 8 + (xsize - xoffset))]) + 1
} else {
dist + 120
}
}
#[inline]
fn find_match_length(array1: &[u32], array2: &[u32], best_len_match: i32, max_limit: i32) -> i32 {
if array1[to_index(best_len_match)] != array2[to_index(best_len_match)] {
return 0;
}
vp8l_vector_mismatch(array1, array2, max_limit)
}
pub fn vp8l_clear_backward_refs(refs: &mut VP8LBackwardRefs) {
while let Some(block) = refs.refs.pop() {
refs.free_blocks.push(block);
}
}
pub fn vp8l_backward_refs_clear(refs: &mut VP8LBackwardRefs) {
vp8l_clear_backward_refs(refs);
refs.free_blocks = Vec::new();
}
fn backward_refs_swap(refs1: &mut VP8LBackwardRefs, refs2: &mut VP8LBackwardRefs) {
std::mem::swap(refs1, refs2);
}
pub fn vp8l_backward_refs_init(refs: &mut VP8LBackwardRefs, block_size: i32) {
*refs = VP8LBackwardRefs::default();
refs.block_size = if block_size < MIN_BLOCK_SIZE {
MIN_BLOCK_SIZE
} else {
block_size
};
}
#[must_use]
pub fn vp8l_refs_cursor_init(refs: &VP8LBackwardRefs) -> VP8LRefsCursor {
match refs.refs.first() {
Some(block) => VP8LRefsCursor {
cur_pos: 0,
cur_block: 0,
last_pos: to_index(block.size),
ok: true,
},
None => VP8LRefsCursor::default(),
}
}
pub fn vp8l_refs_cursor_next_block(c: &mut VP8LRefsCursor, refs: &VP8LBackwardRefs) {
let b = c.cur_block + 1;
if let Some(block) = refs.refs.get(b) {
c.cur_pos = 0;
c.last_pos = to_index(block.size);
c.ok = true;
} else {
c.cur_pos = 0;
c.last_pos = 0;
c.ok = false;
}
c.cur_block = b;
}
fn backward_refs_new_block(refs: &mut VP8LBackwardRefs) -> bool {
let block = if let Some(block) = refs.free_blocks.pop() {
block
} else {
let block_size = to_index(refs.block_size);
let total_size =
PixOrCopyBlock::C_SIZE as u64 + block_size as u64 * PixOrCopy::C_SIZE as u64;
let start = usize::try_from(total_size)
.ok()
.filter(|&total| safe_malloc_test(1, total))
.and_then(|_| try_filled(block_size, PixOrCopy::default()));
let Some(start) = start.filter(|_| refs.refs.try_reserve(1).is_ok()) else {
refs.error = true;
return false;
};
PixOrCopyBlock { start, size: 0 }
};
refs.refs.push(PixOrCopyBlock { size: 0, ..block });
true
}
fn backward_refs_clone(from: &VP8LBackwardRefs, to: &mut VP8LBackwardRefs) -> bool {
vp8l_clear_backward_refs(to);
for block_from in &from.refs {
if !backward_refs_new_block(to) {
return false;
}
let block_to = to.refs.last_mut().expect("the new block is the last one");
let size = to_index(block_from.size);
block_to.start[..size].copy_from_slice(&block_from.start[..size]);
block_to.size = block_from.size;
}
true
}
pub fn vp8l_backward_refs_cursor_add(refs: &mut VP8LBackwardRefs, v: PixOrCopy) {
let full = refs
.refs
.last()
.is_none_or(|block| block.size == refs.block_size);
if full && !backward_refs_new_block(refs) {
return; }
let b = refs.refs.last_mut().expect("a block to add to");
b.start[to_index(b.size)] = v;
b.size += 1;
}
#[must_use]
pub fn vp8l_hash_chain_init(p: &mut VP8LHashChain, size: i32) -> bool {
debug_assert_eq!(p.size, 0);
debug_assert_eq!(p.offset_length.len(), 0);
debug_assert!(size > 0);
let count = i64::from(size).cast_unsigned();
let Some(offset_length) = webp_safe_malloc::<u32>(count, 4).map(|mut buffer| {
buffer.resize(to_index(size), 0);
buffer
}) else {
return false;
};
p.offset_length = offset_length;
p.size = size;
true
}
pub fn vp8l_hash_chain_clear(p: &mut VP8LHashChain) {
p.size = 0;
p.offset_length = Vec::new();
}
const HASH_MULTIPLIER_HI: u32 = 0xc6a4_a793;
const HASH_MULTIPLIER_LO: u32 = 0x5bd1_e996;
#[inline]
fn get_pix_pair_hash64(argb: &[u32]) -> u32 {
let mut key = argb[1].wrapping_mul(HASH_MULTIPLIER_HI);
key = key.wrapping_add(argb[0].wrapping_mul(HASH_MULTIPLIER_LO));
key >> (32 - HASH_BITS)
}
fn get_max_iters_for_quality(quality: i32) -> i32 {
8 + (quality * quality) / 128
}
fn get_window_size_for_hash_chain(quality: i32, xsize: i32) -> i32 {
let max_window_size = if quality > 75 {
WINDOW_SIZE
} else if quality > 50 {
xsize << 8
} else if quality > 25 {
xsize << 6
} else {
xsize << 4
};
debug_assert!(xsize > 0);
if max_window_size > WINDOW_SIZE {
WINDOW_SIZE
} else {
max_window_size
}
}
#[inline]
fn max_find_copy_length(len: i32) -> i32 {
if len < MAX_LENGTH { len } else { MAX_LENGTH }
}
#[expect(
clippy::cast_possible_wrap,
reason = "the C conversion of the unsigned sum to the int parameter"
)]
fn unsigned_progress(percent_start: i32, percent_range: i32, done: u32, total: u32) -> i32 {
percent_start
.cast_unsigned()
.wrapping_add(percent_range.cast_unsigned().wrapping_mul(done) / total) as i32
}
#[expect(
clippy::too_many_arguments,
reason = "the C signature of VP8LHashChainFill has nine parameters"
)]
#[expect(
clippy::cast_sign_loss,
clippy::cast_possible_wrap,
reason = "the C conversions between the int and uint32_t positions"
)]
#[expect(
clippy::too_many_lines,
reason = "the C function VP8LHashChainFill is translated as one function"
)]
pub fn vp8l_hash_chain_fill(
p: &mut VP8LHashChain,
quality: i32,
argb: &[u32],
xsize: i32,
ysize: i32,
low_effort: bool,
pic: &mut WebPPicture<'_>,
mut percent_range: i32,
percent: &mut i32,
) -> Result<(), WebPEncodingError> {
let size = xsize * ysize;
let iter_max = get_max_iters_for_quality(quality);
let window_size = get_window_size_for_hash_chain(quality, xsize) as u32;
let mut remaining_percent = percent_range;
let mut percent_start = *percent;
debug_assert!(size > 0);
debug_assert!(p.size != 0);
debug_assert_ne!(p.offset_length.len(), 0);
if size <= 2 {
p.offset_length[to_index(size - 1)] = 0;
p.offset_length[0] = 0;
return Ok(());
}
let Some(mut hash_to_first_index) = webp_safe_malloc::<i32>(HASH_SIZE as u64, 4) else {
return Err(webp_encoding_set_error(
pic,
WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY,
));
};
percent_range = remaining_percent / 2;
remaining_percent -= percent_range;
hash_to_first_index.resize(to_index(HASH_SIZE), -1);
let chain = &mut p.offset_length;
let mut argb_comp = argb[0] == argb[1];
let mut pos: i32 = 0;
while pos < size - 2 {
let hash_code: u32;
let argb_comp_next = argb[to_index(pos + 1)] == argb[to_index(pos + 2)];
if argb_comp && argb_comp_next {
let mut tmp = [0_u32; 2];
let mut len: u32 = 1;
tmp[0] = argb[to_index(pos)];
while pos + len as i32 + 2 < size
&& argb[to_index(pos) + len as usize + 2] == argb[to_index(pos)]
{
len += 1;
}
if len > MAX_LENGTH as u32 {
let skip = (len - MAX_LENGTH as u32) as usize;
chain[to_index(pos)..to_index(pos) + skip].fill(u32::MAX);
pos += (len - MAX_LENGTH as u32) as i32;
len = MAX_LENGTH as u32;
}
while len != 0 {
tmp[1] = len;
len -= 1;
let code = get_pix_pair_hash64(&tmp);
chain[to_index(pos)] = hash_to_first_index[code as usize].cast_unsigned();
hash_to_first_index[code as usize] = pos;
pos += 1;
}
argb_comp = false;
} else {
hash_code = get_pix_pair_hash64(&argb[to_index(pos)..]);
chain[to_index(pos)] = hash_to_first_index[hash_code as usize].cast_unsigned();
hash_to_first_index[hash_code as usize] = pos;
pos += 1;
argb_comp = argb_comp_next;
}
let progress = percent_start + percent_range * pos / (size - 2);
webp_report_progress(pic, progress, Some(&mut *percent))?;
}
chain[to_index(pos)] =
hash_to_first_index[get_pix_pair_hash64(&argb[to_index(pos)..]) as usize].cast_unsigned();
drop(hash_to_first_index);
percent_start += percent_range;
webp_report_progress(pic, percent_start, Some(&mut *percent))?;
percent_range = remaining_percent;
debug_assert!(size > 2);
p.offset_length[to_index(size - 1)] = 0;
p.offset_length[0] = 0;
let mut base_position = (size - 2) as u32;
while base_position > 0 {
let max_len =
max_find_copy_length((size - 1).cast_unsigned().wrapping_sub(base_position) as i32);
let argb_start = base_position as usize;
let mut iter = iter_max;
let mut best_length: i32 = 0;
let mut best_distance: u32 = 0;
let min_pos: i32 = if base_position > window_size {
(base_position - window_size) as i32
} else {
0
};
let length_max = if max_len < 256 { max_len } else { 256 };
let mut pos: i32 = p.offset_length[argb_start].cast_signed();
if !low_effort {
let mut curr_length;
if base_position >= xsize as u32 {
curr_length = find_match_length(
&argb[argb_start - to_index(xsize)..],
&argb[argb_start..],
best_length,
max_len,
);
if curr_length > best_length {
best_length = curr_length;
best_distance = xsize as u32;
}
iter -= 1;
}
curr_length = find_match_length(
&argb[argb_start - 1..],
&argb[argb_start..],
best_length,
max_len,
);
if curr_length > best_length {
best_length = curr_length;
best_distance = 1;
}
iter -= 1;
if best_length == MAX_LENGTH {
pos = min_pos - 1;
}
}
let mut best_argb = argb[argb_start + to_index(best_length)];
while pos >= min_pos && {
iter -= 1;
iter != 0
} {
debug_assert!(base_position > pos as u32);
if argb[to_index(pos + best_length)] == best_argb {
let curr_length =
vp8l_vector_mismatch(&argb[to_index(pos)..], &argb[argb_start..], max_len);
if best_length < curr_length {
best_length = curr_length;
best_distance = base_position.wrapping_sub(pos as u32);
best_argb = argb[argb_start + to_index(best_length)];
if best_length >= length_max {
break;
}
}
}
pos = p.offset_length[to_index(pos)].cast_signed();
}
let mut max_base_position = base_position;
loop {
debug_assert!(best_length <= MAX_LENGTH);
debug_assert!(best_distance <= WINDOW_SIZE as u32);
p.offset_length[base_position as usize] =
(best_distance << MAX_LENGTH_BITS) | best_length as u32;
base_position -= 1;
if best_distance == 0 || base_position == 0 {
break;
}
if base_position < best_distance
|| argb[(base_position - best_distance) as usize] != argb[base_position as usize]
{
break;
}
if best_length == MAX_LENGTH
&& best_distance != 1
&& base_position.wrapping_add(MAX_LENGTH as u32) < max_base_position
{
break;
}
if best_length < MAX_LENGTH {
best_length += 1;
max_base_position = base_position;
}
}
let total = (size - 2) as u32;
let progress = unsigned_progress(
percent_start,
percent_range,
total.wrapping_sub(base_position),
total,
);
webp_report_progress(pic, progress, Some(&mut *percent))?;
}
webp_report_progress(pic, percent_start + percent_range, Some(percent))
}
#[inline]
fn add_single_literal(
pixel: u32,
use_color_cache: bool,
hashers: &mut VP8LColorCache,
refs: &mut VP8LBackwardRefs,
) {
let v = if use_color_cache {
let key = vp8l_color_cache_get_index(hashers, pixel).cast_unsigned();
if vp8l_color_cache_lookup(hashers, key) == pixel {
pix_or_copy_create_cache_idx(key.cast_signed())
} else {
vp8l_color_cache_set(hashers, key, pixel);
pix_or_copy_create_literal(pixel)
}
} else {
pix_or_copy_create_literal(pixel)
};
vp8l_backward_refs_cursor_add(refs, v);
}
#[inline]
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the C conversion of the int length to uint16_t"
)]
pub(crate) fn copy_len(len: i32) -> u16 {
len as u16
}
fn backward_references_rle(
xsize: i32,
ysize: i32,
argb: &[u32],
cache_bits: i32,
refs: &mut VP8LBackwardRefs,
) -> bool {
let pix_count = xsize * ysize;
let use_color_cache = cache_bits > 0;
let mut hashers = VP8LColorCache::default();
if use_color_cache && !vp8l_color_cache_init(&mut hashers, cache_bits) {
return false;
}
vp8l_clear_backward_refs(refs);
add_single_literal(argb[0], use_color_cache, &mut hashers, refs);
let mut i: i32 = 1;
while i < pix_count {
let max_len = max_find_copy_length(pix_count - i);
let rle_len = find_match_length(&argb[to_index(i)..], &argb[to_index(i - 1)..], 0, max_len);
let prev_row_len = if i < xsize {
0
} else {
find_match_length(
&argb[to_index(i)..],
&argb[to_index(i - xsize)..],
0,
max_len,
)
};
if rle_len >= prev_row_len && rle_len >= MIN_LENGTH {
vp8l_backward_refs_cursor_add(refs, pix_or_copy_create_copy(1, copy_len(rle_len)));
i += rle_len;
} else if prev_row_len >= MIN_LENGTH {
vp8l_backward_refs_cursor_add(
refs,
pix_or_copy_create_copy(xsize.cast_unsigned(), copy_len(prev_row_len)),
);
if use_color_cache {
for k in 0..prev_row_len {
vp8l_color_cache_insert(&mut hashers, argb[to_index(i + k)]);
}
}
i += prev_row_len;
} else {
add_single_literal(argb[to_index(i)], use_color_cache, &mut hashers, refs);
i += 1;
}
}
if use_color_cache {
vp8l_color_cache_clear(&mut hashers);
}
!refs.error
}
fn backward_references_lz77(
xsize: i32,
ysize: i32,
argb: &[u32],
cache_bits: i32,
hash_chain: &VP8LHashChain,
refs: &mut VP8LBackwardRefs,
) -> bool {
let mut i_last_check: i32 = -1;
let use_color_cache = cache_bits > 0;
let pix_count = xsize * ysize;
let mut hashers = VP8LColorCache::default();
if use_color_cache {
let cc_init = vp8l_color_cache_init(&mut hashers, cache_bits);
if !cc_init {
return false;
}
}
vp8l_clear_backward_refs(refs);
let mut i: i32 = 0;
while i < pix_count {
let (offset, mut len) = vp8l_hash_chain_find_copy(hash_chain, i);
if len >= MIN_LENGTH {
let len_ini = len;
let mut max_reach: i32 = 0;
let j_max = if i + len_ini >= pix_count {
pix_count - 1
} else {
i + len_ini
};
i_last_check = if i > i_last_check { i } else { i_last_check };
let mut j = i_last_check + 1;
while j <= j_max {
let len_j = vp8l_hash_chain_find_length(hash_chain, j);
let reach = j + if len_j >= MIN_LENGTH { len_j } else { 1 }; if reach > max_reach {
len = j - i;
max_reach = reach;
if max_reach >= pix_count {
break;
}
}
j += 1;
}
} else {
len = 1;
}
debug_assert!(len > 0);
if len == 1 {
add_single_literal(argb[to_index(i)], use_color_cache, &mut hashers, refs);
} else {
vp8l_backward_refs_cursor_add(
refs,
pix_or_copy_create_copy(offset.cast_unsigned(), copy_len(len)),
);
if use_color_cache {
for j in i..i + len {
vp8l_color_cache_insert(&mut hashers, argb[to_index(j)]);
}
}
}
i += len;
}
let ok = !refs.error;
if use_color_cache {
vp8l_color_cache_clear(&mut hashers);
}
ok
}
const WINDOW_OFFSETS_SIZE_MAX: i32 = 32;
#[expect(
clippy::cast_sign_loss,
reason = "the C conversions of the offset and length to the packed uint32_t"
)]
#[expect(
clippy::too_many_lines,
reason = "the C function BackwardReferencesLz77Box is translated as one function"
)]
fn backward_references_lz77_box(
xsize: i32,
ysize: i32,
argb: &[u32],
cache_bits: i32,
hash_chain_best: &VP8LHashChain,
hash_chain: &mut VP8LHashChain,
refs: &mut VP8LBackwardRefs,
) -> bool {
const OFFSETS: usize = WINDOW_OFFSETS_SIZE_MAX as usize;
let pix_count = xsize * ysize;
let mut window_offsets = [0_i32; OFFSETS];
let mut window_offsets_new = [0_i32; OFFSETS];
let mut window_offsets_size: usize = 0;
let mut window_offsets_new_size: usize = 0;
let Some(mut counts_ini) = webp_safe_malloc::<u16>(i64::from(xsize * ysize).cast_unsigned(), 2)
else {
return false;
};
counts_ini.resize(to_index(pix_count), 0);
let mut best_offset_prev: i32 = -1;
let mut best_length_prev: i32 = -1;
counts_ini[to_index(pix_count - 1)] = 1;
let mut i = pix_count - 2;
while i >= 0 {
let at = to_index(i);
if argb[at] == argb[at + 1] {
let next = counts_ini[at + 1];
counts_ini[at] = next + u16::from(i32::from(next) != MAX_LENGTH);
} else {
counts_ini[at] = 1;
}
i -= 1;
}
{
for y in 0..=6 {
for x in -6..=6 {
let offset = y * xsize + x;
if offset <= 0 {
continue;
}
let plane_code = vp8l_distance_to_plane_code(xsize, offset) - 1;
if plane_code >= WINDOW_OFFSETS_SIZE_MAX {
continue;
}
window_offsets[to_index(plane_code)] = offset;
}
}
for i in 0..OFFSETS {
if window_offsets[i] == 0 {
continue;
}
window_offsets[window_offsets_size] = window_offsets[i];
window_offsets_size += 1;
}
for i in 0..window_offsets_size {
let mut is_reachable = false;
let mut j = 0;
while j < window_offsets_size && !is_reachable {
is_reachable |= window_offsets[i] == window_offsets[j] + 1;
j += 1;
}
if !is_reachable {
window_offsets_new[window_offsets_new_size] = window_offsets[i];
window_offsets_new_size += 1;
}
}
}
hash_chain.offset_length[0] = 0;
for i in 1..pix_count {
let mut best_length = vp8l_hash_chain_find_length(hash_chain_best, i);
let mut best_offset: i32 = 0;
let mut do_compute = true;
if best_length >= MAX_LENGTH {
best_offset = vp8l_hash_chain_find_offset(hash_chain_best, i);
for &window_offset in &window_offsets[..window_offsets_size] {
if best_offset == window_offset {
do_compute = false;
break;
}
}
}
if do_compute {
let use_prev = (best_length_prev > 1) && (best_length_prev < MAX_LENGTH);
let num_ind = if use_prev {
window_offsets_new_size
} else {
window_offsets_size
};
best_length = if use_prev { best_length_prev - 1 } else { 0 };
best_offset = if use_prev { best_offset_prev } else { 0 };
for ind in 0..num_ind {
let mut curr_length: i32 = 0;
let mut j = i;
let mut j_offset = if use_prev {
i - window_offsets_new[ind]
} else {
i - window_offsets[ind]
};
if j_offset < 0 || argb[to_index(j_offset)] != argb[to_index(i)] {
continue;
}
loop {
let counts_j_offset = i32::from(counts_ini[to_index(j_offset)]);
let counts_j = i32::from(counts_ini[to_index(j)]);
if counts_j_offset != counts_j {
curr_length += if counts_j_offset < counts_j {
counts_j_offset
} else {
counts_j
};
break;
}
curr_length += counts_j_offset;
j_offset += counts_j_offset;
j += counts_j_offset;
if !(curr_length <= MAX_LENGTH
&& j < pix_count
&& argb[to_index(j_offset)] == argb[to_index(j)])
{
break;
}
}
if best_length < curr_length {
best_offset = if use_prev {
window_offsets_new[ind]
} else {
window_offsets[ind]
};
if curr_length >= MAX_LENGTH {
best_length = MAX_LENGTH;
break;
}
best_length = curr_length;
}
}
}
debug_assert!(i + best_length <= pix_count);
debug_assert!(best_length <= MAX_LENGTH);
if best_length <= MIN_LENGTH {
hash_chain.offset_length[to_index(i)] = 0;
best_offset_prev = 0;
best_length_prev = 0;
} else {
hash_chain.offset_length[to_index(i)] =
((best_offset as u32) << MAX_LENGTH_BITS) | best_length as u32;
best_offset_prev = best_offset;
best_length_prev = best_length;
}
}
hash_chain.offset_length[0] = 0;
drop(counts_ini);
backward_references_lz77(xsize, ysize, argb, cache_bits, hash_chain, refs)
}
fn backward_references_2d_locality(xsize: i32, refs: &mut VP8LBackwardRefs) {
let mut c = vp8l_refs_cursor_init(refs);
while vp8l_refs_cursor_ok(&c) {
let v = c.get_mut(refs);
if pix_or_copy_is_copy(v) {
let dist = v.argb_or_distance.cast_signed();
let transformed_dist = vp8l_distance_to_plane_code(xsize, dist);
v.argb_or_distance = transformed_dist.cast_unsigned();
}
vp8l_refs_cursor_next(&mut c, refs);
}
}
#[expect(
clippy::many_single_char_names,
reason = "the C names a, r, g, b of the channels"
)]
fn calculate_best_cache_size(
argb: &[u32],
quality: i32,
refs: &VP8LBackwardRefs,
best_cache_bits: &mut i32,
) -> bool {
const SLOTS: usize = MAX_COLOR_CACHE_BITS as usize + 1;
let cache_bits_max = if quality <= 25 { 0 } else { *best_cache_bits };
let mut entropy_min = WEBP_UINT64_MAX;
let mut hashers: [VP8LColorCache; SLOTS] = Default::default();
let mut c = vp8l_refs_cursor_init(refs);
let mut histos: [Option<Box<VP8LHistogram>>; SLOTS] = Default::default();
let max = to_index(cache_bits_max);
debug_assert!((0..=MAX_COLOR_CACHE_BITS).contains(&cache_bits_max));
if cache_bits_max == 0 {
*best_cache_bits = 0;
return true;
}
for i in 0..=max {
let bits = i32::try_from(i).expect("cache bits fit an int");
let Some(mut histo) = vp8l_allocate_histogram(bits) else {
return false;
};
vp8l_histogram_init(&mut histo, bits, true);
histos[i] = Some(histo);
if i == 0 {
continue;
}
if !vp8l_color_cache_init(&mut hashers[i], bits) {
return false;
}
}
let mut h: Vec<&mut VP8LHistogram> = histos
.iter_mut()
.take(max + 1)
.map(|histo| &mut **histo.as_mut().expect("allocated above"))
.collect();
let mut argb_pos: usize = 0;
while vp8l_refs_cursor_ok(&c) {
let v = c.get(refs);
if pix_or_copy_is_literal(v) {
let pix = argb[argb_pos];
argb_pos += 1;
let a = ((pix >> 24) & 0xff) as usize;
let r = ((pix >> 16) & 0xff) as usize;
let g = ((pix >> 8) & 0xff) as usize;
let b = (pix & 0xff) as usize;
let mut key = vp8l_hash_pix(pix, 32 - cache_bits_max);
h[0].blue[b] += 1;
h[0].literal[g] += 1;
h[0].red[r] += 1;
h[0].alpha[a] += 1;
for i in (1..=max).rev() {
if vp8l_color_cache_lookup(&hashers[i], key.cast_unsigned()) == pix {
h[i].literal[to_index(NUM_LITERAL_CODES + NUM_LENGTH_CODES + key)] += 1;
} else {
vp8l_color_cache_set(&mut hashers[i], key.cast_unsigned(), pix);
h[i].blue[b] += 1;
h[i].literal[g] += 1;
h[i].red[r] += 1;
h[i].alpha[a] += 1;
}
key >>= 1;
}
} else {
let mut len = pix_or_copy_length(v).cast_signed();
let mut argb_prev = argb[argb_pos] ^ 0xffff_ffff;
let (code, _extra_bits, _extra_bits_value) = vp8l_prefix_encode(len);
for histo in &mut h {
histo.literal[to_index(NUM_LITERAL_CODES + code)] += 1;
}
loop {
if argb[argb_pos] != argb_prev {
let mut key = vp8l_hash_pix(argb[argb_pos], 32 - cache_bits_max);
for i in (1..=max).rev() {
hashers[i].colors[to_index(key)] = argb[argb_pos];
key >>= 1;
}
argb_prev = argb[argb_pos];
}
argb_pos += 1;
len -= 1;
if len == 0 {
break;
}
}
}
vp8l_refs_cursor_next(&mut c, refs);
}
for (i, histo) in (0..).zip(h.iter()) {
let entropy = vp8l_histogram_estimate_bits(histo);
if i == 0 || entropy < entropy_min {
entropy_min = entropy;
*best_cache_bits = i;
}
}
for hasher in &mut hashers[1..=max] {
vp8l_color_cache_clear(hasher);
}
true
}
fn backward_refs_with_local_cache(
argb: &[u32],
cache_bits: i32,
refs: &mut VP8LBackwardRefs,
) -> bool {
let mut pixel_index: usize = 0;
let mut hashers = VP8LColorCache::default();
let mut c = vp8l_refs_cursor_init(refs);
if !vp8l_color_cache_init(&mut hashers, cache_bits) {
return false;
}
while vp8l_refs_cursor_ok(&c) {
let v = c.get_mut(refs);
if pix_or_copy_is_literal(v) {
let argb_literal = v.argb_or_distance;
let ix = vp8l_color_cache_contains(&hashers, argb_literal);
if ix >= 0 {
*v = pix_or_copy_create_cache_idx(ix);
} else {
vp8l_color_cache_insert(&mut hashers, argb_literal);
}
pixel_index += 1;
} else {
debug_assert!(pix_or_copy_is_copy(v));
for _ in 0..v.len {
vp8l_color_cache_insert(&mut hashers, argb[pixel_index]);
pixel_index += 1;
}
}
vp8l_refs_cursor_next(&mut c, refs);
}
vp8l_color_cache_clear(&mut hashers);
true
}
fn get_backward_references_low_effort(
width: i32,
height: i32,
argb: &[u32],
cache_bits: &mut i32,
hash_chain: &VP8LHashChain,
refs_lz77: &mut VP8LBackwardRefs,
) -> bool {
*cache_bits = 0;
if !backward_references_lz77(width, height, argb, 0, hash_chain, refs_lz77) {
return false;
}
backward_references_2d_locality(width, refs_lz77);
true
}
#[expect(
clippy::too_many_arguments,
reason = "the C signature of GetBackwardReferences has ten parameters"
)]
#[expect(
clippy::too_many_lines,
reason = "the C function GetBackwardReferences is translated as one function"
)]
#[expect(clippy::similar_names, reason = "the C names refs and res")]
fn get_backward_references(
width: i32,
height: i32,
argb: &[u32],
quality: i32,
mut lz77_types_to_try: u32,
cache_bits_max: i32,
do_no_cache: bool,
hash_chain: &VP8LHashChain,
refs: &mut [VP8LBackwardRefs],
cache_bits_best: &mut i32,
) -> bool {
let mut lz77_types_best: [u32; 2] = [0, 0];
let mut bit_costs_best: [u64; 2] = [WEBP_UINT64_MAX, WEBP_UINT64_MAX];
let mut hash_chain_box = VP8LHashChain::default();
let tmp_index: usize = if do_no_cache { 2 } else { 1 };
let Some(mut histo) = vp8l_allocate_histogram(MAX_COLOR_CACHE_BITS) else {
return false;
};
let mut lz77_type: u32 = 1;
while lz77_types_to_try != 0 {
if (lz77_types_to_try & lz77_type) != 0 {
let mut bit_cost: u64 = 0;
let res = match VP8LLZ77Type(lz77_type) {
VP8LLZ77Type::kLZ77RLE => {
backward_references_rle(width, height, argb, 0, &mut refs[tmp_index])
}
VP8LLZ77Type::kLZ77Standard => {
backward_references_lz77(
width,
height,
argb,
0,
hash_chain,
&mut refs[tmp_index],
)
}
VP8LLZ77Type::kLZ77Box => {
if !vp8l_hash_chain_init(&mut hash_chain_box, width * height) {
return false;
}
backward_references_lz77_box(
width,
height,
argb,
0,
hash_chain,
&mut hash_chain_box,
&mut refs[tmp_index],
)
}
_ => {
debug_assert!(false, "an unknown LZ77 type");
false
}
};
if !res {
return false;
}
for i in (0..=1_usize).rev() {
let mut cache_bits = if i == 1 { 0 } else { cache_bits_max };
if i == 1 && !do_no_cache {
continue;
}
if i == 0 {
if !calculate_best_cache_size(argb, quality, &refs[tmp_index], &mut cache_bits)
{
return false;
}
if cache_bits > 0
&& !backward_refs_with_local_cache(argb, cache_bits, &mut refs[tmp_index])
{
return false;
}
}
if i == 0 && do_no_cache && cache_bits == 0 {
} else {
vp8l_histogram_create(&mut histo, &refs[tmp_index], cache_bits);
bit_cost = vp8l_histogram_estimate_bits(&histo);
}
if bit_cost < bit_costs_best[i] {
if i == 1 {
let (refs_tmp, refs_1) = split_pair(refs, tmp_index, 1);
if !backward_refs_clone(refs_tmp, refs_1) {
return false;
}
} else {
let (refs_tmp, refs_0) = split_two(refs, tmp_index, 0);
backward_refs_swap(refs_tmp, refs_0);
}
bit_costs_best[i] = bit_cost;
lz77_types_best[i] = lz77_type;
if i == 0 {
*cache_bits_best = cache_bits;
}
}
}
}
lz77_types_to_try &= !lz77_type;
lz77_type <<= 1;
}
debug_assert!(lz77_types_best[0] > 0);
debug_assert!(!do_no_cache || lz77_types_best[1] > 0);
for i in (0..=1_usize).rev() {
if i == 1 && !do_no_cache {
continue;
}
if (lz77_types_best[i] == VP8LLZ77Type::kLZ77Standard.0
|| lz77_types_best[i] == VP8LLZ77Type::kLZ77Box.0)
&& quality >= 25
{
let hash_chain_tmp = if lz77_types_best[i] == VP8LLZ77Type::kLZ77Standard.0 {
hash_chain
} else {
&hash_chain_box
};
let cache_bits = if i == 1 { 0 } else { *cache_bits_best };
let (refs_i, refs_tmp) = split_pair(refs, i, tmp_index);
if !vp8l_backward_references_trace_backwards(
width,
height,
argb,
cache_bits,
hash_chain_tmp,
refs_i,
refs_tmp,
) {
return false;
}
vp8l_histogram_create(&mut histo, refs_tmp, cache_bits);
let bit_cost_trace = vp8l_histogram_estimate_bits(&histo);
if bit_cost_trace < bit_costs_best[i] {
let (refs_tmp, refs_i) = split_two(refs, tmp_index, i);
backward_refs_swap(refs_tmp, refs_i);
}
}
backward_references_2d_locality(width, &mut refs[i]);
if i == 1 && lz77_types_best[0] == lz77_types_best[1] && *cache_bits_best == 0 {
let (refs_1, refs_0) = split_pair(refs, 1, 0);
if !backward_refs_clone(refs_1, refs_0) {
return false;
}
break;
}
}
true
}
#[expect(
clippy::too_many_arguments,
reason = "the C signature of VP8LGetBackwardReferences has fourteen parameters"
)]
pub fn vp8l_get_backward_references(
width: i32,
height: i32,
argb: &[u32],
quality: i32,
low_effort: bool,
lz77_types_to_try: u32,
cache_bits_max: i32,
do_no_cache: bool,
hash_chain: &VP8LHashChain,
refs: &mut [VP8LBackwardRefs],
cache_bits_best: &mut i32,
pic: &mut WebPPicture<'_>,
percent_range: i32,
percent: &mut i32,
) -> Result<(), WebPEncodingError> {
if low_effort {
*cache_bits_best = cache_bits_max;
if !get_backward_references_low_effort(
width,
height,
argb,
cache_bits_best,
hash_chain,
&mut refs[0],
) {
return Err(webp_encoding_set_error(
pic,
WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY,
));
}
} else if !get_backward_references(
width,
height,
argb,
quality,
lz77_types_to_try,
cache_bits_max,
do_no_cache,
hash_chain,
refs,
cache_bits_best,
) {
return Err(webp_encoding_set_error(
pic,
WebPEncodingError::VP8_ENC_ERROR_OUT_OF_MEMORY,
));
}
let progress = *percent + percent_range;
webp_report_progress(pic, progress, Some(percent))
}