FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Refactor vp9 for strict Clippy checks
Dylan M. Taylorf0ea988d8f6d
diff --git a/crates/vp9/src/decoder.rs b/crates/vp9/src/decoder.rsindex 619d1b5c2..5d144ad00 100644--- a/crates/vp9/src/decoder.rs+++ b/crates/vp9/src/decoder.rs@@ -8,7 +8,7 @@ use crate::frame::{BAND_PAD, Band, Frame, FrameInfo, MiGrid, MiInfo, Pools};use crate::header::{FrameHeader, HeaderState, KEY_FRAME, RefInfo, parse_compressed, parse_uncompressed, split_superframe};use crate::loopfilter::{LfFrame, PlaneView, filter_superblock};use crate::probs::{Counts, adapt_coef_probs, adapt_noncoef_probs};-use crate::tables::*;+use crate::tables::{AC_QLOOKUP, DC_QLOOKUP, SEG_LVL_ALT_Q, SWITCHABLE, TX_MODE_SELECT};use crate::tile::{FrameShared, RefUse, Strip, TileDecoder};use crate::{ColorInfo, Picture, Plane};use std::collections::VecDeque;@@ -829,7 +829,7 @@ impl Wave {let Some(row) = self.rows.get(r) else { return };let mut bottom = lock(&row.bottom);for (p, dst) in bottom.iter_mut().enumerate() {- copy_column(&self.frame, p, c, self.sb_cols, &band.planes[p], self.frame.band_h[p], dst, 0);+ copy_column(&self.frame, Column { p, c, sb_cols: self.sb_cols }, (&band.planes[p], self.frame.band_h[p]), (dst, 0));}}@@ -848,7 +848,7 @@ impl Wave {}let bottom = lock(&above.bottom);for (p, src) in bottom.iter().enumerate() {- copy_column(f, p, c, sb_cols, src, 0, &mut band.planes[p], 0);+ copy_column(f, Column { p, c, sb_cols }, (src, 0), (&mut band.planes[p], 0));}}let [a, b, d] = &mut band.planes;@@ -900,10 +900,18 @@ impl Drop for Wave {}}+/// Superblock column `c` of plane `p` in a frame `sb_cols` superblocks wide.+#[derive(Clone, Copy)]+struct Column {+ p: usize,+ c: usize,+ sb_cols: usize,+}+/// Copy `BAND_PAD` rows of superblock column `c` of plane `p` (the last column takes the rest of-/// the stride) from row `src_row` of `src` to row `dst_row` of `dst`, both `strides[p]` wide.-#[allow(clippy::too_many_arguments)]-fn copy_column(f: &Frame, p: usize, c: usize, sb_cols: usize, src: &[u16], src_row: usize, dst: &mut [u16], dst_row: usize) {+/// the stride) from row `src_row` of `src` to row `dst_row` of `dst` (each given as `(buffer, row)`), both `strides[p]` wide.+fn copy_column(f: &Frame, col: Column, (src, src_row): (&[u16], usize), (dst, dst_row): (&mut [u16], usize)) {+ let Column { p, c, sb_cols } = col;let fs = f.strides[p];let cw = fs / sb_cols.max(1);let x0 = c * cw;diff --git a/crates/vp9/src/header.rs b/crates/vp9/src/header.rsindex 2d76f302f..a381f5536 100644--- a/crates/vp9/src/header.rs+++ b/crates/vp9/src/header.rs@@ -4,7 +4,10 @@use crate::boolcoder::BoolDecoder;use crate::error::{Error, Result, ensure};use crate::probs::FrameContext;-use crate::tables::*;+use crate::tables::{+ ALTREF_FRAME, GOLDEN_FRAME, INV_MAP_TABLE, LAST_FRAME, LITERAL_TO_TYPE, MAX_SEGMENTS, MAX_TILE_WIDTH_B64, MIN_TILE_WIDTH_B64, SEGMENTATION_FEATURE_BITS,+ SEGMENTATION_FEATURE_SIGNED, SWITCHABLE, TX_MODE_SELECT, TX_MODE_TO_BIGGEST_TX_SIZE,+};use filmcraft_bitstream::BitReader;pub const KEY_FRAME: u8 = 0;@@ -216,6 +219,155 @@ fn setup_past_independence(st: &mut HeaderState, fc: &mut FrameContext) {*fc = FrameContext::default();}+/// Intra-only (non-key) frame header tail (6.2): sync code, colour config, refresh flags, sizes.+fn intra_only_header(r: &mut BitReader, h: &mut FrameHeader) -> Result<()> {+ frame_sync_code(r)?;+ h.color = if h.profile > 0 {+ color_config(r, h.profile)?+ } else {+ ColorConfig { bit_depth: 8, color_space: 1, color_range: false, subsampling_x: true, subsampling_y: true }+ };+ h.refresh_frame_flags = r.read_bits(8)? as u8;+ frame_size(r, h)?;+ render_size(r, h)+}++/// frame_size_with_refs (6.2.5): the size is copied from the first flagged reference, or read explicitly.+fn frame_size_with_refs(r: &mut BitReader, h: &mut FrameHeader, refs: &[Option<RefInfo>; 8]) -> Result<()> {+ let mut found = false;+ for i in 0..3 {+ if r.read_flag()? {+ let idx = h.ref_frame_idx[i] as usize;+ let Some(info) = refs[idx] else {+ return Err(Error::MissingReference(format!("frame size from empty slot {idx}")));+ };+ h.width = info.width;+ h.height = info.height;+ found = true;+ break;+ }+ }+ if !found {+ frame_size(r, h)?;+ }+ h.size_from_ref = found;+ Ok(())+}++/// Inter frame header tail (6.2): reference selection, sizes, motion vector precision and filter.+fn inter_frame_header(r: &mut BitReader, h: &mut FrameHeader, st: &HeaderState, refs: &[Option<RefInfo>; 8]) -> Result<()> {+ h.color = st.color;+ h.refresh_frame_flags = r.read_bits(8)? as u8;+ for i in 0..3 {+ h.ref_frame_idx[i] = r.read_bits(3)? as u8;+ h.ref_frame_sign_bias[LAST_FRAME as usize + i] = r.read_flag()?;+ }+ frame_size_with_refs(r, h, refs)?;+ render_size(r, h)?;+ h.allow_high_precision_mv = r.read_flag()?;+ // read_interpolation_filter (6.2.7)+ h.interp_filter = if r.read_flag()? { SWITCHABLE } else { LITERAL_TO_TYPE[r.read_bits(2)? as usize] };+ Ok(())+}++/// Resets the probability contexts for intra / error resilient frames (7.2).+fn reset_frame_contexts(st: &mut HeaderState, h: &mut FrameHeader) {+ let mut fc = FrameContext::default();+ setup_past_independence(st, &mut fc);+ if h.frame_type == KEY_FRAME || h.error_resilient_mode || h.reset_frame_context == 3 {+ for c in st.contexts.iter_mut() {+ *c = fc.clone();+ }+ } else if h.reset_frame_context == 2 {+ st.contexts[h.frame_context_idx as usize] = fc.clone();+ }+ h.frame_context_idx = 0;+}++/// loop_filter_params (6.2.8).+fn read_loop_filter_params(r: &mut BitReader, lf: &mut LoopFilterParams) -> Result<()> {+ lf.level = r.read_bits(6)? as u8;+ lf.sharpness = r.read_bits(3)? as u8;+ lf.delta_enabled = r.read_flag()?;+ if lf.delta_enabled && r.read_flag()? {+ for i in 0..4 {+ if r.read_flag()? {+ lf.ref_deltas[i] = read_s(r, 6)? as i8;+ }+ }+ for i in 0..2 {+ if r.read_flag()? {+ lf.mode_deltas[i] = read_s(r, 6)? as i8;+ }+ }+ }+ Ok(())+}++/// segmentation_params (6.2.11).+fn read_segmentation_params(r: &mut BitReader, seg: &mut Segmentation) -> Result<()> {+ seg.enabled = r.read_flag()?;+ seg.update_map = false;+ seg.temporal_update = false;+ if !seg.enabled {+ return Ok(());+ }+ seg.update_map = r.read_flag()?;+ if seg.update_map {+ for i in 0..7 {+ seg.tree_probs[i] = read_prob(r)?;+ }+ seg.temporal_update = r.read_flag()?;+ for i in 0..3 {+ seg.pred_probs[i] = if seg.temporal_update { read_prob(r)? } else { 255 };+ }+ }+ if r.read_flag()? {+ seg.abs_or_delta_update = r.read_flag()?;+ for i in 0..MAX_SEGMENTS {+ for j in 0..4 {+ let mut value = 0i32;+ let enabled = r.read_flag()?;+ seg.feature_enabled[i][j] = enabled;+ if enabled {+ value = r.read_bits(SEGMENTATION_FEATURE_BITS[j])? as i32;+ if SEGMENTATION_FEATURE_SIGNED[j] && r.read_flag()? {+ value = -value;+ }+ }+ seg.feature_data[i][j] = value as i16;+ }+ }+ }+ Ok(())+}++/// tile_info (6.2.13).+fn read_tile_info(r: &mut BitReader, h: &mut FrameHeader) -> Result<()> {+ let mut min_log2 = 0;+ while (MAX_TILE_WIDTH_B64 << min_log2) < h.sb64_cols {+ min_log2 += 1;+ }+ let mut max_log2 = 1;+ while (h.sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 {+ max_log2 += 1;+ }+ max_log2 -= 1;+ h.tile_cols_log2 = min_log2;+ while h.tile_cols_log2 < max_log2 {+ if r.read_flag()? {+ h.tile_cols_log2 += 1;+ } else {+ break;+ }+ }+ h.tile_rows_log2 = r.read_bits(1)?;+ if h.tile_rows_log2 == 1 {+ h.tile_rows_log2 += r.read_bits(1)?;+ }+ Ok(())+}+/// Parse the uncompressed header (6.2). `refs` gives the sizes of the eight reference slots./// Updates the persistent state (probability contexts on reset, loop filter deltas,/// segmentation, colour configuration).@@ -252,44 +404,9 @@ pub fn parse_uncompressed(data: &[u8], st: &mut HeaderState, refs: &[Option<RefIh.frame_is_intra = h.intra_only;h.reset_frame_context = if h.error_resilient_mode { 0 } else { r.read_bits(2)? as u8 };if h.intra_only {- frame_sync_code(&mut r)?;- h.color = if h.profile > 0 {- color_config(&mut r, h.profile)?- } else {- ColorConfig { bit_depth: 8, color_space: 1, color_range: false, subsampling_x: true, subsampling_y: true }- };- h.refresh_frame_flags = r.read_bits(8)? as u8;- frame_size(&mut r, &mut h)?;- render_size(&mut r, &mut h)?;+ intra_only_header(&mut r, &mut h)?;} else {- h.color = st.color;- h.refresh_frame_flags = r.read_bits(8)? as u8;- for i in 0..3 {- h.ref_frame_idx[i] = r.read_bits(3)? as u8;- h.ref_frame_sign_bias[LAST_FRAME as usize + i] = r.read_flag()?;- }- // frame_size_with_refs (6.2.5)- let mut found = false;- for i in 0..3 {- if r.read_flag()? {- let idx = h.ref_frame_idx[i] as usize;- let Some(info) = refs[idx] else {- return Err(Error::MissingReference(format!("frame size from empty slot {idx}")));- };- h.width = info.width;- h.height = info.height;- found = true;- break;- }- }- if !found {- frame_size(&mut r, &mut h)?;- }- h.size_from_ref = found;- render_size(&mut r, &mut h)?;- h.allow_high_precision_mv = r.read_flag()?;- // read_interpolation_filter (6.2.7)- h.interp_filter = if r.read_flag()? { SWITCHABLE } else { LITERAL_TO_TYPE[r.read_bits(2)? as usize] };+ inter_frame_header(&mut r, &mut h, st, refs)?;}}compute_image_size(&mut h);@@ -302,95 +419,17 @@ pub fn parse_uncompressed(data: &[u8], st: &mut HeaderState, refs: &[Option<RefI}h.frame_context_idx = r.read_bits(2)? as u8;if h.frame_is_intra || h.error_resilient_mode {- let mut fc = FrameContext::default();- setup_past_independence(st, &mut fc);- if h.frame_type == KEY_FRAME || h.error_resilient_mode || h.reset_frame_context == 3 {- for c in st.contexts.iter_mut() {- *c = fc.clone();- }- } else if h.reset_frame_context == 2 {- st.contexts[h.frame_context_idx as usize] = fc.clone();- }- h.frame_context_idx = 0;- }- // loop_filter_params (6.2.8)- st.lf.level = r.read_bits(6)? as u8;- st.lf.sharpness = r.read_bits(3)? as u8;- st.lf.delta_enabled = r.read_flag()?;- if st.lf.delta_enabled && r.read_flag()? {- for i in 0..4 {- if r.read_flag()? {- st.lf.ref_deltas[i] = read_s(&mut r, 6)? as i8;- }- }- for i in 0..2 {- if r.read_flag()? {- st.lf.mode_deltas[i] = read_s(&mut r, 6)? as i8;- }- }+ reset_frame_contexts(st, &mut h);}+ read_loop_filter_params(&mut r, &mut st.lf)?;// quantization_params (6.2.9)h.base_q_idx = r.read_bits(8)? as u8;h.delta_q_y_dc = read_delta_q(&mut r)?;h.delta_q_uv_dc = read_delta_q(&mut r)?;h.delta_q_uv_ac = read_delta_q(&mut r)?;h.lossless = h.base_q_idx == 0 && h.delta_q_y_dc == 0 && h.delta_q_uv_dc == 0 && h.delta_q_uv_ac == 0;- // segmentation_params (6.2.11)- let seg = &mut st.seg;- seg.enabled = r.read_flag()?;- seg.update_map = false;- seg.temporal_update = false;- if seg.enabled {- seg.update_map = r.read_flag()?;- if seg.update_map {- for i in 0..7 {- seg.tree_probs[i] = read_prob(&mut r)?;- }- seg.temporal_update = r.read_flag()?;- for i in 0..3 {- seg.pred_probs[i] = if seg.temporal_update { read_prob(&mut r)? } else { 255 };- }- }- if r.read_flag()? {- seg.abs_or_delta_update = r.read_flag()?;- for i in 0..MAX_SEGMENTS {- for j in 0..4 {- let mut value = 0i32;- let enabled = r.read_flag()?;- seg.feature_enabled[i][j] = enabled;- if enabled {- value = r.read_bits(SEGMENTATION_FEATURE_BITS[j])? as i32;- if SEGMENTATION_FEATURE_SIGNED[j] && r.read_flag()? {- value = -value;- }- }- seg.feature_data[i][j] = value as i16;- }- }- }- }- // tile_info (6.2.13)- let mut min_log2 = 0;- while (MAX_TILE_WIDTH_B64 << min_log2) < h.sb64_cols {- min_log2 += 1;- }- let mut max_log2 = 1;- while (h.sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 {- max_log2 += 1;- }- max_log2 -= 1;- h.tile_cols_log2 = min_log2;- while h.tile_cols_log2 < max_log2 {- if r.read_flag()? {- h.tile_cols_log2 += 1;- } else {- break;- }- }- h.tile_rows_log2 = r.read_bits(1)?;- if h.tile_rows_log2 == 1 {- h.tile_rows_log2 += r.read_bits(1)?;- }+ read_segmentation_params(&mut r, &mut st.seg)?;+ read_tile_info(&mut r, &mut h)?;h.header_size_in_bytes = r.read_bits(16)?;// trailing_bitsh.uncompressed_size = r.position().div_ceil(8);@@ -452,35 +491,25 @@ fn update_mv_prob(bd: &mut BoolDecoder, prob: &mut u8) {}}-/// Parse the compressed header (6.3) into `h` and the probabilities `fc`.-pub fn parse_compressed(data: &[u8], h: &mut FrameHeader, fc: &mut FrameContext) -> Result<()> {- let mut bd = BoolDecoder::new(data);- // read_tx_mode (6.3.1)- h.tx_mode = if h.lossless {- 0- } else {- let mut m = bd.read_literal(2) as u8;- if m == 3 {- m += bd.read_literal(1) as u8;- }- m- };- if h.tx_mode == TX_MODE_SELECT {- for i in 0..2 {- diff_update_prob(&mut bd, &mut fc.tx[1][i][0]);- }- for i in 0..2 {- for j in 0..2 {- diff_update_prob(&mut bd, &mut fc.tx[2][i][j]);- }+/// tx_mode_probs (6.3.2): per-size transform probability updates for `TX_MODE_SELECT`.+fn read_tx_mode_probs(bd: &mut BoolDecoder, fc: &mut FrameContext) {+ for i in 0..2 {+ diff_update_prob(bd, &mut fc.tx[1][i][0]);+ }+ for i in 0..2 {+ for j in 0..2 {+ diff_update_prob(bd, &mut fc.tx[2][i][j]);}- for i in 0..2 {- for j in 0..3 {- diff_update_prob(&mut bd, &mut fc.tx[3][i][j]);- }+ }+ for i in 0..2 {+ for j in 0..3 {+ diff_update_prob(bd, &mut fc.tx[3][i][j]);}}- // read_coef_probs (6.3.7)+}++/// read_coef_probs (6.3.7).+fn read_coef_probs(bd: &mut BoolDecoder, h: &FrameHeader, fc: &mut FrameContext) {let max_tx = TX_MODE_TO_BIGGEST_TX_SIZE[h.tx_mode as usize] as usize;for tx in 0..=max_tx {if bd.read_literal(1) == 1 {@@ -490,7 +519,7 @@ pub fn parse_compressed(data: &[u8], h: &mut FrameHeader, fc: &mut FrameContext)let max_l = if k == 0 { 3 } else { 6 };for l in 0..max_l {for m in 0..3 {- diff_update_prob(&mut bd, &mut fc.coef[tx][i][j][k][l][m]);+ diff_update_prob(bd, &mut fc.coef[tx][i][j][k][l][m]);}}}@@ -498,102 +527,138 @@ pub fn parse_compressed(data: &[u8], h: &mut FrameHeader, fc: &mut FrameContext)}}}- for i in 0..3 {- diff_update_prob(&mut bd, &mut fc.skip[i]);+}++/// frame_reference_mode (6.3.12) including setup_compound_reference_mode (6.3.18).+fn read_frame_reference_mode(bd: &mut BoolDecoder, h: &mut FrameHeader) {+ let bias = h.ref_frame_sign_bias;+ let compound_allowed = bias[2] != bias[1] || bias[3] != bias[1];+ h.reference_mode = 0;+ if !compound_allowed {+ return;}- if !h.frame_is_intra {- for i in 0..7 {- for j in 0..3 {- diff_update_prob(&mut bd, &mut fc.inter_mode[i][j]);- }- }- if h.interp_filter == SWITCHABLE {- for j in 0..4 {- for i in 0..2 {- diff_update_prob(&mut bd, &mut fc.interp_filter[j][i]);- }- }+ if bd.read_literal(1) == 1 {+ h.reference_mode = if bd.read_literal(1) == 1 { 2 } else { 1 };+ }+ if bias[LAST_FRAME as usize] == bias[GOLDEN_FRAME as usize] {+ h.comp_fixed_ref = ALTREF_FRAME;+ h.comp_var_ref = [LAST_FRAME, GOLDEN_FRAME];+ } else if bias[LAST_FRAME as usize] == bias[ALTREF_FRAME as usize] {+ h.comp_fixed_ref = GOLDEN_FRAME;+ h.comp_var_ref = [LAST_FRAME, ALTREF_FRAME];+ } else {+ h.comp_fixed_ref = LAST_FRAME;+ h.comp_var_ref = [GOLDEN_FRAME, ALTREF_FRAME];+ }+}++/// frame_reference_mode_probs (6.3.13).+fn read_frame_reference_mode_probs(bd: &mut BoolDecoder, reference_mode: u8, fc: &mut FrameContext) {+ if reference_mode == 2 {+ for i in 0..5 {+ diff_update_prob(bd, &mut fc.comp_mode[i]);}- for i in 0..4 {- diff_update_prob(&mut bd, &mut fc.is_inter[i]);+ }+ if reference_mode != 1 {+ for i in 0..5 {+ diff_update_prob(bd, &mut fc.single_ref[i][0]);+ diff_update_prob(bd, &mut fc.single_ref[i][1]);}- // frame_reference_mode (6.3.12)- let bias = h.ref_frame_sign_bias;- let compound_allowed = bias[2] != bias[1] || bias[3] != bias[1];- h.reference_mode = 0;- if compound_allowed {- if bd.read_literal(1) == 1 {- h.reference_mode = if bd.read_literal(1) == 1 { 2 } else { 1 };- }- // setup_compound_reference_mode (6.3.18)- if bias[LAST_FRAME as usize] == bias[GOLDEN_FRAME as usize] {- h.comp_fixed_ref = ALTREF_FRAME;- h.comp_var_ref = [LAST_FRAME, GOLDEN_FRAME];- } else if bias[LAST_FRAME as usize] == bias[ALTREF_FRAME as usize] {- h.comp_fixed_ref = GOLDEN_FRAME;- h.comp_var_ref = [LAST_FRAME, ALTREF_FRAME];- } else {- h.comp_fixed_ref = LAST_FRAME;- h.comp_var_ref = [GOLDEN_FRAME, ALTREF_FRAME];- }+ }+ if reference_mode != 0 {+ for i in 0..5 {+ diff_update_prob(bd, &mut fc.comp_ref[i]);}- // frame_reference_mode_probs (6.3.13)- if h.reference_mode == 2 {- for i in 0..5 {- diff_update_prob(&mut bd, &mut fc.comp_mode[i]);- }+ }+}++/// mv_probs (6.3.16).+fn read_mv_probs(bd: &mut BoolDecoder, allow_high_precision_mv: bool, fc: &mut FrameContext) {+ for j in 0..3 {+ update_mv_prob(bd, &mut fc.mv_joint[j]);+ }+ for i in 0..2 {+ update_mv_prob(bd, &mut fc.mv_sign[i]);+ for j in 0..10 {+ update_mv_prob(bd, &mut fc.mv_class[i][j]);}- if h.reference_mode != 1 {- for i in 0..5 {- diff_update_prob(&mut bd, &mut fc.single_ref[i][0]);- diff_update_prob(&mut bd, &mut fc.single_ref[i][1]);- }+ update_mv_prob(bd, &mut fc.mv_class0_bit[i]);+ for j in 0..10 {+ update_mv_prob(bd, &mut fc.mv_bits[i][j]);}- if h.reference_mode != 0 {- for i in 0..5 {- diff_update_prob(&mut bd, &mut fc.comp_ref[i]);+ }+ for i in 0..2 {+ for j in 0..2 {+ for k in 0..3 {+ update_mv_prob(bd, &mut fc.mv_class0_fr[i][j][k]);}}- for i in 0..4 {- for j in 0..9 {- diff_update_prob(&mut bd, &mut fc.y_mode[i][j]);- }+ for k in 0..3 {+ update_mv_prob(bd, &mut fc.mv_fr[i][k]);}- for i in 0..16 {- for j in 0..3 {- diff_update_prob(&mut bd, &mut fc.partition[i][j]);- }+ }+ if allow_high_precision_mv {+ for i in 0..2 {+ update_mv_prob(bd, &mut fc.mv_class0_hp[i]);+ update_mv_prob(bd, &mut fc.mv_hp[i]);}- // mv_probs (6.3.16)+ }+}++/// Probability updates that only inter frames carry (6.3.8 to 6.3.16).+fn read_inter_frame_probs(bd: &mut BoolDecoder, h: &mut FrameHeader, fc: &mut FrameContext) {+ for i in 0..7 {for j in 0..3 {- update_mv_prob(&mut bd, &mut fc.mv_joint[j]);+ diff_update_prob(bd, &mut fc.inter_mode[i][j]);}- for i in 0..2 {- update_mv_prob(&mut bd, &mut fc.mv_sign[i]);- for j in 0..10 {- update_mv_prob(&mut bd, &mut fc.mv_class[i][j]);- }- update_mv_prob(&mut bd, &mut fc.mv_class0_bit[i]);- for j in 0..10 {- update_mv_prob(&mut bd, &mut fc.mv_bits[i][j]);+ }+ if h.interp_filter == SWITCHABLE {+ for j in 0..4 {+ for i in 0..2 {+ diff_update_prob(bd, &mut fc.interp_filter[j][i]);}}- for i in 0..2 {- for j in 0..2 {- for k in 0..3 {- update_mv_prob(&mut bd, &mut fc.mv_class0_fr[i][j][k]);- }- }- for k in 0..3 {- update_mv_prob(&mut bd, &mut fc.mv_fr[i][k]);- }+ }+ for i in 0..4 {+ diff_update_prob(bd, &mut fc.is_inter[i]);+ }+ read_frame_reference_mode(bd, h);+ read_frame_reference_mode_probs(bd, h.reference_mode, fc);+ for i in 0..4 {+ for j in 0..9 {+ diff_update_prob(bd, &mut fc.y_mode[i][j]);}- if h.allow_high_precision_mv {- for i in 0..2 {- update_mv_prob(&mut bd, &mut fc.mv_class0_hp[i]);- update_mv_prob(&mut bd, &mut fc.mv_hp[i]);- }+ }+ for i in 0..16 {+ for j in 0..3 {+ diff_update_prob(bd, &mut fc.partition[i][j]);+ }+ }+ read_mv_probs(bd, h.allow_high_precision_mv, fc);+}++/// Parse the compressed header (6.3) into `h` and the probabilities `fc`.+pub fn parse_compressed(data: &[u8], h: &mut FrameHeader, fc: &mut FrameContext) -> Result<()> {+ let mut bd = BoolDecoder::new(data);+ // read_tx_mode (6.3.1)+ h.tx_mode = if h.lossless {+ 0+ } else {+ let mut m = bd.read_literal(2) as u8;+ if m == 3 {+ m += bd.read_literal(1) as u8;}+ m+ };+ if h.tx_mode == TX_MODE_SELECT {+ read_tx_mode_probs(&mut bd, fc);+ }+ read_coef_probs(&mut bd, h, fc);+ for i in 0..3 {+ diff_update_prob(&mut bd, &mut fc.skip[i]);+ }+ if !h.frame_is_intra {+ read_inter_frame_probs(&mut bd, h, fc);}Ok(())}diff --git a/crates/vp9/src/inter.rs b/crates/vp9/src/inter.rsindex ce9e21a44..9e411de5c 100644--- a/crates/vp9/src/inter.rs+++ b/crates/vp9/src/inter.rs@@ -27,29 +27,30 @@ impl RefPlane<'_> {}}+/// Geometry and filtering parameters of one motion-compensated block.+#[derive(Clone, Copy, Debug)]+pub struct McBlock {+ /// Top-left sample position in 1/16 sample units of the reference.+ pub x: i32,+ pub y: i32,+ /// Step per output sample in 1/16 units (16 = unscaled).+ pub step_x: i32,+ pub step_y: i32,+ pub w: usize,+ pub h: usize,+ pub filter: u8,+ pub bit_depth: u8,+}+/// Predict a `w` x `h` block whose top-left sample is at (`x`, `y`) in 1/16 sample units of the/// reference, stepping `step_x` / `step_y` (16 = unscaled). Output samples go to `out` (stride/// `w`). `tmp` must hold at least `(h * step_y / 16 + 8) * w` entries, `win` at least/// `(w + 7) * (h + 7)` (edge-clamped source window).-#[allow(clippy::too_many_arguments)]-pub fn predict(- r: &RefPlane,- x: i32,- y: i32,- step_x: i32,- step_y: i32,- w: usize,- h: usize,- filter: u8,- bit_depth: u8,- out: &mut [u16],- tmp: &mut [u16],- win: &mut [u16],-) {- if step_x == 16 && step_y == 16 {- predict_unscaled(r, x, y, w, h, filter, bit_depth, out, tmp, win);+pub fn predict(r: &RefPlane, blk: &McBlock, out: &mut [u16], tmp: &mut [u16], win: &mut [u16]) {+ if blk.step_x == 16 && blk.step_y == 16 {+ predict_unscaled(r, blk, out, tmp, win);} else {- predict_scaled(r, x, y, step_x, step_y, w, h, filter, bit_depth, out, tmp);+ predict_scaled(r, blk, out, tmp);}}@@ -72,8 +73,8 @@ fn fetch_window(r: &RefPlane, x0: i32, y0: i32, w: usize, h: usize, win: &mut [uws}-#[allow(clippy::too_many_arguments)]-fn predict_unscaled(r: &RefPlane, x: i32, y: i32, w: usize, h: usize, filter: u8, bit_depth: u8, out: &mut [u16], tmp: &mut [u16], win: &mut [u16]) {+fn predict_unscaled(r: &RefPlane, blk: &McBlock, out: &mut [u16], tmp: &mut [u16], win: &mut [u16]) {+ let McBlock { x, y, w, h, filter, bit_depth, .. } = *blk;let (x0, y0) = (x >> 4, y >> 4);let (fx, fy) = ((x & 15) as usize, (y & 15) as usize);let max = (1i32 << bit_depth) - 1;@@ -238,8 +239,8 @@ fn filter_v_n<const W: usize>(s: &[u16], ss: usize, f: &[i16], max: i32, o: &mut}/// General process of 8.5.2.4 (any step).-#[allow(clippy::too_many_arguments)]-fn predict_scaled(r: &RefPlane, x: i32, y: i32, step_x: i32, step_y: i32, w: usize, h: usize, filter: u8, bit_depth: u8, out: &mut [u16], tmp: &mut [u16]) {+fn predict_scaled(r: &RefPlane, blk: &McBlock, out: &mut [u16], tmp: &mut [u16]) {+ let McBlock { x, y, step_x, step_y, w, h, filter, bit_depth } = *blk;let max = (1i32 << bit_depth) - 1;let ih = ((((h as i32 - 1) * step_y + 15) >> 4) + 8) as usize;for row in 0..ih {@@ -304,8 +305,8 @@ mod tests {for &(bw, bh) in &[(4usize, 4usize), (8, 8), (16, 8)] {let mut a = vec![0u16; bw * bh];let mut b = vec![0u16; bw * bh];- predict_unscaled(&r, x, y, bw, bh, filter, 8, &mut a, &mut tmp, &mut [0u16; 71 * 71]);- predict_scaled(&r, x, y, 16, 16, bw, bh, filter, 8, &mut b, &mut tmp);+ predict_unscaled(&r, &McBlock { x, y, step_x: 16, step_y: 16, w: bw, h: bh, filter, bit_depth: 8 }, &mut a, &mut tmp, &mut [0u16; 71 * 71]);+ predict_scaled(&r, &McBlock { x, y, step_x: 16, step_y: 16, w: bw, h: bh, filter, bit_depth: 8 }, &mut b, &mut tmp);assert_eq!(a, b, "filter {filter} pos ({x},{y}) {bw}x{bh}");}}diff --git a/crates/vp9/src/intra.rs b/crates/vp9/src/intra.rsindex 9c797eea3..78ba60535 100644--- a/crates/vp9/src/intra.rs+++ b/crates/vp9/src/intra.rs@@ -1,6 +1,6 @@//! Intra prediction process (8.5.1).-use crate::tables::*;+use crate::tables::{D45_PRED, D63_PRED, D117_PRED, D135_PRED, D153_PRED, D207_PRED, H_PRED, TM_PRED, V_PRED};/// Edge availability and geometry of one intra-predicted transform block.pub struct IntraEdge {@@ -14,33 +14,54 @@ pub struct IntraEdge {pub bit_depth: u8,}-/// Predict a `4 << tx_size` square block at (`x`, `y`) of a plane buffer. `buf` is addressed as-/// `buf[y * stride + x - x_off]` (the buffer may be a tile-column strip starting at column `x_off`).-pub fn predict(buf: &mut [u16], stride: usize, x_off: usize, x: usize, y: usize, mode: u8, e: &IntraEdge) {- let log2 = e.tx_size as usize + 2;- let size = 1usize << log2;+/// Neighbouring samples of a transform block: `above[0]` is the top-left corner,+/// `above[1..=2*size]` the above row and `left[..size]` the left column.+struct Neighbours {+ above: [i32; 65],+ left: [i32; 32],+}++impl Neighbours {+ /// aboveRow[i] for `i` in `-1..2*size`.+ fn a(&self, i: isize) -> i32 {+ self.above[(i + 1) as usize]+ }+}++type Block = [[i32; 32]; 32];++fn r1(v: i32) -> i32 {+ (v + 1) >> 1+}++fn r2(v: i32) -> i32 {+ (v + 2) >> 2+}++/// Gathers (and pads, per 8.5.1.1) the above row, top-left corner and left column.+fn gather_neighbours(buf: &[u16], stride: usize, x_off: usize, x: usize, y: usize, e: &IntraEdge) -> Neighbours {+ let size = 4usize << e.tx_size;let base = 1i32 << (e.bit_depth - 1);let at = |xx: usize, yy: usize| yy * stride + xx - x_off;// aboveRow[-1..2*size) stored at above[0..2*size+1); leftCol[0..size).- let mut above = [0i32; 65];- let mut left = [0i32; 32];+ let mut n = Neighbours { above: [0i32; 65], left: [0i32; 32] };if !e.have_above {- above[1..=2 * size].fill(base - 1);+ n.above[1..=2 * size].fill(base - 1);} else {let row = (y - 1) * stride;for i in 0..size {- above[1 + i] = buf[row + (x + i).min(e.max_x) - x_off] as i32;+ n.above[1 + i] = buf[row + (x + i).min(e.max_x) - x_off] as i32;}if e.not_on_right && e.tx_size == 0 {for i in size..2 * size {- above[1 + i] = buf[row + (x + i).min(e.max_x) - x_off] as i32;+ n.above[1 + i] = buf[row + (x + i).min(e.max_x) - x_off] as i32;}} else {- let v = above[size];- above[1 + size..=2 * size].fill(v);+ let v = n.above[size];+ n.above[1 + size..=2 * size].fill(v);}}- above[0] = if e.have_above && e.have_left {+ n.above[0] = if e.have_above && e.have_left {buf[at((x - 1).min(e.max_x), y - 1)] as i32} else if e.have_above {base + 1@@ -49,166 +70,161 @@ pub fn predict(buf: &mut [u16], stride: usize, x_off: usize, x: usize, y: usize,};if e.have_left {for i in 0..size {- left[i] = buf[at(x - 1, (y + i).min(e.max_y))] as i32;+ n.left[i] = buf[at(x - 1, (y + i).min(e.max_y))] as i32;}} else {- left[..size].fill(base + 1);+ n.left[..size].fill(base + 1);}- let a = |i: isize| above[(i + 1) as usize];- let max = (1i32 << e.bit_depth) - 1;- let o = at(x, y);- let mut put = |i: usize, j: usize, v: i32| buf[o + i * stride + j] = v as u16;- let r1 = |v: i32| (v + 1) >> 1;- let r2 = |v: i32| (v + 2) >> 2;- match mode {- V_PRED => {- for i in 0..size {- for j in 0..size {- put(i, j, a(j as isize));- }- }+ n+}++fn pred_d207(n: &Neighbours, size: usize) -> Block {+ let left = &n.left;+ let mut p = [[0i32; 32]; 32];+ for j in 0..size {+ p[size - 1][j] = left[size - 1];+ }+ for i in 0..size - 1 {+ p[i][0] = r1(left[i] + left[i + 1]);+ }+ for i in 0..size.saturating_sub(2) {+ p[i][1] = r2(left[i] + 2 * left[i + 1] + left[i + 2]);+ }+ p[size - 2][1] = r2(left[size - 2] + 3 * left[size - 1]);+ for j in 2..size {+ for i in (0..size - 1).rev() {+ p[i][j] = p[i + 1][j - 2];}- H_PRED => {- for i in 0..size {- for j in 0..size {- put(i, j, left[i]);- }- }+ }+ p+}++fn pred_d117(n: &Neighbours, size: usize) -> Block {+ let (left, a) = (&n.left, |i: isize| n.a(i));+ let mut p = [[0i32; 32]; 32];+ for j in 0..size {+ p[0][j] = r1(a(j as isize - 1) + a(j as isize));+ }+ p[1][0] = r2(left[0] + 2 * a(-1) + a(0));+ for j in 1..size {+ p[1][j] = r2(a(j as isize - 2) + 2 * a(j as isize - 1) + a(j as isize));+ }+ p[2][0] = r2(a(-1) + 2 * left[0] + left[1]);+ for i in 3..size {+ p[i][0] = r2(left[i - 3] + 2 * left[i - 2] + left[i - 1]);+ }+ for i in 2..size {+ for j in 1..size {+ p[i][j] = p[i - 2][j - 1];}- D207_PRED => {- let mut p = [[0i32; 32]; 32];- for j in 0..size {- p[size - 1][j] = left[size - 1];- }- for i in 0..size - 1 {- p[i][0] = r1(left[i] + left[i + 1]);- }- for i in 0..size.saturating_sub(2) {- p[i][1] = r2(left[i] + 2 * left[i + 1] + left[i + 2]);- }- p[size - 2][1] = r2(left[size - 2] + 3 * left[size - 1]);- for j in 2..size {- for i in (0..size - 1).rev() {- p[i][j] = p[i + 1][j - 2];- }- }- for i in 0..size {- for j in 0..size {- put(i, j, p[i][j]);- }- }+ }+ p+}++fn pred_d135(n: &Neighbours, size: usize) -> Block {+ let (left, a) = (&n.left, |i: isize| n.a(i));+ let mut p = [[0i32; 32]; 32];+ p[0][0] = r2(left[0] + 2 * a(-1) + a(0));+ for j in 1..size {+ p[0][j] = r2(a(j as isize - 2) + 2 * a(j as isize - 1) + a(j as isize));+ }+ p[1][0] = r2(a(-1) + 2 * left[0] + left[1]);+ for i in 2..size {+ p[i][0] = r2(left[i - 2] + 2 * left[i - 1] + left[i]);+ }+ for i in 1..size {+ for j in 1..size {+ p[i][j] = p[i - 1][j - 1];}- D45_PRED => {- for i in 0..size {- for j in 0..size {- let k = (i + j) as isize;- let v = if i + j + 2 < 2 * size { r2(a(k) + 2 * a(k + 1) + a(k + 2)) } else { a(2 * size as isize - 1) };- put(i, j, v);- }- }+ }+ p+}++fn pred_d153(n: &Neighbours, size: usize) -> Block {+ let (left, a) = (&n.left, |i: isize| n.a(i));+ let mut p = [[0i32; 32]; 32];+ p[0][0] = r1(left[0] + a(-1));+ for i in 1..size {+ p[i][0] = r1(left[i - 1] + left[i]);+ }+ p[0][1] = r2(left[0] + 2 * a(-1) + a(0));+ p[1][1] = r2(a(-1) + 2 * left[0] + left[1]);+ for i in 2..size {+ p[i][1] = r2(left[i - 2] + 2 * left[i - 1] + left[i]);+ }+ for j in 2..size {+ p[0][j] = r2(a(j as isize - 3) + 2 * a(j as isize - 2) + a(j as isize - 1));+ }+ for i in 1..size {+ for j in 2..size {+ p[i][j] = p[i - 1][j - 2];}- D63_PRED => {- for i in 0..size {- for j in 0..size {- let k = (i / 2 + j) as isize;- let v = if i & 1 == 1 { r2(a(k) + 2 * a(k + 1) + a(k + 2)) } else { r1(a(k) + a(k + 1)) };- put(i, j, v);- }+ }+ p+}++/// DC prediction value, depending on which edges are available.+fn dc_value(n: &Neighbours, e: &IntraEdge) -> i32 {+ let log2 = e.tx_size as usize + 2;+ let size = 1usize << log2;+ let left = n.left[..size].iter().sum::<i32>();+ let above = n.above[1..=size].iter().sum::<i32>();+ match (e.have_left, e.have_above) {+ (true, true) => (left + above + size as i32) >> (log2 + 1),+ (true, false) => (left + (1 << (log2 - 1))) >> log2,+ (false, true) => (above + (1 << (log2 - 1))) >> log2,+ (false, false) => 1i32 << (e.bit_depth - 1),+ }+}++/// Predict a `4 << tx_size` square block at (`x`, `y`) of a plane buffer. `buf` is addressed as+/// `buf[y * stride + x - x_off]` (the buffer may be a tile-column strip starting at column `x_off`).+pub fn predict(buf: &mut [u16], stride: usize, x_off: usize, x: usize, y: usize, mode: u8, e: &IntraEdge) {+ let size = 4usize << e.tx_size;+ let n = gather_neighbours(buf, stride, x_off, x, y, e);+ let a = |i: isize| n.a(i);+ let max = (1i32 << e.bit_depth) - 1;+ let o = y * stride + x - x_off;+ let mut put = |i: usize, j: usize, v: i32| buf[o + i * stride + j] = v as u16;+ let mut fill = |f: &dyn Fn(usize, usize) -> i32| {+ for i in 0..size {+ for j in 0..size {+ put(i, j, f(i, j));}}+ };+ match mode {+ V_PRED => fill(&|_, j| a(j as isize)),+ H_PRED => fill(&|i, _| n.left[i]),+ D207_PRED => {+ let p = pred_d207(&n, size);+ fill(&|i, j| p[i][j]);+ }+ D45_PRED => fill(&|i, j| {+ let k = (i + j) as isize;+ if i + j + 2 < 2 * size { r2(a(k) + 2 * a(k + 1) + a(k + 2)) } else { a(2 * size as isize - 1) }+ }),+ D63_PRED => fill(&|i, j| {+ let k = (i / 2 + j) as isize;+ if i & 1 == 1 { r2(a(k) + 2 * a(k + 1) + a(k + 2)) } else { r1(a(k) + a(k + 1)) }+ }),D117_PRED => {- let mut p = [[0i32; 32]; 32];- for j in 0..size {- p[0][j] = r1(a(j as isize - 1) + a(j as isize));- }- p[1][0] = r2(left[0] + 2 * a(-1) + a(0));- for j in 1..size {- p[1][j] = r2(a(j as isize - 2) + 2 * a(j as isize - 1) + a(j as isize));- }- p[2][0] = r2(a(-1) + 2 * left[0] + left[1]);- for i in 3..size {- p[i][0] = r2(left[i - 3] + 2 * left[i - 2] + left[i - 1]);- }- for i in 2..size {- for j in 1..size {- p[i][j] = p[i - 2][j - 1];- }- }- for i in 0..size {- for j in 0..size {- put(i, j, p[i][j]);- }- }+ let p = pred_d117(&n, size);+ fill(&|i, j| p[i][j]);}D135_PRED => {- let mut p = [[0i32; 32]; 32];- p[0][0] = r2(left[0] + 2 * a(-1) + a(0));- for j in 1..size {- p[0][j] = r2(a(j as isize - 2) + 2 * a(j as isize - 1) + a(j as isize));- }- p[1][0] = r2(a(-1) + 2 * left[0] + left[1]);- for i in 2..size {- p[i][0] = r2(left[i - 2] + 2 * left[i - 1] + left[i]);- }- for i in 1..size {- for j in 1..size {- p[i][j] = p[i - 1][j - 1];- }- }- for i in 0..size {- for j in 0..size {- put(i, j, p[i][j]);- }- }+ let p = pred_d135(&n, size);+ fill(&|i, j| p[i][j]);}D153_PRED => {- let mut p = [[0i32; 32]; 32];- p[0][0] = r1(left[0] + a(-1));- for i in 1..size {- p[i][0] = r1(left[i - 1] + left[i]);- }- p[0][1] = r2(left[0] + 2 * a(-1) + a(0));- p[1][1] = r2(a(-1) + 2 * left[0] + left[1]);- for i in 2..size {- p[i][1] = r2(left[i - 2] + 2 * left[i - 1] + left[i]);- }- for j in 2..size {- p[0][j] = r2(a(j as isize - 3) + 2 * a(j as isize - 2) + a(j as isize - 1));- }- for i in 1..size {- for j in 2..size {- p[i][j] = p[i - 1][j - 2];- }- }- for i in 0..size {- for j in 0..size {- put(i, j, p[i][j]);- }- }- }- TM_PRED => {- for i in 0..size {- for j in 0..size {- put(i, j, (a(j as isize) + left[i] - a(-1)).clamp(0, max));- }- }+ let p = pred_d153(&n, size);+ fill(&|i, j| p[i][j]);}+ TM_PRED => fill(&|i, j| (a(j as isize) + n.left[i] - a(-1)).clamp(0, max)),_ => {// DC_PRED- let v = match (e.have_left, e.have_above) {- (true, true) => {- let sum: i32 = left[..size].iter().sum::<i32>() + above[1..=size].iter().sum::<i32>();- (sum + size as i32) >> (log2 + 1)- }- (true, false) => (left[..size].iter().sum::<i32>() + (1 << (log2 - 1))) >> log2,- (false, true) => (above[1..=size].iter().sum::<i32>() + (1 << (log2 - 1))) >> log2,- (false, false) => base,- };- for i in 0..size {- for j in 0..size {- put(i, j, v);- }- }+ let v = dc_value(&n, e);+ fill(&|_, _| v);}}}diff --git a/crates/vp9/src/lib.rs b/crates/vp9/src/lib.rsindex f280da808..7d1776ef8 100644--- a/crates/vp9/src/lib.rs+++ b/crates/vp9/src/lib.rs@@ -17,7 +17,6 @@//! }//! ```-#![allow(clippy::needless_range_loop, clippy::too_many_arguments)]#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]mod boolcoder;@@ -36,7 +35,7 @@ mod tables;mod tile;mod transform;#[rustfmt::skip]-#[allow(dead_code, clippy::all)]+#[allow(dead_code)]mod transform_gen;pub use decoder::{DecodeStats, Decoder};diff --git a/crates/vp9/src/loopfilter.rs b/crates/vp9/src/loopfilter.rsindex 80066b444..942b8bb82 100644--- a/crates/vp9/src/loopfilter.rs+++ b/crates/vp9/src/loopfilter.rs@@ -2,7 +2,10 @@use crate::frame::{MiGrid, MiInfo};use crate::header::{LoopFilterParams, Segmentation};-use crate::tables::*;+use crate::tables::{+ BLOCK_8X8, BLOCK_16X16, INTRA_FRAME, MAX_LOOP_FILTER, MAX_TXSIZE, NEARESTMV, NEARMV, NEWMV, NUM_8X8_HIGH, NUM_8X8_WIDE, SEG_LVL_ALT_L, SS_SIZE_LOOKUP,+ TX_4X4, TX_8X8, TX_16X16,+};/// Frame-level loop filter setup (8.8.1) plus the per-level limits of 8.8.4.pub struct LfFrame {diff --git a/crates/vp9/src/probs.rs b/crates/vp9/src/probs.rsindex 5ac3a3941..6f7b71f93 100644--- a/crates/vp9/src/probs.rs+++ b/crates/vp9/src/probs.rs@@ -1,7 +1,13 @@//! Probability tables (a "frame context"), syntax element counters and the backward adaptation//! processes of section 8.4.-use crate::tables::*;+use crate::tables::{+ BINARY_TREE, COUNT_SAT, DEFAULT_COEF_PROBS, DEFAULT_COMP_MODE_PROB, DEFAULT_COMP_REF_PROB, DEFAULT_INTER_MODE_PROBS, DEFAULT_INTERP_FILTER_PROBS,+ DEFAULT_IS_INTER_PROB, DEFAULT_MV_BITS_PROB, DEFAULT_MV_CLASS_PROBS, DEFAULT_MV_CLASS0_BIT_PROB, DEFAULT_MV_CLASS0_FR_PROBS, DEFAULT_MV_CLASS0_HP_PROB,+ DEFAULT_MV_FR_PROBS, DEFAULT_MV_HP_PROB, DEFAULT_MV_JOINT_PROBS, DEFAULT_MV_SIGN_PROB, DEFAULT_PARTITION_PROBS, DEFAULT_SINGLE_REF_PROB, DEFAULT_SKIP_PROB,+ DEFAULT_TX_PROBS, DEFAULT_UV_MODE_PROBS, DEFAULT_Y_MODE_PROBS, INTER_MODE_TREE, INTERP_FILTER_TREE, INTRA_MODE_TREE, MAX_UPDATE_FACTOR, MV_CLASS_TREE,+ MV_FR_TREE, MV_JOINT_TREE, PARTITION_TREE, SMALL_TOKEN_TREE, TX_SIZE_8_TREE, TX_SIZE_16_TREE, TX_SIZE_32_TREE,+};/// coef_probs[txSz][plane > 0][is_inter][band][ctx][node].pub type CoefProbs = [[[[[[u8; 3]; 6]; 6]; 2]; 2]; 4];@@ -135,6 +141,17 @@ macro_rules! add_nested {add_nested!(x, y, 2);}};+ ($a:expr, $b:expr, 6) => {+ for (x, y) in $a.iter_mut().zip($b.iter()) {+ for (x, y) in x.iter_mut().zip(y.iter()) {+ for (x, y) in x.iter_mut().zip(y.iter()) {+ for (x, y) in x.iter_mut().zip(y.iter()) {+ add_nested!(x, y, 2);+ }+ }+ }+ }+ };}impl Counts {@@ -160,24 +177,13 @@ impl Counts {add_nested!(self.mv_bits, o.mv_bits, 3);add_nested!(self.mv_fr, o.mv_fr, 2);add_nested!(self.mv_hp, o.mv_hp, 2);- for (a, b) in self.token.iter_mut().zip(o.token.iter()) {- for (a, b) in a.iter_mut().zip(b.iter()) {- for (a, b) in a.iter_mut().zip(b.iter()) {- for (a, b) in a.iter_mut().zip(b.iter()) {- add_nested!(a, b, 2);- }- }- }- }- for (a, b) in self.more_coefs.iter_mut().zip(o.more_coefs.iter()) {- for (a, b) in a.iter_mut().zip(b.iter()) {- for (a, b) in a.iter_mut().zip(b.iter()) {- for (a, b) in a.iter_mut().zip(b.iter()) {- add_nested!(a, b, 2);- }- }- }- }+ self.add_coef_counts(o);+ }++ /// Accumulate the per-coefficient token and more_coefs counts of another tile.+ fn add_coef_counts(&mut self, o: &Counts) {+ add_nested!(self.token, o.token, 6);+ add_nested!(self.more_coefs, o.more_coefs, 6);}}diff --git a/crates/vp9/src/tile.rs b/crates/vp9/src/tile.rsindex 0c2ca02b5..2693d5543 100644--- a/crates/vp9/src/tile.rs+++ b/crates/vp9/src/tile.rs@@ -6,7 +6,14 @@ use crate::boolcoder::BoolDecoder;use crate::frame::{Frame, MiGrid, MiInfo, Mv};use crate::header::{FrameHeader, Segmentation};use crate::probs::{Counts, FrameContext};-use crate::tables::*;+use crate::tables::{+ ALTREF_FRAME, B_HEIGHT_LOG2, B_WIDTH_LOG2, BLOCK_8X8, BLOCK_64X64, BLOCK_INVALID, BORDERINPIXELS, COMPANDED_MVREF_THRESH, COUNTER_TO_CONTEXT, DC_PRED,+ GOLDEN_FRAME, IDX_N_COLUMN_TO_SUBBLOCK, INTER_MODE_TREE, INTERP_EXTEND, INTERP_FILTER_TREE, INTRA_FRAME, INTRA_MODE_TREE, KF_PARTITION_PROBS,+ KF_UV_MODE_PROBS, KF_Y_MODE_PROBS, LAST_FRAME, MAX_TXSIZE, MI_WIDTH_LOG2, MODE_2_COUNTER, MV_BORDER, MV_CLASS_TREE, MV_FR_TREE, MV_JOINT_TREE,+ MV_REF_BLOCKS, NEARESTMV, NEARMV, NEWMV, NONE, NUM_4X4_HIGH, NUM_4X4_WIDE, NUM_8X8_HIGH, NUM_8X8_WIDE, PARTITION_TREE, SEG_LVL_REF_FRAME, SEG_LVL_SKIP,+ SEGMENT_TREE, SIZE_GROUP, SS_SIZE_LOOKUP, SUBSIZE_LOOKUP, SWITCHABLE, TX_MODE_SELECT, TX_MODE_TO_BIGGEST_TX_SIZE, TX_SIZE_8_TREE, TX_SIZE_16_TREE,+ TX_SIZE_32_TREE, ZEROMV,+};mod recon;diff --git a/crates/vp9/src/tile/recon.rs b/crates/vp9/src/tile/recon.rsindex 44f1fef78..0f5d3e11a 100644--- a/crates/vp9/src/tile/recon.rs+++ b/crates/vp9/src/tile/recon.rs@@ -5,12 +5,75 @@ use super::{Blk, TileDecoder};use crate::boolcoder::BoolDecoder;use crate::error::Error;use crate::frame::Mv;-use crate::inter::{self, RefPlane};+use crate::inter::{self, McBlock, RefPlane};use crate::intra::{self, IntraEdge};-use crate::tables::*;+use crate::tables::{+ BLOCK_8X8, CAT_PROBS, COEFBAND_4X4, COEFBAND_8X8PLUS, DCT_DCT, ENERGY_CLASS, EXTRA_BITS, INTERP_EXTEND, INTRA_FRAME, MAX_TXSIZE, MODE2TXFM, NUM_4X4_HIGH,+ NUM_4X4_WIDE, NUM_8X8_HIGH, NUM_8X8_WIDE, SS_SIZE_LOOKUP, TX_4X4, TX_32X32, neighbors, pareto_full, scan,+};use crate::transform;+/// Sample rectangle of a block region within its plane.+#[derive(Clone, Copy)]+struct Region {+ x: usize,+ y: usize,+ w: usize,+ h: usize,+}+/// round_mv_comp_q2 / q4 (8.5.2.1).+/// Location and transform parameters of one transform block within a plane.+#[derive(Clone, Copy)]+struct TxBlock {+ plane: usize,+ start_x: usize,+ start_y: usize,+ tx_sz: u8,+ tx_type: u8,+}++/// Walks the pareto part of the token tree, returning a token in `2..=10`.+fn read_large_token(bd: &mut BoolDecoder, pp: &[u8; 8]) -> usize {+ if !bd.read_bool(pp[0]) {+ if !bd.read_bool(pp[1]) {+ 2+ } else if !bd.read_bool(pp[2]) {+ 3+ } else {+ 4+ }+ } else if !bd.read_bool(pp[3]) {+ if !bd.read_bool(pp[4]) { 5 } else { 6 }+ } else if !bd.read_bool(pp[5]) {+ if !bd.read_bool(pp[6]) { 7 } else { 8 }+ } else if !bd.read_bool(pp[7]) {+ 9+ } else {+ 10+ }+}++/// read_coef (6.4.26): the unsigned coefficient magnitude of a token of at least 2.+fn read_coef(bd: &mut BoolDecoder, token: usize, bit_depth: u8) -> i64 {+ let (cat, num_extra, base) = EXTRA_BITS[token];+ let mut v = base as i64;+ if token == 10 {+ for e in 0..(bit_depth as u32 - 8) {+ if bd.read_bool(255) {+ v += 1 << (5 + bit_depth as u32 - e);+ }+ }+ }+ let cp = CAT_PROBS[cat as usize];+ for e in 0..num_extra as usize {+ if bd.read_bool(cp[e]) {+ v += 1 << (num_extra as usize - 1 - e);+ }+ }+ v+}+fn round_q2(v: i32) -> i32 {(if v < 0 { v - 1 } else { v + 1 }) / 2}@@ -36,11 +99,11 @@ impl<'a> TileDecoder<'a> {if b.size < BLOCK_8X8 {for y in 0..n4h {for x in 0..n4w {- self.predict_inter(b, plane, base_x + 4 * x, base_y + 4 * y, 4, 4, y * n4w + x);+ self.predict_inter(b, plane, Region { x: base_x + 4 * x, y: base_y + 4 * y, w: 4, h: 4 }, y * n4w + x);}}} else {- self.predict_inter(b, plane, base_x, base_y, n4w * 4, n4h * 4, 0);+ self.predict_inter(b, plane, Region { x: base_x, y: base_y, w: n4w * 4, h: n4h * 4 }, 0);}}let max_x = (self.mi_cols * 8) >> sx;@@ -74,7 +137,7 @@ impl<'a> TileDecoder<'a> {intra::predict(&mut self.strip.planes[plane], stride, x_off, start_x, start_y, mode, &edge);}if !b.skip {- let (eob, rows) = self.tokens(bd, b, plane, start_x, start_y, tx_sz, tx_type);+ let (eob, rows) = self.tokens(bd, b, &TxBlock { plane, start_x, start_y, tx_sz, tx_type });nonzero = eob > 0;b.eob_total += nonzero as u32;if eob > 0 {@@ -82,12 +145,7 @@ impl<'a> TileDecoder<'a> {let o = start_y * stride + start_x - x_off;transform::inverse_transform_add(&self.coefs,- tx_sz,- tx_type,- self.h.lossless,- eob,- rows,- self.bit_depth,+ &transform::InverseTx { tx_size: tx_sz, tx_type, lossless: self.h.lossless, eob, rows, bit_depth: self.bit_depth },&mut self.strip.planes[plane][o..],stride,);@@ -123,17 +181,8 @@ impl<'a> TileDecoder<'a> {}}- /// tokens (6.4.24): reads and dequantizes the coefficients into `self.coefs`. Returns the end- /// of block position and the number of leading coefficient rows that may be non-zero.- #[allow(clippy::too_many_arguments)]- fn tokens(&mut self, bd: &mut BoolDecoder, b: &Blk, plane: usize, start_x: usize, start_y: usize, tx_sz: u8, tx_type: u8) -> (usize, usize) {- let seg_eob = 16usize << (tx_sz << 1);- let sc = scan(tx_sz, tx_type);- let nb = neighbors(tx_sz, tx_type);- let bands: &[u8] = if tx_sz == 0 { &COEFBAND_4X4 } else { &COEFBAND_8X8PLUS };- let ptype = (plane > 0) as usize;- let rtype = b.is_inter as usize;- let probs = &self.fc.coef[tx_sz as usize][ptype][rtype];+ /// Above/left non-zero context of a transform block (the initial token context).+ fn initial_token_ctx(&self, plane: usize, start_x: usize, start_y: usize, tx_sz: u8) -> usize {let (sx, sy) = if plane > 0 { (self.ss_x, self.ss_y) } else { (0, 0) };let max_x4 = (2 * self.mi_cols) >> sx;let max_y4 = (2 * self.mi_rows) >> sy;@@ -149,7 +198,21 @@ impl<'a> TileDecoder<'a> {left |= self.left_nonzero[plane][y4 + i];}}- let ctx0 = (above + left) as usize;+ (above + left) as usize+ }++ /// tokens (6.4.24): reads and dequantizes the coefficients into `self.coefs`. Returns the end+ /// of block position and the number of leading coefficient rows that may be non-zero.+ fn tokens(&mut self, bd: &mut BoolDecoder, b: &Blk, t: &TxBlock) -> (usize, usize) {+ let TxBlock { plane, start_x, start_y, tx_sz, tx_type } = *t;+ let seg_eob = 16usize << (tx_sz << 1);+ let sc = scan(tx_sz, tx_type);+ let nb = neighbors(tx_sz, tx_type);+ let bands: &[u8] = if tx_sz == 0 { &COEFBAND_4X4 } else { &COEFBAND_8X8PLUS };+ let ptype = (plane > 0) as usize;+ let rtype = b.is_inter as usize;+ let probs = &self.fc.coef[tx_sz as usize][ptype][rtype];+ let ctx0 = self.initial_token_ctx(plane, start_x, start_y, tx_sz);let q = self.s.seg_q[b.seg_id as usize][ptype];let dq_shift = (tx_sz == TX_32X32) as u32;let pareto = pareto_full();@@ -204,40 +267,8 @@ impl<'a> TileDecoder<'a> {counts.token[tx_sz as usize][ptype][rtype][band][ctx][2] += 1;}let pp = &pareto[p[2].max(1) as usize - 1];- token = if !bd.read_bool(pp[0]) {- if !bd.read_bool(pp[1]) {- 2- } else if !bd.read_bool(pp[2]) {- 3- } else {- 4- }- } else if !bd.read_bool(pp[3]) {- if !bd.read_bool(pp[4]) { 5 } else { 6 }- } else if !bd.read_bool(pp[5]) {- if !bd.read_bool(pp[6]) { 7 } else { 8 }- } else if !bd.read_bool(pp[7]) {- 9- } else {- 10- };- // read_coef (6.4.26)- let (cat, num_extra, base) = EXTRA_BITS[token];- let mut v = base as i64;- if token == 10 {- for e in 0..(bit_depth as u32 - 8) {- if bd.read_bool(255) {- v += 1 << (5 + bit_depth as u32 - e);- }- }- }- let cp = CAT_PROBS[cat as usize];- for e in 0..num_extra as usize {- if bd.read_bool(cp[e]) {- v += 1 << (num_extra as usize - 1 - e);- }- }- coef = v;+ token = read_large_token(bd, pp);+ coef = read_coef(bd, token, bit_depth);}tc[pos] = ENERGY_CLASS[token];let sign = bd.read_bool(128);@@ -251,8 +282,8 @@ impl<'a> TileDecoder<'a> {}/// Inter prediction process (8.5.2) for one block region.- #[allow(clippy::too_many_arguments)]- fn predict_inter(&mut self, b: &Blk, plane: usize, x: usize, y: usize, w: usize, h: usize, block_idx: usize) {+ fn predict_inter(&mut self, b: &Blk, plane: usize, region: Region, block_idx: usize) {+ let Region { x, y, w, h } = region;let is_compound = b.ref_frame[1] > INTRA_FRAME;let (sx, sy) = if plane > 0 { (self.ss_x, self.ss_y) } else { (0, 0) };for rl in 0..1 + is_compound as usize {@@ -312,7 +343,8 @@ impl<'a> TileDecoder<'a> {let rp =RefPlane { frame: f, plane, last_x: ((f.info.width as i32 + sx as i32) >> sx) - 1, last_y: ((f.info.height as i32 + sy as i32) >> sy) - 1 };let out = if rl == 0 { &mut self.pred } else { &mut self.pred2 };- inter::predict(&rp, start_x, start_y, step_x, step_y, w, h, b.interp_filter, self.bit_depth, out, &mut self.mc_tmp, &mut self.mc_win);+ let blk = McBlock { x: start_x, y: start_y, step_x, step_y, w, h, filter: b.interp_filter, bit_depth: self.bit_depth };+ inter::predict(&rp, &blk, out, &mut self.mc_tmp, &mut self.mc_win);}let (stride, x_off) = (self.strip.strides[plane], self.strip.x_off[plane]);let dst = &mut self.strip.planes[plane];diff --git a/crates/vp9/src/transform.rs b/crates/vp9/src/transform.rsindex a9d60c19c..218a58a30 100644--- a/crates/vp9/src/transform.rs+++ b/crates/vp9/src/transform.rs@@ -142,10 +142,23 @@ fn sat(v: i32, lim: i32) -> i32 {v.clamp(-lim, lim)}+/// Block description for [`inverse_transform_add`].+#[derive(Clone, Copy, Debug)]+pub struct InverseTx {+ pub tx_size: u8,+ pub tx_type: u8,+ pub lossless: bool,+ /// End-of-block position (number of coded coefficients).+ pub eob: usize,+ /// Number of leading rows that can hold non-zero values.+ pub rows: usize,+ pub bit_depth: u8,+}+/// Inverse transform `coefs` (row-major n x n dequantized coefficients, `rows` = number of leading/// rows that can hold non-zero values) and add the residual to `dst` (8.6.2 step 4).-#[allow(clippy::too_many_arguments)]-pub fn inverse_transform_add(coefs: &[i32], tx_size: u8, tx_type: u8, lossless: bool, eob: usize, rows: usize, bit_depth: u8, dst: &mut [u16], stride: usize) {+pub fn inverse_transform_add(coefs: &[i32], tx: &InverseTx, dst: &mut [u16], stride: usize) {+ let InverseTx { tx_size, tx_type, lossless, eob, rows, bit_depth } = *tx;let n = 4usize << tx_size;let max = (1i32 << bit_depth) - 1;if lossless {@@ -441,8 +454,8 @@ mod tests {coefs[0] = dc;let mut a = vec![128u16; n * n];let mut b = vec![128u16; n * n];- inverse_transform_add(&coefs, tx, DCT_DCT, false, 1, 1, 8, &mut a, n);- inverse_transform_add(&coefs, tx, DCT_DCT, false, 2, n, 8, &mut b, n);+ inverse_transform_add(&coefs, &InverseTx { tx_size: tx, tx_type: DCT_DCT, lossless: false, eob: 1, rows: 1, bit_depth: 8 }, &mut a, n);+ inverse_transform_add(&coefs, &InverseTx { tx_size: tx, tx_type: DCT_DCT, lossless: false, eob: 2, rows: n, bit_depth: 8 }, &mut b, n);assert_eq!(a, b, "tx {tx} dc {dc}");}}@@ -514,7 +527,7 @@ mod tests {let mut coefs = [0i32; 16];coefs[0] = 4 * 4;let mut dst = [100u16; 16];- inverse_transform_add(&coefs, 0, DCT_DCT, true, 1, 4, 8, &mut dst, 4);+ inverse_transform_add(&coefs, &InverseTx { tx_size: 0, tx_type: DCT_DCT, lossless: true, eob: 1, rows: 4, bit_depth: 8 }, &mut dst, 4);let sum: i32 = dst.iter().map(|&v| v as i32 - 100).sum();assert_eq!(sum, 16);}