use crate::coded_header::TokenProbUpdates;
use crate::frame_header::KEY_FRAME_START_CODE;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EncodeError {
InvalidDimensions { width: u32, height: u32 },
LoopFilterLevelOutOfRange { value: u8 },
SharpnessLevelOutOfRange { value: u8 },
InvalidDctPartitionCount { value: u8 },
QuantIndexOutOfRange { value: u8 },
FirstPartitionTooLarge { bytes: usize },
Token(TokenEncodeError),
Reconstruct(crate::reconstruct::ReconstructError),
ReferenceDimensionsMismatch {
source: (u32, u32),
reference: (u32, u32),
},
UnsupportedInterMode {
mode: crate::near_mv::InterMode,
},
InvalidCopyBufferSelector {
which: CopyBufferSelector,
value: u8,
},
LoopFilterDeltaOutOfRange {
which: LoopFilterDeltaSlot,
value: i16,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CopyBufferSelector {
Golden,
Alternate,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopFilterDeltaSlot {
RefCurrent,
RefLast,
RefGolden,
RefAltref,
ModeBpred,
ModeZeroMv,
ModeOtherMv,
ModeSplitMv,
}
impl core::fmt::Display for EncodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
EncodeError::InvalidDimensions { width, height } => write!(
f,
"vp8 encode: invalid frame dimensions {width}x{height} \
(must be 1..=0x3FFF in both axes)"
),
EncodeError::LoopFilterLevelOutOfRange { value } => write!(
f,
"vp8 encode: loop_filter_level={value} exceeds the 6-bit field (0..=63)"
),
EncodeError::SharpnessLevelOutOfRange { value } => write!(
f,
"vp8 encode: sharpness_level={value} exceeds the 3-bit field (0..=7)"
),
EncodeError::InvalidDctPartitionCount { value } => write!(
f,
"vp8 encode: nbr_of_dct_partitions={value} is not one of 1/2/4/8 (§9.5)"
),
EncodeError::QuantIndexOutOfRange { value } => write!(
f,
"vp8 encode: y_ac_qi={value} exceeds the 7-bit field (0..=127)"
),
EncodeError::FirstPartitionTooLarge { bytes } => write!(
f,
"vp8 encode: first-partition size {bytes} exceeds the 19-bit field (0..=0x7_FFFF)"
),
EncodeError::Token(inner) => write!(f, "vp8 encode: {inner}"),
EncodeError::Reconstruct(inner) => write!(f, "vp8 encode: {inner}"),
EncodeError::ReferenceDimensionsMismatch { source, reference } => write!(
f,
"vp8 encode: P-frame source frame {}x{} (macroblock-aligned) does \
not match the supplied reference frame {}x{}",
source.0, source.1, reference.0, reference.1
),
EncodeError::UnsupportedInterMode { mode } => write!(
f,
"vp8 encode: inter-mode {mode:?} is not supported by the \
Phase-11 ZEROMV / NEARESTMV / NEARMV / NEWMV / SPLITMV picker"
),
EncodeError::InvalidCopyBufferSelector { which, value } => write!(
f,
"vp8 encode: copy_buffer_to_{} = {value} is outside the \
2-bit field 0..=2 (§9.7)",
match which {
CopyBufferSelector::Golden => "golden",
CopyBufferSelector::Alternate => "alternate",
}
),
EncodeError::LoopFilterDeltaOutOfRange { which, value } => write!(
f,
"vp8 encode: loop_filter_delta[{}] = {value} is outside the \
§9.4 6-bit-magnitude + 1-bit-sign field (-63..=63)",
match which {
LoopFilterDeltaSlot::RefCurrent => "ref_current",
LoopFilterDeltaSlot::RefLast => "ref_last",
LoopFilterDeltaSlot::RefGolden => "ref_golden",
LoopFilterDeltaSlot::RefAltref => "ref_altref",
LoopFilterDeltaSlot::ModeBpred => "mode_bpred",
LoopFilterDeltaSlot::ModeZeroMv => "mode_zero_mv",
LoopFilterDeltaSlot::ModeOtherMv => "mode_other_mv",
LoopFilterDeltaSlot::ModeSplitMv => "mode_split_mv",
}
),
}
}
}
impl std::error::Error for EncodeError {}
#[derive(Debug, Default)]
pub struct BoolEncoder {
out: Vec<u8>,
range: u32,
bottom: u32,
bit_count: i32,
}
impl BoolEncoder {
pub fn new() -> Self {
BoolEncoder {
out: Vec::new(),
range: 255,
bottom: 0,
bit_count: 24,
}
}
#[inline]
pub fn write_bool(&mut self, prob: u8, value: bool) {
let split = 1 + (((self.range - 1) * prob as u32) >> 8);
let (range, mut bottom) = if value {
(self.range - split, self.bottom.wrapping_add(split))
} else {
(split, self.bottom)
};
let shift = range.leading_zeros() - 24;
let count = self.bit_count as u32;
if shift < count {
bottom <<= shift;
self.bit_count -= shift as i32;
} else {
bottom = self.emit_byte(bottom, shift, count);
}
self.range = range << shift;
self.bottom = bottom;
}
#[cold]
#[inline(never)]
fn emit_byte(&mut self, mut bottom: u32, shift: u32, count: u32) -> u32 {
bottom <<= count - 1;
if bottom >> 31 == 1 {
add_one_to_output(&mut self.out);
}
bottom <<= 1;
self.out.push((bottom >> 24) as u8);
bottom &= (1 << 24) - 1;
let rest = shift - count;
self.bit_count = 8 - rest as i32;
bottom << rest
}
pub fn write_literal(&mut self, value: u32, num_bits: u32) {
debug_assert!(num_bits <= 32);
let mut range = self.range;
let mut bottom = self.bottom;
let mut bit_count = self.bit_count;
let mut i = num_bits;
while i > 0 {
i -= 1;
let split = 1 + ((range - 1) >> 1);
if ((value >> i) & 1) != 0 {
bottom = bottom.wrapping_add(split);
range -= split;
} else {
range = split;
}
while range < 128 {
range <<= 1;
if (bottom >> 31) & 1 == 1 {
add_one_to_output(&mut self.out);
}
bottom <<= 1;
bit_count -= 1;
if bit_count == 0 {
self.out.push((bottom >> 24) as u8);
bottom &= (1 << 24) - 1;
bit_count = 8;
}
}
}
self.range = range;
self.bottom = bottom;
self.bit_count = bit_count;
}
pub fn write_signed_literal(&mut self, value: i32, num_bits: u32) {
let magnitude = value.unsigned_abs();
debug_assert!(
magnitude < (1u32 << num_bits),
"signed literal {value} does not fit in {num_bits} magnitude bits"
);
self.write_literal(magnitude, num_bits);
self.write_bool(128, value < 0);
}
pub fn write_treed<F>(&mut self, tree: &[i8], prob_lookup: F, leaf: u8)
where
F: Fn(usize) -> u8,
{
let mut path = [false; 16];
let len = treed_find_path(tree, leaf, &mut path);
let mut i: i8 = 0;
for &bit in &path[..len] {
self.write_bool(prob_lookup((i as usize) >> 1), bit);
i = tree[i as usize + bit as usize];
}
}
fn write_treed_cached<F>(&mut self, paths: &[TreedLeafPath], prob_lookup: F, leaf: u8)
where
F: Fn(usize) -> u8,
{
let p = &paths[leaf as usize];
for s in 0..p.len as usize {
self.write_bool(prob_lookup(p.prob_index[s] as usize), p.bits[s]);
}
}
pub fn finish(mut self) -> Vec<u8> {
let c = self.bit_count;
let v = self.bottom;
if v & (1u32 << (32 - c)) != 0 {
add_one_to_output(&mut self.out);
}
let mut v = v;
v = v.wrapping_shl((c & 7) as u32);
let mut shifts = c >> 3;
while shifts > 0 {
v = v.wrapping_shl(8);
shifts -= 1;
}
for _ in 0..4 {
self.out.push((v >> 24) as u8);
v = v.wrapping_shl(8);
}
self.out
}
pub fn bytes_written(&self) -> usize {
self.out.len()
}
}
fn add_one_to_output(out: &mut [u8]) {
let mut i = out.len();
while i > 0 {
i -= 1;
if out[i] == 255 {
out[i] = 0;
} else {
out[i] = out[i].wrapping_add(1);
return;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ScaleCode {
None = 0,
FiveFourths = 1,
FiveThirds = 2,
Double = 3,
}
#[allow(clippy::too_many_arguments)]
pub fn write_frame_tag(
out: &mut Vec<u8>,
key_frame: bool,
version: u8,
show_frame: bool,
first_partition_size: u32,
width: u32,
height: u32,
horizontal_scale: ScaleCode,
vertical_scale: ScaleCode,
) -> Result<usize, EncodeError> {
if first_partition_size > 0x7_FFFF {
return Err(EncodeError::FirstPartitionTooLarge {
bytes: first_partition_size as usize,
});
}
let frame_type_bit: u32 = if key_frame { 0 } else { 1 };
let show_bit: u32 = if show_frame { 1 } else { 0 };
let tmp: u32 = frame_type_bit
| ((version as u32 & 0x7) << 1)
| (show_bit << 4)
| ((first_partition_size & 0x7_FFFF) << 5);
out.push((tmp & 0xff) as u8);
out.push(((tmp >> 8) & 0xff) as u8);
out.push(((tmp >> 16) & 0xff) as u8);
if !key_frame {
return Ok(3);
}
if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
return Err(EncodeError::InvalidDimensions { width, height });
}
out.extend_from_slice(&KEY_FRAME_START_CODE);
let h_word: u16 = ((horizontal_scale as u16) << 14) | (width as u16 & 0x3FFF);
let v_word: u16 = ((vertical_scale as u16) << 14) | (height as u16 & 0x3FFF);
out.push((h_word & 0xff) as u8);
out.push(((h_word >> 8) & 0xff) as u8);
out.push((v_word & 0xff) as u8);
out.push(((v_word >> 8) & 0xff) as u8);
Ok(10)
}
pub fn patch_first_partition_size(buf: &mut [u8], size: u32) -> Result<(), EncodeError> {
if size > 0x7_FFFF {
return Err(EncodeError::FirstPartitionTooLarge {
bytes: size as usize,
});
}
debug_assert!(buf.len() >= 3, "frame tag must be present");
let tmp = (buf[0] as u32) | ((buf[1] as u32) << 8) | ((buf[2] as u32) << 16);
let new = (tmp & 0x1F) | ((size & 0x7_FFFF) << 5);
buf[0] = (new & 0xff) as u8;
buf[1] = ((new >> 8) & 0xff) as u8;
buf[2] = ((new >> 16) & 0xff) as u8;
Ok(())
}
pub fn write_segment_update_flags(enc: &mut BoolEncoder, enabled: bool) {
debug_assert!(
!enabled,
"use write_update_segmentation for the segmentation_enabled = true path"
);
enc.write_bool(128, enabled);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct UpdateSegmentationLayer {
pub update_mb_segmentation_map: bool,
pub feature_mode_absolute: bool,
pub quantizer: [Option<i16>; 4],
pub loop_filter: [Option<i16>; 4],
pub segment_prob: [Option<u8>; 3],
}
pub fn write_update_segmentation(enc: &mut BoolEncoder, layer: &UpdateSegmentationLayer) {
enc.write_bool(128, true);
enc.write_bool(128, layer.update_mb_segmentation_map);
let update_feature_data = layer.quantizer.iter().any(Option::is_some)
|| layer.loop_filter.iter().any(Option::is_some);
enc.write_bool(128, update_feature_data);
if update_feature_data {
enc.write_bool(128, layer.feature_mode_absolute);
for slot in &layer.quantizer {
match slot {
Some(v) => {
enc.write_bool(128, true);
enc.write_signed_literal(*v as i32, 7);
}
None => enc.write_bool(128, false),
}
}
for slot in &layer.loop_filter {
match slot {
Some(v) => {
enc.write_bool(128, true);
enc.write_signed_literal(*v as i32, 6);
}
None => enc.write_bool(128, false),
}
}
}
if layer.update_mb_segmentation_map {
for slot in &layer.segment_prob {
match slot {
Some(p) => {
enc.write_bool(128, true);
enc.write_literal(*p as u32, 8);
}
None => enc.write_bool(128, false),
}
}
}
}
pub fn write_loop_filter(
enc: &mut BoolEncoder,
filter_type: bool,
loop_filter_level: u8,
sharpness_level: u8,
loop_filter_adj_enable: bool,
) -> Result<(), EncodeError> {
if loop_filter_level > 63 {
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: loop_filter_level,
});
}
if sharpness_level > 7 {
return Err(EncodeError::SharpnessLevelOutOfRange {
value: sharpness_level,
});
}
debug_assert!(
!loop_filter_adj_enable,
"Phase 1 encoder only supports loop_filter_adj_enable = false"
);
enc.write_bool(128, filter_type);
enc.write_literal(loop_filter_level as u32, 6);
enc.write_literal(sharpness_level as u32, 3);
enc.write_bool(128, loop_filter_adj_enable);
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LoopFilterDeltas {
pub enabled: bool,
pub update: bool,
pub ref_frame_delta: [Option<i8>; 4],
pub mode_delta: [Option<i8>; 4],
}
impl Default for LoopFilterDeltas {
fn default() -> Self {
Self {
enabled: false,
update: false,
ref_frame_delta: [None; 4],
mode_delta: [None; 4],
}
}
}
impl LoopFilterDeltas {
pub fn validate(&self) -> Result<(), EncodeError> {
const REF_SLOTS: [LoopFilterDeltaSlot; 4] = [
LoopFilterDeltaSlot::RefCurrent,
LoopFilterDeltaSlot::RefLast,
LoopFilterDeltaSlot::RefGolden,
LoopFilterDeltaSlot::RefAltref,
];
const MODE_SLOTS: [LoopFilterDeltaSlot; 4] = [
LoopFilterDeltaSlot::ModeBpred,
LoopFilterDeltaSlot::ModeZeroMv,
LoopFilterDeltaSlot::ModeOtherMv,
LoopFilterDeltaSlot::ModeSplitMv,
];
for (slot, value) in REF_SLOTS.iter().zip(self.ref_frame_delta.iter()) {
if let Some(v) = value {
let mag = (*v as i16).unsigned_abs();
if mag > 63 {
return Err(EncodeError::LoopFilterDeltaOutOfRange {
which: *slot,
value: *v as i16,
});
}
}
}
for (slot, value) in MODE_SLOTS.iter().zip(self.mode_delta.iter()) {
if let Some(v) = value {
let mag = (*v as i16).unsigned_abs();
if mag > 63 {
return Err(EncodeError::LoopFilterDeltaOutOfRange {
which: *slot,
value: *v as i16,
});
}
}
}
Ok(())
}
pub fn effective(
&self,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
) -> ([i16; 4], [i16; 4]) {
if !self.enabled {
return ([0; 4], [0; 4]);
}
if !self.update {
return (carried_ref_deltas, carried_mode_deltas);
}
let mut eff_ref = carried_ref_deltas;
let mut eff_mode = carried_mode_deltas;
for (slot, value) in eff_ref.iter_mut().zip(self.ref_frame_delta.iter()) {
if let Some(v) = value {
*slot = *v as i16;
}
}
for (slot, value) in eff_mode.iter_mut().zip(self.mode_delta.iter()) {
if let Some(v) = value {
*slot = *v as i16;
}
}
(eff_ref, eff_mode)
}
}
pub fn write_loop_filter_with_deltas(
enc: &mut BoolEncoder,
filter_type: bool,
loop_filter_level: u8,
sharpness_level: u8,
deltas: &LoopFilterDeltas,
) -> Result<(), EncodeError> {
if loop_filter_level > 63 {
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: loop_filter_level,
});
}
if sharpness_level > 7 {
return Err(EncodeError::SharpnessLevelOutOfRange {
value: sharpness_level,
});
}
deltas.validate()?;
enc.write_bool(128, filter_type);
enc.write_literal(loop_filter_level as u32, 6);
enc.write_literal(sharpness_level as u32, 3);
enc.write_bool(128, deltas.enabled);
if deltas.enabled {
enc.write_bool(128, deltas.update);
if deltas.update {
for slot in &deltas.ref_frame_delta {
match slot {
Some(v) => {
enc.write_bool(128, true);
write_signed_lf_delta(enc, *v);
}
None => enc.write_bool(128, false),
}
}
for slot in &deltas.mode_delta {
match slot {
Some(v) => {
enc.write_bool(128, true);
write_signed_lf_delta(enc, *v);
}
None => enc.write_bool(128, false),
}
}
}
}
Ok(())
}
fn write_signed_lf_delta(enc: &mut BoolEncoder, value: i8) {
debug_assert!((-63..=63).contains(&(value as i16)));
let magnitude = (value as i16).unsigned_abs() as u32;
enc.write_literal(magnitude, 6);
enc.write_bool(128, value < 0);
}
pub fn write_token_partition_count(enc: &mut BoolEncoder, count: u8) -> Result<(), EncodeError> {
let log2: u32 = match count {
1 => 0,
2 => 1,
4 => 2,
8 => 3,
other => return Err(EncodeError::InvalidDctPartitionCount { value: other }),
};
enc.write_literal(log2, 2);
Ok(())
}
pub fn write_quant_indices(
enc: &mut BoolEncoder,
y_ac_qi: u8,
y_dc_delta: Option<i8>,
y2_dc_delta: Option<i8>,
y2_ac_delta: Option<i8>,
uv_dc_delta: Option<i8>,
uv_ac_delta: Option<i8>,
) -> Result<(), EncodeError> {
if y_ac_qi > 127 {
return Err(EncodeError::QuantIndexOutOfRange { value: y_ac_qi });
}
enc.write_literal(y_ac_qi as u32, 7);
for delta in [
y_dc_delta,
y2_dc_delta,
y2_ac_delta,
uv_dc_delta,
uv_ac_delta,
] {
match delta {
Some(d) => {
enc.write_bool(128, true);
enc.write_signed_literal(d as i32, 4);
}
None => enc.write_bool(128, false),
}
}
Ok(())
}
pub fn write_mb_no_skip_coeff(enc: &mut BoolEncoder, enabled: bool, prob_skip_false: u8) {
enc.write_bool(128, enabled);
if enabled {
enc.write_literal(prob_skip_false as u32, 8);
}
}
pub fn write_no_token_prob_updates(enc: &mut BoolEncoder, flag_probs: &[u8; 1056]) {
for &p in flag_probs.iter() {
enc.write_bool(p, false);
}
}
pub fn write_token_prob_updates(
enc: &mut BoolEncoder,
updates: &TokenProbUpdates,
flag_probs: &[u8; 1056],
) {
for i in 0..4 {
for j in 0..8 {
for k in 0..3 {
for t in 0..11 {
let p = flag_probs[i * 8 * 3 * 11 + j * 3 * 11 + k * 11 + t];
match updates[i][j][k][t] {
Some(new_prob) => {
enc.write_bool(p, true);
enc.write_literal(new_prob as u32, 8);
}
None => {
enc.write_bool(p, false);
}
}
}
}
}
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct SilentKeyframeParams {
pub width: u32,
pub height: u32,
pub loop_filter_level: u8,
pub sharpness_level: u8,
pub y_ac_qi: u8,
pub nbr_of_dct_partitions: u8,
}
impl SilentKeyframeParams {
#[must_use]
pub fn with_width(mut self, v: u32) -> Self {
self.width = v;
self
}
#[must_use]
pub fn with_height(mut self, v: u32) -> Self {
self.height = v;
self
}
#[must_use]
pub fn with_loop_filter_level(mut self, v: u8) -> Self {
self.loop_filter_level = v;
self
}
#[must_use]
pub fn with_sharpness_level(mut self, v: u8) -> Self {
self.sharpness_level = v;
self
}
#[must_use]
pub fn with_y_ac_qi(mut self, v: u8) -> Self {
self.y_ac_qi = v;
self
}
#[must_use]
pub fn with_nbr_of_dct_partitions(mut self, v: u8) -> Self {
self.nbr_of_dct_partitions = v;
self
}
}
impl Default for SilentKeyframeParams {
fn default() -> Self {
SilentKeyframeParams {
width: 16,
height: 16,
loop_filter_level: 0,
sharpness_level: 0,
y_ac_qi: 0,
nbr_of_dct_partitions: 1,
}
}
}
impl SilentKeyframeParams {
pub fn new(width: u32, height: u32) -> Self {
SilentKeyframeParams {
width,
height,
..Self::default()
}
}
}
pub fn encode_silent_keyframe(params: SilentKeyframeParams) -> Result<Vec<u8>, EncodeError> {
if params.width == 0 || params.width > 0x3FFF || params.height == 0 || params.height > 0x3FFF {
return Err(EncodeError::InvalidDimensions {
width: params.width,
height: params.height,
});
}
let mb_cols = params.width.div_ceil(16) as usize;
let mb_rows = params.height.div_ceil(16) as usize;
let mut enc = BoolEncoder::new();
enc.write_bool(128, false);
enc.write_bool(128, false);
write_segment_update_flags(&mut enc, false);
write_loop_filter(
&mut enc,
false,
params.loop_filter_level,
params.sharpness_level,
false,
)?;
write_token_partition_count(&mut enc, params.nbr_of_dct_partitions)?;
write_quant_indices(&mut enc, params.y_ac_qi, None, None, None, None, None)?;
enc.write_bool(128, true);
write_no_token_prob_updates(&mut enc, &COEFF_UPDATE_PROBS_FLAT);
write_mb_no_skip_coeff(&mut enc, true, 1);
for _ in 0..(mb_rows * mb_cols) {
enc.write_bool(1, true);
enc.write_bool(145, true);
enc.write_bool(156, false);
enc.write_bool(163, false);
enc.write_bool(142, false);
}
let first_partition = enc.finish();
let first_partition_size = first_partition.len();
if first_partition_size > 0x7_FFFF {
return Err(EncodeError::FirstPartitionTooLarge {
bytes: first_partition_size,
});
}
let mut out: Vec<u8> = Vec::with_capacity(10 + first_partition_size + 16);
write_frame_tag(
&mut out,
true,
0,
true,
first_partition_size as u32,
params.width,
params.height,
ScaleCode::None,
ScaleCode::None,
)?;
out.extend_from_slice(&first_partition);
let num_partitions = params.nbr_of_dct_partitions as usize;
let mut dct_partitions: Vec<Vec<u8>> = Vec::with_capacity(num_partitions);
for _ in 0..num_partitions {
let p = BoolEncoder::new();
dct_partitions.push(p.finish());
}
for part in dct_partitions.iter().take(num_partitions.saturating_sub(1)) {
let sz = part.len();
out.push((sz & 0xff) as u8);
out.push(((sz >> 8) & 0xff) as u8);
out.push(((sz >> 16) & 0xff) as u8);
}
for p in &dct_partitions {
out.extend_from_slice(p);
}
Ok(out)
}
#[doc(hidden)]
pub const COEFF_UPDATE_PROBS_FLAT: [u8; 1056] = {
let mut out = [0u8; 1056];
let mut i = 0;
while i < 4 {
let mut j = 0;
while j < 8 {
let mut k = 0;
while k < 3 {
let mut t = 0;
while t < 11 {
out[i * 8 * 3 * 11 + j * 3 * 11 + k * 11 + t] = COEFF_UPDATE_PROBS[i][j][k][t];
t += 1;
}
k += 1;
}
j += 1;
}
i += 1;
}
out
};
const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [
[
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255],
[249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255],
[234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255],
[250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255],
[254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
],
[
[
[217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255],
[234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255],
],
[
[255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
[250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
],
[
[
[186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255],
[234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255],
[251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255],
],
[
[255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255],
],
[
[255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
],
[
[
[248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255],
[248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
[246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
[252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255],
],
[
[255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255],
[248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
[253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255],
[252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255],
[250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
[
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
],
],
];
use crate::dct_tokens::{BlockType, COEFF_BANDS, CoeffProbs, DctToken};
const ENC_COEFF_TREE: [i8; 22] = [
-(DctToken::Eob as i8),
2,
-(DctToken::Dct0 as i8),
4,
-(DctToken::Dct1 as i8),
6,
8,
12,
-(DctToken::Dct2 as i8),
10,
-(DctToken::Dct3 as i8),
-(DctToken::Dct4 as i8),
14,
16,
-(DctToken::Cat1 as i8),
-(DctToken::Cat2 as i8),
18,
20,
-(DctToken::Cat3 as i8),
-(DctToken::Cat4 as i8),
-(DctToken::Cat5 as i8),
-(DctToken::Cat6 as i8),
];
const ENC_PCAT1: &[u8] = &[159];
const ENC_PCAT2: &[u8] = &[165, 145];
const ENC_PCAT3: &[u8] = &[173, 148, 140];
const ENC_PCAT4: &[u8] = &[176, 155, 140, 135];
const ENC_PCAT5: &[u8] = &[180, 157, 141, 134, 130];
const ENC_PCAT6: &[u8] = &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
const ENC_CAT_BASE: [u16; 6] = [5, 7, 11, 19, 35, 67];
pub fn classify_coeff_token(abs_value: u16) -> DctToken {
match abs_value {
0 => DctToken::Dct0,
1 => DctToken::Dct1,
2 => DctToken::Dct2,
3 => DctToken::Dct3,
4 => DctToken::Dct4,
5..=6 => DctToken::Cat1,
7..=10 => DctToken::Cat2,
11..=18 => DctToken::Cat3,
19..=34 => DctToken::Cat4,
35..=66 => DctToken::Cat5,
_ => DctToken::Cat6,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TokenEncodeError {
CoefficientOutOfRange { index: usize, value: i16 },
}
impl core::fmt::Display for TokenEncodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
TokenEncodeError::CoefficientOutOfRange { index, value } => write!(
f,
"vp8 token encode: coefficient[{index}]={value} exceeds the §13.2 alphabet maximum (±2114)"
),
}
}
}
impl std::error::Error for TokenEncodeError {}
#[derive(Clone, Copy, Debug)]
struct TokenBitStep {
prob_index: u8,
bit: bool,
}
const TOKEN_BIT_PATH_MAX_LEN: usize = 7;
type TokenBitPathEntry = ([TokenBitStep; TOKEN_BIT_PATH_MAX_LEN], u8);
type TokenBitPathTable = [[TokenBitPathEntry; 12]; 2];
static TOKEN_BIT_PATHS: std::sync::LazyLock<TokenBitPathTable> =
std::sync::LazyLock::new(precompute_token_bit_paths);
fn precompute_token_bit_paths() -> TokenBitPathTable {
let zero = TokenBitStep {
prob_index: 0,
bit: false,
};
let mut out = [[([zero; TOKEN_BIT_PATH_MAX_LEN], 0u8); 12]; 2];
fn descend(
i: i8,
target: i8,
buf: &mut [TokenBitStep; TOKEN_BIT_PATH_MAX_LEN],
len: &mut usize,
) -> bool {
for &bit in &[false, true] {
let child = ENC_COEFF_TREE[i as usize + bit as usize];
if child <= 0 {
if -child == target {
buf[*len] = TokenBitStep {
prob_index: (i as usize >> 1) as u8,
bit,
};
*len += 1;
return true;
}
} else {
buf[*len] = TokenBitStep {
prob_index: (i as usize >> 1) as u8,
bit,
};
*len += 1;
if descend(child, target, buf, len) {
return true;
}
*len -= 1;
}
}
false
}
for (slot, &start) in [0i8, 2i8].iter().enumerate() {
for token in 0i8..12 {
let mut buf = [zero; TOKEN_BIT_PATH_MAX_LEN];
let mut len = 0usize;
if descend(start, token, &mut buf, &mut len) {
out[slot][token as usize] = (buf, len as u8);
}
}
}
out
}
fn token_to_bit_path(token: DctToken, start_index: i8) -> &'static [TokenBitStep] {
let slot = match start_index {
0 => 0usize,
2 => 1usize,
_ => {
debug_assert!(false, "unsupported coeff_tree start_index {start_index}");
0
}
};
let (buf, len) = &TOKEN_BIT_PATHS[slot][token as usize];
debug_assert!(
*len > 0,
"token {token:?} not reachable from coeff_tree index {start_index}"
);
&buf[..*len as usize]
}
fn cat_extras(token: DctToken) -> Option<(u16, &'static [u8])> {
match token {
DctToken::Cat1 => Some((ENC_CAT_BASE[0], ENC_PCAT1)),
DctToken::Cat2 => Some((ENC_CAT_BASE[1], ENC_PCAT2)),
DctToken::Cat3 => Some((ENC_CAT_BASE[2], ENC_PCAT3)),
DctToken::Cat4 => Some((ENC_CAT_BASE[3], ENC_PCAT4)),
DctToken::Cat5 => Some((ENC_CAT_BASE[4], ENC_PCAT5)),
DctToken::Cat6 => Some((ENC_CAT_BASE[5], ENC_PCAT6)),
_ => None,
}
}
pub fn encode_coeff_block(
enc: &mut BoolEncoder,
block_type: BlockType,
coeff_probs: &CoeffProbs,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> Result<usize, TokenEncodeError> {
encode_coeff_block_into(
enc,
block_type,
coeff_probs,
above_has_nonzero,
left_has_nonzero,
coeffs,
)
}
trait BoolSink {
fn put(&mut self, prob: u8, value: bool);
#[inline]
fn put_tree(&mut self, _slot: u16, prob: u8, value: bool) {
self.put(prob, value);
}
}
impl BoolSink for BoolEncoder {
#[inline]
fn put(&mut self, prob: u8, value: bool) {
self.write_bool(prob, value);
}
}
fn encode_coeff_block_into<S: BoolSink>(
enc: &mut S,
block_type: BlockType,
coeff_probs: &CoeffProbs,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> Result<usize, TokenEncodeError> {
let plane = block_type.plane_index();
let first_coeff = block_type.first_coeff();
let mut last_non_zero: i32 = -1;
let mut max_abs = 0u16;
for (i, &v) in coeffs.iter().enumerate().skip(first_coeff) {
max_abs = max_abs.max(v.unsigned_abs());
if v != 0 {
last_non_zero = i as i32;
}
}
if max_abs > 2114 {
for (i, &v) in coeffs.iter().enumerate().skip(first_coeff) {
if v.unsigned_abs() > 2114 {
return Err(TokenEncodeError::CoefficientOutOfRange { index: i, value: v });
}
}
}
let token_paths = &*TOKEN_BIT_PATHS;
let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
let mut prev_was_zero = false;
let mut non_zero_count = 0usize;
let mut i = first_coeff;
while i < 16 {
let band = COEFF_BANDS[i];
let probs = &coeff_probs[plane][band][ctx3];
let emit_eob = (i as i32) > last_non_zero;
let (token, abs_value, sign) = if emit_eob {
(DctToken::Eob, 0u16, false)
} else {
let v = coeffs[i];
let abs = v.unsigned_abs();
(classify_coeff_token(abs), abs, v < 0)
};
let (path, path_len) = &token_paths[prev_was_zero as usize][token as usize];
debug_assert!(*path_len > 0, "EOB cannot follow a literal DCT_0");
let slot_base = (((plane * 8 + band) * 3 + ctx3) * 11) as u16;
for step in &path[..*path_len as usize] {
enc.put_tree(
slot_base + step.prob_index as u16,
probs[step.prob_index as usize],
step.bit,
);
}
if token == DctToken::Eob {
break;
}
if let Some((base, plist)) = cat_extras(token) {
let extra = abs_value - base;
let n = plist.len();
for (j, &p) in plist.iter().enumerate() {
let bit = ((extra >> (n - 1 - j)) & 1) == 1;
enc.put(p, bit);
}
}
if abs_value != 0 {
enc.put(128, sign);
non_zero_count += 1;
}
ctx3 = if abs_value == 0 {
0
} else if abs_value == 1 {
1
} else {
2
};
prev_was_zero = token == DctToken::Dct0;
i += 1;
}
Ok(non_zero_count)
}
#[derive(Debug)]
pub struct TokenEncoder {
enc: BoolEncoder,
coeff_probs: CoeffProbs,
}
impl TokenEncoder {
pub fn new(coeff_probs: CoeffProbs) -> Self {
TokenEncoder {
enc: BoolEncoder::new(),
coeff_probs,
}
}
pub fn encode_block(
&mut self,
block_type: BlockType,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> Result<usize, TokenEncodeError> {
encode_coeff_block(
&mut self.enc,
block_type,
&self.coeff_probs,
above_has_nonzero,
left_has_nonzero,
coeffs,
)
}
pub fn finish(self) -> Vec<u8> {
self.enc.finish()
}
pub fn bytes_written(&self) -> usize {
self.enc.bytes_written()
}
}
use crate::dct_tokens::MbEntropyCtx;
use crate::forward_transform::{forward_dct_4x4, forward_wht_4x4, raster_to_scan};
use crate::frame::MbCoeffs;
use crate::intra_predict::{
DEFAULT_ABOVE_PIXEL, DEFAULT_LEFT_PIXEL, predict_b4x4, predict_uv8x8, predict_y16x16,
};
use crate::inverse_transform::{add_residue_4x4, inverse_dct_4x4, inverse_wht_4x4};
use crate::macroblock::{
BMODE_TREE, IF_UV_MODE_PROB_DEFAULTS, IF_YMODE_PROB_DEFAULTS, IF_YMODE_TREE, IntraBmode,
IntraUvMode, IntraYMode, KF_BMODE_PROB, KF_UV_MODE_PROB, KF_YMODE_PROB, KF_YMODE_TREE,
MacroblockModes, UV_MODE_TREE,
};
mod effort;
mod inter;
mod inter_search;
mod pilot;
mod tape;
mod wavefront;
pub use effort::{EncodeEffort, KeyframeEncodeOptions, KeyframeEncoded};
#[inline]
fn enc_round_div(num: i32, den: i32) -> i16 {
debug_assert!(den > 0, "encoder quantiser factor must be positive");
let r = if num >= 0 {
(num + den / 2) / den
} else {
-(((-num) + den / 2) / den)
};
r as i16
}
#[inline]
fn enc_quantize_block(block: &mut [i16; 16], dc: i16, ac: i16) {
block[0] = enc_round_div(block[0] as i32, dc as i32);
for c in block.iter_mut().skip(1) {
*c = enc_round_div(*c as i32, ac as i32);
}
}
#[derive(Debug, Clone, Copy)]
pub struct MbPixels {
pub y: [u8; 256],
pub u: [u8; 64],
pub v: [u8; 64],
}
#[inline]
fn block_ssd(recon: &[u8], src: &[u8]) -> u64 {
debug_assert_eq!(recon.len(), src.len());
recon
.chunks(4096)
.zip(src.chunks(4096))
.map(|(r, s)| {
r.iter()
.zip(s)
.map(|(&a, &b)| {
let d = a as i32 - b as i32;
(d * d) as u32
})
.sum::<u32>() as u64
})
.sum()
}
#[inline]
pub(crate) fn bool_bits(prob: u8, value: bool) -> f64 {
if value {
let idx = 256usize - prob as usize;
BIT_COST_BY_FALSE_PROB[idx.min(255)]
} else {
BIT_COST_BY_FALSE_PROB[prob as usize]
}
}
static BIT_COST_BY_FALSE_PROB: std::sync::LazyLock<[f64; 256]> = std::sync::LazyLock::new(|| {
let mut t = [0f64; 256];
t[0] = -((1.0f64 / 256.0).log2());
for (p, slot) in t.iter_mut().enumerate().skip(1) {
*slot = -((p as f64) / 256.0).log2();
}
t
});
fn treed_find_path(tree: &[i8], leaf: u8, path: &mut [bool; 16]) -> usize {
fn dfs(tree: &[i8], i: i8, target: i8, path: &mut [bool; 16], len: &mut usize) -> bool {
for bit in 0..2 {
let next = tree[i as usize + bit];
path[*len] = bit == 1;
*len += 1;
if next == target {
return true;
}
if next > 0 && dfs(tree, next, target, path, len) {
return true;
}
*len -= 1;
}
false
}
let mut len = 0;
let found = dfs(tree, 0, -(leaf as i8), path, &mut len);
debug_assert!(found, "leaf {leaf} not reachable in tree {tree:?}");
len
}
#[cfg_attr(not(test), allow(dead_code))]
fn treed_bits<F>(tree: &[i8], prob_lookup: F, leaf: u8) -> f64
where
F: Fn(usize) -> u8,
{
let mut path = [false; 16];
let len = treed_find_path(tree, leaf, &mut path);
let mut bits = 0.0;
let mut i: i8 = 0;
for &bit in &path[..len] {
bits += bool_bits(prob_lookup((i as usize) >> 1), bit);
i = tree[i as usize + bit as usize];
}
bits
}
#[derive(Clone, Copy)]
struct TreedLeafPath {
len: u8,
bits: [bool; 16],
prob_index: [u8; 16],
}
fn precompute_treed_paths<const N: usize>(tree: &[i8]) -> [TreedLeafPath; N] {
core::array::from_fn(|leaf| {
let mut bits = [false; 16];
let len = treed_find_path(tree, leaf as u8, &mut bits);
let mut prob_index = [0u8; 16];
let mut i: i8 = 0;
for (s, &bit) in bits[..len].iter().enumerate() {
prob_index[s] = ((i as usize) >> 1) as u8;
i = tree[i as usize + bit as usize];
}
TreedLeafPath {
len: len as u8,
bits,
prob_index,
}
})
}
static KF_YMODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 5]> =
std::sync::LazyLock::new(|| precompute_treed_paths(&KF_YMODE_TREE));
static UV_MODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 4]> =
std::sync::LazyLock::new(|| precompute_treed_paths(&UV_MODE_TREE));
static BMODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 10]> =
std::sync::LazyLock::new(|| precompute_treed_paths(&BMODE_TREE));
static KF_BMODE_BITS: std::sync::LazyLock<[[[f64; 10]; 10]; 10]> = std::sync::LazyLock::new(|| {
core::array::from_fn(|above| {
core::array::from_fn(|left| {
let prob_row = &KF_BMODE_PROB[above][left];
core::array::from_fn(|mode| {
treed_bits_cached(&*BMODE_PATHS, |k| prob_row[k], mode as u8)
})
})
})
});
static IF_YMODE_PATHS: std::sync::LazyLock<[TreedLeafPath; 5]> =
std::sync::LazyLock::new(|| precompute_treed_paths(&IF_YMODE_TREE));
fn treed_bits_cached<F>(paths: &[TreedLeafPath], prob_lookup: F, leaf: u8) -> f64
where
F: Fn(usize) -> u8,
{
let p = &paths[leaf as usize];
let mut bits = 0.0;
for s in 0..p.len as usize {
bits += bool_bits(prob_lookup(p.prob_index[s] as usize), p.bits[s]);
}
bits
}
fn estimate_block_bits(
block_type: BlockType,
coeff_probs: &CoeffProbs,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> f64 {
let plane = block_type.plane_index();
let first_coeff = block_type.first_coeff();
let mut last_non_zero: i32 = -1;
for (i, &v) in coeffs.iter().enumerate() {
if i >= first_coeff && v != 0 {
last_non_zero = i as i32;
}
}
let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
let mut prev_was_zero = false;
let mut bits = 0.0;
let mut i = first_coeff;
while i < 16 {
let band = COEFF_BANDS[i];
let probs = &coeff_probs[plane][band][ctx3];
let emit_eob = (i as i32) > last_non_zero;
let (token, abs_value, _sign) = if emit_eob {
(DctToken::Eob, 0u16, false)
} else {
let v = coeffs[i];
(
classify_coeff_token(v.unsigned_abs()),
v.unsigned_abs(),
v < 0,
)
};
let start = if prev_was_zero { 2i8 } else { 0i8 };
for step in token_to_bit_path(token, start) {
bits += bool_bits(probs[step.prob_index as usize], step.bit);
}
if token == DctToken::Eob {
break;
}
if let Some((base, plist)) = cat_extras(token) {
let extra = abs_value.saturating_sub(base);
let n = plist.len();
for (j, &p) in plist.iter().enumerate() {
let bit = ((extra >> (n - 1 - j)) & 1) == 1;
bits += bool_bits(p, bit);
}
}
if abs_value != 0 {
bits += bool_bits(128, false); }
ctx3 = if abs_value == 0 {
0
} else if abs_value == 1 {
1
} else {
2
};
prev_was_zero = token == DctToken::Dct0;
i += 1;
}
bits
}
fn estimate_block_bits_tabled(
tables: &TrellisRateTables,
block_type: BlockType,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> f64 {
let first_coeff = block_type.first_coeff();
let plane_steps = &tables.step[block_type.plane_index()];
let paths = &*TOKEN_BIT_PATHS;
let mut end = 16;
while end > first_coeff && coeffs[end - 1] == 0 {
end -= 1;
}
let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
let mut prev_was_zero = false;
let mut bits = 0.0;
for (i, &v) in coeffs.iter().enumerate().take(end).skip(first_coeff) {
let steps = &plane_steps[COEFF_BANDS[i]][ctx3];
let abs_value = v.unsigned_abs();
let token = classify_coeff_token(abs_value);
let (path, len) = &paths[prev_was_zero as usize][token as usize];
for step in &path[..*len as usize] {
bits += steps[step.prob_index as usize][step.bit as usize];
}
if let Some((base, plist)) = cat_extras(token) {
let extra = abs_value.saturating_sub(base);
let n = plist.len();
for (j, &p) in plist.iter().enumerate() {
let bit = ((extra >> (n - 1 - j)) & 1) == 1;
bits += bool_bits(p, bit);
}
}
if abs_value != 0 {
bits += bool_bits(128, false);
}
ctx3 = level_ctx3(abs_value);
prev_was_zero = abs_value == 0;
}
if end < 16 {
bits += plane_steps[COEFF_BANDS[end]][ctx3][0][0];
}
bits
}
fn estimate_block_bits_presummed(
tables: &TrellisRateTables,
block_type: BlockType,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> f64 {
let first_coeff = block_type.first_coeff();
let plane = block_type.plane_index();
let small = &tables.small[plane];
let mut end = 16;
while end > first_coeff && coeffs[end - 1] == 0 {
end -= 1;
}
let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
let mut prev_was_zero = 0usize;
let mut bits = 0.0;
for (i, &v) in coeffs.iter().enumerate().take(end).skip(first_coeff) {
let level = v.unsigned_abs() as u32;
let band = COEFF_BANDS[i];
bits += if level <= TRELLIS_SMALL_LEVEL_MAX as u32 {
small[band][ctx3][prev_was_zero][level as usize]
} else {
TrellisRateTables::level_rate(
&small[band],
&tables.cat_path[plane][band],
ctx3,
prev_was_zero == 1,
level,
)
};
ctx3 = (level as usize).min(2);
prev_was_zero = (level == 0) as usize;
}
if end < 16 {
bits += tables.eob[plane][COEFF_BANDS[end]][ctx3];
}
bits
}
const RD_TIE_GUARD: f64 = 1e-3;
#[cfg(test)]
thread_local! {
static FORCE_REFERENCE_SEARCH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn decisive_minimum(costs: &[f64]) -> (usize, bool) {
let mut best = 0usize;
for (n, &cost) in costs.iter().enumerate().skip(1) {
if cost < costs[best] {
best = n;
}
}
#[cfg(test)]
if FORCE_REFERENCE_SEARCH.with(|f| f.get()) {
return (best, false);
}
let decisive = costs
.iter()
.enumerate()
.all(|(n, &cost)| n == best || cost - costs[best] > RD_TIE_GUARD);
(best, decisive)
}
const TRELLIS_LAMBDA_SCALE: f64 = 0.04;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrellisStrength(f64);
impl TrellisStrength {
pub const DEFAULT: TrellisStrength = TrellisStrength(1.0);
pub const OFF: TrellisStrength = TrellisStrength(0.0);
pub const MAX: f64 = 8.0;
pub fn new(strength: f64) -> Self {
if strength.is_nan() {
return Self::DEFAULT;
}
TrellisStrength(strength.clamp(0.0, Self::MAX))
}
pub fn get(self) -> f64 {
self.0
}
fn lambda_scale(self) -> f64 {
self.0 * TRELLIS_LAMBDA_SCALE
}
}
impl Default for TrellisStrength {
fn default() -> Self {
Self::DEFAULT
}
}
static IDCT_BASIS_NORM_SQ: std::sync::LazyLock<[f64; 16]> = std::sync::LazyLock::new(|| {
let mut norms = [0f64; 16];
for (k, slot) in norms.iter_mut().enumerate() {
let raster = crate::dct_tokens::ZIGZAG[k];
let mut coeffs = [0i16; 16];
const IMPULSE: i16 = 256;
coeffs[raster] = IMPULSE;
let mut out = [0i16; 16];
inverse_dct_4x4(&coeffs, &mut out);
let energy: f64 = out.iter().map(|&v| (v as f64).powi(2)).sum();
*slot = energy / (IMPULSE as f64).powi(2);
}
norms
});
#[inline]
fn coeff_token_bits(
coeff_probs: &CoeffProbs,
plane: usize,
i: usize,
ctx3: usize,
prev_was_zero: bool,
abs_level: u16,
) -> f64 {
let band = COEFF_BANDS[i];
let probs = &coeff_probs[plane][band][ctx3];
let token = classify_coeff_token(abs_level);
let start = if prev_was_zero { 2i8 } else { 0i8 };
let mut bits = 0.0;
for step in token_to_bit_path(token, start) {
bits += bool_bits(probs[step.prob_index as usize], step.bit);
}
if let Some((base, plist)) = cat_extras(token) {
let extra = abs_level.saturating_sub(base);
let n = plist.len();
for (j, &p) in plist.iter().enumerate() {
let bit = ((extra >> (n - 1 - j)) & 1) == 1;
bits += bool_bits(p, bit);
}
}
if abs_level != 0 {
bits += bool_bits(128, false); }
bits
}
#[inline]
fn eob_token_bits(coeff_probs: &CoeffProbs, plane: usize, i: usize, ctx3: usize) -> f64 {
let band = COEFF_BANDS[i];
let probs = &coeff_probs[plane][band][ctx3];
bool_bits(probs[0], false)
}
#[inline]
fn level_ctx3(abs_level: u16) -> usize {
match abs_level {
0 => 0,
1 => 1,
_ => 2,
}
}
const TRELLIS_SMALL_LEVEL_MAX: u16 = 4;
struct TrellisRateTables {
small: [[[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
eob: [[[f64; 3]; 8]; 4],
step: [[[[[f64; 2]; 11]; 3]; 8]; 4],
cat_path: [[[[[f64; 6]; 2]; 3]; 8]; 4],
zero_run: [[f64; 17]; 4],
priced: std::sync::OnceLock<Box<PricedRates>>,
}
struct PricedRates {
lambda: f64,
small: [[[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
eob: [[[f64; 3]; 8]; 4],
}
impl PricedRates {
fn new(tables: &TrellisRateTables, lambda: f64) -> Box<Self> {
let mut priced = Box::new(PricedRates {
lambda,
small: tables.small,
eob: tables.eob,
});
let small = priced
.small
.as_flattened_mut()
.as_flattened_mut()
.as_flattened_mut()
.as_flattened_mut();
for rate in small.iter_mut() {
*rate *= lambda;
}
for rate in priced.eob.as_flattened_mut().as_flattened_mut() {
*rate *= lambda;
}
priced
}
}
impl TrellisRateTables {
fn for_probs(coeff_probs: &CoeffProbs) -> Self {
let mut band_pos = [0usize; 8];
for (band, pos) in band_pos.iter_mut().enumerate() {
*pos = COEFF_BANDS
.iter()
.position(|&b| b == band)
.expect("every §13.3 band has at least one scan position");
}
let mut tables = TrellisRateTables {
small: [[[[[0.0; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
eob: [[[0.0; 3]; 8]; 4],
step: [[[[[0.0; 2]; 11]; 3]; 8]; 4],
cat_path: [[[[[0.0; 6]; 2]; 3]; 8]; 4],
zero_run: [[0.0; 17]; 4],
priced: std::sync::OnceLock::new(),
};
for plane in 0..4 {
for (band, &i) in band_pos.iter().enumerate() {
for ctx3 in 0..3 {
let probs = &coeff_probs[plane][band][ctx3];
for (node, costs) in tables.step[plane][band][ctx3].iter_mut().enumerate() {
*costs = [bool_bits(probs[node], false), bool_bits(probs[node], true)];
}
for (pwz, slot) in tables.cat_path[plane][band][ctx3].iter_mut().enumerate() {
for (cat, cell) in slot.iter_mut().enumerate() {
let (path, len) = &TOKEN_BIT_PATHS[pwz][DctToken::Cat1 as usize + cat];
let mut bits = 0.0;
for step in &path[..*len as usize] {
bits += bool_bits(probs[step.prob_index as usize], step.bit);
}
*cell = bits;
}
}
tables.eob[plane][band][ctx3] = eob_token_bits(coeff_probs, plane, i, ctx3);
for (pwz, slot) in tables.small[plane][band][ctx3].iter_mut().enumerate() {
for (abs, cell) in slot.iter_mut().enumerate() {
*cell =
coeff_token_bits(coeff_probs, plane, i, ctx3, pwz == 1, abs as u16);
}
}
}
}
}
for plane in 0..4 {
for k in 0..16 {
tables.zero_run[plane][k + 1] =
tables.zero_run[plane][k] + tables.small[plane][COEFF_BANDS[k]][0][1][0];
}
}
tables
}
#[inline]
fn cat_level_rates(cat_path: &[[[f64; 6]; 2]; 3], zero_run: usize, level: u32) -> [f64; 3] {
let abs_level = level as u16;
let token = classify_coeff_token(abs_level);
let cat = token as usize - DctToken::Cat1 as usize;
let mut rates = [
cat_path[0][zero_run][cat],
cat_path[1][0][cat],
cat_path[2][0][cat],
];
if let Some((base, plist)) = cat_extras(token) {
let extra = abs_level.saturating_sub(base);
let n = plist.len();
for (j, &p) in plist.iter().enumerate() {
let cost = bool_bits(p, ((extra >> (n - 1 - j)) & 1) == 1);
for rate in rates.iter_mut() {
*rate += cost;
}
}
}
let sign = bool_bits(128, false);
for rate in rates.iter_mut() {
*rate += sign;
}
rates
}
#[inline]
fn level_rate(
small: &[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3],
cat_path: &[[[f64; 6]; 2]; 3],
ctx3: usize,
prev_was_zero: bool,
level: u32,
) -> f64 {
if level <= TRELLIS_SMALL_LEVEL_MAX as u32 {
return small[ctx3][prev_was_zero as usize][level as usize];
}
let abs_level = level as u16;
let token = classify_coeff_token(abs_level);
let mut bits =
cat_path[ctx3][prev_was_zero as usize][token as usize - DctToken::Cat1 as usize];
if let Some((base, plist)) = cat_extras(token) {
let extra = abs_level.saturating_sub(base);
let n = plist.len();
for (j, &p) in plist.iter().enumerate() {
let bit = ((extra >> (n - 1 - j)) & 1) == 1;
bits += bool_bits(p, bit);
}
}
bits += bool_bits(128, false);
bits
}
}
#[cfg(test)]
#[derive(Clone, Copy)]
struct TrellisCell {
cost: f64,
level: u16,
prev_ctx: usize,
}
#[derive(Clone, Copy)]
struct TrellisBlockSpec {
dc: i16,
ac: i16,
first_coeff: usize,
entry_ctx3: usize,
plane: usize,
}
fn trellis_quantize_block(
block: &mut [i16; 16],
spec: TrellisBlockSpec,
coeff_probs: &CoeffProbs,
tables: Option<&TrellisRateTables>,
lambda: f64,
) {
if lambda <= 0.0 {
enc_quantize_block_range(block, spec.dc, spec.ac, spec.first_coeff);
return;
}
match tables {
Some(tables) => {
let priced = tables
.priced
.get_or_init(|| PricedRates::new(tables, lambda));
if priced.lambda == lambda {
trellis_scan_tabled::<true>(
block,
spec,
(&priced.small, &priced.eob, &tables.cat_path),
lambda,
)
} else {
trellis_scan_tabled::<false>(
block,
spec,
(&tables.small, &tables.eob, &tables.cat_path),
lambda,
)
}
}
None => trellis_scan_direct(block, spec, coeff_probs, lambda),
}
}
struct TrellisScan {
ax: [u32; 16],
negative: [bool; 16],
m_rounds: [u32; 16],
zero_dist: [f64; 16],
suffix_zero_dist: [f64; 17],
last_cand_nonzero: Option<usize>,
}
impl TrellisScan {
#[inline]
fn new(block: &[i16; 16], dc_q: u32, ac_q: u32, first_coeff: usize) -> Self {
let norms = &*IDCT_BASIS_NORM_SQ;
let mut scan = TrellisScan {
ax: [0; 16],
negative: [false; 16],
m_rounds: [0; 16],
zero_dist: [0.0; 16],
suffix_zero_dist: [0.0; 17],
last_cand_nonzero: None,
};
for k in (first_coeff..16).rev() {
let x = block[crate::dct_tokens::ZIGZAG[k]];
let q = if k == 0 { dc_q } else { ac_q };
let ax = x.unsigned_abs() as u32;
scan.ax[k] = ax;
scan.negative[k] = x < 0;
scan.m_rounds[k] = rounded_level(ax, q);
if scan.m_rounds[k] != 0 && scan.last_cand_nonzero.is_none() {
scan.last_cand_nonzero = Some(k);
}
scan.zero_dist[k] = norms[k] * (ax as u64 * ax as u64) as f64;
scan.suffix_zero_dist[k] = scan.suffix_zero_dist[k + 1] + scan.zero_dist[k];
}
scan
}
#[inline]
fn dist(&self, k: usize, level: u32, q: u32) -> f64 {
let err = self.ax[k] as i64 - level as i64 * q as i64;
IDCT_BASIS_NORM_SQ[k] * (err * err) as f64
}
}
#[inline(always)]
fn select<T: Copy>(take: bool, a: T, b: T) -> T {
if take { a } else { b }
}
#[inline(always)]
fn alive_costs<const ALIVE: u8>(cost: impl Fn(usize) -> f64) -> [f64; 3] {
[
if ALIVE & 1 != 0 {
cost(0)
} else {
f64::INFINITY
},
if ALIVE & 2 != 0 {
cost(1)
} else {
f64::INFINITY
},
if ALIVE & 4 != 0 {
cost(2)
} else {
f64::INFINITY
},
]
}
#[inline(always)]
fn first_min3(c: [f64; 3]) -> (f64, u8) {
let lt1 = c[1] < c[0];
let m01 = select(lt1, c[1], c[0]);
let i01 = lt1 as u8;
let lt2 = c[2] < m01;
(select(lt2, c[2], m01), select(lt2, 2, i01))
}
#[allow(clippy::type_complexity)] fn trellis_scan_tabled<const PRICED: bool>(
block: &mut [i16; 16],
spec: TrellisBlockSpec,
(small, eob, cat_path): (
&[[[[[f64; (TRELLIS_SMALL_LEVEL_MAX + 1) as usize]; 2]; 3]; 8]; 4],
&[[[f64; 3]; 8]; 4],
&[[[[[f64; 6]; 2]; 3]; 8]; 4],
),
lambda: f64,
) {
let price = |rate: f64| if PRICED { rate } else { lambda * rate };
let TrellisBlockSpec {
dc,
ac,
first_coeff,
entry_ctx3,
plane,
} = spec;
let norms: &[f64; 16] = &IDCT_BASIS_NORM_SQ;
let (dc_q, ac_q) = (dc as u32, ac as u32);
let mut ax = [0u32; 16];
let mut m_rounds = [0u32; 16];
let mut negative = 0u32;
let mut candidate = 0u32;
for k in first_coeff..16 {
let x = block[crate::dct_tokens::ZIGZAG[k]];
ax[k] = x.unsigned_abs() as u32;
negative |= ((x < 0) as u32) << k;
let q = if k == 0 { dc_q } else { ac_q };
m_rounds[k] = rounded_level(ax[k], q);
candidate |= ((m_rounds[k] != 0) as u32) << k;
}
if candidate == 0 {
*block = [0i16; 16];
return;
}
let last = 31 - candidate.leading_zeros() as usize;
let mut zero_dist = [0f64; 16];
let mut suffix_zero_dist = [0f64; 17];
for k in first_coeff..16 {
zero_dist[k] = norms[k] * (ax[k] as u64 * ax[k] as u64) as f64;
}
for k in (first_coeff..16).rev() {
suffix_zero_dist[k] = suffix_zero_dist[k + 1] + zero_dist[k];
}
let dist = |k: usize, level: u32, q: u32| -> f64 {
let err = ax[k] as i64 - level as i64 * q as i64;
norms[k] * (err * err) as f64
};
let small = &small[plane];
let cat_path = &cat_path[plane];
let eob = &eob[plane];
const INF: f64 = f64::INFINITY;
let mut surv = [INF, INF, INF];
surv[entry_ctx3] = 0.0;
let mut zero_run = 0usize;
let mut choice_prev = [[0u8; 3]; 16];
let mut choice_level2 = [0u16; 16];
let mut best_term_cost =
0.0 + price(eob[COEFF_BANDS[first_coeff]][entry_ctx3]) + suffix_zero_dist[first_coeff];
let mut best_term_pos = usize::MAX;
let mut best_term_ctx = entry_ctx3;
let mut alive = 1u8 << entry_ctx3;
macro_rules! step {
($alive:literal, $k:expr) => {{
let k: usize = $k;
let m = m_rounds[k];
let band = COEFF_BANDS[k];
let q = if k == 0 { dc_q } else { ac_q };
let band_small = &small[band];
let rows = [
&band_small[0][zero_run],
&band_small[1][0],
&band_small[2][0],
];
let [s0, s1, s2] = surv;
let s = [s0, s1, s2];
let d_zero = zero_dist[k];
let (n0, p0) = first_min3(alive_costs::<$alive>(|i| s[i] + d_zero + price(rows[i][0])));
let level_costs = |level: u32| -> [f64; 3] {
let d = dist(k, level, q);
if level <= TRELLIS_SMALL_LEVEL_MAX as u32 {
alive_costs::<$alive>(|i| s[i] + d + price(rows[i][level as usize]))
} else {
let rates =
TrellisRateTables::cat_level_rates(&cat_path[band], zero_run, level);
alive_costs::<$alive>(|i| s[i] + d + lambda * rates[i])
}
};
let (n1, p1, n2, p2, l2) = match m {
0 => (INF, 0, INF, 0, 0),
1 => {
let (n1, p1) = first_min3(level_costs(1));
(n1, p1, INF, 0, 0)
}
2 => {
let (n2, p2) = first_min3(level_costs(2));
let (n1, p1) = first_min3(level_costs(1));
(n1, p1, n2, p2, 2)
}
_ => {
let high = level_costs(m);
let low = level_costs(m - 1);
let take_low = [low[0] < high[0], low[1] < high[1], low[2] < high[2]];
let (n2, p2) = first_min3([
select(take_low[0], low[0], high[0]),
select(take_low[1], low[1], high[1]),
select(take_low[2], low[2], high[2]),
]);
(INF, 0, n2, p2, m - take_low[p2 as usize] as u32)
}
};
choice_prev[k] = [p0, p1, p2];
choice_level2[k] = l2 as u16;
if m != 0 {
let (t1, t2) = if k + 1 < 16 {
let eob_next = &eob[COEFF_BANDS[k + 1]];
let tail = suffix_zero_dist[k + 1];
(
n1 + price(eob_next[1]) + tail,
n2 + price(eob_next[2]) + tail,
)
} else {
(n1, n2)
};
let better = t1 < best_term_cost;
best_term_cost = select(better, t1, best_term_cost);
best_term_pos = select(better, k, best_term_pos);
best_term_ctx = select(better, 1, best_term_ctx);
let better = t2 < best_term_cost;
best_term_cost = select(better, t2, best_term_cost);
best_term_pos = select(better, k, best_term_pos);
best_term_ctx = select(better, 2, best_term_ctx);
}
surv = [n0, n1, n2];
zero_run = 1;
alive = match m {
0 => 0b001,
1 => 0b011,
2 => 0b111,
_ => 0b101,
};
}};
}
for k in first_coeff..=last {
match alive {
0b001 => step!(0b001, k),
0b010 => step!(0b010, k),
0b100 => step!(0b100, k),
0b011 => step!(0b011, k),
0b101 => step!(0b101, k),
_ => step!(0b111, k),
}
}
*block = [0i16; 16];
if best_term_pos != usize::MAX {
let mut k = best_term_pos;
let mut ctx = best_term_ctx;
loop {
let level = match ctx {
0 => 0,
1 => 1,
_ => choice_level2[k] as i16,
};
block[crate::dct_tokens::ZIGZAG[k]] = if (negative >> k) & 1 != 0 {
-level
} else {
level
};
if k == first_coeff {
break;
}
ctx = choice_prev[k][ctx] as usize;
k -= 1;
}
}
}
fn trellis_scan_direct(
block: &mut [i16; 16],
spec: TrellisBlockSpec,
coeff_probs: &CoeffProbs,
lambda: f64,
) {
let TrellisBlockSpec {
dc,
ac,
first_coeff,
entry_ctx3,
plane,
} = spec;
let (dc_q, ac_q) = (dc as u32, ac as u32);
let scan = TrellisScan::new(block, dc_q, ac_q, first_coeff);
let Some(last) = scan.last_cand_nonzero else {
*block = [0i16; 16];
return;
};
const INF: f64 = f64::INFINITY;
let mut surv_cost = [INF; 3];
let mut surv_pwz = [false; 3];
surv_cost[entry_ctx3] = 0.0;
let mut choice_level = [[0u16; 3]; 16];
let mut choice_prev = [[0u8; 3]; 16];
let entry_eob = eob_token_bits(coeff_probs, plane, first_coeff, entry_ctx3);
let mut best_term_cost = 0.0 + lambda * entry_eob + scan.suffix_zero_dist[first_coeff];
let mut best_term_pos = usize::MAX;
let mut best_term_ctx = entry_ctx3;
for k in first_coeff..=last {
let m = scan.m_rounds[k];
let q = if k == 0 { dc_q } else { ac_q };
let cands = [m, m.saturating_sub(1), 0];
let ncand = (m as usize).min(2) + 1;
let mut cand_dist = [0f64; 3];
for c in 0..ncand {
cand_dist[c] = if cands[c] == 0 {
scan.zero_dist[k]
} else {
scan.dist(k, cands[c], q)
};
}
let mut next_cost = [INF; 3];
let mut next_pwz = [false; 3];
let mut next_level = [0u16; 3];
let mut next_prev = [0u8; 3];
for in_ctx in 0..3 {
let base = surv_cost[in_ctx];
if base >= INF {
continue;
}
let pwz = surv_pwz[in_ctx];
for c in 0..ncand {
let level = cands[c];
let r = coeff_token_bits(coeff_probs, plane, k, in_ctx, pwz, level as u16);
let cost = base + cand_dist[c] + lambda * r;
let out_ctx = level_ctx3(level as u16);
if cost < next_cost[out_ctx] {
next_cost[out_ctx] = cost;
next_pwz[out_ctx] = level == 0;
next_level[out_ctx] = level as u16;
next_prev[out_ctx] = in_ctx as u8;
}
}
}
choice_level[k] = next_level;
choice_prev[k] = next_prev;
for (out_ctx, &cost) in next_cost.iter().enumerate().skip(1) {
if cost >= INF {
continue;
}
let term_cost = if k + 1 < 16 {
cost + lambda * eob_token_bits(coeff_probs, plane, k + 1, out_ctx)
+ scan.suffix_zero_dist[k + 1]
} else {
cost
};
if term_cost < best_term_cost {
best_term_cost = term_cost;
best_term_pos = k;
best_term_ctx = out_ctx;
}
}
surv_cost = next_cost;
surv_pwz = next_pwz;
}
*block = [0i16; 16];
if best_term_pos != usize::MAX {
let mut k = best_term_pos;
let mut ctx = best_term_ctx;
loop {
let level = choice_level[k][ctx] as i16;
block[crate::dct_tokens::ZIGZAG[k]] = if scan.negative[k] { -level } else { level };
if k == first_coeff {
break;
}
ctx = choice_prev[k][ctx] as usize;
k -= 1;
}
}
}
const QUANT_RECIPROCAL: [u64; 1024] = {
let mut table = [0u64; 1024];
let mut q = 1usize;
while q < 1024 {
table[q] = (1u64 << 32) / q as u64 + 1;
q += 1;
}
table
};
#[inline(always)]
fn rounded_level(magnitude: u32, q: u32) -> u32 {
let n = magnitude as u64 + (q / 2) as u64;
if (q as usize) < QUANT_RECIPROCAL.len() && q != 0 {
((n * QUANT_RECIPROCAL[q as usize]) >> 32) as u32
} else {
(n / q as u64) as u32
}
}
#[inline]
fn enc_quantize_block_range(block: &mut [i16; 16], dc: i16, ac: i16, first_coeff: usize) {
if first_coeff == 0 {
block[0] = enc_round_div(block[0] as i32, dc as i32);
} else {
block[0] = 0;
}
for c in block.iter_mut().skip(1) {
*c = enc_round_div(*c as i32, ac as i32);
}
}
struct MbRdCtx<'a> {
factors: &'a crate::dequant::MbDequantFactors,
coeff_probs: &'a CoeffProbs,
rate_tables: Option<&'a TrellisRateTables>,
lambda: f64,
trellis: TrellisStrength,
}
impl MbRdCtx<'_> {
#[inline]
fn trellis_lambda(&self) -> f64 {
self.lambda * self.trellis.lambda_scale()
}
#[inline]
fn trellis_active(&self) -> bool {
self.trellis_lambda() > 0.0
}
#[inline]
fn ranking_block_bits(
&self,
block_type: BlockType,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> f64 {
match self.rate_tables {
Some(tables) => estimate_block_bits_presummed(
tables,
block_type,
above_has_nonzero,
left_has_nonzero,
coeffs,
),
None => estimate_block_bits(
block_type,
self.coeff_probs,
above_has_nonzero,
left_has_nonzero,
coeffs,
),
}
}
#[inline]
fn block_bits(
&self,
block_type: BlockType,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
) -> f64 {
match self.rate_tables {
Some(tables) => estimate_block_bits_tabled(
tables,
block_type,
above_has_nonzero,
left_has_nonzero,
coeffs,
),
None => estimate_block_bits(
block_type,
self.coeff_probs,
above_has_nonzero,
left_has_nonzero,
coeffs,
),
}
}
}
#[inline]
fn rd_lambda(factors: &crate::dequant::MbDequantFactors) -> f64 {
let q = factors.y1_ac as f64;
q * q / 32.0
}
#[inline]
fn reconstruct_block_4x4(pred: &[u8; 16], quant: &[i16; 16], dc: i16, ac: i16) -> [u8; 16] {
let mut dq = *quant;
dq[0] = (dq[0] as i32 * dc as i32) as i16;
for c in dq.iter_mut().skip(1) {
*c = (*c as i32 * ac as i32) as i16;
}
if dq[1..].iter().all(|&c| c == 0) {
let d = ((dq[0] as i32) + 4) >> 3;
if d == 0 {
return *pred;
}
let mut recon = [0u8; 16];
for (r, &p) in recon.iter_mut().zip(pred.iter()) {
*r = (p as i32 + d).clamp(0, 255) as u8;
}
return recon;
}
let mut residue = [0i16; 16];
inverse_dct_4x4(&dq, &mut residue);
let mut recon = [0u8; 16];
add_residue_4x4(pred, &residue, &mut recon);
recon
}
struct WholeBlockLuma {
mode: IntraYMode,
y_coeffs: [[i16; 16]; 16],
y2_coeffs: [i16; 16],
rd_cost: f64,
}
fn transform_whole_block_luma_rd(
src: &[u8; 256],
pred: &[u8; 256],
factors: &crate::dequant::MbDequantFactors,
trellis: Option<&MbRdCtx>,
) -> ([[i16; 16]; 16], [i16; 16]) {
let mut y = [[0i16; 16]; 16];
for i in 0..4 {
for j in 0..4 {
let mut residual = [0i16; 16];
for r in 0..4 {
for c in 0..4 {
let off = (i * 4 + r) * 16 + (j * 4 + c);
residual[r * 4 + c] = src[off] as i16 - pred[off] as i16;
}
}
let mut coeffs = [0i16; 16];
forward_dct_4x4(&residual, &mut coeffs);
y[i * 4 + j] = coeffs;
}
}
let mut y_dc_block = [0i16; 16];
for (slot, blk) in y_dc_block.iter_mut().zip(y.iter()) {
*slot = blk[0];
}
let mut y2 = [0i16; 16];
forward_wht_4x4(&y_dc_block, &mut y2);
for blk in y.iter_mut() {
blk[0] = 0;
}
match trellis {
Some(rd) if rd.trellis_active() => {
let tlambda = rd.trellis_lambda();
trellis_quantize_block(
&mut y2,
TrellisBlockSpec {
dc: factors.y2_dc,
ac: factors.y2_ac,
first_coeff: 0,
entry_ctx3: 0,
plane: BlockType::Y2.plane_index(),
},
rd.coeff_probs,
rd.rate_tables,
tlambda,
);
for blk in y.iter_mut() {
trellis_quantize_block(
blk,
TrellisBlockSpec {
dc: factors.y1_dc,
ac: factors.y1_ac,
first_coeff: BlockType::YAfterY2.first_coeff(),
entry_ctx3: 0,
plane: BlockType::YAfterY2.plane_index(),
},
rd.coeff_probs,
rd.rate_tables,
tlambda,
);
}
}
_ => {
enc_quantize_block(&mut y2, factors.y2_dc, factors.y2_ac);
for blk in y.iter_mut() {
enc_quantize_block(blk, factors.y1_dc, factors.y1_ac);
}
}
}
(y, y2)
}
fn reconstruct_whole_block_luma(
pred: &[u8; 256],
y_quant: &[[i16; 16]; 16],
y2_quant: &[i16; 16],
factors: &crate::dequant::MbDequantFactors,
) -> [u8; 256] {
let mut y2 = *y2_quant;
y2[0] = (y2[0] as i32 * factors.y2_dc as i32) as i16;
for c in y2.iter_mut().skip(1) {
*c = (*c as i32 * factors.y2_ac as i32) as i16;
}
let mut dcs = [0i16; 16];
inverse_wht_4x4(&y2, &mut dcs);
let mut recon = [0u8; 256];
for i in 0..4 {
for j in 0..4 {
let idx = i * 4 + j;
let mut blk = y_quant[idx];
blk[0] = dcs[idx];
for c in blk.iter_mut().skip(1) {
*c = (*c as i32 * factors.y1_ac as i32) as i16;
}
let mut residue = [0i16; 16];
inverse_dct_4x4(&blk, &mut residue);
let mut sb_pred = [0u8; 16];
for r in 0..4 {
for c in 0..4 {
sb_pred[r * 4 + c] = pred[(i * 4 + r) * 16 + (j * 4 + c)];
}
}
let mut sb_recon = [0u8; 16];
add_residue_4x4(&sb_pred, &residue, &mut sb_recon);
for r in 0..4 {
for c in 0..4 {
recon[(i * 4 + r) * 16 + (j * 4 + c)] = sb_recon[r * 4 + c];
}
}
}
}
recon
}
fn estimate_whole_block_luma_bits(
rd: &MbRdCtx,
y_quant: &[[i16; 16]; 16],
y2_quant: &[i16; 16],
ranking: bool,
) -> f64 {
let mut above = MbEntropyCtx::default();
let mut left = MbEntropyCtx::default();
let mut bits = 0.0;
let scan_y2 = raster_to_scan(y2_quant);
bits += estimate_block_bits_with_ctx(
24,
BlockType::Y2,
rd,
&scan_y2,
&mut above,
&mut left,
ranking,
);
for (i, blk) in y_quant.iter().enumerate() {
let scan = raster_to_scan(blk);
bits += estimate_block_bits_with_ctx(
i,
BlockType::YAfterY2,
rd,
&scan,
&mut above,
&mut left,
ranking,
);
}
bits
}
fn estimate_chroma_bits(
rd: &MbRdCtx,
u_quant: &[[i16; 16]; 4],
v_quant: &[[i16; 16]; 4],
ranking: bool,
) -> f64 {
let mut above = MbEntropyCtx::default();
let mut left = MbEntropyCtx::default();
let mut token_bits = 0.0;
for (i, blk) in u_quant.iter().chain(v_quant.iter()).enumerate() {
let scan = raster_to_scan(blk);
token_bits += estimate_block_bits_with_ctx(
16 + i,
BlockType::UV,
rd,
&scan,
&mut above,
&mut left,
ranking,
);
}
token_bits
}
fn estimate_block_bits_with_ctx(
block_index: usize,
block_type: BlockType,
rd: &MbRdCtx,
scan_coeffs: &[i16; 16],
above: &mut MbEntropyCtx,
left: &mut MbEntropyCtx,
ranking: bool,
) -> f64 {
const LEFT_CTX: [usize; 25] = [
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
];
const ABOVE_CTX: [usize; 25] = [
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8,
];
let a_slot = ABOVE_CTX[block_index];
let l_slot = LEFT_CTX[block_index];
let (a_nonzero, l_nonzero) = (above.nonzero[a_slot], left.nonzero[l_slot]);
let bits = if ranking {
rd.ranking_block_bits(block_type, a_nonzero, l_nonzero, scan_coeffs)
} else {
rd.block_bits(block_type, a_nonzero, l_nonzero, scan_coeffs)
};
let first = block_type.first_coeff();
let has_coeffs = scan_coeffs[first..].iter().any(|&v| v != 0);
above.nonzero[a_slot] = has_coeffs;
left.nonzero[l_slot] = has_coeffs;
bits
}
fn pick_y16x16_mode(
src: &[u8; 256],
above: Option<&[u8; 16]>,
left: Option<&[u8; 16]>,
topleft: u8,
rd: &MbRdCtx,
) -> WholeBlockLuma {
const CANDIDATES: [IntraYMode; 4] =
[IntraYMode::Dc, IntraYMode::V, IntraYMode::H, IntraYMode::Tm];
let mut quant = [([[0i16; 16]; 16], [0i16; 16]); 4];
let mut ssd = [0f64; 4];
let mut mode_bits = [0f64; 4];
let mut ranking_cost = [0f64; 4];
for (n, &mode) in CANDIDATES.iter().enumerate() {
let mut pred = [0u8; 256];
predict_y16x16(&mut pred, mode, above, left, topleft).expect("CANDIDATES excludes B_PRED");
let (y_quant, y2_quant) = transform_whole_block_luma_rd(src, &pred, rd.factors, Some(rd));
let recon = reconstruct_whole_block_luma(&pred, &y_quant, &y2_quant, rd.factors);
ssd[n] = block_ssd(&recon, src) as f64;
mode_bits[n] = treed_bits_cached(&*KF_YMODE_PATHS, |i| KF_YMODE_PROB[i], mode.leaf());
let token_bits = estimate_whole_block_luma_bits(rd, &y_quant, &y2_quant, true);
ranking_cost[n] = ssd[n] + rd.lambda * (token_bits + mode_bits[n]);
quant[n] = (y_quant, y2_quant);
}
let reference_cost = |n: usize| {
let token_bits = estimate_whole_block_luma_bits(rd, &quant[n].0, &quant[n].1, false);
ssd[n] + rd.lambda * (token_bits + mode_bits[n])
};
let (leader, decisive) = decisive_minimum(&ranking_cost);
let (winner, rd_cost) = if decisive {
(leader, reference_cost(leader))
} else {
let mut winner = 0usize;
let mut best_cost = reference_cost(0);
for n in 1..CANDIDATES.len() {
let cost = reference_cost(n);
if cost < best_cost {
best_cost = cost;
winner = n;
}
}
(winner, best_cost)
};
WholeBlockLuma {
mode: CANDIDATES[winner],
y_coeffs: quant[winner].0,
y2_coeffs: quant[winner].1,
rd_cost,
}
}
struct ChromaPlane<'a> {
src: &'a [u8; 64],
above: Option<&'a [u8; 8]>,
left: Option<&'a [u8; 8]>,
topleft: u8,
}
fn transform_chroma_plane_rd(
src: &[u8; 64],
pred: &[u8; 64],
factors: &crate::dequant::MbDequantFactors,
trellis: Option<&MbRdCtx>,
) -> [[i16; 16]; 4] {
let mut blocks = [[0i16; 16]; 4];
for i in 0..2 {
for j in 0..2 {
let mut residual = [0i16; 16];
for r in 0..4 {
for c in 0..4 {
let off = (i * 4 + r) * 8 + (j * 4 + c);
residual[r * 4 + c] = src[off] as i16 - pred[off] as i16;
}
}
let mut coeffs = [0i16; 16];
forward_dct_4x4(&residual, &mut coeffs);
match trellis {
Some(rd) if rd.trellis_active() => trellis_quantize_block(
&mut coeffs,
TrellisBlockSpec {
dc: factors.uv_dc,
ac: factors.uv_ac,
first_coeff: BlockType::UV.first_coeff(),
entry_ctx3: 0,
plane: BlockType::UV.plane_index(),
},
rd.coeff_probs,
rd.rate_tables,
rd.trellis_lambda(),
),
_ => enc_quantize_block(&mut coeffs, factors.uv_dc, factors.uv_ac),
}
blocks[i * 2 + j] = coeffs;
}
}
blocks
}
fn reconstruct_chroma_plane(
pred: &[u8; 64],
quant: &[[i16; 16]; 4],
factors: &crate::dequant::MbDequantFactors,
) -> [u8; 64] {
let mut recon = [0u8; 64];
for i in 0..2 {
for j in 0..2 {
let mut sb_pred = [0u8; 16];
for r in 0..4 {
for c in 0..4 {
sb_pred[r * 4 + c] = pred[(i * 4 + r) * 8 + (j * 4 + c)];
}
}
let sb_recon =
reconstruct_block_4x4(&sb_pred, &quant[i * 2 + j], factors.uv_dc, factors.uv_ac);
for r in 0..4 {
for c in 0..4 {
recon[(i * 4 + r) * 8 + (j * 4 + c)] = sb_recon[r * 4 + c];
}
}
}
}
recon
}
fn pick_uv8x8_mode(
u: &ChromaPlane,
v: &ChromaPlane,
rd: &MbRdCtx,
) -> (IntraUvMode, [[i16; 16]; 4], [[i16; 16]; 4]) {
const CANDIDATES: [IntraUvMode; 4] = [
IntraUvMode::Dc,
IntraUvMode::V,
IntraUvMode::H,
IntraUvMode::Tm,
];
let mut quant = [([[0i16; 16]; 4], [[0i16; 16]; 4]); 4];
let mut ssd = [0f64; 4];
let mut mode_bits = [0f64; 4];
let mut ranking_cost = [0f64; 4];
for (n, &mode) in CANDIDATES.iter().enumerate() {
let mut u_pred = [0u8; 64];
let mut v_pred = [0u8; 64];
predict_uv8x8(&mut u_pred, mode, u.above, u.left, u.topleft);
predict_uv8x8(&mut v_pred, mode, v.above, v.left, v.topleft);
let u_quant = transform_chroma_plane_rd(u.src, &u_pred, rd.factors, Some(rd));
let v_quant = transform_chroma_plane_rd(v.src, &v_pred, rd.factors, Some(rd));
let u_recon = reconstruct_chroma_plane(&u_pred, &u_quant, rd.factors);
let v_recon = reconstruct_chroma_plane(&v_pred, &v_quant, rd.factors);
ssd[n] = (block_ssd(&u_recon, u.src) + block_ssd(&v_recon, v.src)) as f64;
mode_bits[n] = treed_bits_cached(&*UV_MODE_PATHS, |i| KF_UV_MODE_PROB[i], mode.leaf());
let token_bits = estimate_chroma_bits(rd, &u_quant, &v_quant, true);
ranking_cost[n] = ssd[n] + rd.lambda * (token_bits + mode_bits[n]);
quant[n] = (u_quant, v_quant);
}
let (leader, decisive) = decisive_minimum(&ranking_cost);
let winner = if decisive {
leader
} else {
let reference_cost = |n: usize| {
let token_bits = estimate_chroma_bits(rd, &quant[n].0, &quant[n].1, false);
ssd[n] + rd.lambda * (token_bits + mode_bits[n])
};
let mut winner = 0usize;
let mut best_cost = reference_cost(0);
for n in 1..CANDIDATES.len() {
let cost = reference_cost(n);
if cost < best_cost {
best_cost = cost;
winner = n;
}
}
winner
};
(CANDIDATES[winner], quant[winner].0, quant[winner].1)
}
const ENC_BPRED_STRIDE: usize = 1 + 16 + 4;
const ENC_BPRED_ROWS: usize = 1 + 16;
const ENC_BPRED_ORIGIN: usize = ENC_BPRED_STRIDE + 1;
const BMODE_CANDIDATES: [IntraBmode; 10] = [
IntraBmode::Dc,
IntraBmode::Tm,
IntraBmode::Ve,
IntraBmode::He,
IntraBmode::Ld,
IntraBmode::Rd,
IntraBmode::Vr,
IntraBmode::Vl,
IntraBmode::Hd,
IntraBmode::Hu,
];
struct BpredLuma {
modes: [IntraBmode; 16],
y_coeffs: [[i16; 16]; 16],
rd_cost: f64,
}
fn build_enc_bpred_buffer(
neighbors: &crate::reconstruct::MbNeighbors,
) -> [u8; ENC_BPRED_ROWS * ENC_BPRED_STRIDE] {
let mut buf = [0u8; ENC_BPRED_ROWS * ENC_BPRED_STRIDE];
let above = neighbors.y_above.unwrap_or([DEFAULT_ABOVE_PIXEL; 16]);
let topleft = neighbors.y_topleft.unwrap_or(DEFAULT_ABOVE_PIXEL);
buf[0] = topleft;
buf[1..17].copy_from_slice(&above);
let above_right = neighbors.y_above_right.unwrap_or([DEFAULT_ABOVE_PIXEL; 4]);
buf[17..21].copy_from_slice(&above_right);
let left = neighbors.y_left.unwrap_or([DEFAULT_LEFT_PIXEL; 16]);
for (r, &v) in left.iter().enumerate() {
buf[(r + 1) * ENC_BPRED_STRIDE] = v;
}
let extra = [buf[17], buf[18], buf[19], buf[20]];
for &recon_row_above in &[3usize, 7, 11] {
let buf_row = 1 + recon_row_above;
let base = buf_row * ENC_BPRED_STRIDE + 17;
buf[base..base + 4].copy_from_slice(&extra);
}
buf
}
fn encode_bpred_luma(
src: &[u8; 256],
neighbors: &crate::reconstruct::MbNeighbors,
rd: &MbRdCtx,
) -> BpredLuma {
let factors = rd.factors;
let mut buf = build_enc_bpred_buffer(neighbors);
let mut modes = [IntraBmode::Dc; 16];
let mut y_coeffs = [[0i16; 16]; 16];
let mut total_cost = 0.0f64;
let mut sub_modes = [IntraBmode::Dc; 16];
let mut tok_above = MbEntropyCtx::default();
let mut tok_left = MbEntropyCtx::default();
for i in 0..4 {
for j in 0..4 {
let idx = i * 4 + j;
let sb_base = ENC_BPRED_ORIGIN + (i * 4) * ENC_BPRED_STRIDE + (j * 4);
let above_base = sb_base - ENC_BPRED_STRIDE;
let mut above = [0u8; 8];
above.copy_from_slice(&buf[above_base..above_base + 8]);
let mut left = [0u8; 4];
for (r, slot) in left.iter_mut().enumerate() {
*slot = buf[sb_base + r * ENC_BPRED_STRIDE - 1];
}
let p = buf[above_base - 1];
let mut sb_src = [0u8; 16];
for r in 0..4 {
for c in 0..4 {
sb_src[r * 4 + c] = src[(i * 4 + r) * 16 + (j * 4 + c)];
}
}
let above_mode = if i == 0 {
IntraBmode::Dc
} else {
sub_modes[(i - 1) * 4 + j]
};
let left_mode = if j == 0 {
IntraBmode::Dc
} else {
sub_modes[i * 4 + (j - 1)]
};
let mode_bits_row = &KF_BMODE_BITS[above_mode.idx()][left_mode.idx()];
let mut cand_coeffs = [[0i16; 16]; 10];
let mut cand_scan = [[0i16; 16]; 10];
let mut cand_recon = [[0u8; 16]; 10];
let mut cand_ssd = [0f64; 10];
let mut cand_rank_bits = [0f64; 10];
let mut cand_pred = [[0u8; 16]; 10];
let mut ranking_cost = [0f64; 10];
let (above_nonzero, left_nonzero) = (tok_above.nonzero[j], tok_left.nonzero[i]);
for (n, &mode) in BMODE_CANDIDATES.iter().enumerate() {
let mut pred = [0u8; 16];
predict_b4x4(&mut pred, mode, &above, &left, p);
cand_pred[n] = pred;
if let Some(twin) = cand_pred[..n].iter().position(|earlier| *earlier == pred) {
cand_coeffs[n] = cand_coeffs[twin];
cand_scan[n] = cand_scan[twin];
cand_recon[n] = cand_recon[twin];
cand_ssd[n] = cand_ssd[twin];
cand_rank_bits[n] = cand_rank_bits[twin];
ranking_cost[n] =
cand_ssd[n] + rd.lambda * (cand_rank_bits[n] + mode_bits_row[mode.idx()]);
continue;
}
let mut residual = [0i16; 16];
for k in 0..16 {
residual[k] = sb_src[k] as i16 - pred[k] as i16;
}
let mut coeffs = [0i16; 16];
forward_dct_4x4(&residual, &mut coeffs);
if rd.trellis_active() {
let entry_ctx3 = (above_nonzero as usize) + (left_nonzero as usize);
trellis_quantize_block(
&mut coeffs,
TrellisBlockSpec {
dc: factors.y1_dc,
ac: factors.y1_ac,
first_coeff: BlockType::YNoY2.first_coeff(),
entry_ctx3,
plane: BlockType::YNoY2.plane_index(),
},
rd.coeff_probs,
rd.rate_tables,
rd.trellis_lambda(),
);
} else {
enc_quantize_block(&mut coeffs, factors.y1_dc, factors.y1_ac);
}
let recon = reconstruct_block_4x4(&pred, &coeffs, factors.y1_dc, factors.y1_ac);
let scan = raster_to_scan(&coeffs);
let token_bits =
rd.ranking_block_bits(BlockType::YNoY2, above_nonzero, left_nonzero, &scan);
cand_ssd[n] = block_ssd(&recon, &sb_src) as f64;
cand_rank_bits[n] = token_bits;
ranking_cost[n] =
cand_ssd[n] + rd.lambda * (token_bits + mode_bits_row[mode.idx()]);
cand_coeffs[n] = coeffs;
cand_scan[n] = scan;
cand_recon[n] = recon;
}
let reference_cost = |n: usize| {
let token_bits =
rd.block_bits(BlockType::YNoY2, above_nonzero, left_nonzero, &cand_scan[n]);
cand_ssd[n] + rd.lambda * (token_bits + mode_bits_row[BMODE_CANDIDATES[n].idx()])
};
let (leader, decisive) = decisive_minimum(&ranking_cost);
let (winner, best_cost) = if decisive {
(leader, reference_cost(leader))
} else {
let mut winner = 0usize;
let mut best_cost = reference_cost(0);
for n in 1..BMODE_CANDIDATES.len() {
let cost = reference_cost(n);
if cost < best_cost {
best_cost = cost;
winner = n;
}
}
(winner, best_cost)
};
let best_mode = BMODE_CANDIDATES[winner];
let best_coeffs = cand_coeffs[winner];
let best_recon = cand_recon[winner];
modes[idx] = best_mode;
sub_modes[idx] = best_mode;
y_coeffs[idx] = best_coeffs;
total_cost += best_cost;
let has_coeffs = best_coeffs.iter().any(|&v| v != 0);
tok_above.nonzero[j] = has_coeffs;
tok_left.nonzero[i] = has_coeffs;
for r in 0..4 {
let dst = sb_base + r * ENC_BPRED_STRIDE;
buf[dst..dst + 4].copy_from_slice(&best_recon[r * 4..r * 4 + 4]);
}
}
}
BpredLuma {
modes,
y_coeffs,
rd_cost: total_cost,
}
}
#[derive(Debug, Clone)]
pub struct EncodedMb {
pub coeffs: MbCoeffs,
pub bytes: Vec<u8>,
pub nonzero_block_count: usize,
pub y_mode: IntraYMode,
pub uv_mode: IntraUvMode,
pub b_subblock_modes: Option<[IntraBmode; 16]>,
}
pub fn encode_mb_block_set(
pixels: &MbPixels,
yac_qi: u8,
coeff_probs: &crate::dct_tokens::CoeffProbs,
) -> Result<EncodedMb, TokenEncodeError> {
encode_mb_block_set_with_neighbors(
pixels,
&crate::reconstruct::MbNeighbors::default(),
yac_qi,
coeff_probs,
)
}
pub fn encode_mb_block_set_with_neighbors(
pixels: &MbPixels,
neighbors: &crate::reconstruct::MbNeighbors,
yac_qi: u8,
coeff_probs: &crate::dct_tokens::CoeffProbs,
) -> Result<EncodedMb, TokenEncodeError> {
encode_mb_block_set_with_neighbors_strength(
pixels,
neighbors,
yac_qi,
coeff_probs,
TrellisStrength::DEFAULT,
)
}
pub fn encode_mb_block_set_with_neighbors_strength(
pixels: &MbPixels,
neighbors: &crate::reconstruct::MbNeighbors,
yac_qi: u8,
coeff_probs: &crate::dct_tokens::CoeffProbs,
trellis: TrellisStrength,
) -> Result<EncodedMb, TokenEncodeError> {
encode_mb_block_set_with_neighbors_strength_rates(
pixels,
neighbors,
yac_qi,
coeff_probs,
None,
trellis,
)
}
struct MbAnalysis {
coeffs: MbCoeffs,
y_mode: IntraYMode,
uv_mode: IntraUvMode,
b_subblock_modes: Option<[IntraBmode; 16]>,
nonzero_block_count: usize,
}
impl MbAnalysis {
fn from_coeffs(
coeffs: MbCoeffs,
y_mode: IntraYMode,
uv_mode: IntraUvMode,
b_subblock_modes: Option<[IntraBmode; 16]>,
) -> Self {
let use_bpred = y_mode == IntraYMode::B;
let y_first = usize::from(!use_bpred);
let any = |block: &[i16]| block.iter().any(|&v| v != 0);
let nonzero_block_count = usize::from(!use_bpred && any(&coeffs.y2))
+ coeffs.y.iter().filter(|b| any(&b[y_first..])).count()
+ coeffs.u.iter().filter(|b| any(&b[..])).count()
+ coeffs.v.iter().filter(|b| any(&b[..])).count();
MbAnalysis {
coeffs,
y_mode,
uv_mode,
b_subblock_modes,
nonzero_block_count,
}
}
}
fn analyze_mb_exhaustive(
pixels: &MbPixels,
neighbors: &crate::reconstruct::MbNeighbors,
rd: &MbRdCtx,
) -> MbAnalysis {
let default_corner = crate::intra_predict::DEFAULT_ABOVE_PIXEL;
let whole = pick_y16x16_mode(
&pixels.y,
neighbors.y_above.as_ref(),
neighbors.y_left.as_ref(),
neighbors.y_topleft.unwrap_or(default_corner),
rd,
);
let bpred = encode_bpred_luma(&pixels.y, neighbors, rd);
let bpred_flag_bits =
treed_bits_cached(&*KF_YMODE_PATHS, |i| KF_YMODE_PROB[i], IntraYMode::B.leaf());
let bpred_total_cost = bpred.rd_cost + rd.lambda * bpred_flag_bits;
let use_bpred = bpred_total_cost < whole.rd_cost;
let y_mode = if use_bpred { IntraYMode::B } else { whole.mode };
let (uv_mode, u_coeffs, v_coeffs) = pick_uv8x8_mode(
&ChromaPlane {
src: &pixels.u,
above: neighbors.u_above.as_ref(),
left: neighbors.u_left.as_ref(),
topleft: neighbors.u_topleft.unwrap_or(default_corner),
},
&ChromaPlane {
src: &pixels.v,
above: neighbors.v_above.as_ref(),
left: neighbors.v_left.as_ref(),
topleft: neighbors.v_topleft.unwrap_or(default_corner),
},
rd,
);
let mut raw_coeffs = MbCoeffs::default();
if use_bpred {
raw_coeffs.y = bpred.y_coeffs;
} else {
raw_coeffs.y = whole.y_coeffs;
raw_coeffs.y2 = whole.y2_coeffs;
}
raw_coeffs.u = u_coeffs;
raw_coeffs.v = v_coeffs;
MbAnalysis::from_coeffs(
raw_coeffs,
y_mode,
uv_mode,
use_bpred.then_some(bpred.modes),
)
}
fn encode_mb_block_set_with_neighbors_strength_rates(
pixels: &MbPixels,
neighbors: &crate::reconstruct::MbNeighbors,
yac_qi: u8,
coeff_probs: &crate::dct_tokens::CoeffProbs,
rate_tables: Option<&TrellisRateTables>,
trellis: TrellisStrength,
) -> Result<EncodedMb, TokenEncodeError> {
let factors =
crate::dequant::MbDequantFactors::from_base_and_deltas(yac_qi as i32, 0, 0, 0, 0, 0);
let rd = MbRdCtx {
factors: &factors,
coeff_probs,
rate_tables,
lambda: rd_lambda(&factors),
trellis,
};
let MbAnalysis {
coeffs: raw_coeffs,
y_mode,
uv_mode,
b_subblock_modes,
..
} = analyze_mb_exhaustive(pixels, neighbors, &rd);
let use_bpred = y_mode == IntraYMode::B;
let mut enc = BoolEncoder::new();
let mut above = MbEntropyCtx::default();
let mut left = MbEntropyCtx::default();
let nonzero_block_count = encode_mb_tokens(
&mut enc,
&raw_coeffs,
use_bpred,
coeff_probs,
&mut above,
&mut left,
)?;
let bytes = enc.finish();
Ok(EncodedMb {
coeffs: raw_coeffs,
bytes,
nonzero_block_count,
y_mode,
uv_mode,
b_subblock_modes,
})
}
fn encode_mb_tokens<S: BoolSink>(
enc: &mut S,
raw_coeffs: &MbCoeffs,
use_bpred: bool,
coeff_probs: &crate::dct_tokens::CoeffProbs,
above: &mut MbEntropyCtx,
left: &mut MbEntropyCtx,
) -> Result<usize, TokenEncodeError> {
let mut nonzero_block_count = 0usize;
if !use_bpred {
let scan_y2 = raster_to_scan(&raw_coeffs.y2);
let nz = encode_block_with_ctx(enc, 24, BlockType::Y2, coeff_probs, &scan_y2, above, left)?;
if nz != 0 {
nonzero_block_count += 1;
}
}
let y_block_type = if use_bpred {
BlockType::YNoY2
} else {
BlockType::YAfterY2
};
for (i, y_block) in raw_coeffs.y.iter().enumerate() {
let scan = raster_to_scan(y_block);
let nz = encode_block_with_ctx(enc, i, y_block_type, coeff_probs, &scan, above, left)?;
if nz != 0 {
nonzero_block_count += 1;
}
}
for (i, u_block) in raw_coeffs.u.iter().enumerate() {
let scan = raster_to_scan(u_block);
let nz =
encode_block_with_ctx(enc, 16 + i, BlockType::UV, coeff_probs, &scan, above, left)?;
if nz != 0 {
nonzero_block_count += 1;
}
}
for (i, v_block) in raw_coeffs.v.iter().enumerate() {
let scan = raster_to_scan(v_block);
let nz =
encode_block_with_ctx(enc, 20 + i, BlockType::UV, coeff_probs, &scan, above, left)?;
if nz != 0 {
nonzero_block_count += 1;
}
}
Ok(nonzero_block_count)
}
fn encode_block_with_ctx<S: BoolSink>(
enc: &mut S,
block_index: usize,
block_type: BlockType,
coeff_probs: &crate::dct_tokens::CoeffProbs,
scan_coeffs: &[i16; 16],
above: &mut MbEntropyCtx,
left: &mut MbEntropyCtx,
) -> Result<usize, TokenEncodeError> {
const LEFT_CTX: [usize; 25] = [
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, ];
const ABOVE_CTX: [usize; 25] = [
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, ];
let a_slot = ABOVE_CTX[block_index];
let l_slot = LEFT_CTX[block_index];
let nz = encode_coeff_block_into(
enc,
block_type,
coeff_probs,
above.nonzero[a_slot],
left.nonzero[l_slot],
scan_coeffs,
)?;
let has_coeffs = nz != 0;
above.nonzero[a_slot] = has_coeffs;
left.nonzero[l_slot] = has_coeffs;
Ok(nz)
}
pub type BranchCounts = [[[[(u32, u32); 11]; 3]; 8]; 4];
pub fn empty_branch_counts() -> BranchCounts {
[[[[(0u32, 0u32); 11]; 3]; 8]; 4]
}
pub fn count_block_branches(
block_type: BlockType,
above_has_nonzero: bool,
left_has_nonzero: bool,
coeffs: &[i16; 16],
counts: &mut BranchCounts,
) -> usize {
let plane = block_type.plane_index();
let first_coeff = block_type.first_coeff();
let mut last_non_zero: i32 = -1;
for (i, &v) in coeffs.iter().enumerate() {
if i >= first_coeff && v != 0 {
last_non_zero = i as i32;
}
}
let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
let mut prev_was_zero = false;
let mut non_zero_count = 0usize;
let mut i = first_coeff;
while i < 16 {
let band = COEFF_BANDS[i];
let emit_eob = (i as i32) > last_non_zero;
let (token, abs_value) = if emit_eob {
(DctToken::Eob, 0u16)
} else {
let v = coeffs[i];
let abs = v.unsigned_abs();
(classify_coeff_token(abs), abs)
};
let start = if prev_was_zero { 2i8 } else { 0i8 };
for step in token_to_bit_path(token, start) {
let slot = &mut counts[plane][band][ctx3][step.prob_index as usize];
if step.bit {
slot.1 += 1;
} else {
slot.0 += 1;
}
}
if token == DctToken::Eob {
break;
}
if abs_value != 0 {
non_zero_count += 1;
}
ctx3 = if abs_value == 0 {
0
} else if abs_value == 1 {
1
} else {
2
};
prev_was_zero = token == DctToken::Dct0;
i += 1;
}
non_zero_count
}
pub fn count_mb_branches(
raw_coeffs: &MbCoeffs,
use_bpred: bool,
above: &mut MbEntropyCtx,
left: &mut MbEntropyCtx,
counts: &mut BranchCounts,
) {
const LEFT_CTX: [usize; 25] = [
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, ];
const ABOVE_CTX: [usize; 25] = [
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, ];
let walk = |block_index: usize,
block_type: BlockType,
scan: &[i16; 16],
above: &mut MbEntropyCtx,
left: &mut MbEntropyCtx,
counts: &mut BranchCounts| {
let a = ABOVE_CTX[block_index];
let l = LEFT_CTX[block_index];
let nz = count_block_branches(block_type, above.nonzero[a], left.nonzero[l], scan, counts);
let has = nz != 0;
above.nonzero[a] = has;
left.nonzero[l] = has;
};
if !use_bpred {
let scan_y2 = raster_to_scan(&raw_coeffs.y2);
walk(24, BlockType::Y2, &scan_y2, above, left, counts);
}
let y_plane = if use_bpred {
BlockType::YNoY2
} else {
BlockType::YAfterY2
};
for (i, y_block) in raw_coeffs.y.iter().enumerate() {
let scan = raster_to_scan(y_block);
walk(i, y_plane, &scan, above, left, counts);
}
for (i, u_block) in raw_coeffs.u.iter().enumerate() {
let scan = raster_to_scan(u_block);
walk(16 + i, BlockType::UV, &scan, above, left, counts);
}
for (i, v_block) in raw_coeffs.v.iter().enumerate() {
let scan = raster_to_scan(v_block);
walk(20 + i, BlockType::UV, &scan, above, left, counts);
}
}
pub fn count_keyframe_branches(
modes: &[MacroblockModes],
all_coeffs: &[MbCoeffs],
mb_cols: usize,
mb_rows: usize,
counts: &mut BranchCounts,
) {
let mut above_ctx: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
for mb_row in 0..mb_rows {
let mut left_ctx = MbEntropyCtx::default();
for (mb_col, above_col) in above_ctx.iter_mut().enumerate() {
let raster = mb_row * mb_cols + mb_col;
let mb = &modes[raster];
let use_bpred = mb.y_mode == IntraYMode::B;
if mb.mb_skip_coeff {
clear_skip_ctx(use_bpred, above_col, &mut left_ctx);
continue;
}
count_mb_branches(
&all_coeffs[raster],
use_bpred,
above_col,
&mut left_ctx,
counts,
);
}
}
}
pub fn count_inter_frame_branches(
modes: &[MacroblockModes],
use_bpred_per_mb: &[bool],
all_coeffs: &[MbCoeffs],
mb_cols: usize,
mb_rows: usize,
counts: &mut BranchCounts,
) {
debug_assert_eq!(modes.len(), mb_cols * mb_rows);
debug_assert_eq!(use_bpred_per_mb.len(), mb_cols * mb_rows);
debug_assert_eq!(all_coeffs.len(), mb_cols * mb_rows);
let mut above_ctx: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
for mb_row in 0..mb_rows {
let mut left_ctx = MbEntropyCtx::default();
for (mb_col, above_col) in above_ctx.iter_mut().enumerate() {
let raster = mb_row * mb_cols + mb_col;
let mb = &modes[raster];
let use_bpred = use_bpred_per_mb[raster];
if mb.mb_skip_coeff {
clear_skip_ctx(use_bpred, above_col, &mut left_ctx);
continue;
}
count_mb_branches(
&all_coeffs[raster],
use_bpred,
above_col,
&mut left_ctx,
counts,
);
}
}
}
pub fn fit_token_prob_updates(
counts: &BranchCounts,
min_saving_bits: f64,
) -> crate::coded_header::TokenProbUpdates {
let defaults = &crate::dct_tokens::DEFAULT_COEFF_PROBS;
let mut out: crate::coded_header::TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
for i in 0..4 {
for j in 0..8 {
for k in 0..3 {
for t in 0..11 {
let (n0, n1) = counts[i][j][k][t];
let total = n0 + n1;
if total == 0 {
continue;
}
let p_old = defaults[i][j][k][t];
let p_new_raw = ((n0 as u64) * 256 + (total as u64) / 2) / (total as u64);
let p_new = p_new_raw.clamp(1, 255) as u8;
if p_new == p_old {
continue;
}
let body_old = (n0 as f64) * bool_bits(p_old, false)
+ (n1 as f64) * bool_bits(p_old, true);
let body_new = (n0 as f64) * bool_bits(p_new, false)
+ (n1 as f64) * bool_bits(p_new, true);
let body_saving = body_old - body_new;
let update_prob =
COEFF_UPDATE_PROBS_FLAT[i * 8 * 3 * 11 + j * 3 * 11 + k * 11 + t];
let header_extra =
bool_bits(update_prob, true) + 8.0 - bool_bits(update_prob, false);
if body_saving > header_extra + min_saving_bits {
out[i][j][k][t] = Some(p_new);
}
}
}
}
}
out
}
fn any_token_prob_update(updates: &crate::coded_header::TokenProbUpdates) -> bool {
updates.iter().any(|p| {
p.iter()
.any(|b| b.iter().any(|c| c.iter().any(|s| s.is_some())))
})
}
#[derive(Debug, Clone, Copy)]
pub struct I420Frame<'a> {
pub width: u32,
pub height: u32,
pub y: &'a [u8],
pub u: &'a [u8],
pub v: &'a [u8],
pub y_stride: usize,
pub uv_stride: usize,
}
impl<'a> I420Frame<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
width: u32,
height: u32,
y: &'a [u8],
u: &'a [u8],
v: &'a [u8],
y_stride: usize,
uv_stride: usize,
) -> Self {
Self {
width,
height,
y,
u,
v,
y_stride,
uv_stride,
}
}
#[must_use]
pub fn with_width(mut self, v: u32) -> Self {
self.width = v;
self
}
#[must_use]
pub fn with_height(mut self, v: u32) -> Self {
self.height = v;
self
}
#[must_use]
pub fn with_y(mut self, v: &'a [u8]) -> Self {
self.y = v;
self
}
#[must_use]
pub fn with_u(mut self, v: &'a [u8]) -> Self {
self.u = v;
self
}
#[must_use]
pub fn with_v(mut self, v: &'a [u8]) -> Self {
self.v = v;
self
}
#[must_use]
pub fn with_y_stride(mut self, v: usize) -> Self {
self.y_stride = v;
self
}
#[must_use]
pub fn with_uv_stride(mut self, v: usize) -> Self {
self.uv_stride = v;
self
}
pub fn packed(width: u32, height: u32, y: &'a [u8], u: &'a [u8], v: &'a [u8]) -> Self {
I420Frame {
width,
height,
y,
u,
v,
y_stride: width as usize,
uv_stride: width.div_ceil(2) as usize,
}
}
#[inline]
fn y_at(&self, x: usize, py: usize) -> u8 {
let w = self.width as usize;
let h = self.height as usize;
let cx = x.min(w - 1);
let cy = py.min(h - 1);
self.y[cy * self.y_stride + cx]
}
#[inline]
fn uv_at(&self, x: usize, py: usize, is_v: bool) -> u8 {
let cw = self.width.div_ceil(2) as usize;
let ch = self.height.div_ceil(2) as usize;
let cx = x.min(cw - 1);
let cy = py.min(ch - 1);
let plane = if is_v { self.v } else { self.u };
plane[cy * self.uv_stride + cx]
}
fn extract_mb(&self, mb_row: usize, mb_col: usize) -> MbPixels {
let mut p = MbPixels {
y: [0u8; 256],
u: [0u8; 64],
v: [0u8; 64],
};
let y0 = mb_row * 16;
let x0 = mb_col * 16;
let cy0 = mb_row * 8;
let cx0 = mb_col * 8;
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
if x0 + 16 <= w && y0 + 16 <= h && cx0 + 8 <= cw && cy0 + 8 <= ch {
for r in 0..16 {
let src = (y0 + r) * self.y_stride + x0;
p.y[r * 16..r * 16 + 16].copy_from_slice(&self.y[src..src + 16]);
}
for r in 0..8 {
let src = (cy0 + r) * self.uv_stride + cx0;
p.u[r * 8..r * 8 + 8].copy_from_slice(&self.u[src..src + 8]);
p.v[r * 8..r * 8 + 8].copy_from_slice(&self.v[src..src + 8]);
}
return p;
}
for r in 0..16 {
for c in 0..16 {
p.y[r * 16 + c] = self.y_at(x0 + c, y0 + r);
}
}
for r in 0..8 {
for c in 0..8 {
p.u[r * 8 + c] = self.uv_at(cx0 + c, cy0 + r, false);
p.v[r * 8 + c] = self.uv_at(cx0 + c, cy0 + r, true);
}
}
p
}
}
#[derive(Debug, Clone, Copy)]
pub struct KeyframeParams {
pub y_ac_qi: u8,
pub loop_filter_level: u8,
pub sharpness_level: u8,
pub nbr_of_dct_partitions: u8,
pub filter_type: bool,
pub trellis_strength: TrellisStrength,
}
impl KeyframeParams {
#[must_use]
pub fn with_y_ac_qi(mut self, v: u8) -> Self {
self.y_ac_qi = v;
self
}
#[must_use]
pub fn with_loop_filter_level(mut self, v: u8) -> Self {
self.loop_filter_level = v;
self
}
#[must_use]
pub fn with_sharpness_level(mut self, v: u8) -> Self {
self.sharpness_level = v;
self
}
#[must_use]
pub fn with_nbr_of_dct_partitions(mut self, v: u8) -> Self {
self.nbr_of_dct_partitions = v;
self
}
#[must_use]
pub fn with_filter_type(mut self, v: bool) -> Self {
self.filter_type = v;
self
}
#[must_use]
pub fn with_trellis_strength(mut self, v: TrellisStrength) -> Self {
self.trellis_strength = v;
self
}
}
impl Default for KeyframeParams {
fn default() -> Self {
KeyframeParams {
y_ac_qi: 32,
loop_filter_level: 0,
sharpness_level: 0,
nbr_of_dct_partitions: 1,
filter_type: false,
trellis_strength: TrellisStrength::DEFAULT,
}
}
}
pub fn encode_keyframe(frame: &I420Frame, params: &KeyframeParams) -> Result<Vec<u8>, EncodeError> {
let (bytes, _planes) = encode_keyframe_with_reconstruction(frame, params)?;
Ok(bytes)
}
pub fn encode_keyframe_with_token_prob_updates(
frame: &I420Frame,
params: &KeyframeParams,
updates: &TokenProbUpdates,
) -> Result<Vec<u8>, EncodeError> {
let (bytes, _planes) =
encode_keyframe_with_reconstruction_and_token_updates(frame, params, Some(updates))?;
Ok(bytes)
}
pub fn encode_keyframe_with_fitted_token_prob_updates(
frame: &I420Frame,
params: &KeyframeParams,
) -> Result<Vec<u8>, EncodeError> {
let mut counts = empty_branch_counts();
let (bytes_default, _planes_default) =
encode_keyframe_inner(frame, params, None, Some(&mut counts))?;
let fitted = fit_token_prob_updates(&counts, 2.0);
let any_update = any_token_prob_update(&fitted);
if !any_update {
return Ok(bytes_default);
}
let bytes_fitted = encode_keyframe_with_token_prob_updates(frame, params, &fitted)?;
if bytes_fitted.len() <= bytes_default.len() {
Ok(bytes_fitted)
} else {
Ok(bytes_default)
}
}
pub fn encode_keyframe_with_reconstruction_and_fitted_token_prob_updates(
frame: &I420Frame,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
let mut counts = empty_branch_counts();
let (bytes_default, planes_default) =
encode_keyframe_inner(frame, params, None, Some(&mut counts))?;
let fitted = fit_token_prob_updates(&counts, 2.0);
let any_update = any_token_prob_update(&fitted);
if !any_update {
return Ok((bytes_default, planes_default));
}
let (bytes_fitted, planes_fitted) =
encode_keyframe_with_reconstruction_and_token_updates(frame, params, Some(&fitted))?;
if bytes_fitted.len() <= bytes_default.len() {
Ok((bytes_fitted, planes_fitted))
} else {
Ok((bytes_default, planes_default))
}
}
pub fn encode_keyframe_with_reconstruction(
frame: &I420Frame,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_with_reconstruction_and_token_updates(frame, params, None)
}
pub fn encode_keyframe_auto_loop_filter(
frame: &I420Frame,
params: &KeyframeParams,
) -> Result<Vec<u8>, EncodeError> {
encode_keyframe_inner_lf(frame, params, None, None, true).map(|(bytes, _)| bytes)
}
pub fn encode_keyframe_auto_loop_filter_with_reconstruction(
frame: &I420Frame,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_inner_lf(frame, params, None, None, true)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct KeyframeCodingOptions {
pub auto_loop_filter: bool,
pub fitted_token_prob_updates: bool,
}
impl KeyframeCodingOptions {
#[must_use]
pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
self.auto_loop_filter = v;
self
}
#[must_use]
pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
self.fitted_token_prob_updates = v;
self
}
}
pub fn encode_keyframe_with_reconstruction_and_coding_options(
frame: &I420Frame,
params: &KeyframeParams,
options: &KeyframeCodingOptions,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
if !options.fitted_token_prob_updates {
return encode_keyframe_inner_lf(frame, params, None, None, options.auto_loop_filter);
}
let mut counts = empty_branch_counts();
let (bytes_default, planes_default) = encode_keyframe_inner_lf(
frame,
params,
None,
Some(&mut counts),
options.auto_loop_filter,
)?;
let fitted = fit_token_prob_updates(&counts, 2.0);
if !any_token_prob_update(&fitted) {
return Ok((bytes_default, planes_default));
}
let (bytes_fitted, planes_fitted) =
encode_keyframe_inner_lf(frame, params, Some(&fitted), None, options.auto_loop_filter)?;
if bytes_fitted.len() <= bytes_default.len() {
Ok((bytes_fitted, planes_fitted))
} else {
Ok((bytes_default, planes_default))
}
}
pub fn encode_keyframe_with_options(
frame: &I420Frame,
params: &KeyframeParams,
options: &KeyframeEncodeOptions,
) -> Result<Vec<u8>, EncodeError> {
encode_keyframe_with_reconstruction_and_options(frame, params, options).map(|(bytes, _)| bytes)
}
pub fn encode_keyframe_with_reconstruction_and_options(
frame: &I420Frame,
params: &KeyframeParams,
options: &KeyframeEncodeOptions,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_under_options(frame, params, options).map(|out| (out.bytes, out.planes))
}
pub fn encode_keyframe_detailed(
frame: &I420Frame,
params: &KeyframeParams,
options: &KeyframeEncodeOptions,
) -> Result<KeyframeEncoded, EncodeError> {
let out = encode_keyframe_under_options(frame, params, options)?;
Ok(KeyframeEncoded {
bytes: out.bytes,
reconstruction: out.planes,
token_prob_updates: out.shipped_updates,
loop_filter_level: out.loop_filter.0,
sharpness_level: out.loop_filter.1,
})
}
fn encode_keyframe_under_options(
frame: &I420Frame,
params: &KeyframeParams,
options: &KeyframeEncodeOptions,
) -> Result<KeyframeDriven, EncodeError> {
let drive = KeyframeDrive {
search_updates: options.search_token_probs.as_ref(),
fit_in_place: options.token_prob_fit,
pilot_stride: (options.effort != EncodeEffort::Fastest).then_some(4),
loop_filter: if options.auto_loop_filter {
LoopFilterPick::Search
} else if options.sampled_loop_filter {
LoopFilterPick::Sampled
} else {
LoopFilterPick::Fixed
},
effort: options.effort,
threads: options.threads,
};
if !options.fitted_token_prob_updates {
return encode_keyframe_driven(frame, params, None, &drive);
}
let mut counts = empty_branch_counts();
let first = encode_keyframe_driven(frame, params, Some(&mut counts), &drive)?;
let fitted = if drive.fit_in_place {
first.shipped_updates
} else {
let fitted = fit_token_prob_updates(&counts, 2.0);
any_token_prob_update(&fitted).then_some(fitted)
};
let Some(fitted) = fitted else {
return Ok(first);
};
let second = encode_keyframe_driven(
frame,
params,
None,
&KeyframeDrive {
search_updates: Some(&fitted),
..drive
},
)?;
Ok(if second.bytes.len() <= first.bytes.len() {
second
} else {
first
})
}
pub fn encode_keyframe_with_reconstruction_and_token_updates(
frame: &I420Frame,
params: &KeyframeParams,
token_updates: Option<&TokenProbUpdates>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_inner(frame, params, token_updates, None)
}
fn encode_keyframe_inner(
frame: &I420Frame,
params: &KeyframeParams,
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_inner_lf(frame, params, token_updates, counts, false)
}
fn encode_keyframe_inner_lf(
frame: &I420Frame,
params: &KeyframeParams,
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
auto_lf: bool,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_tuned(
frame,
params,
token_updates,
counts,
auto_lf,
EncodeEffort::Thorough,
1,
)
}
fn encode_keyframe_tuned(
frame: &I420Frame,
params: &KeyframeParams,
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
auto_lf: bool,
effort: EncodeEffort,
threads: usize,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
let drive = KeyframeDrive {
search_updates: token_updates,
fit_in_place: false,
pilot_stride: None,
loop_filter: if auto_lf {
LoopFilterPick::Search
} else {
LoopFilterPick::Fixed
},
effort,
threads,
};
encode_keyframe_driven(frame, params, counts, &drive).map(|out| (out.bytes, out.planes))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LoopFilterPick {
Fixed,
Sampled,
Search,
}
struct KeyframeDrive<'a> {
search_updates: Option<&'a TokenProbUpdates>,
fit_in_place: bool,
pilot_stride: Option<usize>,
loop_filter: LoopFilterPick,
effort: EncodeEffort,
threads: usize,
}
struct KeyframeDriven {
bytes: Vec<u8>,
planes: crate::frame::KeyframePlanes,
shipped_updates: Option<TokenProbUpdates>,
loop_filter: (u8, u8),
}
fn encode_keyframe_driven(
frame: &I420Frame,
params: &KeyframeParams,
counts: Option<&mut BranchCounts>,
drive: &KeyframeDrive,
) -> Result<KeyframeDriven, EncodeError> {
let (effort, threads) = (drive.effort, drive.threads);
let token_updates = drive.search_updates;
let auto_lf = drive.loop_filter == LoopFilterPick::Search;
let width = frame.width;
let height = frame.height;
if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
return Err(EncodeError::InvalidDimensions { width, height });
}
if params.y_ac_qi > 127 {
return Err(EncodeError::QuantIndexOutOfRange {
value: params.y_ac_qi,
});
}
if params.loop_filter_level > 63 {
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: params.loop_filter_level,
});
}
if params.sharpness_level > 7 {
return Err(EncodeError::SharpnessLevelOutOfRange {
value: params.sharpness_level,
});
}
let num_partitions = match params.nbr_of_dct_partitions {
1 | 2 | 4 | 8 => params.nbr_of_dct_partitions as usize,
other => return Err(EncodeError::InvalidDctPartitionCount { value: other }),
};
let mb_cols = width.div_ceil(16) as usize;
let mb_rows = height.div_ceil(16) as usize;
let mut coeff_probs = match token_updates {
Some(u) => crate::dct_tokens::merge_default_token_probs(u),
None => crate::dct_tokens::DEFAULT_COEFF_PROBS,
};
let factors = crate::dequant::MbDequantFactors::from_base_and_deltas(
params.y_ac_qi as i32,
0,
0,
0,
0,
0,
);
if let (Some(stride), None) = (drive.pilot_stride, token_updates)
&& drive.fit_in_place
{
let defaults = crate::dct_tokens::DEFAULT_COEFF_PROBS;
let default_tables = TrellisRateTables::for_probs(&defaults);
let pilot_rd = MbRdCtx {
factors: &factors,
coeff_probs: &defaults,
rate_tables: Some(&default_tables),
lambda: rd_lambda(&factors),
trellis: params.trellis_strength,
};
let seen =
pilot::pilot_branch_counts(frame, &pilot_rd, (mb_cols, mb_rows), stride, threads);
coeff_probs = pilot::blend_into_defaults(&seen);
}
let trellis_rate_tables = Some(TrellisRateTables::for_probs(&coeff_probs));
let mut planes = crate::frame::KeyframePlanes {
y: vec![0u8; mb_cols * 16 * mb_rows * 16],
u: vec![0u8; mb_cols * 8 * mb_rows * 8],
v: vec![0u8; mb_cols * 8 * mb_rows * 8],
y_stride: mb_cols * 16,
uv_stride: mb_cols * 8,
mb_cols,
mb_rows,
};
let search = wavefront::KeyframeSearch {
frame,
rd: MbRdCtx {
factors: &factors,
coeff_probs: &coeff_probs,
rate_tables: trellis_rate_tables.as_ref(),
lambda: rd_lambda(&factors),
trellis: params.trellis_strength,
},
effort,
mb_cols,
mb_rows,
num_partitions,
defer_token_coding: drive.fit_in_place,
tape_hint: std::sync::atomic::AtomicUsize::new(0),
};
let mut analysed = wavefront::analyse_and_tokenize(&search, &mut planes, threads)?;
let shipped_updates: Option<TokenProbUpdates> = if drive.fit_in_place {
let mut observed = empty_branch_counts();
analysed.tally(&mut observed, threads);
let fitted = fit_token_prob_updates(&observed, 0.0);
any_token_prob_update(&fitted).then_some(fitted)
} else {
token_updates.copied()
};
let coded_in_search = analysed.partitions.take();
let code_tapes = |analysed: &wavefront::AnalysedFrame, threads: usize| {
let emit_probs = match &shipped_updates {
Some(u) => crate::dct_tokens::merge_default_token_probs(u),
None => crate::dct_tokens::DEFAULT_COEFF_PROBS,
};
analysed.code_partitions(&emit_probs, num_partitions, threads)
};
let token_updates = shipped_updates.as_ref();
let modes = &analysed.modes;
let has_coeffs = &analysed.has_coeffs;
let filter_stage = |planes: &mut crate::frame::KeyframePlanes| {
let mut lf_config = crate::loop_filter::FrameFilterConfig {
simple: params.filter_type,
key_frame: true,
loop_filter_level: params.loop_filter_level,
sharpness_level: params.sharpness_level,
segmentation_enabled: false,
segment_abs: false,
segment_lf_level: [0; crate::loop_filter::MAX_MB_SEGMENTS],
delta_enabled: false,
ref_delta_current: 0,
bpred_mode_delta: 0,
ref_delta_last: 0,
ref_delta_golden: 0,
ref_delta_altref: 0,
zero_mv_mode_delta: 0,
other_mv_mode_delta: 0,
split_mv_mode_delta: 0,
};
let src = crate::loop_filter::SourcePlanes {
width: width as usize,
height: height as usize,
y: frame.y,
u: frame.u,
v: frame.v,
y_stride: frame.y_stride,
uv_stride: frame.uv_stride,
};
let (eff_lf_level, eff_sharpness) = if auto_lf {
crate::loop_filter::select_filter_params_threaded(
planes, modes, has_coeffs, &lf_config, &src, None, threads,
)
} else if drive.loop_filter == LoopFilterPick::Sampled {
crate::loop_filter::select_filter_params_sampled(
planes,
modes,
has_coeffs,
&lf_config,
&src,
None,
crate::loop_filter::FilterSampling::for_key_frame(mb_rows),
threads,
)
} else {
(params.loop_filter_level, params.sharpness_level)
};
lf_config.loop_filter_level = eff_lf_level;
lf_config.sharpness_level = eff_sharpness;
if eff_lf_level != 0 {
crate::loop_filter::filter_frame_flags_threaded(
planes, modes, has_coeffs, &lf_config, threads,
);
}
(eff_lf_level, eff_sharpness)
};
let ((eff_lf_level, eff_sharpness), dct_partitions) = match coded_in_search {
Some(coded) => (filter_stage(&mut planes), coded),
None if threads > 1 => std::thread::scope(|scope| {
let coder = scope.spawn(|| code_tapes(&analysed, threads));
let filter = filter_stage(&mut planes);
match coder.join() {
Ok(coded) => (filter, coded),
Err(panic) => std::panic::resume_unwind(panic),
}
}),
None => {
let coded = code_tapes(&analysed, 1);
(filter_stage(&mut planes), coded)
}
};
let mut hdr = BoolEncoder::new();
hdr.write_bool(128, false);
hdr.write_bool(128, false);
write_segment_update_flags(&mut hdr, false);
write_loop_filter(
&mut hdr,
params.filter_type,
eff_lf_level,
eff_sharpness,
false,
)?;
write_token_partition_count(&mut hdr, params.nbr_of_dct_partitions)?;
write_quant_indices(&mut hdr, params.y_ac_qi, None, None, None, None, None)?;
let persists_updates = token_updates.is_some_and(any_token_prob_update);
hdr.write_bool(128, !persists_updates);
match token_updates {
Some(u) => write_token_prob_updates(&mut hdr, u, &COEFF_UPDATE_PROBS_FLAT),
None => write_no_token_prob_updates(&mut hdr, &COEFF_UPDATE_PROBS_FLAT),
}
let prob_skip_false = 128u8;
write_mb_no_skip_coeff(&mut hdr, true, prob_skip_false);
write_mode_layer(&mut hdr, modes, mb_rows, mb_cols, prob_skip_false);
let first_partition = hdr.finish();
let first_partition_size = first_partition.len();
if first_partition_size > 0x7_FFFF {
return Err(EncodeError::FirstPartitionTooLarge {
bytes: first_partition_size,
});
}
if let Some(c) = counts {
analysed.tally(c, threads);
}
let dct_total: usize = dct_partitions.iter().map(|p| p.len()).sum();
let size_table_len = (num_partitions - 1) * 3;
let mut out: Vec<u8> =
Vec::with_capacity(10 + first_partition_size + size_table_len + dct_total);
write_frame_tag(
&mut out,
true,
0,
true,
first_partition_size as u32,
width,
height,
ScaleCode::None,
ScaleCode::None,
)?;
out.extend_from_slice(&first_partition);
for part in dct_partitions.iter().take(num_partitions - 1) {
let sz = part.len();
out.push((sz & 0xff) as u8);
out.push(((sz >> 8) & 0xff) as u8);
out.push(((sz >> 16) & 0xff) as u8);
}
for part in &dct_partitions {
out.extend_from_slice(part);
}
Ok(KeyframeDriven {
bytes: out,
planes,
shipped_updates,
loop_filter: (eff_lf_level, eff_sharpness),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct AdaptiveQuantConfig {
pub base_y_ac_qi: u8,
pub variance_boundaries: [u32; 3],
pub quant_delta: [i8; 4],
pub loop_filter_level: u8,
pub sharpness_level: u8,
pub filter_type: bool,
}
impl AdaptiveQuantConfig {
#[must_use]
pub fn with_base_y_ac_qi(mut self, v: u8) -> Self {
self.base_y_ac_qi = v;
self
}
#[must_use]
pub fn with_variance_boundaries(mut self, v: [u32; 3]) -> Self {
self.variance_boundaries = v;
self
}
#[must_use]
pub fn with_quant_delta(mut self, v: [i8; 4]) -> Self {
self.quant_delta = v;
self
}
#[must_use]
pub fn with_loop_filter_level(mut self, v: u8) -> Self {
self.loop_filter_level = v;
self
}
#[must_use]
pub fn with_sharpness_level(mut self, v: u8) -> Self {
self.sharpness_level = v;
self
}
#[must_use]
pub fn with_filter_type(mut self, v: bool) -> Self {
self.filter_type = v;
self
}
}
impl Default for AdaptiveQuantConfig {
fn default() -> Self {
AdaptiveQuantConfig {
base_y_ac_qi: 32,
variance_boundaries: [
SEGMENT_VARIANCE_THRESHOLDS[1],
SEGMENT_VARIANCE_THRESHOLDS[2],
SEGMENT_VARIANCE_THRESHOLDS[3],
],
quant_delta: [8, 0, -6, -12],
loop_filter_level: 0,
sharpness_level: 0,
filter_type: false,
}
}
}
fn mb_luma_variance(y: &[u8; 256]) -> u32 {
let mut sum: u64 = 0;
let mut sumsq: u64 = 0;
for &px in y.iter() {
sum += px as u64;
sumsq += (px as u64) * (px as u64);
}
let n = 256u64;
let mean_sq = (sum * sum) / (n * n);
let e_sq = sumsq / n;
e_sq.saturating_sub(mean_sq) as u32
}
fn classify_segment(variance: u32, boundaries: &[u32; 3]) -> u8 {
boundaries.iter().filter(|&&b| variance >= b).count().min(3) as u8
}
pub fn encode_keyframe_adaptive_quant(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
) -> Result<Vec<u8>, EncodeError> {
let (bytes, _planes) = encode_keyframe_adaptive_quant_with_reconstruction(frame, config)?;
Ok(bytes)
}
pub fn encode_keyframe_adaptive_quant_with_trellis(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
trellis: TrellisStrength,
) -> Result<Vec<u8>, EncodeError> {
let (bytes, _planes) = encode_keyframe_adaptive_quant_inner(frame, config, trellis)?;
Ok(bytes)
}
pub fn encode_keyframe_adaptive_quant_with_reconstruction(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_adaptive_quant_inner(frame, config, TrellisStrength::DEFAULT)
}
pub fn encode_keyframe_adaptive_quant_with_reconstruction_and_trellis(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
trellis: TrellisStrength,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_adaptive_quant_inner(frame, config, trellis)
}
pub fn encode_keyframe_adaptive_quant_with_segment_lf_deltas(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
segment_lf_deltas: &[i8; 4],
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_adaptive_quant_inner_lf(
frame,
config,
TrellisStrength::DEFAULT,
Some(segment_lf_deltas),
)
}
pub fn encode_keyframe_adaptive_quant_with_segment_lf_deltas_and_trellis(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
segment_lf_deltas: &[i8; 4],
trellis: TrellisStrength,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_adaptive_quant_inner_lf(frame, config, trellis, Some(segment_lf_deltas))
}
fn encode_keyframe_adaptive_quant_inner(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
trellis: TrellisStrength,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_keyframe_adaptive_quant_inner_lf(frame, config, trellis, None)
}
fn encode_keyframe_adaptive_quant_inner_lf(
frame: &I420Frame,
config: &AdaptiveQuantConfig,
trellis: TrellisStrength,
segment_lf_deltas: Option<&[i8; 4]>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
let width = frame.width;
let height = frame.height;
if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
return Err(EncodeError::InvalidDimensions { width, height });
}
if config.base_y_ac_qi > 127 {
return Err(EncodeError::QuantIndexOutOfRange {
value: config.base_y_ac_qi,
});
}
if config.loop_filter_level > 63 {
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: config.loop_filter_level,
});
}
if config.sharpness_level > 7 {
return Err(EncodeError::SharpnessLevelOutOfRange {
value: config.sharpness_level,
});
}
if let Some(d) = segment_lf_deltas
&& let Some(&bad) = d.iter().find(|v| v.unsigned_abs() > 63)
{
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: bad.unsigned_abs(),
});
}
let mb_cols = width.div_ceil(16) as usize;
let mb_rows = height.div_ceil(16) as usize;
let coeff_probs = crate::dct_tokens::DEFAULT_COEFF_PROBS;
let trellis_rate_tables = Some(TrellisRateTables::for_probs(&coeff_probs));
let base = config.base_y_ac_qi as i32;
let mut seg_qindex = [0u8; crate::loop_filter::MAX_MB_SEGMENTS];
let mut seg_factors =
[crate::dequant::MbDequantFactors::from_base_and_deltas(base, 0, 0, 0, 0, 0);
crate::loop_filter::MAX_MB_SEGMENTS];
for s in 0..crate::loop_filter::MAX_MB_SEGMENTS {
let q = (base + config.quant_delta[s] as i32).clamp(0, 127) as u8;
seg_qindex[s] = q;
seg_factors[s] =
crate::dequant::MbDequantFactors::from_base_and_deltas(q as i32, 0, 0, 0, 0, 0);
}
let mut planes = crate::frame::KeyframePlanes {
y: vec![0u8; mb_cols * 16 * mb_rows * 16],
u: vec![0u8; mb_cols * 8 * mb_rows * 8],
v: vec![0u8; mb_cols * 8 * mb_rows * 8],
y_stride: mb_cols * 16,
uv_stride: mb_cols * 8,
mb_cols,
mb_rows,
};
let mut modes: Vec<MacroblockModes> = Vec::with_capacity(mb_rows * mb_cols);
let mut all_coeffs: Vec<MbCoeffs> = Vec::with_capacity(mb_rows * mb_cols);
for mb_row in 0..mb_rows {
for mb_col in 0..mb_cols {
let pixels = frame.extract_mb(mb_row, mb_col);
let neighbors = crate::frame::gather_neighbors_public(&planes, mb_row, mb_col);
let variance = mb_luma_variance(&pixels.y);
let seg = classify_segment(variance, &config.variance_boundaries);
let q = seg_qindex[seg as usize];
let encoded = encode_mb_block_set_with_neighbors_strength_rates(
&pixels,
&neighbors,
q,
&coeff_probs,
trellis_rate_tables.as_ref(),
trellis,
)
.map_err(EncodeError::Token)?;
let mb_skip_coeff = encoded.nonzero_block_count == 0;
let mut dq = encoded.coeffs;
seg_factors[seg as usize].dequantize(&mut dq);
let use_bpred = encoded.y_mode == IntraYMode::B;
let recon = if use_bpred {
crate::reconstruct::decode_keyframe_mb_bpred(
encoded.b_subblock_modes.as_ref(),
encoded.uv_mode,
mb_skip_coeff,
&neighbors,
&dq.y,
&dq.u,
&dq.v,
)
} else {
crate::reconstruct::decode_keyframe_mb_non_bpred(
encoded.y_mode,
encoded.uv_mode,
mb_skip_coeff,
&neighbors,
&dq.y2,
&dq.y,
&dq.u,
&dq.v,
)
}
.map_err(EncodeError::Reconstruct)?;
crate::frame::write_mb_public(&mut planes, mb_row, mb_col, &recon);
modes.push(MacroblockModes {
segment_id: Some(seg),
mb_skip_coeff,
y_mode: encoded.y_mode,
subblock_modes: encoded.b_subblock_modes,
uv_mode: encoded.uv_mode,
});
all_coeffs.push(encoded.coeffs);
}
}
if config.loop_filter_level != 0 {
let mut segment_lf_level = [0i16; crate::loop_filter::MAX_MB_SEGMENTS];
if let Some(d) = segment_lf_deltas {
for (dst, &src) in segment_lf_level.iter_mut().zip(d.iter()) {
*dst = i16::from(src);
}
}
let lf_config = crate::loop_filter::FrameFilterConfig {
simple: config.filter_type,
key_frame: true,
loop_filter_level: config.loop_filter_level,
sharpness_level: config.sharpness_level,
segmentation_enabled: segment_lf_deltas.is_some(),
segment_abs: false,
segment_lf_level,
delta_enabled: false,
ref_delta_current: 0,
bpred_mode_delta: 0,
ref_delta_last: 0,
ref_delta_golden: 0,
ref_delta_altref: 0,
zero_mv_mode_delta: 0,
other_mv_mode_delta: 0,
split_mv_mode_delta: 0,
};
crate::loop_filter::filter_frame(&mut planes, &modes, &all_coeffs, &lf_config);
}
let mut hdr = BoolEncoder::new();
hdr.write_bool(128, false);
hdr.write_bool(128, false);
const SEG_TREE_PROB: u8 = 170;
let seg_probs: [u8; 3] = [SEG_TREE_PROB; 3];
let layer = UpdateSegmentationLayer {
update_mb_segmentation_map: true,
feature_mode_absolute: false,
quantizer: [
Some(config.quant_delta[0] as i16),
Some(config.quant_delta[1] as i16),
Some(config.quant_delta[2] as i16),
Some(config.quant_delta[3] as i16),
],
loop_filter: match segment_lf_deltas {
Some(d) => [
Some(i16::from(d[0])),
Some(i16::from(d[1])),
Some(i16::from(d[2])),
Some(i16::from(d[3])),
],
None => [None; 4],
},
segment_prob: [Some(seg_probs[0]), Some(seg_probs[1]), Some(seg_probs[2])],
};
write_update_segmentation(&mut hdr, &layer);
write_loop_filter(
&mut hdr,
config.filter_type,
config.loop_filter_level,
config.sharpness_level,
false,
)?;
write_token_partition_count(&mut hdr, 1)?;
write_quant_indices(&mut hdr, config.base_y_ac_qi, None, None, None, None, None)?;
hdr.write_bool(128, true);
write_no_token_prob_updates(&mut hdr, &COEFF_UPDATE_PROBS_FLAT);
let prob_skip_false = 128u8;
write_mb_no_skip_coeff(&mut hdr, true, prob_skip_false);
write_mode_layer_segmented(
&mut hdr,
&modes,
mb_rows,
mb_cols,
prob_skip_false,
Some(&seg_probs),
);
let first_partition = hdr.finish();
let first_partition_size = first_partition.len();
if first_partition_size > 0x7_FFFF {
return Err(EncodeError::FirstPartitionTooLarge {
bytes: first_partition_size,
});
}
let mut tok = BoolEncoder::new();
let mut above_ctx: Vec<MbEntropyCtx> = vec![MbEntropyCtx::default(); mb_cols];
for mb_row in 0..mb_rows {
let mut left_ctx = MbEntropyCtx::default();
for (mb_col, above_col) in above_ctx.iter_mut().enumerate() {
let raster = mb_row * mb_cols + mb_col;
let mb = &modes[raster];
let use_bpred = mb.y_mode == IntraYMode::B;
if mb.mb_skip_coeff {
clear_skip_ctx(use_bpred, above_col, &mut left_ctx);
continue;
}
encode_mb_tokens(
&mut tok,
&all_coeffs[raster],
use_bpred,
&coeff_probs,
above_col,
&mut left_ctx,
)
.map_err(EncodeError::Token)?;
}
}
let dct_partition = tok.finish();
let mut out: Vec<u8> = Vec::with_capacity(10 + first_partition_size + dct_partition.len());
write_frame_tag(
&mut out,
true,
0,
true,
first_partition_size as u32,
width,
height,
ScaleCode::None,
ScaleCode::None,
)?;
out.extend_from_slice(&first_partition);
out.extend_from_slice(&dct_partition);
Ok((out, planes))
}
fn clear_skip_ctx(use_bpred: bool, above: &mut MbEntropyCtx, left: &mut MbEntropyCtx) {
for slot in 0..8 {
above.nonzero[slot] = false;
left.nonzero[slot] = false;
}
if !use_bpred {
above.nonzero[8] = false;
left.nonzero[8] = false;
}
}
fn write_mode_layer(
hdr: &mut BoolEncoder,
modes: &[MacroblockModes],
mb_rows: usize,
mb_cols: usize,
prob_skip_false: u8,
) {
write_mode_layer_segmented(hdr, modes, mb_rows, mb_cols, prob_skip_false, None);
}
fn write_mode_layer_segmented(
hdr: &mut BoolEncoder,
modes: &[MacroblockModes],
mb_rows: usize,
mb_cols: usize,
prob_skip_false: u8,
segment_probs: Option<&[u8; 3]>,
) {
let mut above_subblock = vec![IntraBmode::Dc; mb_cols * 4];
let bmode_paths: &[TreedLeafPath] = &*BMODE_PATHS;
for mb_row in 0..mb_rows {
let mut left_subblock = [IntraBmode::Dc; 4];
for mb_col in 0..mb_cols {
let mb = &modes[mb_row * mb_cols + mb_col];
if let Some(probs) = segment_probs {
let sid = mb.segment_id.unwrap_or(0);
hdr.write_treed(&crate::macroblock::MB_SEGMENT_TREE, |i| probs[i], sid);
}
hdr.write_bool(prob_skip_false, mb.mb_skip_coeff);
hdr.write_treed_cached(&*KF_YMODE_PATHS, |i| KF_YMODE_PROB[i], mb.y_mode.leaf());
if let Some(sub) = &mb.subblock_modes {
for j in 0..16 {
let row = j >> 2;
let col = j & 3;
let above = if row == 0 {
above_subblock[mb_col * 4 + col]
} else {
sub[(row - 1) * 4 + col]
};
let left = if col == 0 {
left_subblock[row]
} else {
sub[row * 4 + (col - 1)]
};
let prob_row = &KF_BMODE_PROB[above.idx()][left.idx()];
hdr.write_treed_cached(bmode_paths, |i| prob_row[i], sub[j].idx() as u8);
}
}
hdr.write_treed_cached(&*UV_MODE_PATHS, |i| KF_UV_MODE_PROB[i], mb.uv_mode.leaf());
match &mb.subblock_modes {
Some(sub) => {
above_subblock[mb_col * 4..mb_col * 4 + 4].copy_from_slice(&sub[12..16]);
for (row, slot) in left_subblock.iter_mut().enumerate() {
*slot = sub[row * 4 + 3];
}
}
None => {
let projected = mb.y_mode.project_to_subblock_context();
for slot in &mut above_subblock[mb_col * 4..mb_col * 4 + 4] {
*slot = projected;
}
left_subblock.fill(projected);
}
}
}
}
}
#[derive(Debug, Clone)]
struct SplitMvCandidate {
partition: crate::near_mv::MvPartition,
split_mvs: [crate::motion_vector::Mv; 16],
submv_modes: [crate::near_mv::SubMvRefMode; 16],
submv_new_diffs: [crate::motion_vector::Mv; 16],
j: f64,
}
const SPLIT_MV_MAX_DIAMOND_ITERS: u32 = 4;
#[inline]
fn sub_block_sad_4x4(src: &[u8; 16], pred: &[u8; 16]) -> u32 {
let mut sad: u32 = 0;
for i in 0..16 {
sad += (src[i] as i32 - pred[i] as i32).unsigned_abs();
}
sad
}
#[inline]
fn extract_src_subblock_4x4(src: &[u8; 256], b: usize) -> [u8; 16] {
let sb_row = b >> 2; let sb_col = b & 3; let mut out = [0u8; 16];
for r in 0..4 {
let dst_off = r * 4;
let src_off = (sb_row * 4 + r) * 16 + sb_col * 4;
out[dst_off..dst_off + 4].copy_from_slice(&src[src_off..src_off + 4]);
}
out
}
fn group_sad_at_whole_mv(
luma_ref: crate::motion_search::LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
group_subblocks: &[usize],
mv: crate::motion_vector::Mv,
) -> u32 {
let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
let mb_x0 = mb_col * 16;
let mb_y0 = mb_row * 16;
let mut sad: u32 = 0;
let src_x0 = mb_x0 as isize + (mv_eighth.col >> 3) as isize;
let src_y0 = mb_y0 as isize + (mv_eighth.row >> 3) as isize;
if src_x0 >= 0
&& src_y0 >= 0
&& src_x0 + 16 <= luma_ref.width as isize
&& src_y0 + 16 <= luma_ref.height as isize
{
let x0 = src_x0 as usize;
let y0 = src_y0 as usize;
for &b in group_subblocks {
let sb_row = b >> 2;
let sb_col = b & 3;
for r in 0..4 {
let pred_start = (y0 + sb_row * 4 + r) * luma_ref.stride + x0 + sb_col * 4;
let pred_row = &luma_ref.plane[pred_start..pred_start + 4];
let src_start = (sb_row * 4 + r) * 16 + sb_col * 4;
let src_row = &src_y[src_start..src_start + 4];
for c in 0..4 {
sad += (src_row[c] as i32 - pred_row[c] as i32).unsigned_abs();
}
}
}
return sad;
}
for &b in group_subblocks {
let sb_row = b >> 2;
let sb_col = b & 3;
let blk_x = mb_x0 + sb_col * 4;
let blk_y = mb_y0 + sb_row * 4;
let patch = crate::motion_comp::fetch_block_whole_pixel(
luma_ref.plane,
luma_ref.stride,
luma_ref.width,
luma_ref.height,
blk_x,
blk_y,
mv_eighth,
);
let src_sb = extract_src_subblock_4x4(src_y, b);
sad += sub_block_sad_4x4(&src_sb, &patch);
}
sad
}
#[inline]
fn group_rect_rows_sad<const PXW: usize>(
plane: &[u8],
stride: usize,
x0: usize,
y0: usize,
src_y: &[u8; 256],
shape: GroupShape,
) -> u32 {
let mut sad = 0u32;
for r in shape.row0..shape.row0 + shape.h_px {
let pred_start = (y0 + r) * stride + x0 + shape.col0;
let pred: &[u8; PXW] = plane[pred_start..pred_start + PXW]
.try_into()
.expect("row width");
let src: &[u8; PXW] = src_y[r * 16 + shape.col0..r * 16 + shape.col0 + PXW]
.try_into()
.expect("row width");
for i in 0..PXW {
sad += src[i].abs_diff(pred[i]) as u32;
}
}
sad
}
#[allow(clippy::too_many_arguments)] fn group_sad_at_whole_mv_shaped(
luma_ref: crate::motion_search::LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
group_subblocks: &[usize],
shape: GroupShape,
mv: crate::motion_vector::Mv,
) -> u32 {
let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
let mb_x0 = mb_col * 16;
let mb_y0 = mb_row * 16;
let src_x0 = mb_x0 as isize + (mv_eighth.col >> 3) as isize;
let src_y0 = mb_y0 as isize + (mv_eighth.row >> 3) as isize;
if src_x0 >= 0
&& src_y0 >= 0
&& src_x0 + 16 <= luma_ref.width as isize
&& src_y0 + 16 <= luma_ref.height as isize
{
let x0 = src_x0 as usize;
let y0 = src_y0 as usize;
return match shape.w_px {
16 => group_rect_rows_sad::<16>(luma_ref.plane, luma_ref.stride, x0, y0, src_y, shape),
8 => group_rect_rows_sad::<8>(luma_ref.plane, luma_ref.stride, x0, y0, src_y, shape),
_ => group_rect_rows_sad::<4>(luma_ref.plane, luma_ref.stride, x0, y0, src_y, shape),
};
}
group_sad_at_whole_mv(luma_ref, mb_col, mb_row, src_y, group_subblocks, mv)
}
#[allow(clippy::too_many_arguments)] fn group_small_diamond_search(
luma_ref: crate::motion_search::LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
group_subblocks: &[usize],
shape: GroupShape,
center: crate::motion_vector::Mv,
max_iters: u32,
) -> (crate::motion_vector::Mv, u32) {
use crate::motion_search::{MV_MAX, MV_MIN, WHOLE_PIXEL_STEP};
let snap = |v: i16| -> i16 {
let q = (v / WHOLE_PIXEL_STEP) * WHOLE_PIXEL_STEP;
q.clamp(MV_MIN, MV_MAX)
};
let mut best_mv = crate::motion_vector::Mv {
row: snap(center.row),
col: snap(center.col),
};
let mut best_sad = group_sad_at_whole_mv_shaped(
luma_ref,
mb_col,
mb_row,
src_y,
group_subblocks,
shape,
best_mv,
);
let offsets: [(i16, i16); 4] = [
(-WHOLE_PIXEL_STEP, 0),
(WHOLE_PIXEL_STEP, 0),
(0, -WHOLE_PIXEL_STEP),
(0, WHOLE_PIXEL_STEP),
];
for _ in 0..max_iters {
let mut improved = false;
for (dr, dc) in offsets {
let cand_row = (best_mv.row as i32 + dr as i32).clamp(MV_MIN as i32, MV_MAX as i32);
let cand_col = (best_mv.col as i32 + dc as i32).clamp(MV_MIN as i32, MV_MAX as i32);
let cand_mv = crate::motion_vector::Mv {
row: cand_row as i16,
col: cand_col as i16,
};
if cand_mv == best_mv {
continue;
}
let cand_sad = group_sad_at_whole_mv_shaped(
luma_ref,
mb_col,
mb_row,
src_y,
group_subblocks,
shape,
cand_mv,
);
if cand_sad < best_sad {
best_sad = cand_sad;
best_mv = cand_mv;
improved = true;
}
}
if !improved {
break;
}
}
(best_mv, best_sad)
}
struct PartitionGroups {
members: [[usize; 16]; 16],
len: [usize; 16],
shapes: [GroupShape; 16],
num_groups: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct GroupShape {
row0: usize,
col0: usize,
w_px: usize,
h_px: usize,
}
impl PartitionGroups {
const fn build(pid: usize) -> Self {
let table = &crate::near_mv::MV_PARTITIONS[pid];
let mut members = [[0usize; 16]; 16];
let mut len = [0usize; 16];
let mut num_groups = 0usize;
let mut idx = 0usize;
while idx < 16 {
let g = table[idx] as usize;
members[g][len[g]] = idx;
len[g] += 1;
if g + 1 > num_groups {
num_groups = g + 1;
}
idx += 1;
}
let mut shapes = [GroupShape {
row0: 0,
col0: 0,
w_px: 0,
h_px: 0,
}; 16];
let mut g = 0usize;
while g < num_groups {
let (mut min_r, mut max_r, mut min_c, mut max_c) = (3usize, 0usize, 3usize, 0usize);
let mut m = 0usize;
while m < len[g] {
let b = members[g][m];
let (sb_r, sb_c) = (b >> 2, b & 3);
if sb_r < min_r {
min_r = sb_r;
}
if sb_r > max_r {
max_r = sb_r;
}
if sb_c < min_c {
min_c = sb_c;
}
if sb_c > max_c {
max_c = sb_c;
}
m += 1;
}
shapes[g] = GroupShape {
row0: min_r * 4,
col0: min_c * 4,
w_px: (max_c + 1 - min_c) * 4,
h_px: (max_r + 1 - min_r) * 4,
};
g += 1;
}
PartitionGroups {
members,
len,
shapes,
num_groups,
}
}
#[inline]
fn group(&self, g: usize) -> &[usize] {
&self.members[g][..self.len[g]]
}
#[inline]
fn shape(&self, g: usize) -> GroupShape {
self.shapes[g]
}
#[inline]
fn iter(&self) -> impl Iterator<Item = &[usize]> + '_ {
(0..self.num_groups).map(move |g| self.group(g))
}
}
static PARTITION_GROUP_TABLE: [PartitionGroups; 4] = [
PartitionGroups::build(0),
PartitionGroups::build(1),
PartitionGroups::build(2),
PartitionGroups::build(3),
];
#[inline]
fn partition_groups(p: crate::near_mv::MvPartition) -> &'static PartitionGroups {
&PARTITION_GROUP_TABLE[crate::near_mv::partition_id(p)]
}
fn submv_ref_bits(probs: &[u8; 3], mode: crate::near_mv::SubMvRefMode) -> f64 {
use crate::near_mv::SubMvRefMode as M;
match mode {
M::Left4x4 => bool_bits(probs[0], false),
M::Above4x4 => bool_bits(probs[0], true) + bool_bits(probs[1], false),
M::Zero4x4 => {
bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], false)
}
M::New4x4 => {
bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], true)
}
}
}
fn mv_partition_bits(p: crate::near_mv::MvPartition) -> f64 {
let probs = &crate::near_mv::MV_PARTITION_PROBS;
use crate::near_mv::MvPartition as P;
match p {
P::Mv16 => bool_bits(probs[0], false),
P::Quarters => bool_bits(probs[0], true) + bool_bits(probs[1], false),
P::TopBottom => {
bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], false)
}
P::LeftRight => {
bool_bits(probs[0], true) + bool_bits(probs[1], true) + bool_bits(probs[2], true)
}
}
}
#[allow(clippy::too_many_arguments)] fn score_split_partition(
partition: crate::near_mv::MvPartition,
luma_ref: crate::motion_search::LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
best_predictor: crate::motion_vector::Mv,
above_mb: &crate::near_mv::MbInfo,
left_mb: &crate::near_mv::MbInfo,
mv_contexts: &crate::motion_vector::MvContexts,
lambda: f64,
) -> Option<SplitMvCandidate> {
let groups = partition_groups(partition);
let mut split_mvs = [crate::motion_vector::Mv::default(); 16];
let mut submv_modes = [crate::near_mv::SubMvRefMode::Zero4x4; 16];
let mut submv_new_diffs = [crate::motion_vector::Mv::default(); 16];
let mut total_sad: u32 = 0;
let mut total_submv_bits: f64 = 0.0;
for (g_idx, group) in groups.iter().enumerate() {
let anchor = group[0];
let left_neighbour_mv = crate::near_mv::left_block_mv(&split_mvs, left_mb, anchor);
let above_neighbour_mv = crate::near_mv::above_block_mv(&split_mvs, above_mb, anchor);
let ctx = crate::near_mv::submv_ref_context(left_neighbour_mv, above_neighbour_mv);
let probs = &crate::near_mv::SUBMV_REF_PROBS[ctx];
let shape = groups.shape(g_idx);
let (search_mv, search_sad) = group_small_diamond_search(
luma_ref,
mb_col,
mb_row,
src_y,
group,
shape,
best_predictor,
SPLIT_MV_MAX_DIAMOND_ITERS,
);
use crate::near_mv::SubMvRefMode as M;
let mut best_mode: M = M::Zero4x4;
let mut best_group_mv = crate::motion_vector::Mv::default();
let mut best_group_diff = crate::motion_vector::Mv::default();
let mut best_group_j: f64 = f64::INFINITY;
let mut try_cand = |mode: M,
mv: crate::motion_vector::Mv,
diff: crate::motion_vector::Mv,
diff_bits: f64| {
let sad =
group_sad_at_whole_mv_shaped(luma_ref, mb_col, mb_row, src_y, group, shape, mv)
as f64;
let mode_bits = submv_ref_bits(probs, mode);
let j = sad + lambda * (mode_bits + diff_bits);
if j < best_group_j {
best_group_j = j;
best_mode = mode;
best_group_mv = mv;
best_group_diff = diff;
}
};
try_cand(
M::Left4x4,
left_neighbour_mv,
crate::motion_vector::Mv::default(),
0.0,
);
try_cand(
M::Above4x4,
above_neighbour_mv,
crate::motion_vector::Mv::default(),
0.0,
);
try_cand(
M::Zero4x4,
crate::motion_vector::Mv::default(),
crate::motion_vector::Mv::default(),
0.0,
);
let diff_row = (search_mv.row as i32) - (best_predictor.row as i32);
let diff_col = (search_mv.col as i32) - (best_predictor.col as i32);
let diff_in_range =
(-1023..=1023).contains(&diff_row) && (-1023..=1023).contains(&diff_col);
if diff_in_range {
let diff = crate::motion_vector::Mv {
row: diff_row as i16,
col: diff_col as i16,
};
let diff_bits = crate::motion_vector::mv_component_bits(&mv_contexts[0], diff_row)
+ crate::motion_vector::mv_component_bits(&mv_contexts[1], diff_col);
let mode_bits = submv_ref_bits(probs, M::New4x4);
let j = search_sad as f64 + lambda * (mode_bits + diff_bits);
if j < best_group_j {
best_group_j = j;
best_mode = M::New4x4;
best_group_mv = search_mv;
best_group_diff = diff;
}
}
if !best_group_j.is_finite() {
return None;
}
let group_sad = group_sad_at_whole_mv_shaped(
luma_ref,
mb_col,
mb_row,
src_y,
group,
shape,
best_group_mv,
);
for &b in group {
split_mvs[b] = best_group_mv;
}
total_sad += group_sad;
total_submv_bits += submv_ref_bits(probs, best_mode);
if matches!(best_mode, M::New4x4) {
total_submv_bits += crate::motion_vector::mv_bits(mv_contexts, best_group_diff);
}
submv_modes[g_idx] = best_mode;
submv_new_diffs[g_idx] = best_group_diff;
}
let partition_bits = mv_partition_bits(partition);
let j = total_sad as f64 + lambda * (partition_bits + total_submv_bits);
Some(SplitMvCandidate {
partition,
split_mvs,
submv_modes,
submv_new_diffs,
j,
})
}
#[allow(clippy::too_many_arguments)]
fn transform_split_mv_mb_rd(
src: &[u8; 256],
pred: &[u8; 256],
chroma_src_u: &[u8; 64],
chroma_pred_u: &[u8; 64],
chroma_src_v: &[u8; 64],
chroma_pred_v: &[u8; 64],
factors: &crate::dequant::MbDequantFactors,
trellis: Option<&MbRdCtx>,
) -> MbCoeffs {
let mut y = [[0i16; 16]; 16];
for i in 0..4 {
for j in 0..4 {
let mut residual = [0i16; 16];
for r in 0..4 {
for c in 0..4 {
let off = (i * 4 + r) * 16 + (j * 4 + c);
residual[r * 4 + c] = src[off] as i16 - pred[off] as i16;
}
}
let mut coeffs = [0i16; 16];
forward_dct_4x4(&residual, &mut coeffs);
match trellis {
Some(rd) if rd.trellis_active() => trellis_quantize_block(
&mut coeffs,
TrellisBlockSpec {
dc: factors.y1_dc,
ac: factors.y1_ac,
first_coeff: BlockType::YNoY2.first_coeff(),
entry_ctx3: 0,
plane: BlockType::YNoY2.plane_index(),
},
rd.coeff_probs,
rd.rate_tables,
rd.trellis_lambda(),
),
_ => enc_quantize_block(&mut coeffs, factors.y1_dc, factors.y1_ac),
}
y[i * 4 + j] = coeffs;
}
}
let u = transform_chroma_plane_rd(chroma_src_u, chroma_pred_u, factors, trellis);
let v = transform_chroma_plane_rd(chroma_src_v, chroma_pred_v, factors, trellis);
MbCoeffs {
y,
y2: [0i16; 16], u,
v,
}
}
fn write_split_mv_partition(enc: &mut BoolEncoder, partition: crate::near_mv::MvPartition) {
let probs = &crate::near_mv::MV_PARTITION_PROBS;
use crate::near_mv::MvPartition as P;
match partition {
P::Mv16 => {
enc.write_bool(probs[0], false);
}
P::Quarters => {
enc.write_bool(probs[0], true);
enc.write_bool(probs[1], false);
}
P::TopBottom => {
enc.write_bool(probs[0], true);
enc.write_bool(probs[1], true);
enc.write_bool(probs[2], false);
}
P::LeftRight => {
enc.write_bool(probs[0], true);
enc.write_bool(probs[1], true);
enc.write_bool(probs[2], true);
}
}
}
fn write_submv_ref(enc: &mut BoolEncoder, probs: &[u8; 3], mode: crate::near_mv::SubMvRefMode) {
use crate::near_mv::SubMvRefMode as M;
match mode {
M::Left4x4 => {
enc.write_bool(probs[0], false);
}
M::Above4x4 => {
enc.write_bool(probs[0], true);
enc.write_bool(probs[1], false);
}
M::Zero4x4 => {
enc.write_bool(probs[0], true);
enc.write_bool(probs[1], true);
enc.write_bool(probs[2], false);
}
M::New4x4 => {
enc.write_bool(probs[0], true);
enc.write_bool(probs[1], true);
enc.write_bool(probs[2], true);
}
}
}
#[derive(Clone)]
struct PickedMbForRef {
ref_frame: crate::motion_comp::RefFrame,
chosen_mode: crate::near_mv::InterMode,
chosen_mv: crate::motion_vector::Mv,
chosen_split: Option<SplitMvCandidate>,
raw_coeffs: MbCoeffs,
mb_skip_coeff: bool,
recon: crate::reconstruct::ReconstructedMb,
use_bpred: bool,
j: f64,
}
#[allow(clippy::too_many_arguments)]
fn pick_mb_for_ref(
ref_frame: crate::motion_comp::RefFrame,
reference_planes: &crate::motion_comp::ReferencePlanes<'_>,
luma_ref: crate::motion_search::LumaRef<'_>,
pixels: &MbPixels,
above_slot: &crate::near_mv::MbInfo,
left_mb: &crate::near_mv::MbInfo,
aboveleft_mb: &crate::near_mv::MbInfo,
mb_col: usize,
mb_row: usize,
mb_cols: usize,
mb_rows: usize,
mv_contexts: &crate::motion_vector::MvContexts,
lambda: f64,
filters: &[[i32; 6]; 8],
factors: &crate::dequant::MbDequantFactors,
coeff_probs: Option<&CoeffProbs>,
rate_tables: Option<&TrellisRateTables>,
trellis_strength: TrellisStrength,
) -> PickedMbForRef {
let trellis_rd = coeff_probs.map(|cp| MbRdCtx {
factors,
coeff_probs: cp,
rate_tables,
lambda,
trellis: trellis_strength,
});
let near = crate::near_mv::find_near_mvs(
above_slot,
left_mb,
aboveleft_mb,
ref_frame,
crate::near_mv::SignBias::default(),
);
let bounds = crate::near_mv::MvClampRect::for_mb(mb_col, mb_row, mb_cols, mb_rows);
let best_predictor = crate::near_mv::clamp_mv(near.mvs[0], &bounds);
let mv_ref_probs = crate::near_mv::mv_ref_probs(&near.cnt);
let sad_zero = crate::motion_search::mb_luma_sad_at_whole_mv(
luma_ref,
mb_col,
mb_row,
&pixels.y,
crate::motion_vector::Mv::default(),
);
const MAX_DIAMOND_ITERS: u32 = 8;
let whole_pel = crate::motion_search::small_diamond_search_luma(
luma_ref,
mb_col,
mb_row,
&pixels.y,
best_predictor,
MAX_DIAMOND_ITERS,
);
let half_pel = crate::motion_search::half_pixel_refine_luma(
luma_ref,
mb_col,
mb_row,
&pixels.y,
whole_pel.mv,
);
let search = crate::motion_search::quarter_pixel_refine_luma(
luma_ref,
mb_col,
mb_row,
&pixels.y,
half_pel.mv,
);
let bits_mode_zero = bool_bits(mv_ref_probs[0], false);
let bits_mode_nearest = bool_bits(mv_ref_probs[0], true) + bool_bits(mv_ref_probs[1], false);
let bits_mode_near = bool_bits(mv_ref_probs[0], true)
+ bool_bits(mv_ref_probs[1], true)
+ bool_bits(mv_ref_probs[2], false);
let bits_mode_new = bool_bits(mv_ref_probs[0], true)
+ bool_bits(mv_ref_probs[1], true)
+ bool_bits(mv_ref_probs[2], true)
+ bool_bits(mv_ref_probs[3], false);
let diff_row = (search.mv.row as i32) - (best_predictor.row as i32);
let diff_col = (search.mv.col as i32) - (best_predictor.col as i32);
let diff_in_range = (-1023..=1023).contains(&diff_row) && (-1023..=1023).contains(&diff_col);
let bits_mv_diff = if diff_in_range {
crate::motion_vector::mv_component_bits(&mv_contexts[0], diff_row)
+ crate::motion_vector::mv_component_bits(&mv_contexts[1], diff_col)
} else {
f64::INFINITY
};
let nearest_mv = crate::near_mv::clamp_mv(near.mvs[1], &bounds);
let near_mv = crate::near_mv::clamp_mv(near.mvs[2], &bounds);
let sad_nearest =
crate::motion_search::mb_luma_sad_at_mv(luma_ref, mb_col, mb_row, &pixels.y, nearest_mv);
let sad_near =
crate::motion_search::mb_luma_sad_at_mv(luma_ref, mb_col, mb_row, &pixels.y, near_mv);
let j_zero = sad_zero as f64 + lambda * bits_mode_zero;
let j_nearest = sad_nearest as f64 + lambda * bits_mode_nearest;
let j_near = sad_near as f64 + lambda * bits_mode_near;
let j_new = search.sad as f64 + lambda * (bits_mode_new + bits_mv_diff);
let nearest_eligible = nearest_mv != crate::motion_vector::Mv::default();
let near_eligible = near_mv != crate::motion_vector::Mv::default();
let new_eligible = diff_in_range && search.mv != crate::motion_vector::Mv::default();
let mut chosen_mode = crate::near_mv::InterMode::Zero;
let mut chosen_mv = crate::motion_vector::Mv::default();
let mut chosen_j = j_zero;
if nearest_eligible && j_nearest < chosen_j {
chosen_mode = crate::near_mv::InterMode::Nearest;
chosen_mv = nearest_mv;
chosen_j = j_nearest;
}
if near_eligible && j_near < chosen_j {
chosen_mode = crate::near_mv::InterMode::Near;
chosen_mv = near_mv;
chosen_j = j_near;
}
if new_eligible && j_new < chosen_j {
chosen_mode = crate::near_mv::InterMode::New;
chosen_mv = search.mv;
chosen_j = j_new;
}
let bits_mode_split = bool_bits(mv_ref_probs[0], true)
+ bool_bits(mv_ref_probs[1], true)
+ bool_bits(mv_ref_probs[2], true)
+ bool_bits(mv_ref_probs[3], true);
let mut best_split: Option<SplitMvCandidate> = None;
for &partition in &[
crate::near_mv::MvPartition::TopBottom,
crate::near_mv::MvPartition::LeftRight,
crate::near_mv::MvPartition::Quarters,
crate::near_mv::MvPartition::Mv16,
] {
if let Some(cand) = score_split_partition(
partition,
luma_ref,
mb_col,
mb_row,
&pixels.y,
best_predictor,
above_slot,
left_mb,
mv_contexts,
lambda,
) {
let total_j = cand.j + lambda * bits_mode_split;
if best_split
.as_ref()
.map(|b| total_j < b.j + lambda * bits_mode_split)
.unwrap_or(true)
{
best_split = Some(SplitMvCandidate {
partition: cand.partition,
split_mvs: cand.split_mvs,
submv_modes: cand.submv_modes,
submv_new_diffs: cand.submv_new_diffs,
j: total_j,
});
}
}
}
let mut chosen_split: Option<SplitMvCandidate> = None;
if let Some(cand) = best_split
&& cand.j < chosen_j
{
chosen_mode = crate::near_mv::InterMode::Split;
chosen_mv = cand.split_mvs[15];
chosen_j = cand.j;
chosen_split = Some(cand);
}
let (raw_coeffs, use_bpred) = if let Some(ref cand) = chosen_split {
let pred = crate::motion_comp::predict_split_mv(
reference_planes,
mb_col,
mb_row,
&cand.split_mvs,
false,
filters,
);
let raw_coeffs = transform_split_mv_mb_rd(
&pixels.y,
&pred.y,
&pixels.u,
&pred.u,
&pixels.v,
&pred.v,
factors,
trellis_rd.as_ref(),
);
(raw_coeffs, true)
} else {
let pred = crate::motion_comp::predict_inter_mb(
reference_planes,
mb_col,
mb_row,
chosen_mv,
false,
filters,
);
let (y_quant, y2_quant) =
transform_whole_block_luma_rd(&pixels.y, &pred.y, factors, trellis_rd.as_ref());
let u_quant = transform_chroma_plane_rd(&pixels.u, &pred.u, factors, trellis_rd.as_ref());
let v_quant = transform_chroma_plane_rd(&pixels.v, &pred.v, factors, trellis_rd.as_ref());
let raw_coeffs = MbCoeffs {
y: y_quant,
y2: y2_quant,
u: u_quant,
v: v_quant,
};
(raw_coeffs, false)
};
let mut nonzero_block_count = 0usize;
if !use_bpred && raw_coeffs.y2.iter().any(|&v| v != 0) {
nonzero_block_count += 1;
}
for blk in raw_coeffs.y.iter() {
let first = if use_bpred { 0 } else { 1 };
if blk.iter().skip(first).any(|&v| v != 0) {
nonzero_block_count += 1;
}
}
for blk in raw_coeffs.u.iter() {
if blk.iter().any(|&v| v != 0) {
nonzero_block_count += 1;
}
}
for blk in raw_coeffs.v.iter() {
if blk.iter().any(|&v| v != 0) {
nonzero_block_count += 1;
}
}
let mb_skip_coeff = nonzero_block_count == 0;
let mut dq = raw_coeffs;
factors.dequantize(&mut dq);
let recon = if let Some(ref cand) = chosen_split {
crate::motion_comp::reconstruct_split_mv_mb(
reference_planes,
mb_col,
mb_row,
&cand.split_mvs,
false,
filters,
mb_skip_coeff,
&dq.y,
&dq.u,
&dq.v,
)
} else {
crate::motion_comp::reconstruct_inter_mb(
reference_planes,
mb_col,
mb_row,
chosen_mv,
false,
filters,
mb_skip_coeff,
&dq.y2,
&dq.y,
&dq.u,
&dq.v,
)
};
PickedMbForRef {
ref_frame,
chosen_mode,
chosen_mv,
chosen_split,
raw_coeffs,
mb_skip_coeff,
recon,
use_bpred,
j: chosen_j,
}
}
#[derive(Clone)]
struct IntraMbPick {
y_mode: IntraYMode,
uv_mode: IntraUvMode,
raw_coeffs: MbCoeffs,
mb_skip_coeff: bool,
recon: crate::reconstruct::ReconstructedMb,
j: f64,
}
fn if_ymode_tree_bits(mode: IntraYMode) -> f64 {
treed_bits_cached(&*IF_YMODE_PATHS, |i| IF_YMODE_PROB_DEFAULTS[i], mode.leaf())
}
fn if_uv_mode_tree_bits(mode: IntraUvMode) -> f64 {
treed_bits_cached(
&*UV_MODE_PATHS,
|i| IF_UV_MODE_PROB_DEFAULTS[i],
mode.leaf(),
)
}
#[allow(clippy::too_many_arguments)]
fn score_intra_mb_candidate(
y_mode: IntraYMode,
uv_mode: IntraUvMode,
pixels: &MbPixels,
neighbors: &crate::reconstruct::MbNeighbors,
factors: &crate::dequant::MbDequantFactors,
lambda: f64,
coeff_probs: Option<&CoeffProbs>,
rate_tables: Option<&TrellisRateTables>,
trellis_strength: TrellisStrength,
) -> IntraMbPick {
debug_assert!(
y_mode != IntraYMode::B,
"score_intra_mb_candidate is whole-block only; B_PRED is routed via the per-sub-block walker",
);
let trellis_rd = coeff_probs.map(|cp| MbRdCtx {
factors,
coeff_probs: cp,
rate_tables,
lambda,
trellis: trellis_strength,
});
let topleft_y = neighbors
.y_topleft
.unwrap_or(crate::intra_predict::DEFAULT_ABOVE_PIXEL);
let mut y_pred = [0u8; 256];
crate::intra_predict::predict_y16x16(
&mut y_pred,
y_mode,
neighbors.y_above.as_ref(),
neighbors.y_left.as_ref(),
topleft_y,
)
.expect("y_mode != B asserted above");
let topleft_u = neighbors
.u_topleft
.unwrap_or(crate::intra_predict::DEFAULT_ABOVE_PIXEL);
let mut u_pred = [0u8; 64];
crate::intra_predict::predict_uv8x8(
&mut u_pred,
uv_mode,
neighbors.u_above.as_ref(),
neighbors.u_left.as_ref(),
topleft_u,
);
let topleft_v = neighbors
.v_topleft
.unwrap_or(crate::intra_predict::DEFAULT_ABOVE_PIXEL);
let mut v_pred = [0u8; 64];
crate::intra_predict::predict_uv8x8(
&mut v_pred,
uv_mode,
neighbors.v_above.as_ref(),
neighbors.v_left.as_ref(),
topleft_v,
);
let mut sad: u32 = 0;
for (a, b) in pixels.y.iter().zip(y_pred.iter()) {
sad += (*a as i32 - *b as i32).unsigned_abs();
}
let (y_quant, y2_quant) =
transform_whole_block_luma_rd(&pixels.y, &y_pred, factors, trellis_rd.as_ref());
let u_quant = transform_chroma_plane_rd(&pixels.u, &u_pred, factors, trellis_rd.as_ref());
let v_quant = transform_chroma_plane_rd(&pixels.v, &v_pred, factors, trellis_rd.as_ref());
let raw_coeffs = MbCoeffs {
y: y_quant,
y2: y2_quant,
u: u_quant,
v: v_quant,
};
let mut nonzero_block_count = 0usize;
if raw_coeffs.y2.iter().any(|&v| v != 0) {
nonzero_block_count += 1;
}
for blk in raw_coeffs.y.iter() {
if blk.iter().skip(1).any(|&v| v != 0) {
nonzero_block_count += 1;
}
}
for blk in raw_coeffs.u.iter() {
if blk.iter().any(|&v| v != 0) {
nonzero_block_count += 1;
}
}
for blk in raw_coeffs.v.iter() {
if blk.iter().any(|&v| v != 0) {
nonzero_block_count += 1;
}
}
let mb_skip_coeff = nonzero_block_count == 0;
let mut dq = raw_coeffs;
factors.dequantize(&mut dq);
let recon = crate::reconstruct::decode_keyframe_mb_non_bpred(
y_mode,
uv_mode,
mb_skip_coeff,
neighbors,
&dq.y2,
&dq.y,
&dq.u,
&dq.v,
)
.expect("decode_keyframe_mb_non_bpred rejects only B_PRED, ruled out above");
let mode_bits = if_ymode_tree_bits(y_mode) + if_uv_mode_tree_bits(uv_mode);
let j = sad as f64 + lambda * mode_bits;
IntraMbPick {
y_mode,
uv_mode,
raw_coeffs,
mb_skip_coeff,
recon,
j,
}
}
#[allow(clippy::too_many_arguments)]
fn pick_intra_mb_all(
pixels: &MbPixels,
neighbors: &crate::reconstruct::MbNeighbors,
factors: &crate::dequant::MbDequantFactors,
lambda: f64,
coeff_probs: Option<&CoeffProbs>,
rate_tables: Option<&TrellisRateTables>,
trellis_strength: TrellisStrength,
) -> IntraMbPick {
const Y_MODES: [IntraYMode; 4] = [IntraYMode::Dc, IntraYMode::V, IntraYMode::H, IntraYMode::Tm];
const UV_MODES: [IntraUvMode; 4] = [
IntraUvMode::Dc,
IntraUvMode::V,
IntraUvMode::H,
IntraUvMode::Tm,
];
let mut best: Option<IntraMbPick> = None;
for &y_mode in Y_MODES.iter() {
for &uv_mode in UV_MODES.iter() {
let cand = score_intra_mb_candidate(
y_mode,
uv_mode,
pixels,
neighbors,
factors,
lambda,
coeff_probs,
rate_tables,
trellis_strength,
);
match best.as_ref() {
None => best = Some(cand),
Some(b) if cand.j < b.j => best = Some(cand),
_ => {}
}
}
}
best.expect("Y_MODES × UV_MODES is non-empty")
}
fn ref_frame_tree_bits(ref_frame: crate::motion_comp::RefFrame, prob_last: u8, prob_gf: u8) -> f64 {
match ref_frame {
crate::motion_comp::RefFrame::Last => bool_bits(prob_last, false),
crate::motion_comp::RefFrame::Golden => {
bool_bits(prob_last, true) + bool_bits(prob_gf, false)
}
crate::motion_comp::RefFrame::AltRef => {
bool_bits(prob_last, true) + bool_bits(prob_gf, true)
}
}
}
fn fit_prob_l8(count_false: u32, count_true: u32) -> u8 {
let total = count_false + count_true;
if total == 0 {
return 128; }
let raw = ((count_false as u64 * 256) / total as u64) as u32;
raw.clamp(1, 255) as u8
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RefreshControls {
pub refresh_golden_frame: bool,
pub refresh_alternate_frame: bool,
pub copy_buffer_to_golden: u8,
pub copy_buffer_to_alternate: u8,
pub refresh_last: bool,
}
impl Default for RefreshControls {
fn default() -> Self {
Self {
refresh_golden_frame: false,
refresh_alternate_frame: false,
copy_buffer_to_golden: 0,
copy_buffer_to_alternate: 0,
refresh_last: true,
}
}
}
impl RefreshControls {
pub fn validate(&self) -> Result<(), EncodeError> {
if self.copy_buffer_to_golden > 2 {
return Err(EncodeError::InvalidCopyBufferSelector {
which: CopyBufferSelector::Golden,
value: self.copy_buffer_to_golden,
});
}
if self.copy_buffer_to_alternate > 2 {
return Err(EncodeError::InvalidCopyBufferSelector {
which: CopyBufferSelector::Alternate,
value: self.copy_buffer_to_alternate,
});
}
if self.refresh_golden_frame && self.copy_buffer_to_golden != 0 {
return Err(EncodeError::InvalidCopyBufferSelector {
which: CopyBufferSelector::Golden,
value: self.copy_buffer_to_golden,
});
}
if self.refresh_alternate_frame && self.copy_buffer_to_alternate != 0 {
return Err(EncodeError::InvalidCopyBufferSelector {
which: CopyBufferSelector::Alternate,
value: self.copy_buffer_to_alternate,
});
}
Ok(())
}
}
pub fn encode_p_frame_zero_mv(
frame: &I420Frame,
reference: &crate::frame::KeyframePlanes,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref(frame, reference, None, None, params)
}
pub fn encode_p_frame_multi_ref(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_with_refresh(
frame,
last,
golden,
altref,
params,
&RefreshControls::default(),
)
}
pub(crate) fn set_show_frame_bit(frame: &mut [u8], show_frame: bool) {
debug_assert!(
frame.len() >= 3,
"a VP8 frame is at least the 3-byte §9.1 tag"
);
if let Some(b0) = frame.first_mut() {
if show_frame {
*b0 |= 0x10;
} else {
*b0 &= !0x10;
}
}
}
pub fn encode_invisible_altref_update(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
let refresh = RefreshControls {
refresh_alternate_frame: true,
refresh_last: false,
..RefreshControls::default()
};
let (mut bytes, planes) = encode_p_frame_multi_ref_with_refresh_and_intra_pick(
frame, last, golden, altref, params, &refresh,
)?;
set_show_frame_bit(&mut bytes, false);
Ok((bytes, planes))
}
pub fn encode_p_frame_multi_ref_auto_loop_filter(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
&RefreshControls::default(),
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
None,
None,
true,
true,
)
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
token_updates: Option<&TokenProbUpdates>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
token_updates,
)
}
pub fn encode_p_frame_multi_ref_with_token_updates(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
token_updates: Option<&TokenProbUpdates>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner(
frame,
last,
golden,
altref,
params,
&RefreshControls::default(),
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
token_updates,
)
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
let mut counts = empty_branch_counts();
let (bytes_default, planes_default) = encode_p_frame_multi_ref_inner_with_counts(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
None,
Some(&mut counts),
)?;
let fitted = fit_token_prob_updates(&counts, 2.0);
let any_update = any_token_prob_update(&fitted);
if !any_update {
return Ok((bytes_default, planes_default));
}
let (bytes_fitted, planes_fitted) =
encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_token_updates(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
Some(&fitted),
)?;
if bytes_fitted.len() <= bytes_default.len() {
Ok((bytes_fitted, planes_fitted))
} else {
Ok((bytes_default, planes_default))
}
}
pub fn encode_p_frame_multi_ref_with_fitted_token_prob_updates(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_fitted_token_prob_updates(
frame,
last,
golden,
altref,
params,
&RefreshControls::default(),
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
)
}
pub fn encode_p_frame_multi_ref_with_refresh(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner(
frame,
last,
golden,
altref,
params,
refresh,
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
None,
)
}
pub fn encode_p_frame_multi_ref_with_refresh_and_intra_pick(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
refresh.validate()?;
encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
refresh,
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
None,
None,
true,
false,
)
}
pub fn encode_p_frame_multi_ref_with_intra_pick(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_with_refresh_and_intra_pick(
frame,
last,
golden,
altref,
params,
&RefreshControls::default(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
refresh.validate()?;
lf_deltas.validate()?;
encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
None,
None,
true,
false,
)
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_multi_ref_with_refresh_and_lf_deltas_and_intra_pick_and_fitted_token_prob_updates(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
refresh.validate()?;
lf_deltas.validate()?;
let mut counts = empty_branch_counts();
let (bytes_default, planes_default) = encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
None,
Some(&mut counts),
true,
false,
)?;
let fitted = fit_token_prob_updates(&counts, 2.0);
let any_update = any_token_prob_update(&fitted);
if !any_update {
return Ok((bytes_default, planes_default));
}
let (bytes_fitted, planes_fitted) = encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
Some(&fitted),
None,
true,
false,
)?;
if bytes_fitted.len() <= bytes_default.len() {
Ok((bytes_fitted, planes_fitted))
} else {
Ok((bytes_default, planes_default))
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct InterCodingOptions {
pub intra_pick: bool,
pub auto_loop_filter: bool,
pub fitted_token_prob_updates: bool,
pub effort: Option<EncodeEffort>,
pub threads: usize,
pub search_token_probs: Option<TokenProbUpdates>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct InterEncoded {
pub bytes: Vec<u8>,
pub reconstruction: crate::frame::KeyframePlanes,
pub token_prob_updates: Option<TokenProbUpdates>,
}
impl InterCodingOptions {
#[must_use]
pub fn with_effort(mut self, v: EncodeEffort) -> Self {
self.effort = Some(v);
self
}
#[must_use]
pub fn with_threads(mut self, v: usize) -> Self {
self.threads = v;
self
}
fn speed(&self) -> inter::InterSpeed {
inter::InterSpeed {
effort: self.effort,
threads: self.threads,
fit_token_probs: self.fitted_token_prob_updates,
search_token_probs: self.search_token_probs,
}
}
#[must_use]
pub fn with_search_token_probs(mut self, v: Option<TokenProbUpdates>) -> Self {
self.search_token_probs = v;
self
}
#[must_use]
pub fn with_intra_pick(mut self, v: bool) -> Self {
self.intra_pick = v;
self
}
#[must_use]
pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
self.auto_loop_filter = v;
self
}
#[must_use]
pub fn with_fitted_token_prob_updates(mut self, v: bool) -> Self {
self.fitted_token_prob_updates = v;
self
}
}
pub fn encode_p_frame_multi_ref_with_refresh_and_coding_options(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
options: &InterCodingOptions,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_options_and_segmentation(
frame, last, golden, altref, params, refresh, options, None,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct InterSegmentationConfig {
pub variance_boundaries: [u32; 3],
pub quant_delta: [i8; 4],
pub lf_delta: Option<[i8; 4]>,
}
impl InterSegmentationConfig {
#[must_use]
pub fn with_variance_boundaries(mut self, v: [u32; 3]) -> Self {
self.variance_boundaries = v;
self
}
#[must_use]
pub fn with_quant_delta(mut self, v: [i8; 4]) -> Self {
self.quant_delta = v;
self
}
#[must_use]
pub fn with_lf_delta(mut self, v: Option<[i8; 4]>) -> Self {
self.lf_delta = v;
self
}
}
impl Default for InterSegmentationConfig {
fn default() -> Self {
InterSegmentationConfig {
variance_boundaries: [
SEGMENT_VARIANCE_THRESHOLDS[1],
SEGMENT_VARIANCE_THRESHOLDS[2],
SEGMENT_VARIANCE_THRESHOLDS[3],
],
quant_delta: [8, 0, -6, -12],
lf_delta: None,
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_multi_ref_adaptive_quant(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
segmentation: &InterSegmentationConfig,
options: &InterCodingOptions,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
if let Some(d) = segmentation.lf_delta
&& let Some(&bad) = d.iter().find(|v| v.unsigned_abs() > 63)
{
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: bad.unsigned_abs(),
});
}
encode_p_frame_options_and_segmentation(
frame,
last,
golden,
altref,
params,
refresh,
options,
Some(segmentation),
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn encode_p_frame_options_and_segmentation(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
options: &InterCodingOptions,
segmentation: Option<&InterSegmentationConfig>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_options_reporting(
frame,
last,
golden,
altref,
params,
refresh,
options,
segmentation,
&mut None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn encode_p_frame_detailed(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
options: &InterCodingOptions,
) -> Result<InterEncoded, EncodeError> {
let mut shipped = None;
let (bytes, reconstruction) = encode_p_frame_options_reporting(
frame,
last,
golden,
altref,
params,
refresh,
options,
None,
&mut shipped,
)?;
Ok(InterEncoded {
bytes,
reconstruction,
token_prob_updates: shipped,
})
}
#[allow(clippy::too_many_arguments)]
fn encode_p_frame_options_reporting(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
options: &InterCodingOptions,
segmentation: Option<&InterSegmentationConfig>,
shipped: &mut Option<TokenProbUpdates>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
refresh.validate()?;
if let Some(d) = segmentation.and_then(|s| s.lf_delta)
&& let Some(&bad) = d.iter().find(|v| v.unsigned_abs() > 63)
{
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: bad.unsigned_abs(),
});
}
if !options.fitted_token_prob_updates || options.effort.is_some() {
return encode_p_frame_multi_ref_inner_driven(
frame,
last,
golden,
altref,
params,
refresh,
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
None,
None,
options.intra_pick,
options.auto_loop_filter,
segmentation,
options.speed(),
Some(&mut *shipped),
);
}
let two_pass_speed = inter::InterSpeed {
search_token_probs: None,
..options.speed()
};
let mut counts = empty_branch_counts();
let (bytes_default, planes_default) = encode_p_frame_multi_ref_inner_driven(
frame,
last,
golden,
altref,
params,
refresh,
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
None,
Some(&mut counts),
options.intra_pick,
options.auto_loop_filter,
segmentation,
two_pass_speed,
None,
)?;
let fitted = fit_token_prob_updates(&counts, 2.0);
if !any_token_prob_update(&fitted) {
return Ok((bytes_default, planes_default));
}
let (bytes_fitted, planes_fitted) = encode_p_frame_multi_ref_inner_driven(
frame,
last,
golden,
altref,
params,
refresh,
&LoopFilterDeltas::default(),
[0; 4],
[0; 4],
Some(&fitted),
None,
options.intra_pick,
options.auto_loop_filter,
segmentation,
two_pass_speed,
None,
)?;
if bytes_fitted.len() <= bytes_default.len() {
*shipped = Some(fitted);
Ok((bytes_fitted, planes_fitted))
} else {
Ok((bytes_default, planes_default))
}
}
pub fn encode_invisible_altref_update_with_coding_options(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
options: &InterCodingOptions,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_invisible_altref_update_full(frame, last, golden, altref, params, options, None)
}
pub(crate) fn encode_invisible_altref_update_full(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
options: &InterCodingOptions,
segmentation: Option<&InterSegmentationConfig>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
let refresh = RefreshControls {
refresh_alternate_frame: true,
refresh_last: false,
..RefreshControls::default()
};
let (mut bytes, planes) = encode_p_frame_options_and_segmentation(
frame,
last,
golden,
altref,
params,
&refresh,
options,
segmentation,
)?;
set_show_frame_bit(&mut bytes, false);
Ok((bytes, planes))
}
#[allow(clippy::too_many_arguments)]
fn encode_p_frame_multi_ref_inner(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
token_updates: Option<&TokenProbUpdates>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
token_updates,
None,
false,
false,
)
}
#[allow(clippy::too_many_arguments)]
fn encode_p_frame_multi_ref_inner_with_counts(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
token_updates,
counts,
false,
false,
)
}
#[allow(clippy::too_many_arguments)]
fn encode_p_frame_multi_ref_inner_with_counts_and_pick(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
pick_intra: bool,
auto_lf: bool,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner_full(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
token_updates,
counts,
pick_intra,
auto_lf,
None,
inter::InterSpeed::default(),
)
}
#[allow(clippy::too_many_arguments)]
fn encode_p_frame_multi_ref_inner_full(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
pick_intra: bool,
auto_lf: bool,
segmentation: Option<&InterSegmentationConfig>,
speed: inter::InterSpeed,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
encode_p_frame_multi_ref_inner_driven(
frame,
last,
golden,
altref,
params,
refresh,
lf_deltas,
carried_ref_deltas,
carried_mode_deltas,
token_updates,
counts,
pick_intra,
auto_lf,
segmentation,
speed,
None,
)
}
#[allow(clippy::too_many_arguments)]
fn encode_p_frame_multi_ref_inner_driven(
frame: &I420Frame,
last: &crate::frame::KeyframePlanes,
golden: Option<&crate::frame::KeyframePlanes>,
altref: Option<&crate::frame::KeyframePlanes>,
params: &KeyframeParams,
refresh: &RefreshControls,
lf_deltas: &LoopFilterDeltas,
carried_ref_deltas: [i16; 4],
carried_mode_deltas: [i16; 4],
token_updates: Option<&TokenProbUpdates>,
counts: Option<&mut BranchCounts>,
pick_intra: bool,
auto_lf: bool,
segmentation: Option<&InterSegmentationConfig>,
speed: inter::InterSpeed,
shipped_out: Option<&mut Option<TokenProbUpdates>>,
) -> Result<(Vec<u8>, crate::frame::KeyframePlanes), EncodeError> {
refresh.validate()?;
lf_deltas.validate()?;
let width = frame.width;
let height = frame.height;
if width == 0 || width > 0x3FFF || height == 0 || height > 0x3FFF {
return Err(EncodeError::InvalidDimensions { width, height });
}
if params.y_ac_qi > 127 {
return Err(EncodeError::QuantIndexOutOfRange {
value: params.y_ac_qi,
});
}
if params.loop_filter_level > 63 {
return Err(EncodeError::LoopFilterLevelOutOfRange {
value: params.loop_filter_level,
});
}
if params.sharpness_level > 7 {
return Err(EncodeError::SharpnessLevelOutOfRange {
value: params.sharpness_level,
});
}
let num_partitions = match params.nbr_of_dct_partitions {
1 | 2 | 4 | 8 => params.nbr_of_dct_partitions as usize,
other => return Err(EncodeError::InvalidDctPartitionCount { value: other }),
};
let inter_trellis_strength = params.trellis_strength;
let mb_cols = width.div_ceil(16) as usize;
let mb_rows = height.div_ceil(16) as usize;
if last.mb_cols != mb_cols || last.mb_rows != mb_rows {
return Err(EncodeError::ReferenceDimensionsMismatch {
source: ((mb_cols * 16) as u32, (mb_rows * 16) as u32),
reference: ((last.mb_cols * 16) as u32, (last.mb_rows * 16) as u32),
});
}
if let Some(g) = golden
&& (g.mb_cols != mb_cols || g.mb_rows != mb_rows)
{
return Err(EncodeError::ReferenceDimensionsMismatch {
source: ((mb_cols * 16) as u32, (mb_rows * 16) as u32),
reference: ((g.mb_cols * 16) as u32, (g.mb_rows * 16) as u32),
});
}
if let Some(a) = altref
&& (a.mb_cols != mb_cols || a.mb_rows != mb_rows)
{
return Err(EncodeError::ReferenceDimensionsMismatch {
source: ((mb_cols * 16) as u32, (mb_rows * 16) as u32),
reference: ((a.mb_cols * 16) as u32, (a.mb_rows * 16) as u32),
});
}
let search_updates = token_updates.or(speed.search_token_probs.as_ref());
let coeff_probs = match search_updates {
Some(u) => crate::dct_tokens::merge_default_token_probs(u),
None => crate::dct_tokens::DEFAULT_COEFF_PROBS,
};
let reduced_search = speed.effort.is_some();
let trellis_rate_tables = (reduced_search || inter_trellis_strength.get() > 0.0)
.then(|| TrellisRateTables::for_probs(&coeff_probs));
let factors = crate::dequant::MbDequantFactors::from_base_and_deltas(
params.y_ac_qi as i32,
0,
0,
0,
0,
0,
);
let seg_ctx = segmentation.map(|s| {
let mut seg_factors = [factors; crate::loop_filter::MAX_MB_SEGMENTS];
let mut seg_lambdas = [0.0f64; crate::loop_filter::MAX_MB_SEGMENTS];
for i in 0..crate::loop_filter::MAX_MB_SEGMENTS {
seg_factors[i] = crate::dequant::MbDequantFactors::from_base_and_deltas(
params.y_ac_qi as i32 + s.quant_delta[i] as i32,
0,
0,
0,
0,
0,
);
seg_lambdas[i] = rd_lambda(&seg_factors[i]);
}
(s, seg_factors, seg_lambdas)
});
let reference_planes_last = crate::motion_comp::ReferencePlanes {
y: &last.y,
u: &last.u,
v: &last.v,
y_stride: last.y_stride,
uv_stride: last.uv_stride,
mb_cols: last.mb_cols,
mb_rows: last.mb_rows,
};
let reference_planes_golden = golden.map(|g| crate::motion_comp::ReferencePlanes {
y: &g.y,
u: &g.u,
v: &g.v,
y_stride: g.y_stride,
uv_stride: g.uv_stride,
mb_cols: g.mb_cols,
mb_rows: g.mb_rows,
});
let reference_planes_altref = altref.map(|a| crate::motion_comp::ReferencePlanes {
y: &a.y,
u: &a.u,
v: &a.v,
y_stride: a.y_stride,
uv_stride: a.uv_stride,
mb_cols: a.mb_cols,
mb_rows: a.mb_rows,
});
let filters = crate::motion_comp::filter_set_for_version(0).taps();
let mut planes = crate::frame::KeyframePlanes {
y: vec![0u8; mb_cols * 16 * mb_rows * 16],
u: vec![0u8; mb_cols * 8 * mb_rows * 8],
v: vec![0u8; mb_cols * 8 * mb_rows * 8],
y_stride: mb_cols * 16,
uv_stride: mb_cols * 8,
mb_cols,
mb_rows,
};
let mv_contexts = crate::motion_vector::default_mv_contexts();
let lambda = rd_lambda(&factors);
let mut available_refs: Vec<inter::RefPicture> = Vec::with_capacity(3);
available_refs.push(inter::RefPicture {
frame: crate::motion_comp::RefFrame::Last,
planes: reference_planes_last,
});
if let Some(rp) = reference_planes_golden {
available_refs.push(inter::RefPicture {
frame: crate::motion_comp::RefFrame::Golden,
planes: rp,
});
}
if let Some(rp) = reference_planes_altref {
available_refs.push(inter::RefPicture {
frame: crate::motion_comp::RefFrame::AltRef,
planes: rp,
});
}
let analysis = inter::analyse_inter_frame(
&inter::InterSearch {
frame,
refs: &available_refs,
factors: &factors,
lambda,
segments: seg_ctx.as_ref().map(|(s, f, l)| inter::SegmentContext {
config: s,
factors: *f,
lambdas: *l,
}),
coeff_probs: &coeff_probs,
rate_tables: trellis_rate_tables.as_ref(),
trellis_strength: inter_trellis_strength,
mv_contexts: &mv_contexts,
filters,
pick_intra,
effort: speed.effort,
mv_costs: reduced_search.then(|| inter_search::MvCostTable::new(&mv_contexts)),
mb_cols,
mb_rows,
},
&mut planes,
speed.threads,
)?;
let fit_in_place = reduced_search && speed.fit_token_probs && token_updates.is_none();
let fitted_in_place: Option<TokenProbUpdates> = if fit_in_place {
let mut observed = empty_branch_counts();
for tape in &analysis.tapes {
tape.tally(&mut observed);
}
let fitted = fit_token_prob_updates(&observed, 2.0);
any_token_prob_update(&fitted).then_some(fitted)
} else {
None
};
let token_updates = if fit_in_place {
fitted_in_place.as_ref()
} else {
search_updates
};
let emit_probs = match token_updates {
Some(u) if fit_in_place => crate::dct_tokens::merge_default_token_probs(u),
None if fit_in_place => crate::dct_tokens::DEFAULT_COEFF_PROBS,
_ => coeff_probs,
};
if let Some(out) = shipped_out {
*out = token_updates.filter(|u| any_token_prob_update(u)).copied();
}
let seg_counts = analysis.segment_counts;
let records = &analysis.records;
let modes: Vec<MacroblockModes> = records
.iter()
.map(|r| MacroblockModes {
segment_id: r.segment_id,
mb_skip_coeff: r.skip,
y_mode: if r.is_intra {
r.y_mode
} else if r.split.is_some() {
IntraYMode::B
} else {
IntraYMode::Dc
},
subblock_modes: None,
uv_mode: if r.is_intra {
r.uv_mode
} else {
IntraUvMode::Dc
},
})
.collect();
let has_coeffs: Vec<bool> = records.iter().map(|r| r.has_coeffs).collect();
let ref_frames_out: Vec<Option<crate::motion_comp::RefFrame>> = records
.iter()
.map(|r| (!r.is_intra).then_some(r.ref_frame))
.collect();
let inter_modes_out: Vec<Option<crate::near_mv::InterMode>> = records
.iter()
.map(|r| (!r.is_intra).then_some(r.mode))
.collect();
let mut count_last: u32 = 0;
let mut count_golden: u32 = 0;
let mut count_altref: u32 = 0;
for r in ref_frames_out.iter().flatten() {
match r {
crate::motion_comp::RefFrame::Last => count_last += 1,
crate::motion_comp::RefFrame::Golden => count_golden += 1,
crate::motion_comp::RefFrame::AltRef => count_altref += 1,
}
}
let prob_last_fit = fit_prob_l8(count_last, count_golden + count_altref);
let prob_gf_fit = fit_prob_l8(count_golden, count_altref);
let seg_tree_probs: Option<[u8; 3]> = seg_ctx.as_ref().map(|_| {
[
fit_prob_l8(seg_counts[0] + seg_counts[1], seg_counts[2] + seg_counts[3]),
fit_prob_l8(seg_counts[0], seg_counts[1]),
fit_prob_l8(seg_counts[2], seg_counts[3]),
]
});
let (effective_ref_deltas, effective_mode_deltas) =
lf_deltas.effective(carried_ref_deltas, carried_mode_deltas);
let mut seg_lf_level = [0i16; crate::loop_filter::MAX_MB_SEGMENTS];
if let Some((s, _, _)) = &seg_ctx
&& let Some(d) = s.lf_delta
{
for (dst, &src) in seg_lf_level.iter_mut().zip(d.iter()) {
*dst = i16::from(src);
}
}
let mut lf_config = crate::loop_filter::FrameFilterConfig {
simple: params.filter_type,
key_frame: false,
loop_filter_level: params.loop_filter_level,
sharpness_level: params.sharpness_level,
segmentation_enabled: seg_ctx.is_some(),
segment_abs: false,
segment_lf_level: seg_lf_level,
delta_enabled: lf_deltas.enabled,
ref_delta_current: effective_ref_deltas[0],
bpred_mode_delta: effective_mode_deltas[0],
ref_delta_last: effective_ref_deltas[1],
ref_delta_golden: effective_ref_deltas[2],
ref_delta_altref: effective_ref_deltas[3],
zero_mv_mode_delta: effective_mode_deltas[1],
other_mv_mode_delta: effective_mode_deltas[2],
split_mv_mode_delta: effective_mode_deltas[3],
};
let (eff_lf_level, eff_sharpness) = if auto_lf {
let src = crate::loop_filter::SourcePlanes {
width: width as usize,
height: height as usize,
y: frame.y,
u: frame.u,
v: frame.v,
y_stride: frame.y_stride,
uv_stride: frame.uv_stride,
};
let inter_info = crate::loop_filter::InterFilterInfo {
ref_frames: &ref_frames_out,
inter_modes: &inter_modes_out,
};
match speed.effort {
None | Some(EncodeEffort::Thorough) => {
crate::loop_filter::select_filter_params_threaded(
&planes,
&modes,
&has_coeffs,
&lf_config,
&src,
Some(&inter_info),
speed.threads,
)
}
Some(effort) => (
crate::loop_filter::select_filter_level_sampled(
&planes,
&modes,
&has_coeffs,
&lf_config,
&src,
&inter_info,
if effort == EncodeEffort::Balanced {
8
} else {
16
},
speed.threads,
),
params.sharpness_level.min(7),
),
}
} else {
(params.loop_filter_level, params.sharpness_level)
};
lf_config.loop_filter_level = eff_lf_level;
lf_config.sharpness_level = eff_sharpness;
if eff_lf_level != 0 {
crate::loop_filter::filter_inter_frame_flags_threaded(
&mut planes,
&modes,
&has_coeffs,
&ref_frames_out,
&inter_modes_out,
&lf_config,
speed.threads,
);
}
let mut hdr = BoolEncoder::new();
match (&seg_ctx, &seg_tree_probs) {
(Some((s, _, _)), Some(probs)) => {
let layer = UpdateSegmentationLayer {
update_mb_segmentation_map: true,
feature_mode_absolute: false,
quantizer: [
Some(i16::from(s.quant_delta[0])),
Some(i16::from(s.quant_delta[1])),
Some(i16::from(s.quant_delta[2])),
Some(i16::from(s.quant_delta[3])),
],
loop_filter: match s.lf_delta {
Some(d) => [
Some(i16::from(d[0])),
Some(i16::from(d[1])),
Some(i16::from(d[2])),
Some(i16::from(d[3])),
],
None => [None; 4],
},
segment_prob: [Some(probs[0]), Some(probs[1]), Some(probs[2])],
};
write_update_segmentation(&mut hdr, &layer);
}
_ => write_segment_update_flags(&mut hdr, false),
}
write_loop_filter_with_deltas(
&mut hdr,
params.filter_type,
eff_lf_level,
eff_sharpness,
lf_deltas,
)?;
write_token_partition_count(&mut hdr, params.nbr_of_dct_partitions)?;
write_quant_indices(&mut hdr, params.y_ac_qi, None, None, None, None, None)?;
hdr.write_bool(128, refresh.refresh_golden_frame); hdr.write_bool(128, refresh.refresh_alternate_frame); if !refresh.refresh_golden_frame {
hdr.write_literal(refresh.copy_buffer_to_golden as u32, 2); }
if !refresh.refresh_alternate_frame {
hdr.write_literal(refresh.copy_buffer_to_alternate as u32, 2); }
hdr.write_bool(128, false); hdr.write_bool(128, false); hdr.write_bool(128, false); hdr.write_bool(128, refresh.refresh_last);
match token_updates {
Some(u) => write_token_prob_updates(&mut hdr, u, &COEFF_UPDATE_PROBS_FLAT),
None => write_no_token_prob_updates(&mut hdr, &COEFF_UPDATE_PROBS_FLAT),
}
let prob_skip_false = if reduced_search {
let skipped = records.iter().filter(|r| r.skip).count() as u32;
fit_prob_l8(records.len() as u32 - skipped, skipped)
} else {
128u8
};
write_mb_no_skip_coeff(&mut hdr, true, prob_skip_false);
let prob_intra: u8 = if pick_intra {
let count_intra: u32 = records.iter().filter(|r| r.is_intra).count() as u32;
let count_inter: u32 = records.len() as u32 - count_intra;
fit_prob_l8(count_intra, count_inter)
} else {
255
};
let prob_last: u8 = prob_last_fit;
let prob_gf: u8 = prob_gf_fit;
hdr.write_literal(prob_intra as u32, 8);
hdr.write_literal(prob_last as u32, 8);
hdr.write_literal(prob_gf as u32, 8);
hdr.write_bool(128, false);
hdr.write_bool(128, false);
for ctx in MV_UPDATE_PROBS_FLAT.iter() {
hdr.write_bool(*ctx, false);
}
let mut above_mb: Vec<crate::near_mv::MbInfo> = vec![crate::near_mv::MbInfo::border(); mb_cols];
for mb_row in 0..mb_rows {
let mut left_mb = crate::near_mv::MbInfo::border();
let mut aboveleft_mb = crate::near_mv::MbInfo::border();
for (mb_col, above_slot) in above_mb.iter_mut().enumerate() {
let raster = mb_row * mb_cols + mb_col;
let mb = &modes[raster];
let record = &records[raster];
let is_intra = record.is_intra;
if let Some(probs) = &seg_tree_probs {
let sid = mb.segment_id.unwrap_or(0);
hdr.write_treed(&crate::macroblock::MB_SEGMENT_TREE, |i| probs[i], sid);
}
hdr.write_bool(prob_skip_false, mb.mb_skip_coeff);
hdr.write_bool(prob_intra, !is_intra);
if is_intra {
hdr.write_treed(
&IF_YMODE_TREE,
|i| IF_YMODE_PROB_DEFAULTS[i],
record.y_mode.leaf(),
);
hdr.write_treed(
&UV_MODE_TREE,
|i| IF_UV_MODE_PROB_DEFAULTS[i],
record.uv_mode.leaf(),
);
let cur = crate::near_mv::MbInfo {
ref_frame: None,
mv: crate::motion_vector::Mv::default(),
is_split: false,
split_mvs: None,
};
aboveleft_mb = *above_slot;
left_mb = cur;
*above_slot = cur;
continue;
}
let chosen_mode = inter_modes_out[raster].expect("inter mode recorded above");
let chosen_mv = record.mv;
let chosen_ref_frame = ref_frames_out[raster].expect("inter ref_frame recorded above");
match chosen_ref_frame {
crate::motion_comp::RefFrame::Last => {
hdr.write_bool(prob_last, false);
}
crate::motion_comp::RefFrame::Golden => {
hdr.write_bool(prob_last, true);
hdr.write_bool(prob_gf, false);
}
crate::motion_comp::RefFrame::AltRef => {
hdr.write_bool(prob_last, true);
hdr.write_bool(prob_gf, true);
}
}
let near = crate::near_mv::find_near_mvs(
above_slot,
&left_mb,
&aboveleft_mb,
chosen_ref_frame,
crate::near_mv::SignBias::default(),
);
let probs = crate::near_mv::mv_ref_probs(&near.cnt);
match chosen_mode {
crate::near_mv::InterMode::Zero => {
hdr.write_bool(probs[0], false);
}
crate::near_mv::InterMode::Nearest => {
hdr.write_bool(probs[0], true);
hdr.write_bool(probs[1], false);
}
crate::near_mv::InterMode::Near => {
hdr.write_bool(probs[0], true);
hdr.write_bool(probs[1], true);
hdr.write_bool(probs[2], false);
}
crate::near_mv::InterMode::New => {
hdr.write_bool(probs[0], true);
hdr.write_bool(probs[1], true);
hdr.write_bool(probs[2], true);
hdr.write_bool(probs[3], false);
let bounds =
crate::near_mv::MvClampRect::for_mb(mb_col, mb_row, mb_cols, mb_rows);
let best = crate::near_mv::clamp_mv(near.mvs[0], &bounds);
let diff = crate::motion_vector::Mv {
row: chosen_mv.row.wrapping_sub(best.row),
col: chosen_mv.col.wrapping_sub(best.col),
};
crate::motion_vector::write_mv(&mut hdr, &mv_contexts, diff);
}
crate::near_mv::InterMode::Split => {
hdr.write_bool(probs[0], true);
hdr.write_bool(probs[1], true);
hdr.write_bool(probs[2], true);
hdr.write_bool(probs[3], true);
let cand = record
.split
.as_ref()
.expect("a SPLITMV macroblock carries its candidate");
write_split_mv_partition(&mut hdr, cand.partition);
let groups = partition_groups(cand.partition);
let mut running_split = [crate::motion_vector::Mv::default(); 16];
for (g_idx, group) in groups.iter().enumerate() {
let anchor = group[0];
let left_nb =
crate::near_mv::left_block_mv(&running_split, &left_mb, anchor);
let above_nb =
crate::near_mv::above_block_mv(&running_split, above_slot, anchor);
let ctx = crate::near_mv::submv_ref_context(left_nb, above_nb);
let sub_probs = &crate::near_mv::SUBMV_REF_PROBS[ctx];
let mode = cand.submv_modes[g_idx];
write_submv_ref(&mut hdr, sub_probs, mode);
if matches!(mode, crate::near_mv::SubMvRefMode::New4x4) {
crate::motion_vector::write_mv(
&mut hdr,
&mv_contexts,
cand.submv_new_diffs[g_idx],
);
}
for &b in group {
running_split[b] = cand.split_mvs[b];
}
}
}
}
let cur = if matches!(chosen_mode, crate::near_mv::InterMode::Split) {
let cand = record.split.as_ref().expect("split candidate");
crate::near_mv::MbInfo {
ref_frame: Some(chosen_ref_frame),
mv: cand.split_mvs[15],
is_split: true,
split_mvs: Some(cand.split_mvs),
}
} else {
crate::near_mv::MbInfo {
ref_frame: Some(chosen_ref_frame),
mv: chosen_mv,
is_split: false,
split_mvs: None,
}
};
aboveleft_mb = *above_slot;
left_mb = cur;
*above_slot = cur;
}
}
let first_partition = hdr.finish();
let first_partition_size = first_partition.len();
if first_partition_size > 0x7_FFFF {
return Err(EncodeError::FirstPartitionTooLarge {
bytes: first_partition_size,
});
}
let mut partitions: Vec<BoolEncoder> =
(0..num_partitions).map(|_| BoolEncoder::new()).collect();
for (mb_row, tape) in analysis.tapes.iter().enumerate() {
tape.replay(&mut partitions[mb_row % num_partitions], &emit_probs);
}
if let Some(c) = counts {
for tape in &analysis.tapes {
tape.tally(c);
}
}
let dct_partitions: Vec<Vec<u8>> = partitions.into_iter().map(|p| p.finish()).collect();
let dct_total: usize = dct_partitions.iter().map(|p| p.len()).sum();
let size_table_len = (num_partitions - 1) * 3;
let mut out: Vec<u8> =
Vec::with_capacity(3 + first_partition_size + size_table_len + dct_total);
write_frame_tag(
&mut out,
false, 0, true, first_partition_size as u32,
width,
height,
ScaleCode::None,
ScaleCode::None,
)?;
out.extend_from_slice(&first_partition);
for part in dct_partitions.iter().take(num_partitions - 1) {
let sz = part.len();
out.push((sz & 0xff) as u8);
out.push(((sz >> 8) & 0xff) as u8);
out.push(((sz >> 16) & 0xff) as u8);
}
for part in &dct_partitions {
out.extend_from_slice(part);
}
Ok((out, planes))
}
const MV_UPDATE_PROBS_FLAT: [u8; 38] = [
237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, 254,
231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, 254,
];
#[derive(Debug, Default, Clone, Copy)]
pub struct SilentKeyframeEncoder;
impl SilentKeyframeEncoder {
pub fn encode_keyframe(
&self,
_pixels: &[u8],
width: u32,
height: u32,
) -> Result<Vec<u8>, EncodeError> {
encode_silent_keyframe(SilentKeyframeParams::new(width, height))
}
}
pub fn make_silent_keyframe_encoder() -> SilentKeyframeEncoder {
SilentKeyframeEncoder
}
pub fn quality_to_qindex(quality: f32) -> u8 {
if quality.is_nan() {
return 127;
}
let clamped = quality.clamp(0.0, 100.0);
let q = ((100.0_f32 - clamped) * 1.27).round();
q.clamp(0.0, 127.0) as u8
}
pub fn quality_to_trellis_strength(quality: f32) -> TrellisStrength {
if quality.is_nan() {
return TrellisStrength::DEFAULT;
}
let clamped = quality.clamp(0.0, 100.0);
const KNEE: f32 = 90.0;
const TOP_STRENGTH: f32 = 4.0;
let ramp = ((KNEE - clamped).max(0.0) / KNEE) * (TOP_STRENGTH - 1.0);
TrellisStrength::new((1.0 + ramp) as f64)
}
#[cfg(feature = "registry")]
mod factory {
use std::collections::VecDeque;
use oxideav_core::time::TimeBase;
use oxideav_core::{
CodecId, CodecParameters, Encoder, Error, Frame, MediaType, Packet, PixelFormat, Result,
VideoFrame,
};
use super::{
EncodeEffort, I420Frame, KeyframeEncodeOptions, KeyframeParams,
encode_keyframe_with_options,
};
use crate::decoder::VP8_CODEC_ID;
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Vp8EncoderOptions {
pub effort: EncodeEffort,
pub threads: usize,
pub qindex: u8,
pub quality: Option<f32>,
pub loop_filter_level: u8,
pub auto_loop_filter: bool,
pub partitions: u8,
}
impl Default for Vp8EncoderOptions {
fn default() -> Self {
let keyframe = KeyframeParams::default();
Vp8EncoderOptions {
effort: EncodeEffort::Thorough,
threads: 0,
qindex: keyframe.y_ac_qi,
quality: None,
loop_filter_level: keyframe.loop_filter_level,
auto_loop_filter: false,
partitions: keyframe.nbr_of_dct_partitions,
}
}
}
impl Vp8EncoderOptions {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_effort(mut self, v: EncodeEffort) -> Self {
self.effort = v;
self
}
#[must_use]
pub fn with_threads(mut self, v: usize) -> Self {
self.threads = v;
self
}
#[must_use]
pub fn with_qindex(mut self, v: u8) -> Self {
self.qindex = v;
self
}
#[must_use]
pub fn with_quality(mut self, v: Option<f32>) -> Self {
self.quality = v;
self
}
#[must_use]
pub fn with_loop_filter_level(mut self, v: u8) -> Self {
self.loop_filter_level = v;
self
}
#[must_use]
pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
self.auto_loop_filter = v;
self
}
#[must_use]
pub fn with_partitions(mut self, v: u8) -> Self {
self.partitions = v;
self
}
}
impl oxideav_core::CodecOptionsStruct for Vp8EncoderOptions {
const SCHEMA: &'static [oxideav_core::OptionField] = &[
oxideav_core::OptionField {
name: "effort",
kind: oxideav_core::OptionKind::U32,
default: oxideav_core::OptionValue::U32(3),
help: "mode-search effort: 0 fastest, 1 fast, 2 balanced, 3 thorough",
},
oxideav_core::OptionField {
name: "threads",
kind: oxideav_core::OptionKind::U32,
default: oxideav_core::OptionValue::U32(0),
help: "thread budget (0 = follow the execution context)",
},
oxideav_core::OptionField {
name: "qindex",
kind: oxideav_core::OptionKind::U32,
default: oxideav_core::OptionValue::U32(32),
help: "quantiser index 0..=127 (lower = better)",
},
oxideav_core::OptionField {
name: "quality",
kind: oxideav_core::OptionKind::F32,
default: oxideav_core::OptionValue::F32(-1.0),
help: "quality 0..=100 (overrides qindex; negative = unset)",
},
oxideav_core::OptionField {
name: "loop_filter_level",
kind: oxideav_core::OptionKind::U32,
default: oxideav_core::OptionValue::U32(0),
help: "loop filter level 0..=63",
},
oxideav_core::OptionField {
name: "auto_loop_filter",
kind: oxideav_core::OptionKind::Bool,
default: oxideav_core::OptionValue::Bool(false),
help: "choose the loop filter level per frame",
},
oxideav_core::OptionField {
name: "partitions",
kind: oxideav_core::OptionKind::U32,
default: oxideav_core::OptionValue::U32(1),
help: "token partition count: 1, 2, 4 or 8",
},
];
fn apply(&mut self, key: &str, value: &oxideav_core::OptionValue) -> Result<()> {
let small = |v: u32, max: u32, what: &str| {
if v > max {
Err(Error::invalid(format!(
"vp8 encoder: option '{what}' out of range (0..={max}), got {v}"
)))
} else {
Ok(v as u8)
}
};
match key {
"effort" => self.effort = EncodeEffort::from_level(small(value.as_u32()?, 3, key)?),
"threads" => self.threads = value.as_u32()? as usize,
"qindex" => self.qindex = small(value.as_u32()?, 127, key)?,
"quality" => {
let q = value.as_f32()?;
self.quality = (q >= 0.0).then_some(q);
}
"loop_filter_level" => self.loop_filter_level = small(value.as_u32()?, 63, key)?,
"auto_loop_filter" => self.auto_loop_filter = value.as_bool()?,
"partitions" => {
let n = value.as_u32()?;
if !matches!(n, 1 | 2 | 4 | 8) {
return Err(Error::invalid(format!(
"vp8 encoder: option 'partitions' must be 1, 2, 4 or 8, got {n}"
)));
}
self.partitions = n as u8;
}
other => {
return Err(Error::invalid(format!(
"vp8 encoder: unknown option '{other}'"
)));
}
}
Ok(())
}
}
pub fn make_encoder_with_options(
params: &CodecParameters,
options: &Vp8EncoderOptions,
) -> Result<Box<dyn Encoder>> {
let (width, height, pixel_format) = validate_video_params(params)?;
if options.qindex > 127 {
return Err(Error::invalid(
"vp8 encoder: qindex out of range (must be 0..=127)",
));
}
if options.loop_filter_level > 63 {
return Err(Error::invalid(
"vp8 encoder: loop_filter_level out of range (must be 0..=63)",
));
}
if !matches!(options.partitions, 1 | 2 | 4 | 8) {
return Err(Error::invalid(
"vp8 encoder: partitions must be 1, 2, 4 or 8",
));
}
let mut keyframe = KeyframeParams::default()
.with_y_ac_qi(options.qindex)
.with_loop_filter_level(options.loop_filter_level)
.with_nbr_of_dct_partitions(options.partitions);
if let Some(quality) = options.quality {
keyframe.y_ac_qi = super::quality_to_qindex(quality);
keyframe.trellis_strength = super::quality_to_trellis_strength(quality);
}
let mut encoder = build_frame_encoder_typed(
params,
width,
height,
pixel_format,
keyframe,
options.auto_loop_filter,
);
encoder.effort = options.effort;
encoder.option_threads = options.threads;
Ok(Box::new(encoder))
}
pub fn make_encoder_from_param_options(params: &CodecParameters) -> Result<Box<dyn Encoder>> {
let options = oxideav_core::parse_options::<Vp8EncoderOptions>(¶ms.options)?;
make_encoder_with_options(params, &options)
}
pub fn make_encoder(params: &CodecParameters) -> Result<Box<dyn Encoder>> {
make_encoder_with_qindex(params, KeyframeParams::default().y_ac_qi)
}
pub fn make_encoder_with_quality(
params: &CodecParameters,
quality: f32,
) -> Result<Box<dyn Encoder>> {
let (width, height, pixel_format) = validate_video_params(params)?;
let keyframe = KeyframeParams {
y_ac_qi: super::quality_to_qindex(quality),
trellis_strength: super::quality_to_trellis_strength(quality),
..KeyframeParams::default()
};
build_frame_encoder(params, width, height, pixel_format, keyframe, false)
}
fn validate_video_params(params: &CodecParameters) -> Result<(u32, u32, PixelFormat)> {
let width = params
.width
.ok_or_else(|| Error::invalid("vp8 encoder: missing width"))?;
let height = params
.height
.ok_or_else(|| Error::invalid("vp8 encoder: missing height"))?;
if width == 0 || height == 0 {
return Err(Error::invalid(
"vp8 encoder: width and height must be positive",
));
}
if width > 0x3FFF || height > 0x3FFF {
return Err(Error::invalid(
"vp8 encoder: width/height exceed VP8 14-bit field (max 16383)",
));
}
let pixel_format = params.pixel_format.unwrap_or(PixelFormat::Yuv420P);
if pixel_format != PixelFormat::Yuv420P {
return Err(Error::unsupported(
"vp8 encoder: only PixelFormat::Yuv420P is supported",
));
}
Ok((width, height, pixel_format))
}
pub fn make_encoder_with_qindex(
params: &CodecParameters,
qindex: u8,
) -> Result<Box<dyn Encoder>> {
let (width, height, pixel_format) = validate_video_params(params)?;
if qindex > 127 {
return Err(Error::invalid(
"vp8 encoder: qindex out of range (must be 0..=127)",
));
}
let keyframe = KeyframeParams {
y_ac_qi: qindex,
..KeyframeParams::default()
};
build_frame_encoder(params, width, height, pixel_format, keyframe, false)
}
pub(crate) fn make_encoder_from_config(
params: &CodecParameters,
config: super::Vp8EncoderConfig,
) -> Result<Box<dyn Encoder>> {
let (width, height, pixel_format) = validate_video_params(params)?;
if config.qindex > 127 {
return Err(Error::invalid(
"vp8 encoder: qindex out of range (must be 0..=127)",
));
}
if config.lf_level > 63 {
return Err(Error::invalid(
"vp8 encoder: lf_level out of range (must be 0..=63)",
));
}
let mut output_params = params.clone();
output_params.media_type = MediaType::Video;
output_params.codec_id = CodecId::new(VP8_CODEC_ID);
output_params.width = Some(width);
output_params.height = Some(height);
output_params.pixel_format = Some(pixel_format);
let time_base = params
.frame_rate
.map_or(TimeBase::new(1, 90_000), |r| TimeBase::new(r.den, r.num));
let window = if config.alt_ref_interval == 0 {
1
} else {
config.alt_ref_interval.min(config.lookahead_window.max(1)) as usize
};
let stream_config = crate::stream::AltrefStreamConfig {
params: KeyframeParams {
y_ac_qi: config.qindex,
loop_filter_level: config.lf_level,
trellis_strength: config.trellis_strength,
nbr_of_dct_partitions: config.stream_partitions(),
..KeyframeParams::default()
},
keyframe_interval: u64::from(config.golden_interval),
altref_window: window,
auto_loop_filter: config.auto_loop_filter,
fitted_token_prob_updates: true,
intra_pick: true,
effort: config.effort,
threads: config.threads,
inter_effort: config.inter_effort,
target_bitrate_bps: config.target_bitrate_bps,
frame_rate: params
.frame_rate
.filter(|r| r.num > 0 && r.den > 0)
.map_or(config.frame_rate, |r| r.num as f64 / r.den as f64),
..crate::stream::AltrefStreamConfig::default()
};
let stream = crate::stream::Vp8AltrefStreamEncoder::new(stream_config)
.expect("window is clamped to >= 1 above");
Ok(Box::new(Vp8LaggedEncoder {
output_params,
width,
height,
stream_config,
stream,
time_base,
pts_queue: VecDeque::new(),
pending: VecDeque::new(),
eof: false,
}))
}
pub(crate) struct Vp8LaggedEncoder {
output_params: CodecParameters,
width: u32,
height: u32,
stream_config: crate::stream::AltrefStreamConfig,
stream: crate::stream::Vp8AltrefStreamEncoder,
time_base: TimeBase,
pts_queue: VecDeque<Option<i64>>,
pending: VecDeque<Packet>,
eof: bool,
}
impl std::fmt::Debug for Vp8LaggedEncoder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vp8LaggedEncoder")
.field("width", &self.width)
.field("height", &self.height)
.field("buffered", &self.stream.buffered())
.field("pending", &self.pending.len())
.field("eof", &self.eof)
.finish()
}
}
impl Vp8LaggedEncoder {
fn enqueue(&mut self, packets: Vec<crate::stream::AltrefStreamPacket>) {
for p in packets {
let is_key = p.kind == crate::stream::AltrefPacketKind::Key;
let pts = match p.source_index {
Some(_) => self.pts_queue.pop_front().flatten(),
None => None,
};
let mut pkt = Packet::new(0, self.time_base, p.bytes);
pkt.pts = pts;
pkt.dts = pts;
pkt.flags.keyframe = is_key;
self.pending.push_back(pkt);
}
}
}
impl Encoder for Vp8LaggedEncoder {
fn codec_id(&self) -> &CodecId {
&self.output_params.codec_id
}
fn output_params(&self) -> &CodecParameters {
&self.output_params
}
fn send_frame(&mut self, frame: &Frame) -> Result<()> {
if self.eof {
return Err(Error::invalid(
"vp8 encoder: send_frame after flush (encoder is drained)",
));
}
let v = match frame {
Frame::Video(v) => v,
Frame::StreamParams(p) => {
let (width, height) = reconfigure_target(p, self.width, self.height)?;
if (width, height) != (self.width, self.height) {
let emitted = self
.stream
.finish()
.map_err(|e| Error::invalid(e.to_string()))?;
self.enqueue(emitted);
self.stream =
crate::stream::Vp8AltrefStreamEncoder::new(self.stream_config)
.expect("the config already built a stream");
self.width = width;
self.height = height;
self.output_params.width = Some(width);
self.output_params.height = Some(height);
}
return Ok(());
}
_ => return Err(Error::invalid("vp8 encoder: video frames only")),
};
let (y, u, vv) = packed_planes_from_video_frame(v, self.width, self.height)?;
let src = I420Frame::packed(self.width, self.height, &y, &u, &vv);
self.pts_queue.push_back(v.pts);
let emitted = self
.stream
.push_frame(&src)
.map_err(|e| Error::invalid(e.to_string()))?;
self.enqueue(emitted);
Ok(())
}
fn receive_packet(&mut self) -> Result<Packet> {
if let Some(p) = self.pending.pop_front() {
Ok(p)
} else if self.eof {
Err(Error::Eof)
} else {
Err(Error::NeedMore)
}
}
fn flush(&mut self) -> Result<()> {
if !self.eof {
let emitted = self
.stream
.finish()
.map_err(|e| Error::invalid(e.to_string()))?;
self.enqueue(emitted);
self.eof = true;
}
Ok(())
}
fn set_execution_context(&mut self, ctx: &oxideav_core::ExecutionContext) {
if self.stream_config.threads <= 1 {
self.stream_config.threads = ctx.threads;
self.stream.set_threads(ctx.threads);
}
}
}
pub(crate) fn build_frame_encoder(
params: &CodecParameters,
width: u32,
height: u32,
pixel_format: PixelFormat,
keyframe: KeyframeParams,
auto_lf: bool,
) -> Result<Box<dyn Encoder>> {
Ok(Box::new(build_frame_encoder_typed(
params,
width,
height,
pixel_format,
keyframe,
auto_lf,
)))
}
fn build_frame_encoder_typed(
params: &CodecParameters,
width: u32,
height: u32,
pixel_format: PixelFormat,
keyframe: KeyframeParams,
auto_lf: bool,
) -> Vp8FrameEncoder {
let mut output_params = params.clone();
output_params.media_type = MediaType::Video;
output_params.codec_id = CodecId::new(VP8_CODEC_ID);
output_params.width = Some(width);
output_params.height = Some(height);
output_params.pixel_format = Some(pixel_format);
let time_base = params
.frame_rate
.map_or(TimeBase::new(1, 90_000), |r| TimeBase::new(r.den, r.num));
Vp8FrameEncoder {
output_params,
width,
height,
keyframe,
auto_lf,
effort: EncodeEffort::Thorough,
option_threads: 0,
context_threads: 1,
time_base,
pending: VecDeque::new(),
eof: false,
}
}
pub(crate) struct Vp8FrameEncoder {
output_params: CodecParameters,
width: u32,
height: u32,
keyframe: KeyframeParams,
auto_lf: bool,
effort: EncodeEffort,
option_threads: usize,
context_threads: usize,
time_base: TimeBase,
pending: VecDeque<Packet>,
eof: bool,
}
impl Vp8FrameEncoder {
fn keyframe_options(&self) -> KeyframeEncodeOptions {
let threads = if self.option_threads > 0 {
self.option_threads
} else {
self.context_threads
};
KeyframeEncodeOptions::exhaustive()
.with_effort(self.effort)
.with_threads(threads)
.with_auto_loop_filter(self.auto_lf)
}
}
impl std::fmt::Debug for Vp8FrameEncoder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vp8FrameEncoder")
.field("width", &self.width)
.field("height", &self.height)
.field("y_ac_qi", &self.keyframe.y_ac_qi)
.field("pending", &self.pending.len())
.field("eof", &self.eof)
.finish()
}
}
impl Encoder for Vp8FrameEncoder {
fn codec_id(&self) -> &CodecId {
&self.output_params.codec_id
}
fn output_params(&self) -> &CodecParameters {
&self.output_params
}
fn send_frame(&mut self, frame: &Frame) -> Result<()> {
let v = match frame {
Frame::Video(v) => v,
Frame::StreamParams(p) => {
let (width, height) = reconfigure_target(p, self.width, self.height)?;
self.width = width;
self.height = height;
self.output_params.width = Some(width);
self.output_params.height = Some(height);
return Ok(());
}
_ => return Err(Error::invalid("vp8 encoder: video frames only")),
};
let bytes = encode_video_frame(
v,
self.width,
self.height,
&self.keyframe,
&self.keyframe_options(),
)?;
let mut pkt = Packet::new(0, self.time_base, bytes);
pkt.pts = v.pts;
pkt.dts = v.pts;
pkt.flags.keyframe = true;
self.pending.push_back(pkt);
Ok(())
}
fn receive_packet(&mut self) -> Result<Packet> {
if let Some(p) = self.pending.pop_front() {
Ok(p)
} else if self.eof {
Err(Error::Eof)
} else {
Err(Error::NeedMore)
}
}
fn flush(&mut self) -> Result<()> {
self.eof = true;
Ok(())
}
fn set_execution_context(&mut self, ctx: &oxideav_core::ExecutionContext) {
self.context_threads = ctx.threads;
}
}
fn reconfigure_target(params: &CodecParameters, width: u32, height: u32) -> Result<(u32, u32)> {
if params.media_type != MediaType::Video {
return Err(Error::unsupported(
"vp8 encoder: stream-params event does not describe video",
));
}
if params
.pixel_format
.is_some_and(|pf| pf != PixelFormat::Yuv420P)
{
return Err(Error::unsupported(
"vp8 encoder: cannot switch away from PixelFormat::Yuv420P mid-stream",
));
}
let width = params.width.unwrap_or(width);
let height = params.height.unwrap_or(height);
if width == 0 || height == 0 || width > 0x3FFF || height > 0x3FFF {
return Err(Error::unsupported(
"vp8 encoder: stream-params size outside the §9.1 14-bit range (1..=16383)",
));
}
Ok((width, height))
}
fn packed_planes_from_video_frame(
frame: &VideoFrame,
width: u32,
height: u32,
) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
if frame.planes.len() < 3 {
return Err(Error::invalid(
"vp8 encoder: VideoFrame must carry 3 planes (Y/U/V)",
));
}
let w = width as usize;
let h = height as usize;
let uvw = w.div_ceil(2);
let uvh = h.div_ceil(2);
let y_plane = &frame.planes[0];
let u_plane = &frame.planes[1];
let v_plane = &frame.planes[2];
fn validate_plane(
plane: &oxideav_core::frame::VideoPlane,
row_w: usize,
rows: usize,
name: &str,
) -> Result<()> {
if rows == 0 {
return Ok(());
}
if plane.stride < row_w {
return Err(Error::invalid(format!(
"vp8 encoder: {name} plane stride {} narrower than row width {row_w}",
plane.stride
)));
}
let needed = plane
.stride
.checked_mul(rows - 1)
.and_then(|n| n.checked_add(row_w))
.ok_or_else(|| {
Error::invalid(format!(
"vp8 encoder: {name} plane stride {} x {rows} rows overflows",
plane.stride
))
})?;
if plane.data.len() < needed {
return Err(Error::invalid(format!(
"vp8 encoder: {name} plane buffer {} bytes, needs {needed} \
(stride {}, {rows} rows of {row_w})",
plane.data.len(),
plane.stride
)));
}
Ok(())
}
validate_plane(y_plane, w, h, "Y")?;
validate_plane(u_plane, uvw, uvh, "U")?;
validate_plane(v_plane, uvw, uvh, "V")?;
Ok((
repack_plane(&y_plane.data, y_plane.stride, w, h),
repack_plane(&u_plane.data, u_plane.stride, uvw, uvh),
repack_plane(&v_plane.data, v_plane.stride, uvw, uvh),
))
}
fn encode_video_frame(
frame: &VideoFrame,
width: u32,
height: u32,
keyframe: &KeyframeParams,
options: &KeyframeEncodeOptions,
) -> Result<Vec<u8>> {
let (y_packed, u_packed, v_packed) = packed_planes_from_video_frame(frame, width, height)?;
let src = I420Frame::packed(width, height, &y_packed, &u_packed, &v_packed);
encode_keyframe_with_options(&src, keyframe, options)
.map_err(|e| Error::invalid(e.to_string()))
}
fn repack_plane(data: &[u8], stride: usize, w: usize, h: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(w * h);
for r in 0..h {
let off = r * stride;
out.extend_from_slice(&data[off..off + w]);
}
out
}
}
#[cfg(feature = "registry")]
pub use factory::{
Vp8EncoderOptions, make_encoder, make_encoder_from_param_options, make_encoder_with_options,
make_encoder_with_qindex, make_encoder_with_quality,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum LoopFilterMode {
#[default]
Auto,
Normal,
Simple,
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct FrameComplexity {
pub frame_index: u32,
pub bits_per_mb: f32,
pub scene_cut: bool,
}
impl FrameComplexity {
#[must_use]
pub fn with_frame_index(mut self, v: u32) -> Self {
self.frame_index = v;
self
}
#[must_use]
pub fn with_bits_per_mb(mut self, v: f32) -> Self {
self.bits_per_mb = v;
self
}
#[must_use]
pub fn with_scene_cut(mut self, v: bool) -> Self {
self.scene_cut = v;
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Vp8EncoderStats {
pub frames_encoded: u64,
pub bytes_emitted: u64,
pub keyframes_emitted: u64,
}
impl Vp8EncoderStats {
#[must_use]
pub fn with_frames_encoded(mut self, v: u64) -> Self {
self.frames_encoded = v;
self
}
#[must_use]
pub fn with_bytes_emitted(mut self, v: u64) -> Self {
self.bytes_emitted = v;
self
}
#[must_use]
pub fn with_keyframes_emitted(mut self, v: u64) -> Self {
self.keyframes_emitted = v;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Vp8EncoderConfig {
pub qindex: u8,
pub lf_level: u8,
pub lf_mode: LoopFilterMode,
pub golden_interval: u32,
pub alt_ref_interval: u32,
pub lookahead_window: u32,
pub target_bitrate_bps: u32,
pub auto_loop_filter: bool,
pub trellis_strength: TrellisStrength,
pub effort: EncodeEffort,
pub threads: usize,
pub inter_effort: EncodeEffort,
pub partitions: u8,
pub frame_rate: f64,
}
impl Vp8EncoderConfig {
#[must_use]
pub fn with_effort(mut self, v: EncodeEffort) -> Self {
self.effort = v;
self
}
#[must_use]
pub fn with_threads(mut self, v: usize) -> Self {
self.threads = v;
self
}
#[must_use]
pub fn with_inter_effort(mut self, v: EncodeEffort) -> Self {
self.inter_effort = v;
self
}
#[must_use]
pub fn with_partitions(mut self, v: u8) -> Self {
self.partitions = v;
self
}
#[must_use]
pub fn with_frame_rate(mut self, v: f64) -> Self {
self.frame_rate = v;
self
}
fn stream_partitions(&self) -> u8 {
match self.partitions {
2 | 4 | 8 => self.partitions,
_ => 1,
}
}
fn keyframe_options(&self) -> KeyframeEncodeOptions {
KeyframeEncodeOptions::exhaustive()
.with_effort(self.effort)
.with_threads(self.threads)
.with_auto_loop_filter(self.auto_loop_filter)
}
#[must_use]
pub fn with_qindex(mut self, v: u8) -> Self {
self.qindex = v;
self
}
#[must_use]
pub fn with_lf_level(mut self, v: u8) -> Self {
self.lf_level = v;
self
}
#[must_use]
pub fn with_lf_mode(mut self, v: LoopFilterMode) -> Self {
self.lf_mode = v;
self
}
#[must_use]
pub fn with_golden_interval(mut self, v: u32) -> Self {
self.golden_interval = v;
self
}
#[must_use]
pub fn with_alt_ref_interval(mut self, v: u32) -> Self {
self.alt_ref_interval = v;
self
}
#[must_use]
pub fn with_lookahead_window(mut self, v: u32) -> Self {
self.lookahead_window = v;
self
}
#[must_use]
pub fn with_target_bitrate_bps(mut self, v: u32) -> Self {
self.target_bitrate_bps = v;
self
}
#[must_use]
pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
self.auto_loop_filter = v;
self
}
#[must_use]
pub fn with_trellis_strength(mut self, v: TrellisStrength) -> Self {
self.trellis_strength = v;
self
}
}
impl Default for Vp8EncoderConfig {
fn default() -> Self {
Self {
qindex: DEFAULT_QINDEX,
lf_level: 0,
lf_mode: LoopFilterMode::Auto,
golden_interval: DEFAULT_GOLDEN_INTERVAL,
alt_ref_interval: DEFAULT_ALT_REF_INTERVAL,
lookahead_window: DEFAULT_LOOKAHEAD_WINDOW,
target_bitrate_bps: 0,
auto_loop_filter: false,
trellis_strength: TrellisStrength::DEFAULT,
effort: EncodeEffort::Thorough,
threads: 1,
inter_effort: EncodeEffort::Balanced,
partitions: 1,
frame_rate: 30.0,
}
}
}
#[derive(Debug, Clone)]
pub struct Vp8Encoder {
config: Vp8EncoderConfig,
stats: Vp8EncoderStats,
}
impl Vp8Encoder {
pub fn new(config: Vp8EncoderConfig) -> Self {
Self {
config,
stats: Vp8EncoderStats::default(),
}
}
pub fn config(&self) -> &Vp8EncoderConfig {
&self.config
}
pub fn stats(&self) -> &Vp8EncoderStats {
&self.stats
}
pub fn encode_keyframe(&mut self, frame: &I420Frame<'_>) -> crate::error::Result<Vec<u8>> {
let params = KeyframeParams {
y_ac_qi: self.config.qindex,
loop_filter_level: self.config.lf_level,
trellis_strength: self.config.trellis_strength,
..KeyframeParams::default()
};
let bytes = encode_keyframe_with_options(frame, ¶ms, &self.config.keyframe_options())
.map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?;
self.stats.frames_encoded += 1;
self.stats.keyframes_emitted += 1;
self.stats.bytes_emitted += bytes.len() as u64;
Ok(bytes)
}
pub fn encode_sequence(
&mut self,
frames: &[I420Frame<'_>],
) -> crate::error::Result<Vec<crate::stream::AltrefStreamPacket>> {
let window = if self.config.alt_ref_interval == 0 {
1
} else {
self.config
.alt_ref_interval
.min(self.config.lookahead_window.max(1)) as usize
};
let config = crate::stream::AltrefStreamConfig {
params: KeyframeParams {
y_ac_qi: self.config.qindex,
loop_filter_level: self.config.lf_level,
trellis_strength: self.config.trellis_strength,
nbr_of_dct_partitions: self.config.stream_partitions(),
..KeyframeParams::default()
},
keyframe_interval: u64::from(self.config.golden_interval),
altref_window: window,
auto_loop_filter: self.config.auto_loop_filter,
fitted_token_prob_updates: true,
intra_pick: true,
effort: self.config.effort,
threads: self.config.threads,
inter_effort: self.config.inter_effort,
target_bitrate_bps: self.config.target_bitrate_bps,
frame_rate: self.config.frame_rate,
..crate::stream::AltrefStreamConfig::default()
};
let mut enc = crate::stream::Vp8AltrefStreamEncoder::new(config)
.expect("window is clamped to >= 1 above");
let mut packets = Vec::new();
for frame in frames {
packets.extend(
enc.push_frame(frame)
.map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?,
);
}
packets.extend(
enc.finish()
.map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?,
);
for p in &packets {
self.stats.frames_encoded += 1;
self.stats.bytes_emitted += p.bytes.len() as u64;
if p.kind == crate::stream::AltrefPacketKind::Key {
self.stats.keyframes_emitted += 1;
}
}
Ok(packets)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Vp8TwoPassConfig {
pub base: Vp8EncoderConfig,
pub target_bitrate_bps: u32,
pub overshoot_ratio: f32,
pub fps_num: u32,
pub fps_den: u32,
pub auto_loop_filter: bool,
}
impl Vp8TwoPassConfig {
#[must_use]
pub fn with_base(mut self, v: Vp8EncoderConfig) -> Self {
self.base = v;
self
}
#[must_use]
pub fn with_target_bitrate_bps(mut self, v: u32) -> Self {
self.target_bitrate_bps = v;
self
}
#[must_use]
pub fn with_overshoot_ratio(mut self, v: f32) -> Self {
self.overshoot_ratio = v;
self
}
#[must_use]
pub fn with_fps_num(mut self, v: u32) -> Self {
self.fps_num = v;
self
}
#[must_use]
pub fn with_fps_den(mut self, v: u32) -> Self {
self.fps_den = v;
self
}
#[must_use]
pub fn with_auto_loop_filter(mut self, v: bool) -> Self {
self.auto_loop_filter = v;
self
}
}
impl Default for Vp8TwoPassConfig {
fn default() -> Self {
Self {
base: Vp8EncoderConfig::default(),
target_bitrate_bps: 0,
overshoot_ratio: 1.2,
fps_num: 0,
fps_den: 1,
auto_loop_filter: false,
}
}
}
impl Vp8TwoPassConfig {
pub fn fps(&self) -> Option<f32> {
if self.fps_num == 0 {
None
} else {
Some(self.fps_num as f32 / self.fps_den.max(1) as f32)
}
}
pub fn bitrate_targeted(&self) -> bool {
self.target_bitrate_bps > 0 && self.fps().is_some()
}
}
#[derive(Debug, Clone)]
pub struct Vp8TwoPassEncoder {
config: Vp8TwoPassConfig,
global_mean_cost: Option<f32>,
last_reconstruction: Option<crate::frame::KeyframePlanes>,
frame_count: u64,
last_keyframe_index: Option<u64>,
solved_base_qindex: Option<u8>,
frame_byte_budget: Option<u64>,
rate_debt_bytes: i64,
}
impl Vp8TwoPassEncoder {
pub fn new(config: Vp8TwoPassConfig) -> Self {
Self {
config,
global_mean_cost: None,
last_reconstruction: None,
frame_count: 0,
last_keyframe_index: None,
solved_base_qindex: None,
frame_byte_budget: None,
rate_debt_bytes: 0,
}
}
pub fn config(&self) -> &Vp8TwoPassConfig {
&self.config
}
pub fn first_pass_analyze(
&mut self,
frames: &[I420Frame<'_>],
) -> crate::error::Result<Vec<FrameComplexity>> {
let stats = first_pass_analyze(frames, &self.config)?;
self.global_mean_cost = Some(mean_complexity_cost(&stats));
self.rate_debt_bytes = 0;
if self.config.bitrate_targeted() && !stats.is_empty() {
let (w, h) = frames
.first()
.map(|f| (f.width, f.height))
.unwrap_or((0, 0));
self.solved_base_qindex =
Some(solve_base_qindex_for_budget(&self.config, &stats, w, h));
self.frame_byte_budget =
gop_byte_budget(&self.config, stats.len()).map(|b| b / stats.len() as u64);
} else {
self.solved_base_qindex = None;
self.frame_byte_budget = None;
}
Ok(stats)
}
pub fn encode_frame(
&mut self,
frame: &I420Frame<'_>,
complexity: FrameComplexity,
) -> crate::error::Result<Vec<u8>> {
let qindex = self.qindex_for(complexity);
let params = KeyframeParams {
y_ac_qi: qindex,
loop_filter_level: self.config.base.lf_level,
trellis_strength: self.config.base.trellis_strength,
..KeyframeParams::default()
};
let force_key = self.last_reconstruction.is_none()
|| complexity.scene_cut
|| self
.last_keyframe_index
.map(|anchor| {
self.frame_count.saturating_sub(anchor)
>= self.config.base.golden_interval.max(1) as u64
})
.unwrap_or(false);
let auto_lf = self.config.auto_loop_filter;
let (bytes, planes) = if force_key {
encode_keyframe_with_reconstruction_and_options(
frame,
¶ms,
&self
.config
.base
.keyframe_options()
.with_auto_loop_filter(auto_lf),
)
.map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?
} else {
let reference = self
.last_reconstruction
.as_ref()
.expect("force_key=false implies a reference exists");
if auto_lf {
encode_p_frame_multi_ref_auto_loop_filter(frame, reference, None, None, ¶ms)
} else {
encode_p_frame_multi_ref(frame, reference, None, None, ¶ms)
}
.map_err(|e| crate::error::Vp8Error::invalid(e.to_string()))?
};
self.last_reconstruction = Some(planes);
if force_key {
self.last_keyframe_index = Some(self.frame_count);
}
if let Some(budget) = self.frame_byte_budget {
let spent = bytes.len() as i64;
self.rate_debt_bytes = self.rate_debt_bytes.saturating_add(spent - budget as i64);
}
self.frame_count += 1;
Ok(bytes)
}
pub fn rate_debt_bytes(&self) -> i64 {
self.rate_debt_bytes
}
fn qindex_for(&self, complexity: FrameComplexity) -> u8 {
let Some(solved_base) = self.solved_base_qindex else {
return match self.global_mean_cost {
Some(mean) => qindex_from_complexity(&self.config, complexity, mean),
None => qindex_from_complexity(&self.config, complexity, complexity.bits_per_mb),
};
};
let mut cfg = self.config;
cfg.base.qindex = solved_base;
let mean = self.global_mean_cost.unwrap_or(complexity.bits_per_mb);
let centred = qindex_from_complexity(&cfg, complexity, mean) as i32;
let correction = self.rate_feedback_delta();
(centred + correction).clamp(0, 127) as u8
}
fn rate_feedback_delta(&self) -> i32 {
let Some(budget) = self.frame_byte_budget else {
return 0;
};
if budget == 0 {
return 0;
}
let debt_frames = self.rate_debt_bytes as f32 / budget as f32;
let raw = (debt_frames * RATE_FEEDBACK_QSTEP_PER_FRAME as f32).round() as i32;
raw.clamp(-RATE_FEEDBACK_MAX_QSTEP, RATE_FEEDBACK_MAX_QSTEP)
}
}
pub fn first_pass_analyze(
frames: &[I420Frame<'_>],
_config: &Vp8TwoPassConfig,
) -> crate::error::Result<Vec<FrameComplexity>> {
let mut out = Vec::with_capacity(frames.len());
let mut prev_luma_sample: Option<(Vec<u8>, u32, u32)> = None;
let mut prev_variance: f32 = 0.0;
for (idx, frame) in frames.iter().enumerate() {
let (_mean, variance) = luma_mean_and_variance(frame);
let mad = match &prev_luma_sample {
Some((prev, pw, ph)) if *pw == frame.width && *ph == frame.height => {
luma_mad(frame, prev)
}
_ => 0.0,
};
let cost = 30.0 * (1.0 + mad).log2() + 25.0 * (1.0 + variance).log2();
let cost = cost.max(0.0);
let scene_cut = if idx == 0 {
false
} else {
let ratio = (mad * 1024.0) / (prev_variance + 1.0);
ratio >= DEFAULT_SCENE_CUT_THRESHOLD as f32
&& (mad * 1024.0) >= SCENE_CUT_ABS_FLOOR as f32
};
out.push(FrameComplexity {
frame_index: idx as u32,
bits_per_mb: cost,
scene_cut,
});
let plane_len = (frame.height as usize) * frame.y_stride;
let mut buf = vec![0u8; plane_len];
let take = plane_len.min(frame.y.len());
buf[..take].copy_from_slice(&frame.y[..take]);
prev_luma_sample = Some((buf, frame.width, frame.height));
prev_variance = variance;
}
Ok(out)
}
pub fn two_pass_qindex_for_frame(
config: &Vp8TwoPassConfig,
complexity: FrameComplexity,
) -> crate::error::Result<u8> {
if config.base.qindex > 127 {
return Err(crate::error::Vp8Error::invalid(format!(
"vp8 two-pass: config.base.qindex={} out of RFC 6386 §9.6 range 0..=127",
config.base.qindex
)));
}
Ok(qindex_from_complexity(
config,
complexity,
complexity.bits_per_mb,
))
}
pub fn two_pass_qindices(
config: &Vp8TwoPassConfig,
complexities: &[FrameComplexity],
) -> crate::error::Result<Vec<u8>> {
if config.base.qindex > 127 {
return Err(crate::error::Vp8Error::invalid(format!(
"vp8 two-pass: config.base.qindex={} out of RFC 6386 §9.6 range 0..=127",
config.base.qindex
)));
}
if complexities.is_empty() {
return Ok(Vec::new());
}
let mean = mean_complexity_cost(complexities);
Ok(complexities
.iter()
.map(|c| qindex_from_complexity(config, *c, mean))
.collect())
}
pub fn make_two_pass_encoder(config: Vp8TwoPassConfig) -> Vp8TwoPassEncoder {
Vp8TwoPassEncoder::new(config)
}
pub fn gop_byte_budget(config: &Vp8TwoPassConfig, frame_count: usize) -> Option<u64> {
if frame_count == 0 {
return None;
}
let fps = config.fps()?;
if config.target_bitrate_bps == 0 {
return None;
}
let bytes_per_sec = config.target_bitrate_bps as f64 / 8.0;
let gop_seconds = frame_count as f64 / fps as f64;
Some((bytes_per_sec * gop_seconds).floor() as u64)
}
fn predict_gop_bytes_at_qindex(
complexities: &[FrameComplexity],
width: u32,
height: u32,
base_qindex: i32,
) -> u64 {
complexities.iter().fold(0u64, |acc, c| {
acc.saturating_add(estimate_frame_bytes(
c.bits_per_mb,
base_qindex,
width,
height,
))
})
}
pub fn solve_base_qindex_for_budget(
config: &Vp8TwoPassConfig,
complexities: &[FrameComplexity],
width: u32,
height: u32,
) -> u8 {
if !config.bitrate_targeted() || complexities.is_empty() {
return config.base.qindex.min(127);
}
let budget = match gop_byte_budget(config, complexities.len()) {
Some(b) => b,
None => return config.base.qindex.min(127),
};
let ceiling = {
let r = config.overshoot_ratio.max(1.0) as f64;
(budget as f64 * r) as u64
};
let fits = |qi: i32| predict_gop_bytes_at_qindex(complexities, width, height, qi) <= ceiling;
if !fits(127) {
return 127;
}
if fits(0) {
return 0;
}
let mut lo = 0i32; let mut hi = 127i32; while hi - lo > 1 {
let mid = (lo + hi) / 2;
if fits(mid) {
hi = mid;
} else {
lo = mid;
}
}
hi as u8
}
pub fn two_pass_qindices_for_bitrate(
config: &Vp8TwoPassConfig,
complexities: &[FrameComplexity],
width: u32,
height: u32,
) -> crate::error::Result<Vec<u8>> {
if config.base.qindex > 127 {
return Err(crate::error::Vp8Error::invalid(format!(
"vp8 two-pass: config.base.qindex={} out of RFC 6386 §9.6 range 0..=127",
config.base.qindex
)));
}
if complexities.is_empty() {
return Ok(Vec::new());
}
let solved_base = solve_base_qindex_for_budget(config, complexities, width, height);
let mut solved_config = *config;
solved_config.base.qindex = solved_base;
let mean = mean_complexity_cost(complexities);
Ok(complexities
.iter()
.map(|c| qindex_from_complexity(&solved_config, *c, mean))
.collect())
}
fn mean_complexity_cost(stats: &[FrameComplexity]) -> f32 {
if stats.is_empty() {
0.0
} else {
let sum: f32 = stats.iter().map(|c| c.bits_per_mb).sum();
sum / stats.len() as f32
}
}
pub const RATE_MODEL_GAMMA_X256: i32 = 200;
pub const RATE_FEEDBACK_QSTEP_PER_FRAME: i32 = 4;
pub const RATE_FEEDBACK_MAX_QSTEP: i32 = 24;
pub const RATE_MODEL_MB_FLOOR_BITS: f32 = 6.0;
const RATE_MODEL_REF_QINDEX: usize = DEFAULT_QINDEX as usize;
#[inline]
fn ac_step_for_qindex(qindex: i32) -> f32 {
crate::inverse_transform::AC_QLOOKUP[crate::inverse_transform::clamp_qindex(qindex)] as f32
}
pub fn estimate_bits_per_mb(complexity: f32, qindex: i32) -> f32 {
let gamma = RATE_MODEL_GAMMA_X256 as f32 / 256.0;
let ref_step = ac_step_for_qindex(RATE_MODEL_REF_QINDEX as i32);
let step = ac_step_for_qindex(qindex);
let scaled = complexity.max(0.0) * (ref_step / step).powf(gamma);
scaled + RATE_MODEL_MB_FLOOR_BITS
}
pub fn estimate_frame_bytes(complexity: f32, qindex: i32, width: u32, height: u32) -> u64 {
let mb_cols = (width as u64).div_ceil(16);
let mb_rows = (height as u64).div_ceil(16);
let mb_count = mb_cols.saturating_mul(mb_rows);
let bits_per_mb = estimate_bits_per_mb(complexity, qindex);
let total_bits = (bits_per_mb.max(0.0) as f64) * (mb_count as f64);
(total_bits / 8.0).ceil() as u64
}
fn luma_mean_and_variance(frame: &I420Frame<'_>) -> (f32, f32) {
let w = frame.width as usize;
let h = frame.height as usize;
if w == 0 || h == 0 {
return (0.0, 0.0);
}
let stride = frame.y_stride.max(w);
let mut sum: u64 = 0;
let mut sumsq: u64 = 0;
let mut count: u64 = 0;
for r in 0..h {
let row_off = r * stride;
if row_off >= frame.y.len() {
break;
}
let row_end = (row_off + w).min(frame.y.len());
for &px in &frame.y[row_off..row_end] {
sum += px as u64;
sumsq += (px as u64) * (px as u64);
count += 1;
}
}
if count == 0 {
return (0.0, 0.0);
}
let count_f = count as f32;
let mean = sum as f32 / count_f;
let var = (sumsq as f32 / count_f) - (mean * mean);
(mean, var.max(0.0))
}
fn luma_mad(frame: &I420Frame<'_>, prev: &[u8]) -> f32 {
let w = frame.width as usize;
let h = frame.height as usize;
if w == 0 || h == 0 {
return 0.0;
}
let stride = frame.y_stride.max(w);
let mut sum: u64 = 0;
let mut count: u64 = 0;
for r in 0..h {
let row_off = r * stride;
if row_off >= frame.y.len() || row_off >= prev.len() {
break;
}
let row_end = (row_off + w).min(frame.y.len()).min(prev.len());
let cur = &frame.y[row_off..row_end];
let pre = &prev[row_off..row_end];
for (a, b) in cur.iter().zip(pre.iter()) {
sum += (*a as i32 - *b as i32).unsigned_abs() as u64;
count += 1;
}
}
if count == 0 {
0.0
} else {
sum as f32 / count as f32
}
}
fn qindex_from_complexity(
config: &Vp8TwoPassConfig,
complexity: FrameComplexity,
reference_mean: f32,
) -> u8 {
let base = config.base.qindex as i32;
let range = DEFAULT_AQ_QINDEX_RANGE.max(0);
let delta = if reference_mean > 1.0 {
let normed = (complexity.bits_per_mb - reference_mean) / reference_mean;
let raw = -(normed * range as f32);
raw.round() as i32
} else {
0
};
let mut qindex = base + delta.clamp(-range, range);
if complexity.scene_cut {
qindex -= DEFAULT_SCENE_CUT_QUANT_BOOST;
}
qindex.clamp(0, 127) as u8
}
#[cfg(feature = "registry")]
pub fn make_encoder_with_config(
params: &oxideav_core::CodecParameters,
config: Vp8EncoderConfig,
) -> oxideav_core::Result<Box<dyn oxideav_core::Encoder>> {
factory::make_encoder_from_config(params, config)
}
pub fn make_encoder_typed_with_config(config: Vp8EncoderConfig) -> Vp8Encoder {
Vp8Encoder::new(config)
}
pub const DEFAULT_QINDEX: u8 = 50;
pub const AQ_QINDEX_RANGE_MAX: i32 = 16;
pub const DEFAULT_AQ_QINDEX_RANGE: i32 = 8;
pub const DEFAULT_ADAPTIVE_SEGMENT_THRESHOLDS: [u32; 4] = [80, 320, 1_280, 5_120];
pub const DEFAULT_ALT_REF_INTERVAL: u32 = 16;
pub const DEFAULT_GOLDEN_INTERVAL: u32 = 8;
pub const DEFAULT_CHROMA_AWARE_SPATIAL_CHROMA_WEIGHT_X256: i32 = 96;
pub const DEFAULT_CHROMA_AWARE_SPATIAL_LUMA_WEIGHT_X256: i32 = 160;
pub const DEFAULT_JOINT_R44R49_PICKER_MAX_ITERS: u32 = 4;
pub const JOINT_R44R49_PICKER_MAX_ITERS_MAX: u32 = 16;
pub const DEFAULT_KMEANS_CONVERGENCE_THRESHOLD: i32 = 8;
pub const DEFAULT_KMEANS_SPATIAL_ALPHA_X256: i32 = 128;
pub const KMEANS_SPATIAL_MAX_ITERS: u32 = 32;
pub const DEFAULT_LAMBDA_LONG_REF_SCALE_X256: i32 = 256;
pub const LAMBDA_SCALE_DEFAULT: i32 = 256;
pub const DEFAULT_LOOKAHEAD_WINDOW: u32 = 16;
pub const DEFAULT_NLM_H2: i32 = 100;
pub const DEFAULT_PSY_RD_STRENGTH: i32 = 30;
pub const DEFAULT_SCENE_CUT_BOOST_FRAMES: u32 = 2;
pub const DEFAULT_SCENE_CUT_QUANT_BOOST: i32 = 8;
pub const DEFAULT_SCENE_CUT_THRESHOLD: i32 = 4_096;
pub const DEFAULT_SEGMENT_LF_DELTAS: [i8; 4] = [0, 0, 0, 0];
pub const DEFAULT_SEGMENT_QUANT_DELTAS: [i8; 4] = [0, 0, 0, 0];
pub const DEFAULT_SIMPLE_LF_MAX_LEVEL: u8 = 32;
pub const DEFAULT_SPATIAL_LF_N_COL_BANDS: u32 = 4;
pub const DEFAULT_SPATIAL_LF_N_ROW_BANDS: u32 = 4;
pub const DEFAULT_SPLIT_MV_JOINT_REFINE_PASSES: u32 = 2;
pub const SPLIT_MV_JOINT_REFINE_PASSES_MAX: u32 = 8;
pub const INTRA_IN_P_BPRED_VARIANCE_THRESHOLD: i32 = 256;
pub const QP_SENSITIVITY_X8: i32 = 8;
pub const SCENE_CUT_ABS_FLOOR: i32 = 32;
pub const SEGMENT_VARIANCE_THRESHOLDS: [u32; 4] = [64, 256, 1_024, 4_096];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reconstruct_block_4x4_dc_only_matches_general() {
let mut st = 0x5EED_0441u32;
let mut next = move || {
st = st.wrapping_mul(1_103_515_245).wrapping_add(12345);
(st >> 16) as i32
};
for case in 0..4096 {
let mut pred = [0u8; 16];
for p in pred.iter_mut() {
*p = (next() & 0xFF) as u8;
}
let (dc, ac) = (4 + (next() % 280) as i16, 4 + (next() % 280) as i16);
let mut quant = [0i16; 16];
match case % 4 {
0 => {}
1 => quant[0] = (next() % 9 - 4) as i16,
2 => quant[0] = (next() % 60_000 - 30_000) as i16,
_ => {
for c in quant.iter_mut() {
*c = (next() % 41 - 20) as i16;
}
}
}
let mut dq = quant;
dq[0] = (dq[0] as i32 * dc as i32) as i16;
for c in dq.iter_mut().skip(1) {
*c = (*c as i32 * ac as i32) as i16;
}
let mut residue = [0i16; 16];
inverse_dct_4x4(&dq, &mut residue);
let mut want = [0u8; 16];
add_residue_4x4(&pred, &residue, &mut want);
let got = reconstruct_block_4x4(&pred, &quant, dc, ac);
assert_eq!(want, got, "case {case} dc {dc} ac {ac} quant {quant:?}");
}
}
#[allow(clippy::needless_range_loop)]
fn trellis_quantize_block_reference(
block: &mut [i16; 16],
spec: super::TrellisBlockSpec,
coeff_probs: &super::CoeffProbs,
lambda: f64,
) {
let super::TrellisBlockSpec {
dc,
ac,
first_coeff,
entry_ctx3,
plane,
} = spec;
if lambda <= 0.0 {
super::enc_quantize_block_range(block, dc, ac, first_coeff);
return;
}
let mut scan_x = [0i32; 16];
let mut step = [0i32; 16];
for k in 0..16 {
scan_x[k] = block[crate::dct_tokens::ZIGZAG[k]] as i32;
step[k] = if k == 0 { dc as i32 } else { ac as i32 };
}
let norms = &*super::IDCT_BASIS_NORM_SQ;
let dist = |k: usize, m: i64| -> f64 {
let q = step[k] as i64;
let recon = m * q;
let err = (scan_x[k] as i64).abs() - recon;
norms[k] * (err * err) as f64
};
let mut suffix_zero_dist = [0f64; 17];
for k in (first_coeff..16).rev() {
suffix_zero_dist[k] = suffix_zero_dist[k + 1] + dist(k, 0);
}
const INF: f64 = f64::INFINITY;
#[derive(Clone, Copy)]
struct Surv {
cost: f64,
prev_was_zero: bool,
}
let mut surv = [Surv {
cost: INF,
prev_was_zero: false,
}; 3];
surv[entry_ctx3] = Surv {
cost: 0.0,
prev_was_zero: false,
};
let mut choice = [[super::TrellisCell {
cost: INF,
level: 0,
prev_ctx: 0,
}; 3]; 16];
let mut best_term_cost = {
let mut c = INF;
let s = &surv[entry_ctx3];
if s.cost < INF {
c = s.cost
+ lambda * super::eob_token_bits(coeff_probs, plane, first_coeff, entry_ctx3)
+ suffix_zero_dist[first_coeff];
}
c
};
let mut best_term_pos: i32 = -1; let mut best_term_ctx = entry_ctx3;
for k in first_coeff..16 {
let m_round = {
let q = step[k] as i64;
let num = scan_x[k].unsigned_abs() as i64;
(num + q / 2) / q
};
let mut cands = [0i64; 3];
let mut ncand = 0usize;
for cand in [m_round, m_round - 1, 0] {
if cand >= 0 && !cands[..ncand].contains(&cand) {
cands[ncand] = cand;
ncand += 1;
}
}
let mut next = [Surv {
cost: INF,
prev_was_zero: false,
}; 3];
let mut next_choice = [super::TrellisCell {
cost: INF,
level: 0,
prev_ctx: 0,
}; 3];
for (in_ctx, &s) in surv.iter().enumerate() {
if s.cost >= INF {
continue;
}
for &m in &cands[..ncand] {
let abs = m as u16;
let d = dist(k, m);
let r = super::coeff_token_bits(
coeff_probs,
plane,
k,
in_ctx,
s.prev_was_zero,
abs,
);
let cost = s.cost + d + lambda * r;
let out_ctx = super::level_ctx3(abs);
if cost < next[out_ctx].cost {
next[out_ctx] = Surv {
cost,
prev_was_zero: abs == 0,
};
next_choice[out_ctx] = super::TrellisCell {
cost,
level: abs,
prev_ctx: in_ctx,
};
}
}
}
choice[k] = next_choice;
for (out_ctx, &cell) in next_choice.iter().enumerate() {
if cell.cost >= INF || cell.level == 0 {
continue;
}
let term_cost = if k + 1 < 16 {
cell.cost
+ lambda * super::eob_token_bits(coeff_probs, plane, k + 1, out_ctx)
+ suffix_zero_dist[k + 1]
} else {
cell.cost };
if term_cost < best_term_cost {
best_term_cost = term_cost;
best_term_pos = k as i32;
best_term_ctx = out_ctx;
}
}
surv = next;
}
let mut scan_levels = [0i32; 16];
if best_term_pos >= 0 {
let mut k = best_term_pos as usize;
let mut ctx = best_term_ctx;
loop {
let cell = choice[k][ctx];
let lvl = cell.level as i32;
let signed = if scan_x[k] < 0 { -lvl } else { lvl };
scan_levels[k] = signed;
if k == first_coeff {
break;
}
ctx = cell.prev_ctx;
k -= 1;
}
}
for v in block.iter_mut() {
*v = 0;
}
for (k, &lvl) in scan_levels.iter().enumerate() {
block[crate::dct_tokens::ZIGZAG[k]] = lvl as i16;
}
}
use crate::bool_decoder::BoolDecoder;
use crate::coded_header::Vp8CodedHeader;
use crate::decode_vp8;
use crate::frame_header::Vp8FrameHeader;
#[test]
fn level_rate_matches_coeff_token_bits() {
let probs = &crate::DEFAULT_COEFF_PROBS;
let tables = TrellisRateTables::for_probs(probs);
for plane in 0..4 {
for (i, &band) in COEFF_BANDS.iter().enumerate() {
for ctx3 in 0..3 {
for pwz in [false, true] {
for level in 0u32..=2114 {
let want = coeff_token_bits(probs, plane, i, ctx3, pwz, level as u16);
let got = TrellisRateTables::level_rate(
&tables.small[plane][band],
&tables.cat_path[plane][band],
ctx3,
pwz,
level,
);
assert_eq!(want.to_bits(), got.to_bits());
}
}
}
}
}
}
#[test]
fn write_bool_matches_bitwise_listing() {
fn write_bool_bitwise(enc: &mut BoolEncoder, prob: u8, value: bool) {
let split = 1 + (((enc.range - 1) * prob as u32) >> 8);
if value {
enc.bottom = enc.bottom.wrapping_add(split);
enc.range -= split;
} else {
enc.range = split;
}
while enc.range < 128 {
enc.range <<= 1;
if (enc.bottom >> 31) & 1 == 1 {
add_one_to_output(&mut enc.out);
}
enc.bottom <<= 1;
enc.bit_count -= 1;
if enc.bit_count == 0 {
enc.out.push((enc.bottom >> 24) as u8);
enc.bottom &= (1 << 24) - 1;
enc.bit_count = 8;
}
}
}
let mut lcg = 0x0BAD_5EEDu32;
let mut next = move || {
lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
lcg >> 8
};
for regime in 0..8 {
let mut fast = BoolEncoder::new();
let mut slow = BoolEncoder::new();
for n in 0..300_000u32 {
let r = next();
let (prob, value) = match regime {
0 => ((r & 0xFF) as u8, r & 0x100 != 0),
1 => (128, r & 1 != 0),
2 => (1, r & 0xFF00 != 0),
3 => (255, r & 0xFF00 == 0),
4 => (1, true),
5 => (255, n % 97 == 0),
6 => ((r & 0xFF) as u8, true),
_ => (2 + (r & 3) as u8, r & 0x700 != 0),
};
fast.write_bool(prob, value);
write_bool_bitwise(&mut slow, prob, value);
assert_eq!(
(fast.range, fast.bottom, fast.bit_count),
(slow.range, slow.bottom, slow.bit_count),
"regime {regime} symbol {n}"
);
}
assert_eq!(fast.out, slow.out, "regime {regime}");
assert_eq!(fast.finish(), slow.finish(), "regime {regime}");
}
}
#[test]
fn presummed_estimate_tracks_reference_estimate() {
let probs = &crate::DEFAULT_COEFF_PROBS;
let tables = TrellisRateTables::for_probs(probs);
let mut lcg = 0x0DDB_A11Du32;
let mut next = move || {
lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
(lcg >> 16) as i32
};
let mut worst = 0f64;
for case in 0..40_000 {
let mut coeffs = [0i16; 16];
for (k, c) in coeffs.iter_mut().enumerate() {
*c = match case % 4 {
0 => (next() % 3 - 1) as i16,
1 => ((next() % 9 == 0) as i32 * (next() % 41 - 20)) as i16,
2 => ((next() % 4229 - 2114) / (1 + k as i32)) as i16,
_ => (next() % 4229 - 2114) as i16,
};
}
for block_type in [
BlockType::Y2,
BlockType::YAfterY2,
BlockType::YNoY2,
BlockType::UV,
] {
let (above, left) = (case % 2 == 0, case % 3 == 0);
let reference = estimate_block_bits(block_type, probs, above, left, &coeffs);
let ranking =
estimate_block_bits_presummed(&tables, block_type, above, left, &coeffs);
worst = worst.max((reference - ranking).abs());
}
}
assert!(worst < 1e-9, "pre-summed estimate drifted by {worst} bits");
}
#[test]
fn decisive_minimum_takes_the_first_minimum_and_flags_close_calls() {
assert_eq!(decisive_minimum(&[5.0, 3.0, 9.0]), (1, true));
assert_eq!(decisive_minimum(&[3.0, 3.0, 9.0]), (0, false));
assert_eq!(
decisive_minimum(&[3.0 + RD_TIE_GUARD / 2.0, 3.0, 9.0]),
(1, false)
);
assert_eq!(
decisive_minimum(&[3.0 + RD_TIE_GUARD * 2.0, 3.0]),
(1, true)
);
assert_eq!(decisive_minimum(&[7.0]), (0, true));
}
#[test]
fn ranked_search_matches_reference_search() {
let (w, h) = (112usize, 80usize);
let mut lcg = 0x7E57_F00Du32;
let mut y = vec![0u8; w * h];
for row in 0..h {
for col in 0..w {
lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let grain = ((lcg >> 24) % 7) as i32 - 3;
let mut v = (col * 2 + row) as i32 % 256;
if (32..64).contains(&col) && (16..48).contains(&row) {
v = 90;
} else if col > 70 {
v = if (col / 6 + row / 9) % 2 == 0 {
40
} else {
210
} + grain;
} else if row > 56 {
v += grain * 6;
}
y[row * w + col] = v.clamp(0, 255) as u8;
}
}
let u: Vec<u8> = (0..(w / 2) * (h / 2))
.map(|i| (100 + (i % 37)) as u8)
.collect();
let v: Vec<u8> = (0..(w / 2) * (h / 2))
.map(|i| (150 - (i % 23)) as u8)
.collect();
let frame = I420Frame::packed(w as u32, h as u32, &y, &u, &v);
for qi in [0u8, 6, 20, 45, 90, 127] {
for strength in [0.0, 1.0, 3.0] {
let params = KeyframeParams::default()
.with_y_ac_qi(qi)
.with_trellis_strength(TrellisStrength::new(strength));
let ranked = encode_keyframe(&frame, ¶ms).unwrap();
FORCE_REFERENCE_SEARCH.with(|f| f.set(true));
let reference = encode_keyframe(&frame, ¶ms);
FORCE_REFERENCE_SEARCH.with(|f| f.set(false));
assert_eq!(ranked, reference.unwrap(), "qi {qi} strength {strength}");
}
}
}
#[test]
fn rounded_level_matches_division() {
for q in 1u32..1100 {
for magnitude in 0u32..=32768 {
let want = (magnitude + q / 2) / q;
assert_eq!(
rounded_level(magnitude, q),
want,
"magnitude {magnitude} q {q}"
);
}
}
}
#[test]
fn estimate_block_bits_tabled_matches_direct() {
let mut perturbed = crate::DEFAULT_COEFF_PROBS;
let mut st = 0x1357_9BDFu32;
for prob in perturbed.iter_mut().flatten().flatten().flatten() {
st = st.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
*prob = ((st >> 24) as u8).max(1);
}
let mut lcg = 0xDEAD_BEEFu32;
let mut next = move || {
lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
(lcg >> 16) as i32
};
let mut cases = 0usize;
for probs in [&crate::DEFAULT_COEFF_PROBS, &perturbed] {
let tables = TrellisRateTables::for_probs(probs);
for block_type in [
BlockType::Y2,
BlockType::YAfterY2,
BlockType::YNoY2,
BlockType::UV,
] {
for shape in 0..6 {
for _ in 0..200 {
let mut coeffs = [0i16; 16];
for (k, c) in coeffs.iter_mut().enumerate() {
let v = match shape {
0 => 0,
1 => (next() % 8 == 0) as i32 * (next() % 3 - 1),
2 => next() % 5 - 2,
3 => next() % 2 * 2 - 1,
4 => (next() % 4200 - 2100) / (1 + k as i32),
_ => (next() % 3 == 0) as i32 * (next() % 140 - 70),
};
*c = v as i16;
}
for above in [false, true] {
for left in [false, true] {
let want =
estimate_block_bits(block_type, probs, above, left, &coeffs);
let got = estimate_block_bits_tabled(
&tables, block_type, above, left, &coeffs,
);
assert_eq!(
want.to_bits(),
got.to_bits(),
"{block_type:?} above {above} left {left} {coeffs:?}"
);
cases += 1;
}
}
}
}
}
}
assert!(cases > 30_000);
}
#[test]
fn trellis_rate_tables_match_direct_calls() {
let mut perturbed = crate::DEFAULT_COEFF_PROBS;
let mut st = 0x1357_9BDFu32;
for plane in perturbed.iter_mut() {
for band in plane.iter_mut() {
for ctx in band.iter_mut() {
for prob in ctx.iter_mut() {
st = st.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
*prob = ((st >> 24) as u8).max(1);
}
}
}
}
for probs in [&crate::DEFAULT_COEFF_PROBS, &perturbed] {
let t = TrellisRateTables::for_probs(probs);
for plane in 0..4 {
for (i, &band) in COEFF_BANDS.iter().enumerate() {
for ctx3 in 0..3 {
assert_eq!(
t.eob[plane][band][ctx3].to_bits(),
eob_token_bits(probs, plane, i, ctx3).to_bits(),
"eob: plane {plane} pos {i} ctx {ctx3}"
);
for (pwz, small) in t.small[plane][band][ctx3].iter().enumerate() {
for abs in 0..=TRELLIS_SMALL_LEVEL_MAX {
assert_eq!(
small[abs as usize].to_bits(),
coeff_token_bits(probs, plane, i, ctx3, pwz == 1, abs)
.to_bits(),
"plane {plane} pos {i} ctx {ctx3} pwz {pwz} abs {abs}"
);
}
}
}
}
}
}
}
#[test]
fn trellis_lut_and_early_exit_match_reference() {
let mut perturbed = crate::DEFAULT_COEFF_PROBS;
let mut st = 0xA5A5_1234u32;
for plane in perturbed.iter_mut() {
for band in plane.iter_mut() {
for ctx in band.iter_mut() {
for prob in ctx.iter_mut() {
st = st.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
*prob = ((st >> 24) as u8).max(1);
}
}
}
}
let block_specs = [
(BlockType::Y2, 0usize),
(BlockType::YAfterY2, 0),
(BlockType::YNoY2, 1),
(BlockType::UV, 2),
];
let mut cases = 0usize;
for probs in [&crate::DEFAULT_COEFF_PROBS, &perturbed] {
let tables = TrellisRateTables::for_probs(probs);
for qi in [8i32, 40, 100] {
let factors =
crate::dequant::MbDequantFactors::from_base_and_deltas(qi, 0, 0, 0, 0, 0);
let base_lambda = rd_lambda(&factors) * TRELLIS_LAMBDA_SCALE;
for (block_type, entry_ctx3) in block_specs {
let (dc, ac) = match block_type {
BlockType::Y2 => (factors.y2_dc, factors.y2_ac),
BlockType::UV => (factors.uv_dc, factors.uv_ac),
_ => (factors.y1_dc, factors.y1_ac),
};
let spec = TrellisBlockSpec {
dc,
ac,
first_coeff: block_type.first_coeff(),
entry_ctx3,
plane: block_type.plane_index(),
};
for (scale, offset) in [
(1i32, 0i32),
(ac as i32, 0),
(ac as i32 * 3, 8),
(ac as i32 * 24, 64),
] {
for seed in 0u32..12 {
let mut lcg = 0xC0FF_EE00u32
.wrapping_add(seed)
.wrapping_mul(2_891_336_453);
let mut next = move || {
lcg = lcg.wrapping_mul(1_103_515_245).wrapping_add(12345);
(lcg >> 16) as i32
};
let mut base = [0i16; 16];
for (k, c) in base.iter_mut().enumerate() {
let mag = (next() % (scale + offset + 1)) / (1 + k as i32 / 4);
let sign = if next() % 2 == 0 { 1 } else { -1 };
*c = (sign * mag).clamp(-2048, 2047) as i16;
}
for lambda in [base_lambda * 0.25, base_lambda, base_lambda * 6.0] {
let mut want = base;
trellis_quantize_block_reference(&mut want, spec, probs, lambda);
let mut got_direct = base;
trellis_quantize_block(&mut got_direct, spec, probs, None, lambda);
let mut got_lut = base;
trellis_quantize_block(
&mut got_lut,
spec,
probs,
Some(&tables),
lambda,
);
assert_eq!(
want, got_direct,
"direct path drifted: qi {qi} type {block_type:?} scale {scale} seed {seed} lambda {lambda}"
);
assert_eq!(
want, got_lut,
"LUT path drifted: qi {qi} type {block_type:?} scale {scale} seed {seed} lambda {lambda}"
);
cases += 1;
}
}
}
}
}
}
assert!(cases >= 3000, "stress matrix shrank: {cases} cases");
}
#[derive(Debug, PartialEq, Eq)]
struct DecodedSegLayer {
feature_absolute: bool,
update_map: bool,
quant: [Option<i16>; 4],
lf: [Option<i16>; 4],
probs: [Option<u8>; 3],
}
fn read_update_segmentation_for_test(dec: &mut BoolDecoder<'_>) -> DecodedSegLayer {
let update_map = dec.read_bool(128).unwrap();
let update_feature = dec.read_bool(128).unwrap();
let mut feature_absolute = false;
let mut quant: [Option<i16>; 4] = [None; 4];
let mut lf: [Option<i16>; 4] = [None; 4];
if update_feature {
feature_absolute = dec.read_bool(128).unwrap();
for slot in &mut quant {
if dec.read_bool(128).unwrap() {
let mag = dec.read_literal(7).unwrap() as i16;
let sign = dec.read_bool(128).unwrap();
*slot = Some(if sign { -mag } else { mag });
}
}
for slot in &mut lf {
if dec.read_bool(128).unwrap() {
let mag = dec.read_literal(6).unwrap() as i16;
let sign = dec.read_bool(128).unwrap();
*slot = Some(if sign { -mag } else { mag });
}
}
}
let mut probs: [Option<u8>; 3] = [None; 3];
if update_map {
for slot in &mut probs {
if dec.read_bool(128).unwrap() {
*slot = Some(dec.read_literal(8).unwrap() as u8);
}
}
}
DecodedSegLayer {
feature_absolute,
update_map,
quant,
lf,
probs,
}
}
#[test]
fn update_segmentation_writer_round_trips_full_layer() {
let layer = UpdateSegmentationLayer {
update_mb_segmentation_map: true,
feature_mode_absolute: false,
quantizer: [Some(-12), None, Some(40), Some(-1)],
loop_filter: [None, Some(7), None, Some(-3)],
segment_prob: [Some(200), None, Some(31)],
};
let mut enc = BoolEncoder::new();
write_update_segmentation(&mut enc, &layer);
let buf = enc.finish();
let mut dec = BoolDecoder::init(&buf).unwrap();
assert!(dec.read_bool(128).unwrap());
let got = read_update_segmentation_for_test(&mut dec);
assert_eq!(got.feature_absolute, layer.feature_mode_absolute);
assert_eq!(got.update_map, layer.update_mb_segmentation_map);
assert_eq!(got.quant, layer.quantizer);
assert_eq!(got.lf, layer.loop_filter);
assert_eq!(got.probs, layer.segment_prob);
}
#[test]
fn update_segmentation_writer_absolute_no_map_update() {
let layer = UpdateSegmentationLayer {
update_mb_segmentation_map: false,
feature_mode_absolute: true,
quantizer: [Some(20), Some(35), Some(60), Some(90)],
loop_filter: [None; 4],
segment_prob: [None; 3],
};
let mut enc = BoolEncoder::new();
write_update_segmentation(&mut enc, &layer);
let buf = enc.finish();
let mut dec = BoolDecoder::init(&buf).unwrap();
assert!(dec.read_bool(128).unwrap());
let got = read_update_segmentation_for_test(&mut dec);
assert!(got.feature_absolute);
assert!(!got.update_map);
assert_eq!(got.quant, layer.quantizer);
assert_eq!(got.lf, [None; 4]);
assert_eq!(got.probs, [None; 3]);
}
#[test]
fn update_segmentation_writer_map_only_no_features() {
let layer = UpdateSegmentationLayer {
update_mb_segmentation_map: true,
feature_mode_absolute: false,
quantizer: [None; 4],
loop_filter: [None; 4],
segment_prob: [Some(255), Some(128), Some(1)],
};
let mut enc = BoolEncoder::new();
write_update_segmentation(&mut enc, &layer);
let buf = enc.finish();
let mut dec = BoolDecoder::init(&buf).unwrap();
assert!(dec.read_bool(128).unwrap());
let got = read_update_segmentation_for_test(&mut dec);
assert!(got.update_map);
assert_eq!(got.quant, [None; 4]);
assert_eq!(got.lf, [None; 4]);
assert_eq!(got.probs, layer.segment_prob);
}
#[test]
fn partition_group_table_matches_mv_partitions() {
use crate::near_mv::{MV_PARTITIONS, MvPartition, partition_id};
for (p, expected_groups) in [
(MvPartition::TopBottom, 2usize),
(MvPartition::LeftRight, 2),
(MvPartition::Quarters, 4),
(MvPartition::Mv16, 16),
] {
let groups = partition_groups(p);
assert_eq!(groups.num_groups, expected_groups, "{p:?} group count");
let table = &MV_PARTITIONS[partition_id(p)];
let mut seen = [false; 16];
for g in 0..groups.num_groups {
let members = groups.group(g);
assert!(!members.is_empty(), "{p:?} group {g} empty");
let mut prev: Option<usize> = None;
for &b in members {
assert_eq!(
table[b] as usize, g,
"{p:?} sub-block {b} listed under group {g}"
);
assert!(!seen[b], "{p:?} sub-block {b} listed twice");
seen[b] = true;
if let Some(prev) = prev {
assert!(prev < b, "{p:?} group {g} not raster-ascending");
}
prev = Some(b);
}
}
assert!(seen.iter().all(|&s| s), "{p:?} does not cover all 16");
}
}
#[test]
fn group_sad_fused_fast_path_matches_per_subblock_fetch() {
use crate::motion_vector::Mv;
use crate::near_mv::MvPartition;
let width = 48usize;
let height = 48usize;
let mut plane = vec![0u8; width * height];
for y in 0..height {
for x in 0..width {
plane[y * width + x] = ((x * 11 + y * 17) % 251) as u8;
}
}
let luma = crate::motion_search::LumaRef {
plane: &plane,
stride: width,
width,
height,
};
let mut src_y = [0u8; 256];
for (i, slot) in src_y.iter_mut().enumerate() {
*slot = ((i * 3 + 41) % 249) as u8;
}
let per_subblock_reference =
|mb_col: usize, mb_row: usize, group_subblocks: &[usize], mv: Mv| -> u32 {
let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
let mut sad: u32 = 0;
for &b in group_subblocks {
let patch = crate::motion_comp::fetch_block_whole_pixel(
luma.plane,
luma.stride,
luma.width,
luma.height,
mb_col * 16 + (b & 3) * 4,
mb_row * 16 + (b >> 2) * 4,
mv_eighth,
);
let src_sb = extract_src_subblock_4x4(&src_y, b);
sad += sub_block_sad_4x4(&src_sb, &patch);
}
sad
};
let candidates: [Mv; 11] = [
Mv { row: 0, col: 0 },
Mv { row: 4, col: -4 },
Mv { row: -8, col: 12 },
Mv { row: 16, col: 16 },
Mv { row: -16, col: -16 },
Mv { row: 64, col: -64 },
Mv { row: -1020, col: 0 },
Mv { row: 0, col: -1020 },
Mv { row: 1020, col: 0 },
Mv { row: 0, col: 1020 },
Mv {
row: -1020,
col: 1020,
},
];
for p in [
MvPartition::TopBottom,
MvPartition::LeftRight,
MvPartition::Quarters,
MvPartition::Mv16,
] {
let groups = partition_groups(p);
for (mb_col, mb_row) in [(0usize, 0usize), (1, 1), (2, 2)] {
for g in 0..groups.num_groups {
let members = groups.group(g);
for mv in candidates {
let expected = per_subblock_reference(mb_col, mb_row, members, mv);
let got = group_sad_at_whole_mv(luma, mb_col, mb_row, &src_y, members, mv);
assert_eq!(
got, expected,
"fused group SAD diverged: {p:?} group {g} \
MB({mb_col},{mb_row}) mv={mv:?}"
);
}
}
}
}
}
#[test]
fn partition_group_shapes_are_exact_rectangles() {
use crate::near_mv::MvPartition;
for p in [
MvPartition::TopBottom,
MvPartition::LeftRight,
MvPartition::Quarters,
MvPartition::Mv16,
] {
let groups = partition_groups(p);
for g in 0..groups.num_groups {
let shape = groups.shape(g);
let members = groups.group(g);
assert_eq!(
members.len() * 16,
shape.w_px * shape.h_px,
"{p:?} group {g}: members must tile the shape"
);
for &b in members {
let (r0, c0) = ((b >> 2) * 4, (b & 3) * 4);
assert!(
r0 >= shape.row0
&& r0 + 4 <= shape.row0 + shape.h_px
&& c0 >= shape.col0
&& c0 + 4 <= shape.col0 + shape.w_px,
"{p:?} group {g}: member {b} outside shape {shape:?}"
);
}
}
}
}
#[test]
fn group_sad_shaped_matches_per_subblock_fetch() {
use crate::motion_vector::Mv;
use crate::near_mv::MvPartition;
let width = 48usize;
let height = 48usize;
let mut plane = vec![0u8; width * height];
for y in 0..height {
for x in 0..width {
plane[y * width + x] = ((x * 11 + y * 17) % 251) as u8;
}
}
let luma = crate::motion_search::LumaRef {
plane: &plane,
stride: width,
width,
height,
};
let mut src_y = [0u8; 256];
for (i, slot) in src_y.iter_mut().enumerate() {
*slot = ((i * 3 + 41) % 249) as u8;
}
let per_subblock_reference =
|mb_col: usize, mb_row: usize, group_subblocks: &[usize], mv: Mv| -> u32 {
let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
let mut sad: u32 = 0;
for &b in group_subblocks {
let patch = crate::motion_comp::fetch_block_whole_pixel(
luma.plane,
luma.stride,
luma.width,
luma.height,
mb_col * 16 + (b & 3) * 4,
mb_row * 16 + (b >> 2) * 4,
mv_eighth,
);
let src_sb = extract_src_subblock_4x4(&src_y, b);
sad += sub_block_sad_4x4(&src_sb, &patch);
}
sad
};
let candidates: [Mv; 9] = [
Mv { row: 0, col: 0 },
Mv { row: 4, col: -4 },
Mv { row: -8, col: 12 },
Mv { row: 16, col: 16 },
Mv { row: -16, col: -16 },
Mv { row: 64, col: -64 },
Mv { row: -1020, col: 0 },
Mv { row: 0, col: 1020 },
Mv {
row: -1020,
col: 1020,
},
];
for p in [
MvPartition::TopBottom,
MvPartition::LeftRight,
MvPartition::Quarters,
MvPartition::Mv16,
] {
let groups = partition_groups(p);
for (mb_col, mb_row) in [(0usize, 0usize), (1, 1), (2, 2)] {
for g in 0..groups.num_groups {
let members = groups.group(g);
let shape = groups.shape(g);
for mv in candidates {
let expected = per_subblock_reference(mb_col, mb_row, members, mv);
let got = group_sad_at_whole_mv_shaped(
luma, mb_col, mb_row, &src_y, members, shape, mv,
);
assert_eq!(got, expected, "{p:?} group {g} mv {mv:?}");
}
}
}
}
}
#[test]
fn token_bit_path_table_matches_tree_descent() {
fn reference_descent(i: i8, target: i8, path: &mut Vec<(usize, bool)>) -> bool {
for &bit in &[false, true] {
let child = ENC_COEFF_TREE[i as usize + bit as usize];
if child <= 0 {
if -child == target {
path.push(((i as usize) >> 1, bit));
return true;
}
} else {
path.push(((i as usize) >> 1, bit));
if reference_descent(child, target, path) {
return true;
}
path.pop();
}
}
false
}
let tokens = [
DctToken::Dct0,
DctToken::Dct1,
DctToken::Dct2,
DctToken::Dct3,
DctToken::Dct4,
DctToken::Cat1,
DctToken::Cat2,
DctToken::Cat3,
DctToken::Cat4,
DctToken::Cat5,
DctToken::Cat6,
DctToken::Eob,
];
for &start in &[0i8, 2i8] {
for &token in &tokens {
let mut reference = Vec::new();
let reachable = reference_descent(start, token as i8, &mut reference);
if !reachable {
assert_eq!(
(start, token),
(2i8, DctToken::Eob),
"unexpected unreachable (start, token) = ({start}, {token:?})"
);
let slot = 1usize;
let (_, len) = &TOKEN_BIT_PATHS[slot][token as usize];
assert_eq!(*len, 0, "(start=2, Eob) must remain a length-0 tombstone");
continue;
}
let table = token_to_bit_path(token, start);
assert_eq!(
table.len(),
reference.len(),
"path-length mismatch for (start={start}, token={token:?})"
);
for (k, &(ref_i, ref_bit)) in reference.iter().enumerate() {
assert_eq!(
table[k].prob_index as usize, ref_i,
"prob_index mismatch at step {k} of (start={start}, token={token:?})"
);
assert_eq!(
table[k].bit, ref_bit,
"bit mismatch at step {k} of (start={start}, token={token:?})"
);
}
}
}
const { assert!(TOKEN_BIT_PATH_MAX_LEN >= 7) };
for (slot, paths) in TOKEN_BIT_PATHS.iter().enumerate() {
for (token, (_, len)) in paths.iter().enumerate() {
assert!(
(*len as usize) <= TOKEN_BIT_PATH_MAX_LEN,
"path length {} > buffer capacity {} at slot={slot} token={token}",
*len,
TOKEN_BIT_PATH_MAX_LEN
);
}
}
}
#[test]
fn coeff_update_probs_flat_walk_is_consistent() {
let s: u32 = COEFF_UPDATE_PROBS_FLAT.iter().map(|&p| p as u32).sum();
assert!(s > 0);
assert_eq!(
COEFF_UPDATE_PROBS_FLAT[3 * 8 * 3 * 11 + 7 * 3 * 11 + 2 * 11 + 10],
COEFF_UPDATE_PROBS[3][7][2][10]
);
}
#[test]
fn write_no_token_prob_updates_matches_all_none_against_spec_flag_probs() {
let no_updates: crate::coded_header::TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
let mut a = BoolEncoder::new();
write_no_token_prob_updates(&mut a, &COEFF_UPDATE_PROBS_FLAT);
let bytes_a = a.finish();
let mut b = BoolEncoder::new();
write_token_prob_updates(&mut b, &no_updates, &COEFF_UPDATE_PROBS_FLAT);
let bytes_b = b.finish();
assert_eq!(
bytes_a, bytes_b,
"writers must agree on the all-None §13.4 payload under \
the real coeff_update_probs[4][8][3][11] table — any \
divergence here means the §13.4 four-nested walk order \
or the per-position probability lookup has drifted \
between the two writers."
);
assert!(
!bytes_a.is_empty(),
"all-None §13.4 payload must still emit at least one byte"
);
}
#[test]
fn mv_update_probs_flat_matches_spec_table() {
use crate::coded_header::{MV_PROB_COUNT, MV_UPDATE_PROBS};
assert_eq!(
MV_UPDATE_PROBS_FLAT.len(),
2 * MV_PROB_COUNT,
"MV_UPDATE_PROBS_FLAT length must match 2 × MV_PROB_COUNT \
(RFC 6386 §17.2 two MV_CONTEXTs × 19 positions)"
);
for i in 0..2 {
for j in 0..MV_PROB_COUNT {
let flat = MV_UPDATE_PROBS_FLAT[i * MV_PROB_COUNT + j];
let spec = MV_UPDATE_PROBS[i][j];
assert_eq!(
flat, spec,
"encoder-side MV_UPDATE_PROBS_FLAT[{i}*{MV_PROB_COUNT}+{j}] \
({flat}) diverges from the §17.2 spec table \
MV_UPDATE_PROBS[{i}][{j}] ({spec}) the decoder reads at"
);
}
}
}
#[test]
fn enc_pcat_and_cat_base_match_spec_listing() {
const SPEC_PCAT1: &[u8] = &[159];
const SPEC_PCAT2: &[u8] = &[165, 145];
const SPEC_PCAT3: &[u8] = &[173, 148, 140];
const SPEC_PCAT4: &[u8] = &[176, 155, 140, 135];
const SPEC_PCAT5: &[u8] = &[180, 157, 141, 134, 130];
const SPEC_PCAT6: &[u8] = &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
const SPEC_CAT_BASE: [u16; 6] = [5, 7, 11, 19, 35, 67];
let enc_lists: [(&[u8], &[u8], &str, usize); 6] = [
(ENC_PCAT1, SPEC_PCAT1, "Pcat1", 1),
(ENC_PCAT2, SPEC_PCAT2, "Pcat2", 2),
(ENC_PCAT3, SPEC_PCAT3, "Pcat3", 3),
(ENC_PCAT4, SPEC_PCAT4, "Pcat4", 4),
(ENC_PCAT5, SPEC_PCAT5, "Pcat5", 5),
(ENC_PCAT6, SPEC_PCAT6, "Pcat6", 11),
];
for (enc_list, spec_list, name, expected_len) in enc_lists.iter() {
assert_eq!(
enc_list.len(),
*expected_len,
"encoder-side {name} carries {} probs but §13.2 \
emits exactly {expected_len} extra bits",
enc_list.len()
);
assert_eq!(
enc_list.len(),
spec_list.len(),
"encoder-side {name} length ({}) diverges from §13.2 \
spec list length ({})",
enc_list.len(),
spec_list.len()
);
for (k, (&enc_p, &spec_p)) in enc_list.iter().zip(spec_list.iter()).enumerate() {
assert_eq!(
enc_p, spec_p,
"encoder-side {name}[{k}] ({enc_p}) diverges from \
§13.2 spec listing {name}[{k}] ({spec_p}) — the \
decoder's DCTextra() reads each cat-residual bit \
at this probability"
);
}
}
assert_eq!(
ENC_CAT_BASE.len(),
SPEC_CAT_BASE.len(),
"encoder-side ENC_CAT_BASE length ({}) diverges from \
§13.2 categoryBase[6] ({})",
ENC_CAT_BASE.len(),
SPEC_CAT_BASE.len()
);
for k in 0..ENC_CAT_BASE.len() {
assert_eq!(
ENC_CAT_BASE[k],
SPEC_CAT_BASE[k],
"encoder-side ENC_CAT_BASE[{k}] ({}) diverges from \
§13.2 spec categoryBase[{k}] ({}) — the decoder adds \
this offset to the cat{}-residual",
ENC_CAT_BASE[k],
SPEC_CAT_BASE[k],
k + 1
);
}
let cat_token_pairs: [(DctToken, usize, usize); 6] = [
(DctToken::Cat1, 0, 1),
(DctToken::Cat2, 1, 2),
(DctToken::Cat3, 2, 3),
(DctToken::Cat4, 3, 4),
(DctToken::Cat5, 4, 5),
(DctToken::Cat6, 5, 11),
];
for (tok, expected_idx, expected_bits) in cat_token_pairs.iter() {
let (base, list) = cat_extras(*tok).expect("cat-token must carry extras");
assert_eq!(
base, ENC_CAT_BASE[*expected_idx],
"cat_extras({tok:?}) returned base {base} but \
§13.2 categoryBase[{expected_idx}] is {}",
ENC_CAT_BASE[*expected_idx]
);
assert_eq!(
list.len(),
*expected_bits,
"cat_extras({tok:?}) returned a Pcat list of len {} \
but §13.2 emits exactly {expected_bits} extra bits",
list.len()
);
}
for tok in [
DctToken::Eob,
DctToken::Dct0,
DctToken::Dct1,
DctToken::Dct2,
DctToken::Dct3,
DctToken::Dct4,
] {
assert!(
cat_extras(tok).is_none(),
"cat_extras({tok:?}) must be None — §13.2 reserves \
the trailing `DCTextra` walk for cat1..cat6 only"
);
}
}
#[test]
fn mode_layer_roundtrips_through_decoder_parser() {
let (w, h) = (32u32, 32u32);
let cw = w.div_ceil(2) as usize;
let ch = h.div_ceil(2) as usize;
let mut y = vec![0u8; (w * h) as usize];
for r in 0..h as usize {
for c in 0..w as usize {
y[r * w as usize + c] = ((r * 8 + c * 8) & 0xff) as u8;
}
}
let u = vec![110u8; cw * ch];
let v = vec![140u8; cw * ch];
let frame = I420Frame::packed(w, h, &y, &u, &v);
let params = KeyframeParams {
y_ac_qi: 32,
loop_filter_level: 0,
sharpness_level: 0,
nbr_of_dct_partitions: 1,
filter_type: false,
trellis_strength: TrellisStrength::DEFAULT,
};
let bytes = encode_keyframe(&frame, ¶ms).expect("encode");
let header = Vp8FrameHeader::parse(&bytes).unwrap();
let off = header.header_bytes_consumed;
let size = header.first_partition_size as usize;
let first = &bytes[off..off + size];
let (coded, mut dec) = Vp8CodedHeader::parse_with_decoder(first, true).unwrap();
let parsed =
crate::macroblock::parse_key_frame_macroblock_modes(&mut dec, &coded, 2, 2).unwrap();
assert_eq!(parsed.len(), 4);
for mb in &parsed {
assert_eq!(
mb.subblock_modes.is_some(),
mb.y_mode == IntraYMode::B,
"subblock_modes presence must track B_PRED"
);
}
let decoded = decode_vp8(&bytes).expect("decode");
assert_eq!(decoded.width, w);
assert_eq!(decoded.height, h);
}
fn natural_test_frame_64x64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
let (w, h) = (64usize, 64usize);
let (cw, ch) = (32usize, 32usize);
let mut y = vec![0u8; w * h];
let mut state: u32 = 0x1234_5678;
let mut next = || {
state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
(state >> 16) & 0x1f
};
for r in 0..h {
for c in 0..w {
let base = 40 + (r + c) * 2;
let tex = next() as usize;
y[r * w + c] = (base + tex).min(235) as u8;
}
}
let mut u = vec![0u8; cw * ch];
let mut v = vec![0u8; cw * ch];
for r in 0..ch {
for c in 0..cw {
u[r * cw + c] = (100 + r) as u8;
v[r * cw + c] = (150 - c) as u8;
}
}
(y, u, v)
}
fn keyframe_luma_psnr(bytes: &[u8], src_y: &[u8], w: usize, h: usize) -> f64 {
let decoded = decode_vp8(bytes).expect("decode");
psnr(&src_y[..w * h], &decoded.y[..w * h])
}
#[test]
fn rd_keyframe_holds_psnr_floor_on_natural_frame() {
let (w, h) = (64u32, 64u32);
let (y, u, v) = natural_test_frame_64x64();
let frame = I420Frame::packed(w, h, &y, &u, &v);
for qi in [16u8, 32, 48] {
let params = KeyframeParams {
y_ac_qi: qi,
loop_filter_level: 0,
sharpness_level: 0,
nbr_of_dct_partitions: 1,
filter_type: false,
trellis_strength: TrellisStrength::DEFAULT,
};
let bytes = encode_keyframe(&frame, ¶ms).expect("encode");
let p = keyframe_luma_psnr(&bytes, &y, w as usize, h as usize);
assert!(
p >= 30.0,
"RD keyframe luma PSNR {p:.2} dB < 30 dB floor at qi={qi}"
);
}
}
#[test]
fn trellis_basis_norm_distortion_tracks_pixel_ssd() {
let norms = &*super::IDCT_BASIS_NORM_SQ;
for &n in norms.iter() {
assert!((0.24..0.26).contains(&n), "basis norm {n} out of range");
}
for seed in 0u32..8 {
let mut st = 0x1357u32.wrapping_add(seed.wrapping_mul(0x9E3D));
let mut next = || {
st = st.wrapping_mul(1_103_515_245).wrapping_add(12345);
(st >> 16) as i32
};
let pred = [128u8; 16];
let mut src = [0u8; 16];
for s in src.iter_mut() {
*s = (128 + (next() % 60) - 30).clamp(0, 255) as u8;
}
let mut residual = [0i16; 16];
for k in 0..16 {
residual[k] = src[k] as i16 - pred[k] as i16;
}
let mut coeffs = [0i16; 16];
super::forward_dct_4x4(&residual, &mut coeffs);
let (dc, ac) = (16i16, 18i16);
let mut q = coeffs;
super::enc_quantize_block(&mut q, dc, ac);
let recon = super::reconstruct_block_4x4(&pred, &q, dc, ac);
let actual = super::block_ssd(&recon, &src) as f64;
let scan_x = super::raster_to_scan(&coeffs);
let scan_q = super::raster_to_scan(&q);
let mut model = 0.0f64;
for k in 0..16 {
let step = if k == 0 { dc } else { ac } as i64;
let err = (scan_x[k] as i64).abs() - (scan_q[k] as i64).abs() * step;
model += norms[k] * (err * err) as f64;
}
let tol = (actual * 0.25).max(8.0);
assert!(
(model - actual).abs() <= tol,
"seed {seed}: model SSD {model:.1} vs actual {actual:.1} (tol {tol:.1})"
);
}
}
#[test]
fn trellis_round_trips_and_never_raises_rd_cost() {
let probs = crate::DEFAULT_COEFF_PROBS;
let factors = crate::dequant::MbDequantFactors::from_base_and_deltas(40, 0, 0, 0, 0, 0);
let lambda = super::rd_lambda(&factors) * super::TRELLIS_LAMBDA_SCALE;
let (dc, ac) = (factors.uv_dc, factors.uv_ac);
for seed in 0u32..32 {
let mut st = 0xBEEFu32.wrapping_add(seed.wrapping_mul(0x9E3D));
let mut next = || {
st = st.wrapping_mul(1_103_515_245).wrapping_add(12345);
(st >> 15) as i32
};
let pred = [128u8; 16];
let mut src = [0u8; 16];
for s in src.iter_mut() {
*s = (128 + (next() % 90) - 45).clamp(0, 255) as u8;
}
let mut residual = [0i16; 16];
for k in 0..16 {
residual[k] = src[k] as i16 - pred[k] as i16;
}
let mut base = [0i16; 16];
super::forward_dct_4x4(&residual, &mut base);
let norms = &*super::IDCT_BASIS_NORM_SQ;
let cost = |quant: &[i16; 16]| -> f64 {
let scan_q = super::raster_to_scan(quant);
let scan_x = super::raster_to_scan(&base);
let mut d = 0.0f64;
for k in 0..16 {
let step = if k == 0 { dc } else { ac } as i64;
let err = (scan_x[k] as i64).abs() - (scan_q[k] as i64).abs() * step;
d += norms[k] * (err * err) as f64;
}
let r = super::estimate_block_bits(BlockType::UV, &probs, false, false, &scan_q);
d + lambda * r
};
let mut plain = base;
super::enc_quantize_block(&mut plain, dc, ac);
let mut trel = base;
super::trellis_quantize_block(
&mut trel,
super::TrellisBlockSpec {
dc,
ac,
first_coeff: BlockType::UV.first_coeff(),
entry_ctx3: 0,
plane: BlockType::UV.plane_index(),
},
&probs,
None,
lambda,
);
let (cp, ct) = (cost(&plain), cost(&trel));
assert!(
ct <= cp + 1e-6,
"seed {seed}: trellis J {ct:.2} > plain J {cp:.2}"
);
let scan = super::raster_to_scan(&trel);
let recovered = encode_then_decode_block(BlockType::UV, &scan, false, false);
assert_eq!(
recovered, scan,
"seed {seed}: trellis block did not round-trip through §13.3"
);
}
}
#[test]
fn rd_beats_sad_baseline_size_and_quality() {
let sad_baseline: [(u8, usize, f64); 5] = [
(16, 1467, 39.293),
(24, 1192, 36.777),
(32, 1003, 34.561),
(48, 731, 31.742),
(64, 383, 29.921),
];
let (w, h) = (64u32, 64u32);
let (y, u, v) = natural_test_frame_64x64();
let frame = I420Frame::packed(w, h, &y, &u, &v);
for (qi, sad_bytes, sad_psnr) in sad_baseline {
let params = KeyframeParams {
y_ac_qi: qi,
loop_filter_level: 0,
sharpness_level: 0,
nbr_of_dct_partitions: 1,
filter_type: false,
trellis_strength: TrellisStrength::DEFAULT,
};
let bytes = encode_keyframe(&frame, ¶ms).expect("encode");
let p = keyframe_luma_psnr(&bytes, &y, w as usize, h as usize);
assert!(
bytes.len() <= sad_bytes,
"RD stream at qi={qi} ({} B) must not exceed the SAD baseline ({sad_bytes} B)",
bytes.len()
);
assert!(
p >= sad_psnr - 0.05,
"RD PSNR at qi={qi} ({p:.3} dB) must hold the SAD baseline ({sad_psnr:.3} dB)"
);
}
}
#[test]
fn trellis_strength_knob_is_monotone_and_round_trips() {
let (w, h) = (64u32, 64u32);
let (y, u, v) = natural_test_frame_64x64();
let frame = I420Frame::packed(w, h, &y, &u, &v);
for qi in [16u8, 24, 32, 48, 64] {
let mk = |s: TrellisStrength| KeyframeParams {
y_ac_qi: qi,
loop_filter_level: 0,
sharpness_level: 0,
nbr_of_dct_partitions: 1,
filter_type: false,
trellis_strength: s,
};
let off = encode_keyframe(&frame, &mk(TrellisStrength::OFF)).expect("off");
let def = encode_keyframe(&frame, &mk(TrellisStrength::DEFAULT)).expect("default");
let hot = encode_keyframe(&frame, &mk(TrellisStrength::new(4.0))).expect("hot");
assert!(
def.len() <= off.len(),
"qi={qi}: DEFAULT trellis ({} B) must not exceed OFF ({} B)",
def.len(),
off.len()
);
assert!(
hot.len() <= def.len(),
"qi={qi}: strength 4.0 ({} B) must not exceed DEFAULT ({} B)",
hot.len(),
def.len()
);
for bytes in [&off, &def, &hot] {
let dec = crate::decode_vp8(bytes).expect("decode at this strength");
assert_eq!(dec.y.len(), w as usize * h as usize);
}
if qi <= 48 {
assert!(
hot.len() < off.len(),
"qi={qi}: strength 4.0 ({} B) should beat OFF ({} B)",
hot.len(),
off.len()
);
}
}
assert_eq!(TrellisStrength::new(-1.0).get(), 0.0);
assert_eq!(TrellisStrength::new(1000.0).get(), TrellisStrength::MAX);
assert_eq!(TrellisStrength::new(f64::NAN), TrellisStrength::DEFAULT);
}
#[test]
fn quality_to_trellis_strength_ramps_monotonically() {
assert_eq!(quality_to_trellis_strength(100.0), TrellisStrength::DEFAULT);
assert_eq!(quality_to_trellis_strength(90.0), TrellisStrength::DEFAULT);
assert_eq!(quality_to_trellis_strength(150.0), TrellisStrength::DEFAULT);
assert!((quality_to_trellis_strength(0.0).get() - 4.0).abs() < 1e-6);
assert_eq!(
quality_to_trellis_strength(f32::NAN),
TrellisStrength::DEFAULT
);
let mut prev = 0.0f64;
for q in (0..=100).rev() {
let s = quality_to_trellis_strength(q as f32).get();
assert!(
s >= prev - 1e-9,
"strength must not fall as quality falls (q={q}: {s} < {prev})"
);
prev = s;
}
}
#[test]
fn bool_encoder_decoder_round_trip_pseudo_random_sequence() {
let mut state: u32 = 0xCAFE_F00D;
let mut next = || {
state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
state
};
let mut bools: Vec<(u8, bool)> = Vec::with_capacity(1024);
for _ in 0..1024 {
let p = ((next() >> 16) as u8).max(1);
let v = (next() & 1) != 0;
bools.push((p, v));
}
let mut enc = BoolEncoder::new();
for (p, v) in &bools {
enc.write_bool(*p, *v);
}
let bytes = enc.finish();
assert!(bytes.len() >= 4);
let mut dec = BoolDecoder::init(&bytes).expect("encoder always emits ≥ 2 bytes");
for (p, v) in &bools {
assert_eq!(dec.read_bool(*p).expect("partition underrun"), *v);
}
}
#[test]
fn write_literal_round_trips_through_read_literal() {
let mut enc = BoolEncoder::new();
enc.write_literal(0xA5, 8);
enc.write_literal(42, 6);
enc.write_signed_literal(-5, 4);
enc.write_signed_literal(7, 4);
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).unwrap();
assert_eq!(dec.read_literal(8).unwrap(), 0xA5);
assert_eq!(dec.read_literal(6).unwrap(), 42);
assert_eq!(dec.read_literal(4).unwrap(), 5);
assert!(dec.read_bool(128).unwrap()); assert_eq!(dec.read_literal(4).unwrap(), 7);
assert!(!dec.read_bool(128).unwrap());
}
#[test]
fn frame_tag_round_trips_through_parser_key_frame() {
let mut buf: Vec<u8> = Vec::new();
let bytes_written = write_frame_tag(
&mut buf,
true, 0, true, 0x1_2345, 640,
480,
ScaleCode::None,
ScaleCode::None,
)
.unwrap();
assert_eq!(bytes_written, 10);
assert_eq!(buf.len(), 10);
assert_eq!(&buf[3..6], &KEY_FRAME_START_CODE);
let hdr = Vp8FrameHeader::parse(&buf).unwrap();
assert!(hdr.key_frame);
assert_eq!(hdr.version, 0);
assert!(hdr.show_frame);
assert_eq!(hdr.first_partition_size, 0x1_2345);
assert_eq!(hdr.width, Some(640));
assert_eq!(hdr.height, Some(480));
}
#[test]
fn patch_first_partition_size_preserves_neighbouring_bits() {
let mut buf: Vec<u8> = Vec::new();
write_frame_tag(
&mut buf,
true,
5, true, 0, 16,
16,
ScaleCode::None,
ScaleCode::None,
)
.unwrap();
patch_first_partition_size(&mut buf[..3], 1234).unwrap();
let hdr = Vp8FrameHeader::parse(&buf).unwrap();
assert_eq!(hdr.version, 5);
assert!(hdr.show_frame);
assert!(hdr.key_frame);
assert_eq!(hdr.first_partition_size, 1234);
}
#[test]
fn set_show_frame_bit_flips_only_bit_4() {
let mut buf: Vec<u8> = Vec::new();
write_frame_tag(
&mut buf,
false, 3, true, 0x5_4321,
16,
16,
ScaleCode::None,
ScaleCode::None,
)
.unwrap();
buf.extend_from_slice(&[0xAA, 0x55, 0xF0]); let visible = buf.clone();
set_show_frame_bit(&mut buf, false);
let hdr = Vp8FrameHeader::parse(&buf).unwrap();
assert!(!hdr.key_frame);
assert_eq!(hdr.version, 3);
assert!(!hdr.show_frame);
assert_eq!(hdr.first_partition_size, 0x5_4321);
assert_eq!(buf[0] ^ visible[0], 0x10);
assert_eq!(&buf[1..], &visible[1..]);
set_show_frame_bit(&mut buf, true);
assert_eq!(buf, visible);
}
#[test]
fn rejects_oversize_dimensions() {
let mut buf = Vec::new();
let err = write_frame_tag(
&mut buf,
true,
0,
true,
0,
0x4000, 16,
ScaleCode::None,
ScaleCode::None,
)
.unwrap_err();
assert!(matches!(err, EncodeError::InvalidDimensions { .. }));
}
#[test]
fn rejects_out_of_range_loop_filter_inputs() {
let mut enc = BoolEncoder::new();
assert!(matches!(
write_loop_filter(&mut enc, false, 64, 0, false),
Err(EncodeError::LoopFilterLevelOutOfRange { value: 64 })
));
let mut enc = BoolEncoder::new();
assert!(matches!(
write_loop_filter(&mut enc, false, 0, 8, false),
Err(EncodeError::SharpnessLevelOutOfRange { value: 8 })
));
}
#[test]
fn rejects_illegal_partition_count() {
let mut enc = BoolEncoder::new();
assert!(matches!(
write_token_partition_count(&mut enc, 3),
Err(EncodeError::InvalidDctPartitionCount { value: 3 })
));
}
#[test]
fn rejects_oversize_quant_index() {
let mut enc = BoolEncoder::new();
assert!(matches!(
write_quant_indices(&mut enc, 128, None, None, None, None, None),
Err(EncodeError::QuantIndexOutOfRange { value: 128 })
));
}
#[test]
fn silent_keyframe_16x16_round_trips_through_own_decoder() {
let bytes = encode_silent_keyframe(SilentKeyframeParams::new(16, 16))
.expect("encoder should produce a valid frame");
let decoded = decode_vp8(&bytes).expect("own decoder must accept emitted frame");
assert_eq!(decoded.width, 16);
assert_eq!(decoded.height, 16);
assert_eq!(decoded.y.len(), 16 * 16);
assert_eq!(decoded.u.len(), 8 * 8);
assert_eq!(decoded.v.len(), 8 * 8);
}
#[test]
fn silent_keyframe_first_partition_round_trips_through_coded_header_parser() {
let bytes = encode_silent_keyframe(SilentKeyframeParams::new(64, 64)).unwrap();
let hdr = Vp8FrameHeader::parse(&bytes).unwrap();
let off = hdr.header_bytes_consumed;
let sz = hdr.first_partition_size as usize;
let partition = &bytes[off..off + sz];
let coded = Vp8CodedHeader::parse(partition, true).unwrap();
assert_eq!(coded.color_space, Some(false));
assert_eq!(coded.clamping_type, Some(false));
assert!(!coded.segmentation_enabled);
assert!(!coded.filter_type);
assert_eq!(coded.loop_filter_level, 0);
assert_eq!(coded.sharpness_level, 0);
assert!(!coded.mb_lf_adjustments.loop_filter_adj_enable);
assert_eq!(coded.log2_nbr_of_dct_partitions, 0);
assert_eq!(coded.nbr_of_dct_partitions, 1);
assert_eq!(coded.quant_indices.y_ac_qi, 0);
assert_eq!(coded.quant_indices.y_dc_delta, None);
assert!(coded.refresh_entropy_probs);
assert!(coded.mb_no_skip_coeff);
assert_eq!(coded.prob_skip_false, Some(1));
}
#[test]
fn silent_keyframe_round_trips_at_all_partition_counts() {
for &count in &[1u8, 2, 4, 8] {
let mut params = SilentKeyframeParams::new(64, 64);
params.nbr_of_dct_partitions = count;
let bytes = encode_silent_keyframe(params)
.unwrap_or_else(|e| panic!("encoder failed at count={count}: {e}"));
let decoded = decode_vp8(&bytes)
.unwrap_or_else(|e| panic!("decoder failed at count={count}: {e}"));
assert_eq!(decoded.width, 64);
assert_eq!(decoded.height, 64);
}
}
#[test]
fn silent_keyframe_non_square_dimensions_round_trip() {
let cases = [(16u32, 16u32), (32, 32), (48, 16), (16, 48), (32, 24)];
for (w, h) in cases {
let bytes = encode_silent_keyframe(SilentKeyframeParams::new(w, h))
.unwrap_or_else(|e| panic!("encoder failed at {w}x{h}: {e}"));
let decoded =
decode_vp8(&bytes).unwrap_or_else(|e| panic!("decoder failed at {w}x{h}: {e}"));
assert_eq!(decoded.width, w);
assert_eq!(decoded.height, h);
}
}
#[test]
fn make_silent_keyframe_encoder_produces_same_bytes_as_top_level_function() {
let enc = make_silent_keyframe_encoder();
let from_factory = enc.encode_keyframe(&[], 32, 32).unwrap();
let from_direct = encode_silent_keyframe(SilentKeyframeParams::new(32, 32)).unwrap();
assert_eq!(from_factory, from_direct);
}
#[test]
fn silent_keyframe_size_is_small() {
let bytes = encode_silent_keyframe(SilentKeyframeParams::new(16, 16)).unwrap();
assert!(
bytes.len() < 100,
"silent 16×16 keyframe ballooned to {} bytes",
bytes.len()
);
assert!(bytes.len() >= 10 + 4 + 4);
}
use crate::dct_tokens::{DEFAULT_COEFF_PROBS, decode_block};
fn encode_then_decode_block(
block_type: BlockType,
coeffs: &[i16; 16],
above_has_nonzero: bool,
left_has_nonzero: bool,
) -> [i16; 16] {
let mut enc = BoolEncoder::new();
let nonzeros = encode_coeff_block(
&mut enc,
block_type,
&DEFAULT_COEFF_PROBS,
above_has_nonzero,
left_has_nonzero,
coeffs,
)
.expect("encode_coeff_block should accept in-range coefficients");
let first = block_type.first_coeff();
let expected_nz = coeffs
.iter()
.enumerate()
.filter(|&(i, &v)| i >= first && v != 0)
.count();
assert_eq!(nonzeros, expected_nz, "non-zero count mismatch");
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).expect("encoder emits ≥ 2 bytes");
let mut recovered = [0i16; 16];
let nz = decode_block(
&mut dec,
block_type,
&DEFAULT_COEFF_PROBS,
above_has_nonzero,
left_has_nonzero,
&mut recovered,
)
.expect("decode_block should consume the encoded byte stream");
assert_eq!(nz, expected_nz);
recovered
}
#[test]
fn classify_coeff_token_covers_full_alphabet() {
assert_eq!(classify_coeff_token(0), DctToken::Dct0);
assert_eq!(classify_coeff_token(1), DctToken::Dct1);
assert_eq!(classify_coeff_token(2), DctToken::Dct2);
assert_eq!(classify_coeff_token(3), DctToken::Dct3);
assert_eq!(classify_coeff_token(4), DctToken::Dct4);
assert_eq!(classify_coeff_token(5), DctToken::Cat1);
assert_eq!(classify_coeff_token(6), DctToken::Cat1);
assert_eq!(classify_coeff_token(7), DctToken::Cat2);
assert_eq!(classify_coeff_token(10), DctToken::Cat2);
assert_eq!(classify_coeff_token(11), DctToken::Cat3);
assert_eq!(classify_coeff_token(18), DctToken::Cat3);
assert_eq!(classify_coeff_token(19), DctToken::Cat4);
assert_eq!(classify_coeff_token(34), DctToken::Cat4);
assert_eq!(classify_coeff_token(35), DctToken::Cat5);
assert_eq!(classify_coeff_token(66), DctToken::Cat5);
assert_eq!(classify_coeff_token(67), DctToken::Cat6);
assert_eq!(classify_coeff_token(2114), DctToken::Cat6);
}
#[test]
fn encode_coeff_block_all_zero_round_trips() {
let coeffs = [0i16; 16];
for &bt in &[
BlockType::YAfterY2,
BlockType::Y2,
BlockType::UV,
BlockType::YNoY2,
] {
let recovered = encode_then_decode_block(bt, &coeffs, false, false);
assert_eq!(recovered, coeffs, "all-zero round-trip failed for {bt:?}");
}
}
#[test]
fn encode_coeff_block_single_nonzero_at_each_position() {
for &bt in &[BlockType::Y2, BlockType::UV, BlockType::YNoY2] {
let first = bt.first_coeff();
for pos in first..16 {
for &value in &[1i16, -1, 2, -3, 4, -4] {
let mut coeffs = [0i16; 16];
coeffs[pos] = value;
let recovered = encode_then_decode_block(bt, &coeffs, false, false);
assert_eq!(
recovered, coeffs,
"single-nonzero round-trip failed at {bt:?} pos={pos} value={value}"
);
}
}
}
let bt = BlockType::YAfterY2;
for pos in 1..16 {
let mut coeffs = [0i16; 16];
coeffs[pos] = 3;
let recovered = encode_then_decode_block(bt, &coeffs, false, false);
assert_eq!(
recovered, coeffs,
"single-nonzero round-trip failed at YAfterY2 pos={pos}"
);
}
}
#[test]
fn encode_coeff_block_each_cat_range_round_trips() {
let cases: &[i16] = &[
5, 6, 7, 8, 10, 11, 15, 18, 19, 27, 34, 35, 50, 66, 67, 200, 1000, 2114, ];
for &v in cases {
for &sign in &[1i16, -1] {
let mut coeffs = [0i16; 16];
coeffs[3] = v * sign;
let recovered = encode_then_decode_block(BlockType::UV, &coeffs, true, false);
assert_eq!(
recovered, coeffs,
"cat-range round-trip failed for value {v}*{sign}"
);
}
}
}
#[test]
fn encode_coeff_block_fully_populated_block_round_trips_with_implicit_eob() {
let mut coeffs = [0i16; 16];
let values = [1, -2, 3, -4, 5, -7, 11, -19, 35, -67, 1, -1, 2, -3, 4, -5];
coeffs.copy_from_slice(&values);
let recovered = encode_then_decode_block(BlockType::YNoY2, &coeffs, false, false);
assert_eq!(recovered, coeffs);
}
#[test]
fn encode_coeff_block_interior_zeros_round_trip() {
let mut coeffs = [0i16; 16];
coeffs[0] = 3;
coeffs[3] = 5;
coeffs[7] = 2;
coeffs[12] = -8;
let recovered = encode_then_decode_block(BlockType::Y2, &coeffs, false, false);
assert_eq!(recovered, coeffs);
}
#[test]
fn encode_coeff_block_neighbour_predictor_combinations() {
let coeffs = {
let mut c = [0i16; 16];
c[0] = 4;
c[1] = -1;
c[5] = 2;
c
};
for above in &[false, true] {
for left in &[false, true] {
let recovered = encode_then_decode_block(BlockType::YNoY2, &coeffs, *above, *left);
assert_eq!(
recovered, coeffs,
"neighbour predictor combination ({above}, {left}) failed"
);
}
}
}
#[test]
fn encode_coeff_block_rejects_out_of_range_coefficient() {
let mut coeffs = [0i16; 16];
coeffs[2] = 2115;
let mut enc = BoolEncoder::new();
let err = encode_coeff_block(
&mut enc,
BlockType::YNoY2,
&DEFAULT_COEFF_PROBS,
false,
false,
&coeffs,
)
.unwrap_err();
assert!(matches!(
err,
TokenEncodeError::CoefficientOutOfRange {
index: 2,
value: 2115
}
));
}
#[test]
fn token_encoder_wrapper_matches_free_function_bytes() {
let mut coeffs = [0i16; 16];
coeffs[0] = 2;
coeffs[4] = -7;
coeffs[9] = 15;
let mut free_enc = BoolEncoder::new();
encode_coeff_block(
&mut free_enc,
BlockType::YNoY2,
&DEFAULT_COEFF_PROBS,
false,
false,
&coeffs,
)
.unwrap();
let free_bytes = free_enc.finish();
let mut wrapper = TokenEncoder::new(DEFAULT_COEFF_PROBS);
wrapper
.encode_block(BlockType::YNoY2, false, false, &coeffs)
.unwrap();
let wrapper_bytes = wrapper.finish();
assert_eq!(free_bytes, wrapper_bytes);
}
#[test]
fn encode_coeff_block_pseudo_random_sweep_round_trips() {
let mut state: u32 = 0xDEAD_BEEF;
let mut next = || {
state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
state
};
for trial in 0..64 {
let bt = match trial % 4 {
0 => BlockType::YAfterY2,
1 => BlockType::Y2,
2 => BlockType::UV,
_ => BlockType::YNoY2,
};
let first = bt.first_coeff();
let mut coeffs = [0i16; 16];
for (i, c) in coeffs.iter_mut().enumerate().skip(first) {
let r = next();
if (r & 0x3) != 0 || i > 10 {
continue;
}
let mag = ((r >> 8) % 100) as i16;
let sign = if (r >> 16) & 1 == 0 { 1 } else { -1 };
*c = mag * sign;
}
let above = (next() & 1) != 0;
let left = (next() & 1) != 0;
let recovered = encode_then_decode_block(bt, &coeffs, above, left);
assert_eq!(
recovered, coeffs,
"pseudo-random round-trip failed at trial {trial}, bt={bt:?}, above={above}, left={left}"
);
}
}
use crate::dct_tokens::decode_mb_coeffs;
use crate::dequant::MbDequantFactors;
use crate::macroblock::{IntraBmode, IntraUvMode, IntraYMode};
use crate::reconstruct::{MbNeighbors, decode_keyframe_mb_bpred, decode_keyframe_mb_non_bpred};
#[test]
fn mb_block_set_roundtrip_flat_color_recovers_within_one_lsb() {
for &pixel in &[100u8, 110, 128, 140, 160, 200] {
let pixels = MbPixels {
y: [pixel; 256],
u: [pixel; 64],
v: [pixel; 64],
};
let (_y_mode, _uv, _sub, y_plane, u_plane, v_plane) =
encode_decode_bpred_aware(&pixels, &MbNeighbors::default(), 0);
for (i, &recon) in y_plane.iter().enumerate() {
assert!(
(recon as i32 - pixel as i32).abs() <= 1,
"pixel {pixel}: y recon[{i}] = {recon} differs by > 1 LSB"
);
}
for (i, &recon) in u_plane.iter().enumerate() {
assert!(
(recon as i32 - pixel as i32).abs() <= 1,
"pixel {pixel}: u recon[{i}] = {recon} differs by > 1 LSB"
);
}
for (i, &recon) in v_plane.iter().enumerate() {
assert!(
(recon as i32 - pixel as i32).abs() <= 1,
"pixel {pixel}: v recon[{i}] = {recon} differs by > 1 LSB"
);
}
}
}
#[test]
fn mb_block_set_constant_128_emits_all_eob_blocks() {
let pixels = MbPixels {
y: [128u8; 256],
u: [128u8; 64],
v: [128u8; 64],
};
let encoded =
encode_mb_block_set(&pixels, 0, &DEFAULT_COEFF_PROBS).expect("encode_mb_block_set");
assert_eq!(
encoded.nonzero_block_count, 0,
"constant 128 MB must produce zero non-zero blocks"
);
assert_eq!(encoded.y_mode, IntraYMode::Dc);
assert_eq!(encoded.uv_mode, IntraUvMode::Dc);
let mut dec = BoolDecoder::init(&encoded.bytes).expect("encoder emits ≥ 2 bytes");
let mut above = MbEntropyCtx::default();
let mut left = MbEntropyCtx::default();
let recovered = decode_mb_coeffs(
&mut dec,
true,
false,
&DEFAULT_COEFF_PROBS,
&mut above,
&mut left,
)
.expect("decode_mb_coeffs");
assert_eq!(recovered.y2, [0i16; 16]);
assert!(recovered.y.iter().all(|b| *b == [0i16; 16]));
assert!(recovered.u.iter().all(|b| *b == [0i16; 16]));
assert!(recovered.v.iter().all(|b| *b == [0i16; 16]));
}
#[test]
fn mb_block_set_roundtrip_flat_color_at_q16_holds_within_2_lsb() {
let pixels = MbPixels {
y: [160u8; 256],
u: [120u8; 64],
v: [140u8; 64],
};
let (_y_mode, _uv, _sub, y_plane, _u_plane, _v_plane) =
encode_decode_bpred_aware(&pixels, &MbNeighbors::default(), 16);
for (i, &recon) in y_plane.iter().enumerate() {
assert!(
(recon as i32 - 160i32).abs() <= 2,
"yac_qi=16 flat 160: recon[{i}] = {recon} differs by > 2 LSB"
);
}
}
fn psnr(src: &[u8], recon: &[u8]) -> f64 {
assert_eq!(src.len(), recon.len());
let mse: f64 = src
.iter()
.zip(recon.iter())
.map(|(&s, &r)| {
let d = s as f64 - r as f64;
d * d
})
.sum::<f64>()
/ src.len() as f64;
if mse == 0.0 {
f64::INFINITY
} else {
10.0 * (255.0f64 * 255.0 / mse).log10()
}
}
fn encode_decode_with_neighbors(
pixels: &MbPixels,
neighbors: &MbNeighbors,
yac_qi: u8,
) -> (IntraYMode, IntraUvMode, Vec<u8>, Vec<u8>, Vec<u8>) {
let encoded =
encode_mb_block_set_with_neighbors(pixels, neighbors, yac_qi, &DEFAULT_COEFF_PROBS)
.expect("encode_mb_block_set_with_neighbors");
let mut dec = BoolDecoder::init(&encoded.bytes).expect("encoder emits ≥ 2 bytes");
let mut above = MbEntropyCtx::default();
let mut left = MbEntropyCtx::default();
let mut raw = decode_mb_coeffs(
&mut dec,
true,
false,
&DEFAULT_COEFF_PROBS,
&mut above,
&mut left,
)
.expect("decode_mb_coeffs");
assert_eq!(raw, encoded.coeffs, "byte-layer roundtrip mismatch");
let factors = MbDequantFactors::from_base_and_deltas(yac_qi as i32, 0, 0, 0, 0, 0);
factors.dequantize(&mut raw);
let recon = decode_keyframe_mb_non_bpred(
encoded.y_mode,
encoded.uv_mode,
false,
neighbors,
&raw.y2,
&raw.y,
&raw.u,
&raw.v,
)
.expect("decode_keyframe_mb_non_bpred");
(
encoded.y_mode,
encoded.uv_mode,
recon.y.to_vec(),
recon.u.to_vec(),
recon.v.to_vec(),
)
}
#[allow(clippy::type_complexity)]
fn encode_decode_bpred_aware(
pixels: &MbPixels,
neighbors: &MbNeighbors,
yac_qi: u8,
) -> (
IntraYMode,
IntraUvMode,
Option<[IntraBmode; 16]>,
Vec<u8>,
Vec<u8>,
Vec<u8>,
) {
let encoded =
encode_mb_block_set_with_neighbors(pixels, neighbors, yac_qi, &DEFAULT_COEFF_PROBS)
.expect("encode_mb_block_set_with_neighbors");
let is_bpred = encoded.y_mode == IntraYMode::B;
let has_y2 = !is_bpred;
let mut dec = BoolDecoder::init(&encoded.bytes).expect("encoder emits ≥ 2 bytes");
let mut above = MbEntropyCtx::default();
let mut left = MbEntropyCtx::default();
let mut raw = decode_mb_coeffs(
&mut dec,
has_y2,
false,
&DEFAULT_COEFF_PROBS,
&mut above,
&mut left,
)
.expect("decode_mb_coeffs");
assert_eq!(raw, encoded.coeffs, "byte-layer roundtrip mismatch");
let factors = MbDequantFactors::from_base_and_deltas(yac_qi as i32, 0, 0, 0, 0, 0);
factors.dequantize(&mut raw);
let recon = if is_bpred {
decode_keyframe_mb_bpred(
encoded.b_subblock_modes.as_ref(),
encoded.uv_mode,
false,
neighbors,
&raw.y,
&raw.u,
&raw.v,
)
.expect("decode_keyframe_mb_bpred")
} else {
decode_keyframe_mb_non_bpred(
encoded.y_mode,
encoded.uv_mode,
false,
neighbors,
&raw.y2,
&raw.y,
&raw.u,
&raw.v,
)
.expect("decode_keyframe_mb_non_bpred")
};
(
encoded.y_mode,
encoded.uv_mode,
encoded.b_subblock_modes,
recon.y.to_vec(),
recon.u.to_vec(),
recon.v.to_vec(),
)
}
#[test]
fn flat_mb_keeps_whole_block_luma_mode() {
let pixels = MbPixels {
y: [120u8; 256],
u: [120u8; 64],
v: [120u8; 64],
};
let neighbors = MbNeighbors {
y_above: Some([120u8; 16]),
y_left: Some([120u8; 16]),
y_topleft: Some(120),
y_above_right: Some([120u8; 4]),
u_above: Some([120u8; 8]),
u_left: Some([120u8; 8]),
u_topleft: Some(120),
v_above: Some([120u8; 8]),
v_left: Some([120u8; 8]),
v_topleft: Some(120),
};
let (y_mode, _uv, sub, ry, _ru, _rv) = encode_decode_bpred_aware(&pixels, &neighbors, 8);
assert_ne!(
y_mode,
IntraYMode::B,
"a flat MB must NOT flip to B_PRED — a whole-block mode reproduces it exactly"
);
assert!(
sub.is_none(),
"whole-block luma decision must carry no sub-block modes"
);
let p_y = psnr(&pixels.y, &ry);
assert!(p_y >= 30.0, "flat luma PSNR {p_y:.2} dB < 30 dB");
}
#[test]
fn diagonal_subblock_mb_picks_bpred_and_decodes_above_30db() {
let mut y = [0u8; 256];
for r in 0..16usize {
for c in 0..16usize {
let lr = r % 4;
let lc = c % 4;
let sb = (r / 4) * 4 + (c / 4);
let d = if sb % 2 == 0 { lr + lc } else { 6 - (lr + lc) };
y[r * 16 + c] = (30 + d * 35) as u8;
}
}
let pixels = MbPixels {
y,
u: [128u8; 64],
v: [128u8; 64],
};
let neighbors = MbNeighbors::default();
let (y_mode, _uv, sub, ry, _ru, _rv) = encode_decode_bpred_aware(&pixels, &neighbors, 4);
assert_eq!(
y_mode,
IntraYMode::B,
"a per-4×4-sub-block-structured MB must pick B_PRED"
);
let sub = sub.expect("B_PRED MB must carry sixteen sub-block modes");
assert_eq!(sub.len(), 16);
let p_y = psnr(&pixels.y, &ry);
assert!(
p_y >= 30.0,
"B_PRED luma reconstruction PSNR {p_y:.2} dB < 30 dB"
);
}
#[test]
fn bpred_neighbour_evolution_roundtrips_at_low_q() {
let mut y = [0u8; 256];
for r in 0..16usize {
for c in 0..16usize {
let lr = r % 4;
let lc = c % 4;
let sb = (r / 4) * 4 + (c / 4);
let d = if sb % 2 == 0 { lr + lc } else { 6 - (lr + lc) };
y[r * 16 + c] = (30 + d * 35) as u8;
}
}
let pixels = MbPixels {
y,
u: [128u8; 64],
v: [128u8; 64],
};
let neighbors = MbNeighbors::default();
let (y_mode, _uv, sub, ry, _ru, _rv) = encode_decode_bpred_aware(&pixels, &neighbors, 8);
assert_eq!(y_mode, IntraYMode::B);
assert!(sub.is_some());
let p_y = psnr(&pixels.y, &ry);
assert!(
p_y >= 40.0,
"B_PRED luma PSNR at q8 {p_y:.2} dB < 40 dB — neighbour evolution likely diverged"
);
}
#[test]
fn mode_pick_chooses_v_pred_for_column_constant_mb() {
let mut y_row = [0u8; 16];
for (c, slot) in y_row.iter_mut().enumerate() {
*slot = (40 + c * 10) as u8;
}
let mut u_row = [0u8; 8];
let mut v_row = [0u8; 8];
for c in 0..8 {
u_row[c] = (50 + c * 12) as u8;
v_row[c] = (200 - c * 12) as u8;
}
let mut y = [0u8; 256];
for r in 0..16 {
y[r * 16..r * 16 + 16].copy_from_slice(&y_row);
}
let mut u = [0u8; 64];
let mut v = [0u8; 64];
for r in 0..8 {
u[r * 8..r * 8 + 8].copy_from_slice(&u_row);
v[r * 8..r * 8 + 8].copy_from_slice(&v_row);
}
let pixels = MbPixels { y, u, v };
let neighbors = MbNeighbors {
y_above: Some(y_row),
u_above: Some(u_row),
v_above: Some(v_row),
..MbNeighbors::default()
};
let (y_mode, uv_mode, ry, ru, rv) = encode_decode_with_neighbors(&pixels, &neighbors, 8);
assert_eq!(
y_mode,
IntraYMode::V,
"column-constant MB must pick V_PRED for luma"
);
assert_eq!(
uv_mode,
IntraUvMode::V,
"column-constant MB must pick V_PRED for chroma"
);
let p_y = psnr(&pixels.y, &ry);
let p_u = psnr(&pixels.u, &ru);
let p_v = psnr(&pixels.v, &rv);
assert!(p_y >= 30.0, "V_PRED luma PSNR {p_y:.2} dB < 30 dB");
assert!(p_u >= 30.0, "V_PRED U PSNR {p_u:.2} dB < 30 dB");
assert!(p_v >= 30.0, "V_PRED V PSNR {p_v:.2} dB < 30 dB");
}
#[test]
fn mode_pick_chooses_h_pred_for_row_constant_mb() {
let mut y_col = [0u8; 16];
for (r, slot) in y_col.iter_mut().enumerate() {
*slot = (200 - r * 10) as u8;
}
let mut u_col = [0u8; 8];
let mut v_col = [0u8; 8];
for r in 0..8 {
u_col[r] = (60 + r * 14) as u8;
v_col[r] = (190 - r * 14) as u8;
}
let mut y = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
y[r * 16 + c] = y_col[r];
}
}
let mut u = [0u8; 64];
let mut v = [0u8; 64];
for r in 0..8 {
for c in 0..8 {
u[r * 8 + c] = u_col[r];
v[r * 8 + c] = v_col[r];
}
}
let pixels = MbPixels { y, u, v };
let neighbors = MbNeighbors {
y_left: Some(y_col),
u_left: Some(u_col),
v_left: Some(v_col),
..MbNeighbors::default()
};
let (y_mode, uv_mode, ry, ru, rv) = encode_decode_with_neighbors(&pixels, &neighbors, 8);
assert_eq!(
y_mode,
IntraYMode::H,
"row-constant MB must pick H_PRED for luma"
);
assert_eq!(
uv_mode,
IntraUvMode::H,
"row-constant MB must pick H_PRED for chroma"
);
let p_y = psnr(&pixels.y, &ry);
let p_u = psnr(&pixels.u, &ru);
let p_v = psnr(&pixels.v, &rv);
assert!(p_y >= 30.0, "H_PRED luma PSNR {p_y:.2} dB < 30 dB");
assert!(p_u >= 30.0, "H_PRED U PSNR {p_u:.2} dB < 30 dB");
assert!(p_v >= 30.0, "H_PRED V PSNR {p_v:.2} dB < 30 dB");
}
#[test]
fn mode_pick_chooses_tm_pred_for_planar_ramp_mb() {
let corner: i32 = 100;
let mut a = [0u8; 16];
let mut l = [0u8; 16];
for k in 0..16 {
a[k] = (corner + k as i32 + 1) as u8;
l[k] = (corner + k as i32 + 1) as u8;
}
let mut ua = [0u8; 8];
let mut ul = [0u8; 8];
let mut va = [0u8; 8];
let mut vl = [0u8; 8];
for k in 0..8 {
ua[k] = (corner + k as i32 + 1) as u8;
ul[k] = (corner + k as i32 + 1) as u8;
va[k] = (corner + k as i32 + 1) as u8;
vl[k] = (corner + k as i32 + 1) as u8;
}
let mut y = [0u8; 256];
for i in 0..16 {
for j in 0..16 {
y[i * 16 + j] = (l[i] as i32 + a[j] as i32 - corner).clamp(0, 255) as u8;
}
}
let mut u = [0u8; 64];
let mut v = [0u8; 64];
for i in 0..8 {
for j in 0..8 {
u[i * 8 + j] = (ul[i] as i32 + ua[j] as i32 - corner).clamp(0, 255) as u8;
v[i * 8 + j] = (vl[i] as i32 + va[j] as i32 - corner).clamp(0, 255) as u8;
}
}
let pixels = MbPixels { y, u, v };
let neighbors = MbNeighbors {
y_above: Some(a),
y_left: Some(l),
y_topleft: Some(corner as u8),
u_above: Some(ua),
u_left: Some(ul),
u_topleft: Some(corner as u8),
v_above: Some(va),
v_left: Some(vl),
v_topleft: Some(corner as u8),
..MbNeighbors::default()
};
let (y_mode, _uv_mode, ry, _ru, _rv) = encode_decode_with_neighbors(&pixels, &neighbors, 8);
assert_eq!(
y_mode,
IntraYMode::Tm,
"planar-ramp MB must pick TM_PRED for luma"
);
let p_y = psnr(&pixels.y, &ry);
assert!(p_y >= 30.0, "TM_PRED luma PSNR {p_y:.2} dB < 30 dB");
}
#[test]
fn isolated_mb_textured_roundtrips_above_30db() {
let mut y = [0u8; 256];
for i in 0..16 {
for j in 0..16 {
y[i * 16 + j] = (120 + ((i + j) % 8) * 2) as u8;
}
}
let mut u = [0u8; 64];
let mut v = [0u8; 64];
for i in 0..8 {
for j in 0..8 {
u[i * 8 + j] = (124 + ((i + j) % 4) * 2) as u8;
v[i * 8 + j] = (132 - ((i + j) % 4) * 2) as u8;
}
}
let pixels = MbPixels { y, u, v };
let (_y_mode, _uv, _sub, ry, ru, rv) =
encode_decode_bpred_aware(&pixels, &MbNeighbors::default(), 8);
let p_y = psnr(&pixels.y, &ry);
let p_u = psnr(&pixels.u, &ru);
let p_v = psnr(&pixels.v, &rv);
assert!(p_y >= 30.0, "isolated luma PSNR {p_y:.2} dB < 30 dB");
assert!(p_u >= 30.0, "isolated U PSNR {p_u:.2} dB < 30 dB");
assert!(p_v >= 30.0, "isolated V PSNR {p_v:.2} dB < 30 dB");
}
#[test]
fn pick_intra_mb_all_selects_v_h_tm_for_structured_sources() {
use crate::dequant::MbDequantFactors;
use crate::macroblock::{IntraUvMode, IntraYMode};
use crate::reconstruct::MbNeighbors;
let factors = MbDequantFactors::from_base_and_deltas(32, 0, 0, 0, 0, 0);
let lambda = rd_lambda(&factors);
let above_y: [u8; 16] = core::array::from_fn(|j| (40 + j * 8) as u8);
let left_y: [u8; 16] = core::array::from_fn(|i| (40 + i * 8) as u8);
let above_uv: [u8; 8] = core::array::from_fn(|j| (60 + j * 4) as u8);
let left_uv: [u8; 8] = core::array::from_fn(|i| (60 + i * 4) as u8);
let corner_y: u8 = 40;
let corner_uv: u8 = 60;
let make_neighbors = || MbNeighbors {
y_above: Some(above_y),
y_left: Some(left_y),
y_above_right: Some([above_y[15]; 4]),
y_topleft: Some(corner_y),
u_above: Some(above_uv),
u_left: Some(left_uv),
u_topleft: Some(corner_uv),
v_above: Some(above_uv),
v_left: Some(left_uv),
v_topleft: Some(corner_uv),
};
let mut y_vstripe = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
y_vstripe[r * 16 + c] = above_y[c];
}
}
let mut uv_vstripe = [0u8; 64];
for r in 0..8 {
for c in 0..8 {
uv_vstripe[r * 8 + c] = above_uv[c];
}
}
let pixels_v = MbPixels {
y: y_vstripe,
u: uv_vstripe,
v: uv_vstripe,
};
let pick_v = pick_intra_mb_all(
&pixels_v,
&make_neighbors(),
&factors,
lambda,
None,
None,
TrellisStrength::DEFAULT,
);
assert_eq!(
pick_v.y_mode,
IntraYMode::V,
"vertical-stripe source should pick V_PRED for Y, got {:?}",
pick_v.y_mode
);
assert!(matches!(
pick_v.uv_mode,
IntraUvMode::Dc | IntraUvMode::V | IntraUvMode::H | IntraUvMode::Tm
));
let mut y_hstripe = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
y_hstripe[r * 16 + c] = left_y[r];
}
}
let mut uv_hstripe = [0u8; 64];
for r in 0..8 {
for c in 0..8 {
uv_hstripe[r * 8 + c] = left_uv[r];
}
}
let pixels_h = MbPixels {
y: y_hstripe,
u: uv_hstripe,
v: uv_hstripe,
};
let pick_h = pick_intra_mb_all(
&pixels_h,
&make_neighbors(),
&factors,
lambda,
None,
None,
TrellisStrength::DEFAULT,
);
assert_eq!(
pick_h.y_mode,
IntraYMode::H,
"horizontal-stripe source should pick H_PRED for Y, got {:?}",
pick_h.y_mode
);
assert!(matches!(
pick_h.uv_mode,
IntraUvMode::Dc | IntraUvMode::V | IntraUvMode::H | IntraUvMode::Tm
));
let mut y_tm = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
let v = (corner_y as i32) + 8 * (r as i32 + c as i32) - 40;
let surface = 8 * (r as i32 + c as i32 + 2);
let _ = v; y_tm[r * 16 + c] = surface.clamp(0, 255) as u8;
}
}
let mut uv_tm = [0u8; 64];
for r in 0..8 {
for c in 0..8 {
let surface = 4 * (r as i32 + c as i32) + 2 * 4 + (corner_uv as i32);
uv_tm[r * 8 + c] = surface.clamp(0, 255) as u8;
}
}
let pixels_tm = MbPixels {
y: y_tm,
u: uv_tm,
v: uv_tm,
};
let pick_tm = pick_intra_mb_all(
&pixels_tm,
&make_neighbors(),
&factors,
lambda,
None,
None,
TrellisStrength::DEFAULT,
);
assert_eq!(
pick_tm.y_mode,
IntraYMode::Tm,
"planar-ramp source should pick TM_PRED for Y, got {:?}",
pick_tm.y_mode
);
assert!(matches!(
pick_tm.uv_mode,
IntraUvMode::Dc | IntraUvMode::V | IntraUvMode::H | IntraUvMode::Tm
));
let flat_y = [128u8; 256];
let flat_uv = [128u8; 64];
let pixels_flat = MbPixels {
y: flat_y,
u: flat_uv,
v: flat_uv,
};
let pick_flat = pick_intra_mb_all(
&pixels_flat,
&MbNeighbors::default(),
&factors,
lambda,
None,
None,
TrellisStrength::DEFAULT,
);
assert_eq!(
pick_flat.y_mode,
IntraYMode::Dc,
"flat-grey source with off-frame neighbours should still pick DC_PRED for Y"
);
assert_eq!(
pick_flat.uv_mode,
IntraUvMode::Dc,
"flat-grey source should pick DC_PRED for UV"
);
}
#[test]
fn estimate_bits_per_mb_falls_as_qindex_rises() {
let complexity = 200.0;
let lo = estimate_bits_per_mb(complexity, 10);
let mid = estimate_bits_per_mb(complexity, 50);
let hi = estimate_bits_per_mb(complexity, 110);
assert!(
lo > mid && mid > hi,
"bits/MB must fall as qindex rises: qi10={lo} qi50={mid} qi110={hi}"
);
}
#[test]
fn estimate_bits_per_mb_rises_with_complexity() {
let qi = 40;
let flat = estimate_bits_per_mb(10.0, qi);
let busy = estimate_bits_per_mb(800.0, qi);
assert!(
busy > flat,
"busier frame must cost more bits at the same qindex: flat={flat} busy={busy}"
);
}
#[test]
fn estimate_bits_per_mb_reproduces_surrogate_at_reference_qindex() {
let complexity = 137.0;
let predicted = estimate_bits_per_mb(complexity, RATE_MODEL_REF_QINDEX as i32);
assert!(
(predicted - (complexity + RATE_MODEL_MB_FLOOR_BITS)).abs() < 1e-3,
"at the reference qindex the model must reproduce the surrogate + floor, got {predicted}"
);
}
#[test]
fn estimate_bits_per_mb_keeps_the_floor_at_coarsest_quant() {
let predicted = estimate_bits_per_mb(0.0, 127);
assert!(
(predicted - RATE_MODEL_MB_FLOOR_BITS).abs() < 1e-3,
"zero-complexity frame at qi127 must charge exactly the floor, got {predicted}"
);
}
#[test]
fn estimate_frame_bytes_scales_with_macroblock_count() {
let small = estimate_frame_bytes(150.0, 40, 32, 32); let big = estimate_frame_bytes(150.0, 40, 64, 64); assert!(
big >= small.saturating_mul(3),
"4× the MBs must predict roughly 4× the bytes: small={small} big={big}"
);
}
#[test]
fn estimate_frame_bytes_rounds_partial_macroblocks_up() {
let partial = estimate_frame_bytes(100.0, 40, 17, 17);
let full = estimate_frame_bytes(100.0, 40, 32, 32);
assert_eq!(
partial, full,
"17×17 and 32×32 both span 2×2 MBs — byte estimate must match"
);
}
#[test]
fn estimate_frame_bytes_zero_dimensions_is_zero() {
assert_eq!(estimate_frame_bytes(500.0, 40, 0, 64), 0);
assert_eq!(estimate_frame_bytes(500.0, 40, 64, 0), 0);
}
fn busy_clip(n: usize) -> Vec<FrameComplexity> {
(0..n)
.map(|i| FrameComplexity {
frame_index: i as u32,
bits_per_mb: 600.0,
scene_cut: false,
})
.collect()
}
#[test]
fn gop_byte_budget_tracks_bitrate_and_rate() {
let mut config = Vp8TwoPassConfig {
target_bitrate_bps: 8_000_000, fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let b = gop_byte_budget(&config, 30).expect("budget defined");
assert_eq!(b, 1_000_000);
let b2 = gop_byte_budget(&config, 15).expect("budget defined");
assert_eq!(b2, 500_000);
config.fps_num = 0;
assert!(gop_byte_budget(&config, 30).is_none());
}
#[test]
fn solver_returns_base_when_not_bitrate_targeted() {
let config = Vp8TwoPassConfig {
base: Vp8EncoderConfig {
qindex: 44,
..Vp8EncoderConfig::default()
},
..Vp8TwoPassConfig::default()
};
let qi = solve_base_qindex_for_budget(&config, &busy_clip(10), 176, 144);
assert_eq!(qi, 44);
}
#[test]
fn solver_raises_qindex_under_a_tight_budget() {
let config = Vp8TwoPassConfig {
target_bitrate_bps: 8_000, fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let qi = solve_base_qindex_for_budget(&config, &busy_clip(30), 176, 144);
assert!(
qi > Vp8EncoderConfig::default().qindex,
"tight budget must raise the base qindex above the default, got {qi}"
);
}
#[test]
fn solver_lowers_qindex_under_a_generous_budget() {
let config = Vp8TwoPassConfig {
target_bitrate_bps: 800_000_000, fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let qi = solve_base_qindex_for_budget(&config, &busy_clip(30), 176, 144);
assert_eq!(qi, 0, "generous budget must spend all quality (qindex 0)");
}
#[test]
fn solver_is_monotone_in_budget() {
let base = Vp8TwoPassConfig {
fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let clip = busy_clip(30);
let mut prev = 128i32;
for &bps in &[8_000u32, 40_000, 200_000, 1_000_000, 5_000_000] {
let config = Vp8TwoPassConfig {
target_bitrate_bps: bps,
..base
};
let qi = solve_base_qindex_for_budget(&config, &clip, 176, 144) as i32;
assert!(
qi <= prev,
"a larger budget ({bps} bps) must not raise the solved qindex: {qi} > {prev}"
);
prev = qi;
}
}
#[test]
fn solver_respects_predicted_ceiling() {
let config = Vp8TwoPassConfig {
target_bitrate_bps: 100_000,
overshoot_ratio: 1.2,
fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let clip = busy_clip(30);
let qi = solve_base_qindex_for_budget(&config, &clip, 176, 144) as i32;
let budget = gop_byte_budget(&config, clip.len()).unwrap();
let ceiling = (budget as f64 * 1.2) as u64;
let predicted = predict_gop_bytes_at_qindex(&clip, 176, 144, qi);
assert!(
predicted <= ceiling || qi == 127,
"predicted {predicted} must fit ceiling {ceiling} unless pinned at qi127 (qi={qi})"
);
}
#[test]
fn two_pass_qindices_for_bitrate_recenters_schedule() {
let config = Vp8TwoPassConfig {
base: Vp8EncoderConfig {
qindex: 30,
..Vp8EncoderConfig::default()
},
target_bitrate_bps: 8_000,
fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let clip: Vec<_> = (0..6)
.map(|i| FrameComplexity {
frame_index: i,
bits_per_mb: 200.0 + i as f32 * 200.0,
scene_cut: false,
})
.collect();
let sched = two_pass_qindices_for_bitrate(&config, &clip, 176, 144).unwrap();
assert_eq!(sched.len(), clip.len());
let mean_qi: f32 = sched.iter().map(|&q| q as f32).sum::<f32>() / sched.len() as f32;
assert!(
mean_qi > config.base.qindex as f32,
"tight budget must raise the schedule mean above the configured base: \
mean={mean_qi} base={}",
config.base.qindex
);
for &q in &sched {
assert!(q <= 127);
}
}
#[test]
fn two_pass_qindices_for_bitrate_matches_cq_when_untargeted() {
let config = Vp8TwoPassConfig::default();
let clip: Vec<_> = (0..5)
.map(|i| FrameComplexity {
frame_index: i,
bits_per_mb: 100.0 + i as f32 * 50.0,
scene_cut: false,
})
.collect();
let cq = two_pass_qindices(&config, &clip).unwrap();
let br = two_pass_qindices_for_bitrate(&config, &clip, 176, 144).unwrap();
assert_eq!(
cq, br,
"untargeted bitrate schedule must equal the CQ schedule"
);
}
#[test]
fn rate_feedback_delta_sign_and_clamp() {
let config = Vp8TwoPassConfig {
target_bitrate_bps: 100_000,
fps_num: 30,
fps_den: 1,
..Vp8TwoPassConfig::default()
};
let mut enc = Vp8TwoPassEncoder::new(config);
assert_eq!(enc.rate_feedback_delta(), 0);
enc.frame_byte_budget = Some(1000);
enc.rate_debt_bytes = 1000;
assert_eq!(enc.rate_feedback_delta(), RATE_FEEDBACK_QSTEP_PER_FRAME);
enc.rate_debt_bytes = -1000;
assert_eq!(enc.rate_feedback_delta(), -RATE_FEEDBACK_QSTEP_PER_FRAME);
enc.rate_debt_bytes = 1_000_000;
assert_eq!(enc.rate_feedback_delta(), RATE_FEEDBACK_MAX_QSTEP);
enc.rate_debt_bytes = -1_000_000;
assert_eq!(enc.rate_feedback_delta(), -RATE_FEEDBACK_MAX_QSTEP);
}
#[test]
fn two_pass_qindices_for_bitrate_empty_and_bad_base() {
let config = Vp8TwoPassConfig::default();
assert!(
two_pass_qindices_for_bitrate(&config, &[], 176, 144)
.unwrap()
.is_empty()
);
let bad = Vp8TwoPassConfig {
base: Vp8EncoderConfig {
qindex: 200,
..Vp8EncoderConfig::default()
},
..Vp8TwoPassConfig::default()
};
assert!(two_pass_qindices_for_bitrate(&bad, &busy_clip(3), 176, 144).is_err());
}
#[test]
fn treed_bits_cached_matches_dfs_walk() {
fn check<const N: usize>(
tree: &'static [i8],
paths: &[TreedLeafPath; N],
real_probs: &'static [u8],
) {
let synthetic = |i: usize| -> u8 { (37 * i + 11) as u8 };
for leaf in 0..N as u8 {
for lookup in [
Box::new(|i: usize| real_probs[i]) as Box<dyn Fn(usize) -> u8>,
Box::new(synthetic),
] {
let reference = treed_bits(tree, &lookup, leaf);
let cached = treed_bits_cached(paths, &lookup, leaf);
assert_eq!(
cached.to_bits(),
reference.to_bits(),
"tree {tree:?} leaf {leaf}"
);
}
}
}
check(&KF_YMODE_TREE, &KF_YMODE_PATHS, &KF_YMODE_PROB);
check(&UV_MODE_TREE, &UV_MODE_PATHS, &KF_UV_MODE_PROB);
check(&BMODE_TREE, &BMODE_PATHS, &KF_BMODE_PROB[0][0]);
check(&IF_YMODE_TREE, &IF_YMODE_PATHS, &IF_YMODE_PROB_DEFAULTS);
check(&UV_MODE_TREE, &UV_MODE_PATHS, &IF_UV_MODE_PROB_DEFAULTS);
}
#[test]
fn write_literal_fast_matches_generic_loop() {
let mut fast = BoolEncoder::new();
let mut generic = BoolEncoder::new();
let mut x: u32 = 0x1234_5678;
for step in 0..4096u32 {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
let num_bits = step % 33; let value = if num_bits == 32 {
x
} else {
x & ((1u32 << num_bits) - 1)
};
fast.write_literal(value, num_bits);
let mut i = num_bits;
while i > 0 {
i -= 1;
generic.write_bool(128, ((value >> i) & 1) != 0);
}
assert_eq!(fast.range, generic.range, "range diverged at step {step}");
assert_eq!(
fast.bottom, generic.bottom,
"bottom diverged at step {step}"
);
assert_eq!(
fast.bit_count, generic.bit_count,
"bit_count diverged at step {step}"
);
assert_eq!(fast.out, generic.out, "bytes diverged at step {step}");
}
assert_eq!(fast.finish(), generic.finish());
}
}