edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching0 forksRust370.3 MiB8fd360cTahinli2 months ago2655 commits
| 1 | //! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out. |
| 2 | //! |
| 3 | //! This is the layer that turns the pieces below it — the intra predictors of |
| 4 | //! [`crate::intra`], the forward transform and quantizer of |
| 5 | //! [`crate::transform`], and the tile writer of [`crate::tile`] — into |
| 6 | //! something that takes a picture. Every block is 32x32 (its chroma 16x16), |
| 7 | //! which is the subset the tile writer codes, and each one picks its luma mode |
| 8 | //! from the seven non-directional ones by rate-distortion; chroma searches |
| 9 | //! its own `uv_mode` over the seven that read no further than the row above |
| 10 | //! and the column to the left, its transform type derived from that mode the |
| 11 | //! way the decoder derives it. Block sizes are what a loop above this would |
| 12 | //! choose between. |
| 13 | //! |
| 14 | //! The encoder carries its own reconstruction, because prediction reads it: a |
| 15 | //! block predicts from the reconstructed samples above and to its left, exactly |
| 16 | //! as the decoder will. That makes the reconstruction a claim about what a |
| 17 | //! decoder produces, and it is gated as one — sample for sample against ffmpeg. |
| 18 | |
| 19 | use crate::decode::WithRef; |
| 20 | use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader}; |
| 21 | use ec_av1_syntax::{ |
| 22 | CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, |
| 23 | LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode, |
| 24 | }; |
| 25 | use ec_core::{Error, Result}; |
| 26 | |
| 27 | use crate::cdf; |
| 28 | use crate::cdf_state::TxbSet; |
| 29 | use crate::frame::frame_obu; |
| 30 | use crate::intra::{ |
| 31 | D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, |
| 32 | SMOOTH_V_PRED, V_PRED, |
| 33 | }; |
| 34 | use crate::mc; |
| 35 | use crate::motion; |
| 36 | use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16}; |
| 37 | use crate::obu::temporal_delimiter; |
| 38 | use crate::quant::ac_q; |
| 39 | use crate::sequence::sequence_header_obu; |
| 40 | use crate::tile::{ |
| 41 | BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits, |
| 42 | }; |
| 43 | use crate::transform::{ |
| 44 | TxType, dequant_and_inverse_typed_wh, forward_and_quantize, |
| 45 | forward_and_quantize_typed, |
| 46 | }; |
| 47 | |
| 48 | /// The side of the larger of the two luma blocks this encoder codes, in |
| 49 | /// samples. |
| 50 | const BLOCK: usize = 32; |
| 51 | |
| 52 | /// The side of the smaller one, which a 32x32 block may be split into four of. |
| 53 | const SUB: usize = 16; |
| 54 | |
| 55 | /// The side of a superblock, which is what the partition tree starts from. |
| 56 | pub(crate) const SUPERBLOCK: usize = 64; |
| 57 | |
| 58 | // lane-sb128 r1: the superblock size in samples the intra-reach rules |
| 59 | // (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the |
| 60 | // block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and |
| 61 | // tests the "top row"/"rightmost column" of THAT superblock, so a 128x128 |
| 62 | // superblock changes every answer inside it (the tables themselves are |
| 63 | // already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`] |
| 64 | // stays the encoder's own fixed 64. |
| 65 | |
| 66 | /// Sets the superblock size [`Reach`] answers against (64 or 128). |
| 67 | pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) { |
| 68 | fctx.reach_sb_px.with(|c| c.set(px)); |
| 69 | } |
| 70 | |
| 71 | fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize { |
| 72 | fctx.reach_sb_px.with(|c| c.get()) |
| 73 | } |
| 74 | |
| 75 | /// How heavily the mode search weighs rate against squared error, in units of |
| 76 | /// the quantizer's reconstruction step squared per bit. |
| 77 | /// |
| 78 | /// Swept three times over his clips and three synthetic pictures |
| 79 | /// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in |
| 80 | /// the three lane reports). The first sweep, before the mode symbol was |
| 81 | /// costed, put the best point at 0.05; costing it moved the point to 0.1. The |
| 82 | /// third sweep, after the levels were costed through the writer's own CDFs |
| 83 | /// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98% |
| 84 | /// on film and -0.20% against -0.14% on screen capture. |
| 85 | /// |
| 86 | /// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than |
| 87 | /// those ladders, and 0.1 was far off the point: the rate term was carrying |
| 88 | /// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom / |
| 89 | /// vs rav1e for 1080p film, 2160p film, screen capture: |
| 90 | /// |
| 91 | /// | lambda | 1080p | 2160p | screen | |
| 92 | /// |--------|-------|-------|--------| |
| 93 | /// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 | |
| 94 | /// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 | |
| 95 | /// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 | |
| 96 | /// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 | |
| 97 | /// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 | |
| 98 | /// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 | |
| 99 | /// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 | |
| 100 | /// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 | |
| 101 | /// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 | |
| 102 | /// |
| 103 | /// and on the native 1920x1024 crops, which is the table that decides: |
| 104 | /// |
| 105 | /// | lambda | film 1080p | film 2160p | screen | |
| 106 | /// |--------|------------|------------|--------| |
| 107 | /// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 | |
| 108 | /// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 | |
| 109 | /// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 | |
| 110 | /// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 | |
| 111 | /// |
| 112 | /// 0.0375 was the best point on two clips of three there and cost the "2160p |
| 113 | /// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept |
| 114 | /// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the |
| 115 | /// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of |
| 116 | /// whose cells have no intra cost -- no real film supported the point. |
| 117 | /// |
| 118 | /// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL |
| 119 | /// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs |
| 120 | /// libaom / vs rav1e, everything else at the shipped defaults: |
| 121 | /// |
| 122 | /// | lambda | bars 1080p | bars 2160p | film A | film B | screen | |
| 123 | /// |--------|------------|------------|--------|--------|--------| |
| 124 | /// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 | |
| 125 | /// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 | |
| 126 | /// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 | |
| 127 | /// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 | |
| 128 | /// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 | |
| 129 | /// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 | |
| 130 | /// |
| 131 | /// Real film wants roughly HALF the rate weight the bars asked for: the bowl |
| 132 | /// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep |
| 133 | /// against the shipped 0.05, while the bars rows walk the other way (they are |
| 134 | /// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so |
| 135 | /// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture |
| 136 | /// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx |
| 137 | /// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall. |
| 138 | const LAMBDA_SCALE: f64 = 0.0275; |
| 139 | |
| 140 | /// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes |
| 141 | /// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen). |
| 142 | /// |
| 143 | /// The ARF-vs-ARF census says our top ARF codes residual over HALF its area |
| 144 | /// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x |
| 145 | /// its bytes at the same PSNR, while every leaf that predicts from it is |
| 146 | /// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at |
| 147 | /// a rate weight fitted on shown frames and does not propagate. This is the |
| 148 | /// one knob that prices a hidden frame's rate differently from its q, which |
| 149 | /// the pyramid's q offsets cannot do (they move lambda and step together). |
| 150 | const HIDDEN_LAMBDA_FACTOR: f64 = 1.0; |
| 151 | |
| 152 | /// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build. |
| 153 | fn hidden_lambda_factor() -> f64 { |
| 154 | match std::env::var("EC_AV1_LAMBDA_HIDDEN").ok().and_then(|v| v.parse().ok()) { |
| 155 | Some(f) => f, |
| 156 | None => HIDDEN_LAMBDA_FACTOR, |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that |
| 161 | /// picks it is the thing running. A release build has no such knob. |
| 162 | fn lambda_scale() -> f64 { |
| 163 | let swept = std::env::var("EC_AV1_LAMBDA") |
| 164 | .ok() |
| 165 | .and_then(|v| v.parse::<f64>().ok()); |
| 166 | match swept { |
| 167 | Some(scale) if cfg!(test) => scale, |
| 168 | _ => LAMBDA_SCALE, |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// How a key frame's lambda differs from an inter frame's: libaom weighs the |
| 173 | /// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out |
| 174 | /// of 128), because every later frame predicts from the key frame, so an error |
| 175 | /// left in it is paid for over the whole group. This encoder has no temporal |
| 176 | /// propagation model at all, and this factor is the cheapest stand-in for one. |
| 177 | /// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`]. |
| 178 | /// |
| 179 | /// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs |
| 180 | /// libaom / vs rav1e: |
| 181 | /// |
| 182 | /// | k_key | 1080p | 2160p | screen | |
| 183 | /// |---|---|---|---| |
| 184 | /// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 | |
| 185 | /// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 | |
| 186 | /// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 | |
| 187 | /// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 | |
| 188 | /// |
| 189 | /// The two films want the key frame coded finer and the screen capture wants |
| 190 | /// the opposite, by about the same amount, and at native the whole lever is |
| 191 | /// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3, |
| 192 | /// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2, |
| 193 | /// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a |
| 194 | /// per-frame-type weight; the real lever here is temporal propagation |
| 195 | /// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames |
| 196 | /// predict from, not each frame. |
| 197 | const KEY_LAMBDA_FACTOR: f64 = 1.0; |
| 198 | |
| 199 | /// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build. |
| 200 | fn key_lambda_factor() -> f64 { |
| 201 | match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) { |
| 202 | Some(k) if cfg!(test) => k, |
| 203 | _ => KEY_LAMBDA_FACTOR, |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // Every frame's predicted coefficient bits since the last |
| 208 | // `take_predicted_bits`, in coding order -- the encoder half of |
| 209 | // `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement. |
| 210 | #[cfg(test)] |
| 211 | thread_local! { |
| 212 | static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) }; |
| 213 | } |
| 214 | |
| 215 | /// Records one frame's predicted coefficient bits. |
| 216 | #[cfg(test)] |
| 217 | fn record_predicted_bits(bits: f64) { |
| 218 | PREDICTED_BITS.with(|p| p.borrow_mut().push(bits)); |
| 219 | } |
| 220 | |
| 221 | /// Takes (and clears) what the frames encoded on this thread were predicted to |
| 222 | /// spend on coefficients. |
| 223 | #[cfg(test)] |
| 224 | pub(crate) fn take_predicted_bits() -> Vec<f64> { |
| 225 | PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut())) |
| 226 | } |
| 227 | |
| 228 | /// Whether a 16x16 inter leaf may split into four 8x8 ones of its own. |
| 229 | pub(crate) const SPLIT_INTER_8: bool = true; |
| 230 | |
| 231 | /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build. |
| 232 | /// Whether a key frame codes `tx_mode == TxMode::Select` and searches each |
| 233 | /// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0` |
| 234 | /// turns it off for an A/B on one build. |
| 235 | /// Whether an INTER frame also carries `TxMode::Select`: an inter block's |
| 236 | /// residual as one transform over the whole block or as the four transforms |
| 237 | /// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every |
| 238 | /// intra block inside the inter frame. ON since lane-av1tx2, which found why |
| 239 | /// the streams desynced -- the writer counted the [`crate::decode:: |
| 240 | /// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the |
| 241 | /// reader drops the term -- and measured the split search: BD-rate vs libaom |
| 242 | /// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the |
| 243 | /// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an |
| 244 | /// A/B on one build. |
| 245 | fn tx_select_inter() -> bool { |
| 246 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 247 | crate::envflags::var("EC_AV1_TX_SELECT_INTER") |
| 248 | .ok() |
| 249 | .map(|v| !matches!(v.as_str(), "0" | "off")) |
| 250 | }); |
| 251 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER)) |
| 252 | } |
| 253 | |
| 254 | fn tx_select() -> bool { |
| 255 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 256 | crate::envflags::var("EC_AV1_TX_SELECT") |
| 257 | .ok() |
| 258 | .map(|v| !matches!(v.as_str(), "0" | "off")) |
| 259 | }); |
| 260 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY)) |
| 261 | } |
| 262 | |
| 263 | fn split_inter_8() -> bool { |
| 264 | match std::env::var("EC_AV1_SPLIT_INTER8").ok() { |
| 265 | Some(v) if cfg!(test) => v != "0", |
| 266 | _ => crate::speed::at(&crate::speed::SPLIT_8), |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the |
| 271 | /// NEARESTMV candidate it always had. |
| 272 | pub(crate) const LEAF_NEW_MV: bool = true; |
| 273 | |
| 274 | /// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the |
| 275 | /// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0 |
| 276 | /// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion |
| 277 | /// searches (the census `bd_rate_vs_libaom_and_rav1e` prints). |
| 278 | pub(crate) const EXTRA_REF_NEW_MV: bool = true; |
| 279 | |
| 280 | /// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's |
| 281 | /// own best vector before that reference's `NEWMV` search is skipped: a |
| 282 | /// factor on the search cost scale, `1.0` meaning "as good or better". |
| 283 | /// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`, |
| 284 | /// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9 |
| 285 | /// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the |
| 286 | /// extra searches drop from +27% to +4% of the base count -- and on screen |
| 287 | /// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of |
| 288 | /// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7). |
| 289 | /// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25 |
| 290 | /// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7, |
| 291 | /// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1, |
| 292 | /// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's |
| 293 | /// own noise. 0.35 stays; the lever that did move at the new rate weight is |
| 294 | /// [`LEAF_SECOND_NEW_MARGIN`], not this one. |
| 295 | const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35; |
| 296 | |
| 297 | /// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`. |
| 298 | fn extra_new_skip_margin() -> f64 { |
| 299 | match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() { |
| 300 | Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN), |
| 301 | _ => EXTRA_NEW_SKIP_MARGIN, |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// The margin on a LEAF's SECOND-reference motion search, the same early-out |
| 306 | /// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference |
| 307 | /// `NEWMV`: the search is skipped when that reference's own |
| 308 | /// `NEAREST_NEARESTMV` vector already prices this many times better than the |
| 309 | /// leaf's `LAST` search found. `0.0` never skips. |
| 310 | /// |
| 311 | /// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs |
| 312 | /// libaom (1080p/2160p/screen) against the extra `motion::search` calls at |
| 313 | /// 2160p (38195 with no second-reference search at all): |
| 314 | /// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093, |
| 315 | /// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at |
| 316 | /// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the |
| 317 | /// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter |
| 318 | /// of its extra searches; past it the calls double for another -0.3/-0.5. |
| 319 | /// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is |
| 320 | /// all `NEAREST_NEARESTMV` and no searched second vector ever wins there -- |
| 321 | /// so the margin is pure wall on that content (+10% searches at 0.8). |
| 322 | /// |
| 323 | /// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on |
| 324 | /// the native gate with local warp on, BD vs libaom / vs rav1e: |
| 325 | /// |
| 326 | /// | margin | film 1080p | film 2160p | screen | |
| 327 | /// |---|---|---|---| |
| 328 | /// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 | |
| 329 | /// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 | |
| 330 | /// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 | |
| 331 | /// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 | |
| 332 | /// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 | |
| 333 | /// |
| 334 | /// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns |
| 335 | /// with screen flat -- and it beats never-skipping, i.e. the early-out is |
| 336 | /// still worth having, just at a looser margin than the old rate weight |
| 337 | /// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs |
| 338 | /// 32.6s at 2160p), which is the price of the extra second-reference |
| 339 | /// searches. |
| 340 | const LEAF_SECOND_NEW_MARGIN: f64 = 1.2; |
| 341 | |
| 342 | /// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the |
| 343 | /// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`. |
| 344 | fn leaf_second_new_margin() -> f64 { |
| 345 | match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() { |
| 346 | Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN), |
| 347 | None => LEAF_SECOND_NEW_MARGIN, |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// Whether a leaf searches its SECOND reference at all (lane-av1comp4). |
| 352 | fn leaf_second_new_mv() -> bool { |
| 353 | match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() { |
| 354 | Some(v) => v != "0", |
| 355 | None => crate::speed::at(&crate::speed::LEAF_SECOND), |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | /// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the |
| 360 | /// whole 32x32 block is (lane-av1comp3). The writer already codes a compound |
| 361 | /// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both |
| 362 | /// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what |
| 363 | /// was missing was the encoder ever forming one below 32x32. |
| 364 | pub(crate) const LEAF_COMPOUND: bool = true; |
| 365 | |
| 366 | /// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build. |
| 367 | fn leaf_compound() -> bool { |
| 368 | match std::env::var("EC_AV1_LEAF_COMPOUND").ok() { |
| 369 | Some(v) => v != "0", |
| 370 | None => crate::speed::at(&crate::speed::LEAF_COMPOUND), |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build. |
| 375 | fn leaf_new_mv() -> bool { |
| 376 | match std::env::var("EC_AV1_LEAF_NEWMV").ok() { |
| 377 | Some(v) if cfg!(test) => v != "0", |
| 378 | _ => LEAF_NEW_MV, |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Whether an INTER frame's 32x32 block may be split into four 16x16 ones |
| 383 | /// when the trial says four cost less. Before lane-av1rd2 only a quadrant |
| 384 | /// the true frame edge cut through was ever split there; inside the frame |
| 385 | /// every block was coded whole, which left the partition decision the key |
| 386 | /// frame already makes unmade for eleven frames out of twelve. |
| 387 | pub(crate) const SPLIT_INTER_BLOCKS: bool = true; |
| 388 | |
| 389 | /// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the |
| 390 | /// measurement that keeps it is running (test builds only, like |
| 391 | /// [`lambda_scale`]). |
| 392 | fn split_inter_blocks() -> bool { |
| 393 | match std::env::var("EC_AV1_SPLIT_INTER").ok() { |
| 394 | Some(v) if cfg!(test) => v != "0", |
| 395 | _ => crate::speed::at(&crate::speed::SPLIT_INTER), |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | /// Whether the inter search offers the whole superblock as ONE 64x64 block |
| 400 | /// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32 |
| 401 | /// quadrants it would otherwise always split into. |
| 402 | /// |
| 403 | /// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6 |
| 404 | /// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of |
| 405 | /// them skip at 328 bytes a frame -- while every block this encoder wrote was |
| 406 | /// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669 |
| 407 | /// bits against rav1e's 61,988, about 46% of the film B gap. |
| 408 | /// |
| 409 | /// lane-tx64: no longer skip-only. The root also prices a REAL residual -- |
| 410 | /// one TX_64X64 luma transform (`transform.rs`'s forward network has always |
| 411 | /// reached 64 points; what was missing was the block coder and the writer |
| 412 | /// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`], |
| 413 | /// which carries that arm's own gate table. Still refused at the 64 root: |
| 414 | /// compound references, a depth-1 4x32x32 var-tx tree, intra, and a |
| 415 | /// superblock the true frame edge cuts through. |
| 416 | /// |
| 417 | /// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the |
| 418 | /// root and restores the skip-only shape lane-b64 shipped. |
| 419 | pub(crate) const B64_ROOT: bool = true; |
| 420 | |
| 421 | /// How many superblocks took the 64x64 root since the last |
| 422 | /// [`take_b64_root_hits`], so a gate reports how often it fires rather than |
| 423 | /// assuming it does (class `gate-blind-to-feature`). |
| 424 | static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 425 | |
| 426 | /// The 64x64-root count since the last call, and zero it. |
| 427 | pub fn take_b64_root_hits() -> usize { |
| 428 | B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 429 | } |
| 430 | |
| 431 | /// [`B64_ROOT`], or what `EC_AV1_B64` names. |
| 432 | fn b64_root() -> bool { |
| 433 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 434 | crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0") |
| 435 | }); |
| 436 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT)) |
| 437 | } |
| 438 | |
| 439 | /// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the |
| 440 | /// winner's prediction through one TX_64X64 luma transform and two TX_32X32 |
| 441 | /// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root |
| 442 | /// lane-b64 shipped, so the two can be measured against each other on the |
| 443 | /// same build. |
| 444 | /// |
| 445 | /// MEASURED on the native gate (two arms of one build, baseline reproduced to |
| 446 | /// the tenth): both film rows improve on both columns -- film A |
| 447 | /// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and |
| 448 | /// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's |
| 449 | /// +-0.3 screen clause. So the caller gates this off on a screen frame |
| 450 | /// (`allow_screen_content_tools`), the same content gate the coding pyramid |
| 451 | /// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm |
| 452 | /// already codes them for nothing, and a residual there only spends bits the |
| 453 | /// intra/palette tools would have spent better. |
| 454 | /// |
| 455 | /// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` + |
| 456 | /// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on: |
| 457 | /// |
| 458 | /// | | skip-only | + residual | |
| 459 | /// |---|---|---| |
| 460 | /// | 64x64 share, all frames | 36.4% | 38.3% | |
| 461 | /// | 64x64 share, leaf frames | 53.3% | 56.0% | |
| 462 | /// | skip area, all frames | 80.4% | 78.8% | |
| 463 | /// | skip area, leaf frames | 90.2% | 88.5% | |
| 464 | /// | stream bytes | 34,366 | 34,295 | |
| 465 | /// | encoder wall | 13.4s | 9.6s | |
| 466 | /// |
| 467 | /// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the |
| 468 | /// TX_64X64 coefficients are really being coded. The root wins MORE often |
| 469 | /// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is |
| 470 | /// 45.2%), which is also why the arm is 28% FASTER despite costing three more |
| 471 | /// transforms per superblock: a root that wins is four quadrant searches that |
| 472 | /// never run. |
| 473 | fn b64_residual() -> bool { |
| 474 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 475 | crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0") |
| 476 | }); |
| 477 | ENV.unwrap_or(true) && b64_root() |
| 478 | } |
| 479 | |
| 480 | /// How many 64x64 roots came out cheaper with a residual than skipped, since |
| 481 | /// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate |
| 482 | /// rather than assuming one (class `gate-blind-to-feature`). |
| 483 | static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 484 | |
| 485 | /// The non-skip 64x64-root count since the last call, and zero it. |
| 486 | pub fn take_b64_residual_hits() -> usize { |
| 487 | B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 488 | } |
| 489 | |
| 490 | /// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the |
| 491 | /// `LAST` + extra-reference pairs the 32x32 level already offers, at the |
| 492 | /// three modes a root can form without a second 64x64 motion search -- |
| 493 | /// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half |
| 494 | /// is the vector `search_skip_64`'s own single-reference search already |
| 495 | /// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own |
| 496 | /// `NEWMV` vector, which only a second search per superblock produces -- the |
| 497 | /// wall this root exists to save -- so they are not offered here. |
| 498 | /// |
| 499 | /// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build. |
| 500 | fn b64_compound() -> bool { |
| 501 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 502 | crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0") |
| 503 | }); |
| 504 | ENV.unwrap_or(true) && b64_root() |
| 505 | } |
| 506 | |
| 507 | /// How many 64x64 roots took a COMPOUND candidate since the last |
| 508 | /// [`take_b64_compound_hits`] (class `gate-blind-to-feature`). |
| 509 | static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 510 | |
| 511 | /// The compound 64x64-root count since the last call, and zero it. |
| 512 | pub fn take_b64_compound_hits() -> usize { |
| 513 | B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 514 | } |
| 515 | |
| 516 | /// Whether a 64x64 root that codes a residual may SPLIT its luma transform |
| 517 | /// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by |
| 518 | /// [`commit_inter_luma`] like every other inter block's var-tx, and coded by |
| 519 | /// the writer's `Whole64` arm as `txfm_split = 1`. It exists because |
| 520 | /// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose |
| 521 | /// residual has detail in the other three quadrants cannot code it at all. |
| 522 | /// |
| 523 | /// Off by `EC_AV1_B64VARTX=0`. |
| 524 | fn b64_var_tx() -> bool { |
| 525 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 526 | crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0") |
| 527 | }); |
| 528 | ENV.unwrap_or(true) && b64_root() |
| 529 | } |
| 530 | |
| 531 | /// How many 64x64 roots split their luma transform since the last |
| 532 | /// [`take_b64_var_tx_hits`]. |
| 533 | static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 534 | |
| 535 | /// The split-luma 64x64-root count since the last call, and zero it. |
| 536 | pub fn take_b64_var_tx_hits() -> usize { |
| 537 | B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 538 | } |
| 539 | |
| 540 | /// Whether a superblock the true frame edge CUTS THROUGH may be left whole |
| 541 | /// (lane-b64b). AV1 asks only that the block's own half is inside |
| 542 | /// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already |
| 543 | /// codes that case; what was missing was a trial whose SSE is scored over the |
| 544 | /// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse) |
| 545 | /// instead of over the padding the encoder |
| 546 | /// invented past the edge. Both gate films are superblock-aligned, so this |
| 547 | /// only reaches the user's own arbitrary export sizes. |
| 548 | /// |
| 549 | /// Off by `EC_AV1_B64EDGE=0`. |
| 550 | fn b64_edge() -> bool { |
| 551 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 552 | crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0") |
| 553 | }); |
| 554 | ENV.unwrap_or(true) && b64_root() |
| 555 | } |
| 556 | |
| 557 | /// How many 64x64 roots the frame edge cut through since the last |
| 558 | /// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are |
| 559 | /// superblock-aligned, so nothing but a synthetic size fires this). |
| 560 | static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 561 | |
| 562 | /// The edge 64x64-root count since the last call, and zero it. |
| 563 | pub fn take_b64_edge_hits() -> usize { |
| 564 | B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 565 | } |
| 566 | |
| 567 | /// Whether the encoder searches loop restoration at all (spec 7.17): one |
| 568 | /// Wiener filter per 64x64 luma restoration unit, picked from |
| 569 | /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a |
| 570 | /// test build, like [`lambda_scale`]. |
| 571 | pub(crate) const RESTORATION: bool = true; |
| 572 | |
| 573 | /// [`RESTORATION`], or what `EC_AV1_LR` names in a test build. |
| 574 | fn restoration_enabled() -> bool { |
| 575 | match std::env::var("EC_AV1_LR").ok() { |
| 576 | Some(v) if cfg!(test) => v != "0", |
| 577 | _ => crate::speed::at(&crate::speed::RESTORATION), |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | /// libaom's `partition_search_breakout` shape: how many non-zero luma |
| 582 | /// coefficients per 256 luma samples a block may code and still be judged |
| 583 | /// well enough predicted that the split below it is not worth trying. `0` |
| 584 | /// disables the breakout (only the existing all-skip prune applies), which |
| 585 | /// is the default until the sweep below justifies otherwise. |
| 586 | /// |
| 587 | /// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which |
| 588 | /// is where this lane's wall would have gone: 1 cuts the three clips' |
| 589 | /// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9 |
| 590 | /// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs |
| 591 | /// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this |
| 592 | /// encoder's inter quality lives, so `0` ships and the knob stays for a |
| 593 | /// future explicit speed preset. |
| 594 | pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0; |
| 595 | |
| 596 | /// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own |
| 597 | /// currency: a 32x32 inter block whose whole-block RD cost per pixel comes |
| 598 | /// out under `threshold * lambda` is not offered the split at all, and a |
| 599 | /// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both |
| 600 | /// always, as before this lever. |
| 601 | /// |
| 602 | /// The census is what points here: the split trial runs on nearly every |
| 603 | /// non-skip block (15132 leaf searches per ladder point on the 1080p clip) |
| 604 | /// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient |
| 605 | /// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD |
| 606 | /// points, so the gate has to read the block's own RD cost, not its levels. |
| 607 | /// |
| 608 | /// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of |
| 609 | /// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for |
| 610 | /// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and |
| 611 | /// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs |
| 612 | /// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships -- |
| 613 | /// the largest threshold whose BD stays inside the +0.3 keep rule on every |
| 614 | /// clip. |
| 615 | /// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base |
| 616 | /// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1, |
| 617 | /// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is |
| 618 | /// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off |
| 619 | /// the screen wall). Neither clears the keep rule; 0.125 stays. |
| 620 | pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125; |
| 621 | |
| 622 | /// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build. |
| 623 | fn split_rd_threshold() -> f64 { |
| 624 | static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| { |
| 625 | crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok()) |
| 626 | }); |
| 627 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD)) |
| 628 | } |
| 629 | |
| 630 | /// Whether `cost` over a `side` x `side` block is cheap enough per pixel that |
| 631 | /// [`split_rd_threshold`] withholds the split trial. |
| 632 | fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool { |
| 633 | split_rd_breakout_at(split_rd_threshold(), cost, side, lambda) |
| 634 | } |
| 635 | |
| 636 | /// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own |
| 637 | /// early-out reads. |
| 638 | fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool { |
| 639 | t > 0.0 && cost < t * lambda * (side * side) as f64 |
| 640 | } |
| 641 | |
| 642 | /// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`] |
| 643 | /// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64). |
| 644 | /// |
| 645 | /// The 32x32 level is allowed to loosen its breakout with the speed preset |
| 646 | /// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured |
| 647 | /// what that does one size up: at 0.5 a whole superblock is taken at 64x64 |
| 648 | /// without its four quadrants ever being searched, and film B goes |
| 649 | /// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the |
| 650 | /// same per-pixel threshold withholds four times as much search -- the |
| 651 | /// preset's step is priced for the 32 level and does not carry up here. |
| 652 | fn b64_breakout_threshold() -> f64 { |
| 653 | split_rd_threshold().min(SPLIT_RD_THRESHOLD) |
| 654 | } |
| 655 | |
| 656 | /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test |
| 657 | /// build. |
| 658 | fn split_breakout_coeffs() -> usize { |
| 659 | match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() { |
| 660 | Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS), |
| 661 | _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT), |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | /// How often each partition decision was taken since the last |
| 666 | /// [`take_partition_hits`], so a gate can report how often a new partition |
| 667 | /// fires rather than assume it does (gate-blind-to-feature). Index 0 is an |
| 668 | /// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is |
| 669 | /// such a leaf left whole, 3 one split into four 8x8 leaves of its own. |
| 670 | static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [ |
| 671 | std::sync::atomic::AtomicUsize::new(0), |
| 672 | std::sync::atomic::AtomicUsize::new(0), |
| 673 | std::sync::atomic::AtomicUsize::new(0), |
| 674 | std::sync::atomic::AtomicUsize::new(0), |
| 675 | ]; |
| 676 | |
| 677 | /// Records one such decision. |
| 678 | fn partition_hit(which: usize) { |
| 679 | PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 680 | } |
| 681 | |
| 682 | /// Takes (and clears) the counts. |
| 683 | #[cfg(test)] |
| 684 | pub(crate) fn take_partition_hits() -> [usize; 4] { |
| 685 | [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 686 | } |
| 687 | |
| 688 | /// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full |
| 689 | /// rate-distortion trials the block search actually runs, by kind, and where |
| 690 | /// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by |
| 691 | /// default, and a measurement build rather than a speed one -- the census |
| 692 | /// runs the SAD pre-pass the unpruned search otherwise skips. |
| 693 | pub fn census_on() -> bool { |
| 694 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 695 | *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1"))) |
| 696 | } |
| 697 | |
| 698 | /// What each [`CENSUS`] counter counts. |
| 699 | pub const CENSUS_KINDS: [&str; 11] = [ |
| 700 | "intra blocks searched (key frame + inter leaves)", |
| 701 | "intra luma mode trials", |
| 702 | "chroma searches", |
| 703 | "chroma mode trials (each = 2 plane trials)", |
| 704 | "tx-depth trials (transform units, depth >= 1)", |
| 705 | "inter 32x32 blocks searched", |
| 706 | "inter block intra-mode trials", |
| 707 | "inter mv candidates (each = 3 mc trials)", |
| 708 | "inter leaves searched (intra vs NEARESTMV/NEWMV)", |
| 709 | " of those, intra won", |
| 710 | " of those, the NEARESTMV trial coded no residual", |
| 711 | ]; |
| 712 | |
| 713 | /// The census counters themselves, indexed by [`CENSUS_KINDS`]. |
| 714 | static CENSUS: [std::sync::atomic::AtomicUsize; 11] = |
| 715 | [const { std::sync::atomic::AtomicUsize::new(0) }; 11]; |
| 716 | |
| 717 | /// Where the RD winner sat in the SAD ranking, for the luma intra search and |
| 718 | /// the chroma mode search -- what says whether a top-N prune would have kept |
| 719 | /// the block the search actually chose. |
| 720 | static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] = |
| 721 | [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; |
| 722 | static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] = |
| 723 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 724 | |
| 725 | fn census_add(kind: usize, n: usize) { |
| 726 | if census_on() { |
| 727 | CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | /// Reads (and clears) the census, so a driver can attribute it to its own encode. |
| 732 | pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) { |
| 733 | let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed); |
| 734 | ( |
| 735 | std::array::from_fn(|i| take(&CENSUS[i])), |
| 736 | std::array::from_fn(|i| take(&LUMA_RANK[i])), |
| 737 | std::array::from_fn(|i| take(&CHROMA_RANK[i])), |
| 738 | ) |
| 739 | } |
| 740 | |
| 741 | /// The rank of `winner` in `scored` ordered by its cheap score, cheapest |
| 742 | /// first -- the census's one shared rule, so the luma and chroma histograms |
| 743 | /// mean the same thing. |
| 744 | fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize { |
| 745 | scored |
| 746 | .iter() |
| 747 | .filter(|&&(score, mode)| { |
| 748 | mode != winner |
| 749 | && score |
| 750 | < scored |
| 751 | .iter() |
| 752 | .find(|&&(_, m)| m == winner) |
| 753 | .map_or(f64::INFINITY, |&(s, _)| s) |
| 754 | }) |
| 755 | .count() |
| 756 | } |
| 757 | |
| 758 | /// Whether a 32x32 block may be split into four 16x16 ones when the trial says |
| 759 | /// four cost less. Set from the measurement in the lane report. |
| 760 | const SPLIT_BLOCKS: bool = true; |
| 761 | |
| 762 | /// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides |
| 763 | /// by calling [`encode_key_frame_inner`] both ways. |
| 764 | pub(crate) fn split_blocks() -> bool { |
| 765 | SPLIT_BLOCKS |
| 766 | } |
| 767 | |
| 768 | /// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as |
| 769 | /// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used |
| 770 | /// `u16` throughout since the round-hbd-r1/r2 widen; this is the last |
| 771 | /// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit |
| 772 | /// stream's decode output actually carries 10-bit precision instead of |
| 773 | /// silently losing its low 2 bits). The encoder only ever produces values in |
| 774 | /// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2 |
| 775 | /// decision); `Plane::source` narrows right back to `u8` at its two |
| 776 | /// construction sites, a lossless round trip for that range. |
| 777 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 778 | pub struct Picture { |
| 779 | /// The picture's width in luma samples. |
| 780 | pub width: usize, |
| 781 | /// Its height in luma samples. |
| 782 | pub height: usize, |
| 783 | /// The luma plane, `width * height` samples in raster order. |
| 784 | pub y: Vec<u16>, |
| 785 | /// The U plane, at half the width and half the height. |
| 786 | pub u: Vec<u16>, |
| 787 | /// The V plane, the same shape as U. |
| 788 | pub v: Vec<u16>, |
| 789 | } |
| 790 | |
| 791 | impl Picture { |
| 792 | /// A mid-grey picture of the given size. |
| 793 | #[must_use] |
| 794 | pub fn grey(width: usize, height: usize) -> Self { |
| 795 | Self { |
| 796 | width, |
| 797 | height, |
| 798 | y: vec![128; width * height], |
| 799 | u: vec![128; width * height / 4], |
| 800 | v: vec![128; width * height / 4], |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | pub(crate) fn check(&self) -> Result<()> { |
| 805 | if self.width == 0 |
| 806 | || !self.width.is_multiple_of(BLOCK) |
| 807 | || !self.height.is_multiple_of(BLOCK) |
| 808 | || !self.height.is_multiple_of(BLOCK) |
| 809 | { |
| 810 | return Err(Error::unsupported( |
| 811 | "AV1 encode", |
| 812 | "the picture must be a whole number of 32x32 blocks in each direction", |
| 813 | )); |
| 814 | } |
| 815 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 816 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 817 | return Err(Error::unsupported( |
| 818 | "AV1 encode", |
| 819 | "each plane must carry one sample per position at 4:2:0", |
| 820 | )); |
| 821 | } |
| 822 | Ok(()) |
| 823 | } |
| 824 | |
| 825 | /// What the public entry points require of the picture they are handed, |
| 826 | /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 |
| 827 | /// needs a whole chroma sample per two luma ones) and one sample per |
| 828 | /// position on each plane. |
| 829 | pub(crate) fn check_even(&self) -> Result<()> { |
| 830 | if self.width == 0 |
| 831 | || self.height == 0 |
| 832 | || !self.width.is_multiple_of(2) |
| 833 | || !self.height.is_multiple_of(2) |
| 834 | { |
| 835 | return Err(Error::unsupported( |
| 836 | "AV1 encode", |
| 837 | "the picture's width and height must each be even and nonzero", |
| 838 | )); |
| 839 | } |
| 840 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 841 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 842 | return Err(Error::unsupported( |
| 843 | "AV1 encode", |
| 844 | "each plane must carry one sample per position at 4:2:0", |
| 845 | )); |
| 846 | } |
| 847 | Ok(()) |
| 848 | } |
| 849 | |
| 850 | /// This picture, padded by edge replication to the next whole number of |
| 851 | /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key |
| 852 | /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a |
| 853 | /// sequence (what the inter tile writer's partition needs on top of |
| 854 | /// that). Identity (a plain clone, not a copy through the replication |
| 855 | /// loop) when the picture is already that size — the multiple-of-32 (or |
| 856 | /// -64) fast path is unchanged. |
| 857 | pub(crate) fn padded_to(&self, align: usize) -> Picture { |
| 858 | let padded_width = self.width.next_multiple_of(align); |
| 859 | let padded_height = self.height.next_multiple_of(align); |
| 860 | if padded_width == self.width && padded_height == self.height { |
| 861 | return self.clone(); |
| 862 | } |
| 863 | Picture { |
| 864 | width: padded_width, |
| 865 | height: padded_height, |
| 866 | y: pad_plane( |
| 867 | &self.y, |
| 868 | self.width, |
| 869 | self.height, |
| 870 | padded_width, |
| 871 | padded_height, |
| 872 | ), |
| 873 | u: pad_plane( |
| 874 | &self.u, |
| 875 | self.width / 2, |
| 876 | self.height / 2, |
| 877 | padded_width / 2, |
| 878 | padded_height / 2, |
| 879 | ), |
| 880 | v: pad_plane( |
| 881 | &self.v, |
| 882 | self.width / 2, |
| 883 | self.height / 2, |
| 884 | padded_width / 2, |
| 885 | padded_height / 2, |
| 886 | ), |
| 887 | } |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | /// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8` |
| 892 | /// (8-bit only, unchanged this round -- widening the encoder is out of this |
| 893 | /// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that |
| 894 | /// lets it keep calling [`crate::intra::predict`] now that shape is `u16` |
| 895 | /// in and out. A block-sized round-trip through `u16` is exact for 8-bit |
| 896 | /// content (every value fits both ways), so this changes no encoder output. |
| 897 | #[allow(clippy::too_many_arguments)] |
| 898 | fn intra_predict_u8( |
| 899 | mode: u8, |
| 900 | angle_delta: i32, |
| 901 | above: Option<&[u8]>, |
| 902 | left: Option<&[u8]>, |
| 903 | corner: Option<u8>, |
| 904 | bw: usize, |
| 905 | bh: usize, |
| 906 | enable_edge_filter: bool, |
| 907 | smooth_neighbor: bool, |
| 908 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 909 | ) { |
| 910 | // Three heap allocations per call became three stack buffers: this runs |
| 911 | // once per mode per trial, and an edge is at most `bw + bh` samples while |
| 912 | // a block is at most `BLOCK * BLOCK`. Same samples either way. |
| 913 | let mut above_buf = [0u16; 2 * BLOCK]; |
| 914 | let mut left_buf = [0u16; 2 * BLOCK]; |
| 915 | // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode |
| 916 | // trial of every block, and a 4x4 block writes 32 bytes of it. The |
| 917 | // predictor fills every sample it is handed, so the zeros are dead |
| 918 | // either way -- size the scratch to the block instead of to the largest |
| 919 | // block there is. |
| 920 | |
| 921 | let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| { |
| 922 | for (d, &v) in buf[..src.len()].iter_mut().zip(src) { |
| 923 | *d = u16::from(v); |
| 924 | } |
| 925 | }; |
| 926 | if let Some(s) = above { |
| 927 | widen(s, &mut above_buf); |
| 928 | } |
| 929 | if let Some(s) = left { |
| 930 | widen(s, &mut left_buf); |
| 931 | } |
| 932 | let above16 = above.map(|s| &above_buf[..s.len()]); |
| 933 | let left16 = left.map(|s| &left_buf[..s.len()]); |
| 934 | let mut run = |dst16: &mut [u16]| { |
| 935 | crate::intra::predict( |
| 936 | mode, |
| 937 | angle_delta, |
| 938 | above16, |
| 939 | left16, |
| 940 | corner.map(u16::from), |
| 941 | bw, |
| 942 | bh, |
| 943 | enable_edge_filter, |
| 944 | smooth_neighbor, |
| 945 | dst16, fctx, |
| 946 | ); |
| 947 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { |
| 948 | *d = s as u8; |
| 949 | } |
| 950 | }; |
| 951 | let n = bw * bh; |
| 952 | if n <= 64 { |
| 953 | run(&mut [0u16; 64][..n]); |
| 954 | } else if n <= 256 { |
| 955 | run(&mut [0u16; 256][..n]); |
| 956 | } else { |
| 957 | run(&mut [0u16; BLOCK * BLOCK][..n]); |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | /// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same |
| 962 | /// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one |
| 963 | /// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode. |
| 964 | fn filter_intra_predict_u8( |
| 965 | mode: usize, |
| 966 | above: Option<&[u8]>, |
| 967 | left: Option<&[u8]>, |
| 968 | corner: Option<u8>, |
| 969 | side: usize, |
| 970 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 971 | ) { |
| 972 | let mut above_buf = [0u16; 2 * BLOCK]; |
| 973 | let mut left_buf = [0u16; 2 * BLOCK]; |
| 974 | let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| { |
| 975 | for (d, &v) in buf[..src.len()].iter_mut().zip(src) { |
| 976 | *d = u16::from(v); |
| 977 | } |
| 978 | }; |
| 979 | if let Some(a) = above { |
| 980 | widen(a, &mut above_buf); |
| 981 | } |
| 982 | if let Some(l) = left { |
| 983 | widen(l, &mut left_buf); |
| 984 | } |
| 985 | let mut dst16 = [0u16; BLOCK * BLOCK]; |
| 986 | let n = side * side; |
| 987 | crate::intra::predict_filter_intra( |
| 988 | mode, |
| 989 | above.map(|a| &above_buf[..a.len()]), |
| 990 | left.map(|l| &left_buf[..l.len()]), |
| 991 | corner.map(u16::from), |
| 992 | side, |
| 993 | side, |
| 994 | &mut dst16[..n], fctx, |
| 995 | ); |
| 996 | for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) { |
| 997 | *d = v as u8; |
| 998 | } |
| 999 | } |
| 1000 | |
| 1001 | /// Pads one plane to `(padded_width, padded_height)` by repeating its last |
| 1002 | /// row and column, so the block coder always sees a whole number of blocks. |
| 1003 | /// [`crop_plane`] undoes this on the way back out. |
| 1004 | fn pad_plane<T: Copy + Default>( |
| 1005 | source: &[T], |
| 1006 | width: usize, |
| 1007 | height: usize, |
| 1008 | padded_width: usize, |
| 1009 | padded_height: usize, |
| 1010 | ) -> Vec<T> { |
| 1011 | let mut out = vec![T::default(); padded_width * padded_height]; |
| 1012 | for row in 0..padded_height { |
| 1013 | let src = source[row.min(height - 1) * width..][..width].as_ref(); |
| 1014 | let dst = &mut out[row * padded_width..][..padded_width]; |
| 1015 | dst[..width].copy_from_slice(src); |
| 1016 | dst[width..].fill(src[width - 1]); |
| 1017 | } |
| 1018 | out |
| 1019 | } |
| 1020 | |
| 1021 | /// The top-left `width` x `height` region of a plane that is `padded_width` |
| 1022 | /// wide, which is the render-size crop [`Picture::padded`]'s replication |
| 1023 | /// exists to let a decoder undo. |
| 1024 | fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> { |
| 1025 | let mut out = Vec::with_capacity(width * height); |
| 1026 | for row in 0..height { |
| 1027 | out.extend_from_slice(&source[row * padded_width..][..width]); |
| 1028 | } |
| 1029 | out |
| 1030 | } |
| 1031 | |
| 1032 | /// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size |
| 1033 | /// region a decoder produces, which is the public contract for what a caller |
| 1034 | /// sees back — the padded planes the encoder coded against never leave this |
| 1035 | /// module. Identity when the reconstruction is already that size. |
| 1036 | pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { |
| 1037 | let reconstruction = &encoded.reconstruction; |
| 1038 | let cropped = if reconstruction.width == width && reconstruction.height == height { |
| 1039 | reconstruction.clone() |
| 1040 | } else { |
| 1041 | Picture { |
| 1042 | width, |
| 1043 | height, |
| 1044 | y: crop_plane(&reconstruction.y, reconstruction.width, width, height), |
| 1045 | u: crop_plane( |
| 1046 | &reconstruction.u, |
| 1047 | reconstruction.width / 2, |
| 1048 | width / 2, |
| 1049 | height / 2, |
| 1050 | ), |
| 1051 | v: crop_plane( |
| 1052 | &reconstruction.v, |
| 1053 | reconstruction.width / 2, |
| 1054 | width / 2, |
| 1055 | height / 2, |
| 1056 | ), |
| 1057 | } |
| 1058 | }; |
| 1059 | Encoded { |
| 1060 | stream: encoded.stream.clone(), |
| 1061 | modes: encoded.modes.clone(), |
| 1062 | inter_block_share: encoded.inter_block_share, |
| 1063 | reconstruction: cropped, |
| 1064 | tile: encoded.tile.clone(), |
| 1065 | mi_cols: encoded.mi_cols, |
| 1066 | mi_rows: encoded.mi_rows, |
| 1067 | base_q_idx: encoded.base_q_idx, |
| 1068 | tx_select: encoded.tx_select, |
| 1069 | switchable_motion_mode: encoded.switchable_motion_mode, |
| 1070 | screen: encoded.screen, |
| 1071 | start_cdfs: encoded.start_cdfs.clone(), |
| 1072 | next_cdfs: encoded.next_cdfs.clone(), |
| 1073 | loop_filter: encoded.loop_filter, |
| 1074 | loop_restoration: encoded.loop_restoration, |
| 1075 | allow_intrabc: encoded.allow_intrabc, |
| 1076 | cdef: encoded.cdef, |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | /// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of |
| 1081 | /// numbers nobody wants printed, and [`Encoded`] derives `Debug`. |
| 1082 | #[derive(Clone)] |
| 1083 | pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs); |
| 1084 | |
| 1085 | impl std::fmt::Debug for CdfSnapshot { |
| 1086 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1087 | f.write_str("CdfSnapshot") |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | /// What one call to [`encode_key_frame`] produced. |
| 1092 | #[derive(Clone, Debug)] |
| 1093 | pub struct Encoded { |
| 1094 | /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame |
| 1095 | /// OBU carrying one tile. |
| 1096 | pub stream: Vec<u8>, |
| 1097 | /// What a decoder will produce from `stream` — the encoder's own |
| 1098 | /// reconstruction, which its prediction was built on. |
| 1099 | pub reconstruction: Picture, |
| 1100 | /// The luma intra mode each block was coded under, in the order the blocks |
| 1101 | /// are coded — raster order among the quadrants of each superblock, and |
| 1102 | /// among the four 16x16 blocks of a quadrant that was split. |
| 1103 | pub modes: Vec<u8>, |
| 1104 | /// The fraction of this frame's 32x32 blocks that were coded inter (any |
| 1105 | /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0` |
| 1106 | /// for a key frame, which has no such choice — so a caller can tell a |
| 1107 | /// frame with no motion worth coding from one that never got the chance. |
| 1108 | pub inter_block_share: f64, |
| 1109 | /// The tile payload alone, undecorated by any OBU framing, and the frame |
| 1110 | /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`. |
| 1111 | /// `crate::decode`'s tests are the only reader; a real decoder gets these |
| 1112 | /// off the wire by parsing `stream`'s OBUs instead. |
| 1113 | pub(crate) tile: Vec<u8>, |
| 1114 | pub(crate) mi_cols: u32, |
| 1115 | pub(crate) mi_rows: u32, |
| 1116 | pub(crate) base_q_idx: u8, |
| 1117 | /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and |
| 1118 | /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it, |
| 1119 | /// and reading it off `stream`'s header is what `decode_stream` does. A |
| 1120 | /// test that decodes `tile` directly must pass this one along, or it reads |
| 1121 | /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first |
| 1122 | /// block. |
| 1123 | pub(crate) tx_select: bool, |
| 1124 | /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the |
| 1125 | /// bit that makes every eligible single-reference inter block carry a |
| 1126 | /// `motion_mode` symbol. Same contract as `tx_select` above: a test |
| 1127 | /// decoding `tile` directly must pass it along or it desyncs at the |
| 1128 | /// first eligible block. |
| 1129 | pub(crate) switchable_motion_mode: bool, |
| 1130 | /// The CDF state this frame's tile writer started from -- the defaults |
| 1131 | /// for a key frame and for the first inter frame, and the previous |
| 1132 | /// frame's stored tables after that. A test that decodes `tile` directly |
| 1133 | /// must feed the decoder this, exactly as `decode_stream` feeds it what |
| 1134 | /// the frame's `primary_ref_frame` slot holds (same class as |
| 1135 | /// `tx_select`: a header bit a raw tile decode cannot guess). |
| 1136 | pub(crate) start_cdfs: CdfSnapshot, |
| 1137 | /// What this frame stores into the slots it refreshes (spec 7.20, |
| 1138 | /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the |
| 1139 | /// counts reset when `disable_frame_end_update_cdf` is off, and what it |
| 1140 | /// started from when it is on. |
| 1141 | pub(crate) next_cdfs: CdfSnapshot, |
| 1142 | /// This frame header's chosen deblocking parameters |
| 1143 | /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the |
| 1144 | /// picture the decoder produces UNDER them, so a test that decodes |
| 1145 | /// `tile` directly must pass these along, exactly as it must `tx_select` |
| 1146 | /// (class: test asserts against a stale header). |
| 1147 | pub(crate) loop_filter: LoopFilterParams, |
| 1148 | /// This frame header's chosen CDEF parameters, threaded for the same |
| 1149 | /// reason as `loop_filter`. |
| 1150 | pub(crate) cdef: CdefParams, |
| 1151 | /// This frame header's `allow_screen_content_tools` |
| 1152 | /// ([`screen_content`]) -- every intra block of the tile carries the two |
| 1153 | /// palette-mode symbols under it, so a raw tile decode that guessed |
| 1154 | /// `false` would desync at the first block (same class as `tx_select`). |
| 1155 | pub(crate) screen: bool, |
| 1156 | /// This frame header's chosen loop restoration parameters, threaded for |
| 1157 | /// the same reason as `loop_filter` -- and doubly so: the per-unit |
| 1158 | /// filters themselves are coded in `tile`, so a decode of it under a |
| 1159 | /// stale `RESTORE_NONE` header desyncs at the first superblock. |
| 1160 | pub(crate) loop_restoration: LoopRestorationParams, |
| 1161 | /// This frame header's `allow_intrabc` -- every intra block of the tile |
| 1162 | /// carries a `use_intrabc` symbol under it, so a raw tile decode that |
| 1163 | /// guessed `false` would desync at the first block (same class as |
| 1164 | /// `screen`/`tx_select`). |
| 1165 | pub(crate) allow_intrabc: bool, |
| 1166 | } |
| 1167 | |
| 1168 | thread_local! { |
| 1169 | /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat |
| 1170 | /// for on the last key frame encoded on this thread -- read by the gates, |
| 1171 | /// which print it beside the block counts (class `gate-blind-to-feature`). |
| 1172 | static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) }; |
| 1173 | } |
| 1174 | |
| 1175 | /// [`IBC_SHARE`] for the last key frame encoded on this thread. |
| 1176 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1177 | pub(crate) fn intrabc_source_share() -> f64 { |
| 1178 | IBC_SHARE.with(std::cell::Cell::get) |
| 1179 | } |
| 1180 | |
| 1181 | thread_local! { |
| 1182 | /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence |
| 1183 | /// header offers the per-frame `allow_screen_content_tools` bit at all. |
| 1184 | /// Armed once by the key frame ([`encode_key_frame_inner`], from |
| 1185 | /// [`screen_content`]) and read by every header builder after it, so that |
| 1186 | /// the inter frames of a screen sequence lay their headers out the same |
| 1187 | /// way the sequence header the key frame wrote says they do -- a per-call |
| 1188 | /// parameter would have to thread through `inter_frame_headers`' four |
| 1189 | /// public entry points and every hand-built-stream test that calls them. |
| 1190 | /// A sequence with no screen content leaves this false and writes exactly |
| 1191 | /// the bits it wrote before this lane. |
| 1192 | static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 1193 | } |
| 1194 | |
| 1195 | thread_local! { |
| 1196 | /// Overrides [`screen_content`] for the calling thread, which is what the |
| 1197 | /// intra-MODE ablations use: on a two-colour synthetic picture the palette |
| 1198 | /// codes every block losslessly, so both arms of a mode ablation reach |
| 1199 | /// infinite PSNR and the ablation measures nothing at all (the |
| 1200 | /// `fixture-proves-the-symbol-not-the-signal` class). An environment |
| 1201 | /// variable cannot do this -- the tests run in one process, in parallel. |
| 1202 | static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 1203 | } |
| 1204 | |
| 1205 | thread_local! { |
| 1206 | /// What the last [`encode_sequence_with_ctx`] call on this thread coded |
| 1207 | /// under, AFTER the content gate: the pyramid, or `None` for a stream |
| 1208 | /// that stayed flat. Read by the BD gates, which print the requested and |
| 1209 | /// the effective pyramid side by side -- a screen clip requests one and |
| 1210 | /// codes flat, and that difference is the gate (class |
| 1211 | /// `gate-blind-to-feature`). |
| 1212 | static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> = |
| 1213 | const { std::cell::Cell::new(None) }; |
| 1214 | } |
| 1215 | |
| 1216 | /// The pyramid the last sequence coded on this thread was EFFECTIVELY under. |
| 1217 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1218 | pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> { |
| 1219 | LAST_SEQ_PYRAMID.with(std::cell::Cell::get) |
| 1220 | } |
| 1221 | |
| 1222 | #[cfg(test)] |
| 1223 | pub(crate) fn force_screen(value: Option<bool>) { |
| 1224 | SCREEN_FORCE.with(|c| c.set(value)); |
| 1225 | } |
| 1226 | |
| 1227 | // lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE |
| 1228 | // ablation can measure the mode search alone. Setting it also clears the |
| 1229 | // sequence header's own `enable_filter_intra` bit, so the stream the arm |
| 1230 | // writes is exactly the one this encoder wrote before the lane. |
| 1231 | #[cfg(test)] |
| 1232 | thread_local! { |
| 1233 | static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 1234 | } |
| 1235 | |
| 1236 | #[cfg(test)] |
| 1237 | pub(crate) fn force_filter_intra(value: Option<bool>) { |
| 1238 | FILTER_INTRA_FORCE.with(|c| c.set(value)); |
| 1239 | } |
| 1240 | |
| 1241 | pub(crate) fn arm_seq_screen(on: bool) { |
| 1242 | SEQ_SCREEN.with(|c| c.set(on)); |
| 1243 | } |
| 1244 | |
| 1245 | fn seq_screen() -> bool { |
| 1246 | SEQ_SCREEN.with(std::cell::Cell::get) |
| 1247 | } |
| 1248 | |
| 1249 | /// How many distinct colours a 16x16 luma block may hold and still count as |
| 1250 | /// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own |
| 1251 | /// `av1_set_screen_content_options` bound is 4, which separates nothing on |
| 1252 | /// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against |
| 1253 | /// the variance floor below on the five gate clips at BOTH the native crop |
| 1254 | /// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of |
| 1255 | /// the frame is the widest-margin split of those ten rows -- every |
| 1256 | /// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5 |
| 1257 | /// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6% |
| 1258 | /// native and 17.9% scaled. |
| 1259 | fn screen_colors() -> usize { |
| 1260 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 1261 | *N.get_or_init(|| { |
| 1262 | std::env::var("EC_AV1_SCREEN_COLORS") |
| 1263 | .ok() |
| 1264 | .and_then(|v| v.parse().ok()) |
| 1265 | .unwrap_or(16) |
| 1266 | }) |
| 1267 | } |
| 1268 | |
| 1269 | /// The reciprocal of the frame area those blocks must cover, in tenths -- |
| 1270 | /// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth; |
| 1271 | /// 8 (an eighth) is the midpoint of the two populations |
| 1272 | /// `probe_screen_detect` measures at the colour bound and variance floor |
| 1273 | /// around it. `EC_AV1_SCREEN_PCT`. |
| 1274 | fn screen_pct() -> usize { |
| 1275 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 1276 | *N.get_or_init(|| { |
| 1277 | std::env::var("EC_AV1_SCREEN_PCT") |
| 1278 | .ok() |
| 1279 | .and_then(|v| v.parse().ok()) |
| 1280 | .unwrap_or(10) |
| 1281 | }) |
| 1282 | } |
| 1283 | |
| 1284 | /// The per-pixel variance a few-colour block must clear before it counts as |
| 1285 | /// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its |
| 1286 | /// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it |
| 1287 | /// a smooth dark film frame is all few-colour blocks and reads as a desktop |
| 1288 | /// capture -- which is exactly what this detector did until 2026-09-07, when |
| 1289 | /// it called BOTH real films screen content on 48/48 frames, priced every |
| 1290 | /// coefficient against the default CDFs and ran the palette search over |
| 1291 | /// film. `probe_screen_detect`: at 16 colours the floor takes both films |
| 1292 | /// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to |
| 1293 | /// 23.6%. |
| 1294 | fn screen_var() -> u64 { |
| 1295 | static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); |
| 1296 | *N.get_or_init(|| { |
| 1297 | std::env::var("EC_AV1_SCREEN_VAR") |
| 1298 | .ok() |
| 1299 | .and_then(|v| v.parse().ok()) |
| 1300 | .unwrap_or(16) |
| 1301 | }) |
| 1302 | } |
| 1303 | |
| 1304 | /// How many frames [`screen_content`] said yes/no to, so a gate can print |
| 1305 | /// whether the detector fired at all (class `gate-blind-to-feature`). |
| 1306 | pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] = |
| 1307 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 1308 | |
| 1309 | /// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count |
| 1310 | /// the distinct colours of every 16x16 block and turn the screen-content |
| 1311 | /// tools on when the blocks holding between 2 and [`screen_colors`] of them |
| 1312 | /// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the |
| 1313 | /// frame. `width` is the plane's |
| 1314 | /// stride, `true_*` the frame's real (decodable) extent. |
| 1315 | fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool { |
| 1316 | if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) { |
| 1317 | SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1318 | return forced; |
| 1319 | } |
| 1320 | if let Ok(v) = std::env::var("EC_AV1_SCREEN") { |
| 1321 | let on = v != "0"; |
| 1322 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1323 | return on; |
| 1324 | } |
| 1325 | let (blk, limit, floor) = (16usize, screen_colors(), screen_var()); |
| 1326 | let mut counted = 0usize; |
| 1327 | for by in (0..true_height).step_by(blk) { |
| 1328 | for bx in (0..true_width).step_by(blk) { |
| 1329 | let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk)); |
| 1330 | let mut seen = [false; 256]; |
| 1331 | let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64); |
| 1332 | for row in 0..h { |
| 1333 | for col in 0..w { |
| 1334 | let v = y[(by + row) * width + bx + col]; |
| 1335 | sum += u64::from(v); |
| 1336 | sq += u64::from(v) * u64::from(v); |
| 1337 | if !seen[usize::from(v)] { |
| 1338 | seen[usize::from(v)] = true; |
| 1339 | colors += 1; |
| 1340 | } |
| 1341 | } |
| 1342 | } |
| 1343 | // Per-pixel variance over the block's real (edge-clipped) extent. |
| 1344 | let n = (h * w) as u64; |
| 1345 | let var = (sq - sum * sum / n) / n; |
| 1346 | if colors > 1 && colors <= limit && var > floor { |
| 1347 | counted += 1; |
| 1348 | } |
| 1349 | } |
| 1350 | } |
| 1351 | let on = counted * blk * blk * screen_pct() > true_width * true_height; |
| 1352 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1353 | on |
| 1354 | } |
| 1355 | |
| 1356 | /// Whether this SOURCE picture reads as screen content, for a caller that has |
| 1357 | /// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`] |
| 1358 | /// gates its coding pyramid on this (a desktop capture keeps the flat |
| 1359 | /// one-in-one-out structure the BD gate measured it on, camera material takes |
| 1360 | /// the mini-GOP). The key frame runs the same detector again when it builds |
| 1361 | /// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to |
| 1362 | /// count, so this probe undoes its own tick and leaves the gate prints |
| 1363 | /// reading one detection per coded frame. |
| 1364 | pub(crate) fn picture_is_screen(picture: &Picture) -> bool { |
| 1365 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 1366 | let on = screen_content(&y, picture.width, picture.width, picture.height); |
| 1367 | SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); |
| 1368 | on |
| 1369 | } |
| 1370 | |
| 1371 | /// The sequence and frame headers a picture of this size is coded under: one |
| 1372 | /// tile, one transform size per block, no in-loop filter parameters yet |
| 1373 | /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and |
| 1374 | /// CDEF strengths in once the tile is coded), no CDF adaptation |
| 1375 | /// and no tool the tile writer does not code. |
| 1376 | /// |
| 1377 | /// # Errors |
| 1378 | /// Returns an error when the picture is larger than the 16-bit frame size the |
| 1379 | /// sequence header carries. |
| 1380 | pub fn key_frame_headers( |
| 1381 | width: usize, |
| 1382 | height: usize, |
| 1383 | base_q_idx: u8, |
| 1384 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1385 | key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config()) |
| 1386 | } |
| 1387 | |
| 1388 | /// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and |
| 1389 | /// studio (limited) range: what this crate's sequence header carried before |
| 1390 | /// [`crate::encoder`]'s facade could configure it, and what |
| 1391 | /// [`key_frame_headers`] still asks for. |
| 1392 | fn unspecified_color_config() -> ColorConfig { |
| 1393 | ColorConfig { |
| 1394 | bit_depth: 8, |
| 1395 | mono_chrome: false, |
| 1396 | num_planes: 3, |
| 1397 | color_primaries: 2, |
| 1398 | transfer_characteristics: 2, |
| 1399 | matrix_coefficients: 2, |
| 1400 | color_range: false, |
| 1401 | subsampling_x: 1, |
| 1402 | subsampling_y: 1, |
| 1403 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 1404 | separate_uv_delta_q: false, |
| 1405 | } |
| 1406 | } |
| 1407 | |
| 1408 | /// [`key_frame_headers`] with the sequence header's colour config named |
| 1409 | /// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`, |
| 1410 | /// `transfer_characteristics`, `matrix_coefficients` and `color_range`, |
| 1411 | /// which is all a player picks a colour transform from and which |
| 1412 | /// [`crate::encoder::Colour`] is the facade's own name for. |
| 1413 | /// |
| 1414 | /// # Errors |
| 1415 | /// The same as [`key_frame_headers`]. |
| 1416 | pub(crate) fn key_frame_headers_colour( |
| 1417 | width: usize, |
| 1418 | height: usize, |
| 1419 | base_q_idx: u8, |
| 1420 | color_config: ColorConfig, |
| 1421 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1422 | let bits = |n: usize| -> Result<u32> { |
| 1423 | let n = u32::try_from(n).map_err(|_| too_large())?; |
| 1424 | if n == 0 || n > 1 << 16 { |
| 1425 | return Err(too_large()); |
| 1426 | } |
| 1427 | Ok((32 - (n - 1).leading_zeros()).max(1)) |
| 1428 | }; |
| 1429 | let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?); |
| 1430 | let (w, h) = (width as u32, height as u32); |
| 1431 | let seq = SequenceHeader { |
| 1432 | seq_profile: 0, |
| 1433 | operating_points: vec![OperatingPoint { |
| 1434 | seq_level_idx: 8, |
| 1435 | ..OperatingPoint::default() |
| 1436 | }], |
| 1437 | frame_width_bits, |
| 1438 | frame_height_bits, |
| 1439 | max_frame_width: w, |
| 1440 | max_frame_height: h, |
| 1441 | use_128x128_superblock: false, |
| 1442 | // lane-fintra: the encoder's intra search offers the five recursive |
| 1443 | // filter-intra modes on eligible blocks, so the sequence bit is set |
| 1444 | // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both |
| 1445 | // off and restores the streams this encoder wrote before the lane). |
| 1446 | enable_filter_intra: filter_intra_on(), |
| 1447 | enable_intra_edge_filter: false, |
| 1448 | enable_order_hint: true, |
| 1449 | order_hint_bits: 7, |
| 1450 | enable_superres: false, |
| 1451 | // spec 5.9.19: with the sequence bit set every frame header carries |
| 1452 | // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength |
| 1453 | // pair for the whole frame, chosen by `crate::filter_search` -- so no |
| 1454 | // `cdef_idx` literal is coded in the tile and a frame that wants no |
| 1455 | // CDEF simply carries zero strengths. |
| 1456 | enable_cdef: true, |
| 1457 | enable_restoration: true, |
| 1458 | // SELECT (2) when this sequence's key frame detected screen content |
| 1459 | // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit |
| 1460 | // is then coded in every frame header, and only the frames that want |
| 1461 | // the palette syntax set it. 0 -- the forced-off form, no bit at all |
| 1462 | // -- otherwise, which is what every non-screen stream this encoder |
| 1463 | // writes still carries. |
| 1464 | seq_force_screen_content_tools: if seq_screen() { |
| 1465 | ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS |
| 1466 | } else { |
| 1467 | 0 |
| 1468 | }, |
| 1469 | seq_force_integer_mv: 0, |
| 1470 | color_config, |
| 1471 | still_picture: false, |
| 1472 | reduced_still_picture_header: false, |
| 1473 | timing_info: None, |
| 1474 | decoder_model_info: None, |
| 1475 | initial_display_delay_present_flag: false, |
| 1476 | operating_point: 0, |
| 1477 | operating_point_idc: 0, |
| 1478 | frame_id_numbers_present_flag: false, |
| 1479 | delta_frame_id_length: 0, |
| 1480 | additional_frame_id_length: 0, |
| 1481 | enable_interintra_compound: false, |
| 1482 | enable_masked_compound: false, |
| 1483 | // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on |
| 1484 | // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence |
| 1485 | // header is byte-identical to the streams before this lane. |
| 1486 | enable_warped_motion: warp_on(), |
| 1487 | enable_dual_filter: false, |
| 1488 | enable_jnt_comp: false, |
| 1489 | enable_ref_frame_mvs: false, |
| 1490 | film_grain_params_present: false, |
| 1491 | }; |
| 1492 | // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's |
| 1493 | // own (true, unpadded) width and height, not from any block-grid |
| 1494 | // alignment — a decoder derives these straight from `frame_width`/ |
| 1495 | // `frame_height` below, so this must match it exactly. |
| 1496 | let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3)); |
| 1497 | let header = FrameHeader { |
| 1498 | frame_type: FrameType::Key, |
| 1499 | frame_is_intra: true, |
| 1500 | show_frame: true, |
| 1501 | error_resilient_mode: true, |
| 1502 | // The tile writer keeps the same CDF state the decoder does and |
| 1503 | // updates it in the same order, so the frame lets the decoder adapt. |
| 1504 | disable_cdf_update: false, |
| 1505 | // Nothing reads the state this frame leaves behind: a key frame always |
| 1506 | // starts from the defaults, and this encoder emits one frame. |
| 1507 | disable_frame_end_update_cdf: true, |
| 1508 | force_integer_mv: true, |
| 1509 | refresh_frame_flags: 0xFF, |
| 1510 | primary_ref_frame: PRIMARY_REF_NONE, |
| 1511 | frame_width: w, |
| 1512 | frame_height: h, |
| 1513 | upscaled_width: w, |
| 1514 | render_width: w, |
| 1515 | render_height: h, |
| 1516 | mi_cols, |
| 1517 | mi_rows, |
| 1518 | tile_info: TileInfo { |
| 1519 | uniform_spacing: true, |
| 1520 | cols: 1, |
| 1521 | rows: 1, |
| 1522 | mi_col_starts: vec![0, mi_cols], |
| 1523 | mi_row_starts: vec![0, mi_rows], |
| 1524 | tile_size_bytes: 1, |
| 1525 | ..TileInfo::default() |
| 1526 | }, |
| 1527 | quantization: QuantizationParams { |
| 1528 | base_q_idx, |
| 1529 | ..QuantizationParams::default() |
| 1530 | }, |
| 1531 | tx_mode: TxMode::Largest, |
| 1532 | // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every |
| 1533 | // intra transform below 32x32, not only 16x16 -- the set this crate |
| 1534 | // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`). |
| 1535 | // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`), |
| 1536 | // so a decoder honouring the header picks the same CDF the writer |
| 1537 | // used only if this is set here too, not only on the inter variant |
| 1538 | // below -- an r14 lane-av1-rect fix: a key frame's own header used to |
| 1539 | // default this to `false`, so `av1_get_ext_tx_set_type` picked the |
| 1540 | // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the |
| 1541 | // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging |
| 1542 | // the arithmetic coder's `rng` register from the very first 8x8-leaf |
| 1543 | // luma transform onward with no symbol value ever differing. |
| 1544 | reduced_tx_set: true, |
| 1545 | ..FrameHeader::default() |
| 1546 | }; |
| 1547 | Ok((seq, header)) |
| 1548 | } |
| 1549 | |
| 1550 | /// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the |
| 1551 | /// key frame refreshes all eight slots, each inter frame only slot 0, so slot |
| 1552 | /// 1 still holds the key frame however long the GOP runs. |
| 1553 | pub const GOLDEN_SLOT: u8 = 1; |
| 1554 | |
| 1555 | /// The frame header for a shown inter frame that predicts from the single |
| 1556 | /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that |
| 1557 | /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s, |
| 1558 | /// reused verbatim: an inter frame never changes the sequence. |
| 1559 | /// |
| 1560 | /// # Errors |
| 1561 | /// Returns an error under the same conditions as [`key_frame_headers`]. |
| 1562 | pub fn inter_frame_headers( |
| 1563 | width: usize, |
| 1564 | height: usize, |
| 1565 | base_q_idx: u8, |
| 1566 | order_hint: u32, |
| 1567 | last_slot: u8, |
| 1568 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1569 | inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot) |
| 1570 | } |
| 1571 | |
| 1572 | /// [`inter_frame_headers`] with the three slots named apart: the one read as |
| 1573 | /// `LAST_FRAME`, the one this frame refreshes, and the one read as |
| 1574 | /// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2 |
| 1575 | /// so that the frame two back is still intact in the slot this one is about |
| 1576 | /// to overwrite -- read before write, spec 7.20's decode order. |
| 1577 | /// |
| 1578 | /// # Errors |
| 1579 | /// As [`inter_frame_headers`]. |
| 1580 | pub fn inter_frame_headers_slots( |
| 1581 | width: usize, |
| 1582 | height: usize, |
| 1583 | base_q_idx: u8, |
| 1584 | order_hint: u32, |
| 1585 | last_slot: u8, |
| 1586 | self_slot: u8, |
| 1587 | altref_slot: u8, |
| 1588 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1589 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; |
| 1590 | let header = FrameHeader { |
| 1591 | frame_type: FrameType::Inter, |
| 1592 | frame_is_intra: false, |
| 1593 | show_frame: true, |
| 1594 | error_resilient_mode: false, |
| 1595 | disable_cdf_update: false, |
| 1596 | // The tile writer hands its end-of-tile tables to the next frame |
| 1597 | // (`encode_sequence_with_ctx`), so the frame stores them the way the |
| 1598 | // decoder will load them (spec 7.20). |
| 1599 | disable_frame_end_update_cdf: false, |
| 1600 | force_integer_mv: false, |
| 1601 | order_hint, |
| 1602 | primary_ref_frame: 0, |
| 1603 | refresh_frame_flags: 1 << self_slot, |
| 1604 | // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`) |
| 1605 | // names the slot this frame both predicts from and refreshes; |
| 1606 | // GOLDEN names slot 1, which the key frame wrote when it refreshed |
| 1607 | // all eight and which no inter frame ever overwrites, so it holds |
| 1608 | // the key frame's own picture for the whole GOP. |
| 1609 | ref_frame_idx: { |
| 1610 | let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME]; |
| 1611 | idx[3] = GOLDEN_SLOT; |
| 1612 | idx[6] = altref_slot; |
| 1613 | idx |
| 1614 | }, |
| 1615 | allow_high_precision_mv: false, |
| 1616 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, |
| 1617 | // lane-av1obmc: with this bit set every single-reference inter block |
| 1618 | // libaom's `motion_mode_allowed` accepts carries a `motion_mode` |
| 1619 | // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion` |
| 1620 | // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied |
| 1621 | // to the OBMC knob rather than always on: with every block choosing |
| 1622 | // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the |
| 1623 | // gate clip), so the DEFAULT path writes no motion_mode syntax at all |
| 1624 | // and stays byte-identical to the streams before this lane. |
| 1625 | // lane-av1obmc2: the warp knob joins that disjunction, and turns on |
| 1626 | // `allow_warped_motion` besides -- which is what makes an eligible |
| 1627 | // block read the 3-symbol `motion_mode_cdf` alphabet instead of the |
| 1628 | // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`). |
| 1629 | is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") |
| 1630 | || warp_on(), |
| 1631 | allow_warped_motion: warp_on(), |
| 1632 | use_ref_frame_mvs: false, |
| 1633 | // Forces `get_tx_set` (spec 5.11.48) to the two-symbol |
| 1634 | // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only |
| 1635 | // set this crate carries a table for at 16x16 (see |
| 1636 | // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter |
| 1637 | // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already |
| 1638 | // reads `TX_SET_INTER_3` regardless of this flag). An intra transform |
| 1639 | // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect: |
| 1640 | // the earlier claim here was wrong and desynced the 8x8-leaf straddle |
| 1641 | // path) -- with this flag set, `get_tx_set`'s intra branch returns |
| 1642 | // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads |
| 1643 | // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`. |
| 1644 | reduced_tx_set: true, |
| 1645 | ..key |
| 1646 | }; |
| 1647 | Ok((seq, header)) |
| 1648 | } |
| 1649 | |
| 1650 | fn too_large() -> Error { |
| 1651 | Error::unsupported( |
| 1652 | "AV1 encode", |
| 1653 | "the picture is larger than a frame size can carry", |
| 1654 | ) |
| 1655 | } |
| 1656 | |
| 1657 | /// One plane of the picture being coded, and the reconstruction being built |
| 1658 | /// beside it. |
| 1659 | /// What one committed 4x4 cell left behind for the coefficient contexts of |
| 1660 | /// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which |
| 1661 | /// is the same state decode.rs records. |
| 1662 | #[derive(Clone, Copy, Default, PartialEq, Eq)] |
| 1663 | struct CoefCtx { |
| 1664 | /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7. |
| 1665 | level: u8, |
| 1666 | /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when |
| 1667 | /// the DC itself was zero (tile.rs `dc_vote`). |
| 1668 | dc: i8, |
| 1669 | } |
| 1670 | |
| 1671 | /// One plane's coefficient contexts, committed in CODING ORDER: the search |
| 1672 | /// prices partition TREES, so the neighbour state a candidate reads has to be |
| 1673 | /// whatever the blocks coded before it left -- the parent's committed |
| 1674 | /// neighbours for a tree's first child, the just-committed sibling for the |
| 1675 | /// later ones. Keeping the map as a full per-4x4-cell grid rather than the |
| 1676 | /// writer's two running bands is what makes that fall out: a trial commits |
| 1677 | /// over its own rectangle ([`Plane::commit`]) and a losing trial is undone |
| 1678 | /// with the pixels ([`Plane::restore`]), so what a candidate reads above and |
| 1679 | /// to its left is exactly what the tile writer's `Neighbours` bands will hold |
| 1680 | /// when it gets there. |
| 1681 | /// |
| 1682 | /// Before this map the pricer took both contexts as zero, which is exact for |
| 1683 | /// a luma transform covering its whole block and the largest remaining row of |
| 1684 | /// the pricer census everywhere else (all-zero chroma under-priced 41-81%). |
| 1685 | #[derive(Default)] |
| 1686 | struct CoefCtxMap { |
| 1687 | cells: Vec<CoefCtx>, |
| 1688 | stride: usize, |
| 1689 | /// Whether the transforms being priced right now are SMALLER than the |
| 1690 | /// block they sit in -- a `TxMode::Select` depth split |
| 1691 | /// ([`Plane::code_tx_depth`]) or an inter var-tx split |
| 1692 | /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a |
| 1693 | /// trial cannot tell, and it is what decides whether luma reads context 0 |
| 1694 | /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`). |
| 1695 | tu_split: bool, |
| 1696 | } |
| 1697 | |
| 1698 | /// Whether [`Plane::block_sse`] scores a block the true frame edge cuts |
| 1699 | /// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the |
| 1700 | /// padding-inclusive score the search used before lane-sse, which is how the |
| 1701 | /// before/after arms of the straddling gate rows are read off ONE binary. |
| 1702 | fn edge_sse() -> bool { |
| 1703 | static ENV: std::sync::LazyLock<Option<bool>> = |
| 1704 | std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0")); |
| 1705 | ENV.unwrap_or(true) |
| 1706 | } |
| 1707 | |
| 1708 | /// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts |
| 1709 | /// through and the share of their raw squared error that sat in the padding |
| 1710 | /// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for |
| 1711 | /// it, but the numbers are an instrument, not a decision (class |
| 1712 | /// `gate-blind-to-feature` -- both gate films are superblock-aligned, so |
| 1713 | /// without this census no gate row can say the clip fires at all). |
| 1714 | fn edge_census() -> bool { |
| 1715 | static ENV: std::sync::LazyLock<bool> = |
| 1716 | std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")); |
| 1717 | *ENV |
| 1718 | } |
| 1719 | |
| 1720 | /// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is |
| 1721 | /// 128x128): how many scores clipped, the inside squared error they kept and |
| 1722 | /// the padding squared error they dropped. |
| 1723 | static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] = |
| 1724 | [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8]; |
| 1725 | |
| 1726 | /// One clipped score, for [`take_edge_census`]. |
| 1727 | fn record_edge_score(side: usize, inside: u64, padding: u64) { |
| 1728 | let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)]; |
| 1729 | row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1730 | row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed); |
| 1731 | row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed); |
| 1732 | } |
| 1733 | |
| 1734 | /// The straddling-block census since the last call, and zero it: one |
| 1735 | /// `(side, scores, inside_sse, padding_sse)` row per block size that fired. |
| 1736 | #[must_use] |
| 1737 | pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> { |
| 1738 | EDGE_SCORES |
| 1739 | .iter() |
| 1740 | .enumerate() |
| 1741 | .filter_map(|(log2, row)| { |
| 1742 | let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed); |
| 1743 | let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed); |
| 1744 | let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed); |
| 1745 | (n != 0).then_some((1usize << log2, n, inside, padding)) |
| 1746 | }) |
| 1747 | .collect() |
| 1748 | } |
| 1749 | |
| 1750 | struct Plane<'a> { |
| 1751 | source: &'a [u8], |
| 1752 | reconstruction: Vec<u8>, |
| 1753 | width: usize, |
| 1754 | height: usize, |
| 1755 | /// The frame's true, decodable extent in this plane's own units -- |
| 1756 | /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples, |
| 1757 | /// not `width`/`height` above, which is the padded coding-surface size. |
| 1758 | /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_ |
| 1759 | /// right_edge`/`mb_to_bottom_edge` clamps (libaom's |
| 1760 | /// `av1/common/reconintra.c` `build_intra_predictors`) never see past |
| 1761 | /// this bound, even though the padded reconstruction buffer holds real |
| 1762 | /// (if never-decoded-by-a-real-decoder) samples out there -- reading |
| 1763 | /// those instead of stopping here is what desyncs prediction at the true |
| 1764 | /// edge. |
| 1765 | true_width: usize, |
| 1766 | true_height: usize, |
| 1767 | /// This plane's own tile's pixel bounds, in this plane's units -- the |
| 1768 | /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra |
| 1769 | /// prediction never reaches across a tile edge even though the |
| 1770 | /// neighbouring tile's real samples sit right there in the shared |
| 1771 | /// reconstruction. `(0, 0, width, height)` is the single-tile case and |
| 1772 | /// leaves every edge exactly as it was before tiles existed. |
| 1773 | tile_x0: usize, |
| 1774 | tile_y0: usize, |
| 1775 | tile_x1: usize, |
| 1776 | tile_y1: usize, |
| 1777 | /// [`CoefCtxMap`]: what the blocks already committed left for the |
| 1778 | /// coefficient contexts of the ones still being priced. Sized on the |
| 1779 | /// first commit, so a plane literal does not have to know its own extent |
| 1780 | /// twice. |
| 1781 | ctx: CoefCtxMap, |
| 1782 | } |
| 1783 | |
| 1784 | impl Plane<'_> { |
| 1785 | /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]), |
| 1786 | /// called at every superblock of the frame-raster search with the rect |
| 1787 | /// of the tile that superblock belongs to. |
| 1788 | fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { |
| 1789 | self.tile_x0 = x0; |
| 1790 | self.tile_y0 = y0; |
| 1791 | self.tile_x1 = x1.min(self.width); |
| 1792 | self.tile_y1 = y1.min(self.height); |
| 1793 | } |
| 1794 | /// The reconstructed samples a block at `(x, y)` predicts from: the row |
| 1795 | /// above it, the column to its left and the sample between them, each |
| 1796 | /// missing where the block sits against an edge of the frame. |
| 1797 | /// |
| 1798 | /// `reach` says whether the samples above the block's right and below its |
| 1799 | /// left are decoded, which is what a directional mode reads into; where |
| 1800 | /// they are not, or where the frame ends first, the edge is shorter and |
| 1801 | /// the predictor repeats its last sample, exactly as the decoder's clamp |
| 1802 | /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2). |
| 1803 | /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and |
| 1804 | /// a free per mode per block, on the search's hottest path -- while an |
| 1805 | /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same |
| 1806 | /// samples, on the caller's stack. |
| 1807 | fn edges_into<'a>( |
| 1808 | &self, |
| 1809 | x: usize, |
| 1810 | y: usize, |
| 1811 | side: usize, |
| 1812 | reach: Reach, |
| 1813 | above_buf: &'a mut [u8; 2 * BLOCK], |
| 1814 | left_buf: &'a mut [u8; 2 * BLOCK], |
| 1815 | ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) { |
| 1816 | // Even a block's *own* edge is clamped to the true frame bound, not |
| 1817 | // just a `reach` extension: libaom's `av1_predict_intra_block` |
| 1818 | // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from |
| 1819 | // this block's own right/bottom to the frame edge -- from |
| 1820 | // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from |
| 1821 | // `mi_cols`/`mi_rows` (the true, decodable extent), never from any |
| 1822 | // padded coding surface. `n_top_px`/`n_left_px` (how many *real* |
| 1823 | // samples the row/column above/left holds before the decoder starts |
| 1824 | // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/ |
| 1825 | // `leftLimit`) is `min(side, xr + side)` even for a block whose own |
| 1826 | // extent straddles that edge legally (`has_half`) -- the transform |
| 1827 | // still covers the whole block, but prediction does not get to read |
| 1828 | // real reconstructed pixels past the true edge for its own row/column, |
| 1829 | // only for the padded tail it invents. |
| 1830 | let own_across = x + side.min(self.true_width.saturating_sub(x)); |
| 1831 | let across = if reach.above_right { |
| 1832 | own_across + side.min(self.true_width.saturating_sub(own_across)) |
| 1833 | } else { |
| 1834 | own_across |
| 1835 | } |
| 1836 | .min(self.width); |
| 1837 | let own_down = y + side.min(self.true_height.saturating_sub(y)); |
| 1838 | let down = if reach.below_left { |
| 1839 | own_down + side.min(self.true_height.saturating_sub(own_down)) |
| 1840 | } else { |
| 1841 | own_down |
| 1842 | } |
| 1843 | .min(self.height); |
| 1844 | // `across`/`down` can still fall at or below `x`/`y` for a sub-block |
| 1845 | // whose own origin already sits past the true edge -- only reachable |
| 1846 | // through a partition trial priced for comparison on a split this |
| 1847 | // frame's straddling quadrant will go on to refuse (see |
| 1848 | // `a_picture_off_the_block_grid_is_refused`), never through a block |
| 1849 | // this encoder actually commits. Such a block has no true-edge |
| 1850 | // samples above or left of it at all, same as `y == 0`/`x == 0`. |
| 1851 | let across = across.min(self.tile_x1); |
| 1852 | let down = down.min(self.tile_y1); |
| 1853 | let above_n = (y > self.tile_y0 && across > x).then(|| across - x); |
| 1854 | if let Some(n) = above_n { |
| 1855 | above_buf[..n] |
| 1856 | .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]); |
| 1857 | } |
| 1858 | let left_n = (x > self.tile_x0 && down > y).then(|| down - y); |
| 1859 | if let Some(n) = left_n { |
| 1860 | for (d, row) in left_buf[..n].iter_mut().zip(y..down) { |
| 1861 | *d = self.reconstruction[row * self.width + x - 1]; |
| 1862 | } |
| 1863 | } |
| 1864 | let corner = (x > self.tile_x0 && y > self.tile_y0) |
| 1865 | .then(|| self.reconstruction[(y - 1) * self.width + x - 1]); |
| 1866 | ( |
| 1867 | above_n.map(|n| &above_buf[..n]), |
| 1868 | left_n.map(|n| &left_buf[..n]), |
| 1869 | corner, |
| 1870 | ) |
| 1871 | } |
| 1872 | |
| 1873 | /// Codes one block under one mode without committing it: hands back the |
| 1874 | /// levels, the block the decoder would reconstruct, the squared error |
| 1875 | /// against the source and an estimate of what the levels cost in bits. |
| 1876 | fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial { |
| 1877 | self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx) |
| 1878 | } |
| 1879 | |
| 1880 | /// [`Self::trial`] under a named transform type -- what an intra chroma |
| 1881 | /// block gets, since chroma codes no `tx_type` symbol and the decoder |
| 1882 | /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`, |
| 1883 | /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps |
| 1884 | /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. |
| 1885 | #[allow(clippy::too_many_arguments)] |
| 1886 | /// Sum of absolute differences between the source block at `(x, y)` and a |
| 1887 | /// `side x side` prediction, as the whole number it is. |
| 1888 | /// |
| 1889 | /// Bit-identical to the `f64` accumulation it replaces: every partial sum |
| 1890 | /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds |
| 1891 | /// exactly, so no add here rounds and the order of the adds cannot change |
| 1892 | /// the result. Dropping the per-pixel `i / side` and `i % side` -- an |
| 1893 | /// integer division per sample -- is what lets the row walk vectorize. |
| 1894 | fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 { |
| 1895 | let mut sad = 0u32; |
| 1896 | for row in 0..side { |
| 1897 | let source = &self.source[(y + row) * self.width + x..][..side]; |
| 1898 | for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) { |
| 1899 | sad += u32::from(s.abs_diff(p)); |
| 1900 | } |
| 1901 | } |
| 1902 | f64::from(sad) |
| 1903 | } |
| 1904 | |
| 1905 | /// Squared error between the source block at `(x, y)` and a reconstruction |
| 1906 | /// of it, over the part of the block that is INSIDE the true frame. |
| 1907 | /// Exact for the same reason [`Self::block_sad`] is: the largest total is |
| 1908 | /// `255^2 * 64 * 64`, under 2^28. |
| 1909 | /// |
| 1910 | /// A block the frame edge cuts through is still coded whole -- the |
| 1911 | /// decoder reconstructs its outside samples too and the display crop |
| 1912 | /// throws them away -- so scoring the padding would rank a mode, a |
| 1913 | /// transform or a partition tree by how well it codes samples the source |
| 1914 | /// does not have (libaom clips the same way: `av1_dist_block` measures |
| 1915 | /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated |
| 1916 | /// edge pixels, so predicting it is nearly free, but coding coefficients |
| 1917 | /// for it spends real bits. Both gate films are superblock-aligned; this |
| 1918 | /// only reaches arbitrary export sizes (lane-sse, generalising |
| 1919 | /// lane-b64b's 64-root-only rescore of the 64 root). |
| 1920 | fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 { |
| 1921 | let inside_rows = side.min(self.true_height.saturating_sub(y)); |
| 1922 | let inside_cols = side.min(self.true_width.saturating_sub(x)); |
| 1923 | let straddles = inside_rows < side || inside_cols < side; |
| 1924 | // The knob is read only for a block the edge cuts, so the interior |
| 1925 | // path -- the hot one -- carries no extra load at all. |
| 1926 | let (rows, cols) = match straddles && !edge_sse() { |
| 1927 | true => (side, side), |
| 1928 | false => (inside_rows, inside_cols), |
| 1929 | }; |
| 1930 | let mut sse = 0u64; |
| 1931 | for row in 0..rows { |
| 1932 | let source = &self.source[(y + row) * self.width + x..][..cols]; |
| 1933 | for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) { |
| 1934 | let d = u32::from(s.abs_diff(r)); |
| 1935 | sse += u64::from(d * d); |
| 1936 | } |
| 1937 | } |
| 1938 | if straddles && edge_census() { |
| 1939 | let (mut inside, mut whole) = (0u64, 0u64); |
| 1940 | for row in 0..side { |
| 1941 | let source = &self.source[(y + row) * self.width + x..][..side]; |
| 1942 | for (col, (&s, &r)) in |
| 1943 | source.iter().zip(&reconstruction[row * side..][..side]).enumerate() |
| 1944 | { |
| 1945 | let d = u64::from(u32::from(s.abs_diff(r)).pow(2)); |
| 1946 | whole += d; |
| 1947 | if row < inside_rows && col < inside_cols { |
| 1948 | inside += d; |
| 1949 | } |
| 1950 | } |
| 1951 | } |
| 1952 | record_edge_score(side, inside, whole - inside); |
| 1953 | } |
| 1954 | sse as f64 |
| 1955 | } |
| 1956 | |
| 1957 | fn trial_typed( |
| 1958 | &self, |
| 1959 | at: At, |
| 1960 | mode: u8, |
| 1961 | // This block's `angle_delta_y`/`angle_delta_uv` (spec |
| 1962 | // `read_intra_angle_info`, -3..=3), zero for every non-directional |
| 1963 | // mode -- the predictor's own `angle_delta` argument. |
| 1964 | angle_delta: i32, |
| 1965 | base_q_idx: u8, |
| 1966 | deadzone: f64, |
| 1967 | tx_type: TxType, |
| 1968 | fctx: &crate::decode::FrameCtx, |
| 1969 | ) -> Trial { |
| 1970 | let At { |
| 1971 | x, y, side, reach, .. |
| 1972 | } = at; |
| 1973 | let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); |
| 1974 | let (above, left, corner) = |
| 1975 | self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); |
| 1976 | // Per-candidate scratch on the search's hottest path, so both buffers |
| 1977 | // live on the stack -- `side` is at most `BLOCK` -- rather than |
| 1978 | // costing a malloc/free pair per trial (`mc_trial` already does this). |
| 1979 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 1980 | let prediction = &mut prediction[..side * side]; |
| 1981 | intra_predict_u8( |
| 1982 | mode, |
| 1983 | angle_delta, |
| 1984 | above, |
| 1985 | left, |
| 1986 | corner, |
| 1987 | side, |
| 1988 | side, |
| 1989 | false, |
| 1990 | false, |
| 1991 | prediction, fctx, |
| 1992 | ); |
| 1993 | |
| 1994 | let mut residual = [0i32; BLOCK * BLOCK]; |
| 1995 | let residual = &mut residual[..side * side]; |
| 1996 | for row in 0..side { |
| 1997 | for col in 0..side { |
| 1998 | residual[row * side + col] = |
| 1999 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 2000 | - i32::from(prediction[row * side + col]); |
| 2001 | } |
| 2002 | } |
| 2003 | #[cfg(test)] |
| 2004 | let t = stage_start(); |
| 2005 | let levels = |
| 2006 | forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); |
| 2007 | // lane-av1speed2: 60% of the transform units of an inter stream carry |
| 2008 | // no coefficient at all, and the square entry point re-inflates that |
| 2009 | // case into `side * side` zeros (one allocate-and-memset per trial) |
| 2010 | // only for the sum below to add them to the prediction. The `_wh` |
| 2011 | // entry hands back the empty all-zero marker instead, and a zero |
| 2012 | // residual reconstructs to the prediction itself -- `clamp(p + 0)` is |
| 2013 | // `p` for a `u8`, so the bytes are the same. |
| 2014 | let coded = dequant_and_inverse_typed_wh( |
| 2015 | &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, |
| 2016 | ); |
| 2017 | #[cfg(test)] |
| 2018 | stage_since(2, t); |
| 2019 | |
| 2020 | let reconstruction: Vec<u8> = if coded.is_empty() { |
| 2021 | prediction.to_vec() |
| 2022 | } else { |
| 2023 | prediction |
| 2024 | .iter() |
| 2025 | .zip(&coded) |
| 2026 | .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) |
| 2027 | .collect() |
| 2028 | }; |
| 2029 | let sse = self.block_sse(x, y, side, &reconstruction); |
| 2030 | // What the levels cost is priced through the same CDFs the tile writer |
| 2031 | // will code them with, so the search ranks modes -- and the partition |
| 2032 | // trial ranks trees -- by the bits they actually spend. |
| 2033 | #[cfg(test)] |
| 2034 | let t = stage_start(); |
| 2035 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 2036 | // What the search used before it could price a block exactly: a |
| 2037 | // level costs its magnitude's width plus a sign and a run. Kept |
| 2038 | // reachable from the sweep so the two rate terms can be compared |
| 2039 | // on one build. |
| 2040 | levels |
| 2041 | .iter() |
| 2042 | .filter(|&&level| level != 0) |
| 2043 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 2044 | .sum() |
| 2045 | } else { |
| 2046 | { |
| 2047 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); |
| 2048 | crate::tile::coeff_bits( |
| 2049 | &levels, |
| 2050 | at.set, |
| 2051 | crate::decode::q_ctx_of(base_q_idx), |
| 2052 | skip_ctx, |
| 2053 | sign_ctx, |
| 2054 | ) |
| 2055 | } |
| 2056 | }; |
| 2057 | #[cfg(test)] |
| 2058 | stage_since(3, t); |
| 2059 | Trial { |
| 2060 | levels, |
| 2061 | reconstruction, |
| 2062 | sse, |
| 2063 | bits, |
| 2064 | } |
| 2065 | } |
| 2066 | |
| 2067 | /// [`Self::trial`] with the prediction already built, so that an inter |
| 2068 | /// block's motion-compensated prediction can go through the same |
| 2069 | /// residual/quantize/reconstruct path an intra block's does. `skip` |
| 2070 | /// takes the prediction as the reconstruction outright, coding no |
| 2071 | /// residual at all — what a `NEARESTMV` block that names no coefficients |
| 2072 | /// codes. |
| 2073 | #[allow(clippy::too_many_arguments)] |
| 2074 | fn code_from_prediction( |
| 2075 | &self, |
| 2076 | x: usize, |
| 2077 | y: usize, |
| 2078 | side: usize, |
| 2079 | prediction: &[u8], |
| 2080 | skip: bool, |
| 2081 | base_q_idx: u8, |
| 2082 | deadzone: f64, |
| 2083 | set: TxbSet, |
| 2084 | ) -> Trial { |
| 2085 | if skip { |
| 2086 | let sse = self.block_sse(x, y, side, prediction); |
| 2087 | return Trial { |
| 2088 | levels: vec![0i32; side * side], |
| 2089 | reconstruction: prediction.to_vec(), |
| 2090 | sse, |
| 2091 | bits: 0.0, |
| 2092 | }; |
| 2093 | } |
| 2094 | // A 64x64 root's residual is four times the scratch every other |
| 2095 | // block coder here sizes for [`BLOCK`]; only that one case pays for |
| 2096 | // a heap buffer, so the 4x4..32x32 path keeps its stack array. |
| 2097 | let mut small = [0i32; BLOCK * BLOCK]; |
| 2098 | let mut big = if side > BLOCK { |
| 2099 | vec![0i32; side * side] |
| 2100 | } else { |
| 2101 | Vec::new() |
| 2102 | }; |
| 2103 | let residual: &mut [i32] = if side > BLOCK { |
| 2104 | &mut big |
| 2105 | } else { |
| 2106 | &mut small[..side * side] |
| 2107 | }; |
| 2108 | for row in 0..side { |
| 2109 | for col in 0..side { |
| 2110 | residual[row * side + col] = |
| 2111 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 2112 | - i32::from(prediction[row * side + col]); |
| 2113 | } |
| 2114 | } |
| 2115 | #[cfg(test)] |
| 2116 | let t = stage_start(); |
| 2117 | let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); |
| 2118 | // The same all-zero shortcut [`Self::trial_typed`] takes. |
| 2119 | let coded = dequant_and_inverse_typed_wh( |
| 2120 | &levels, |
| 2121 | side, |
| 2122 | side, |
| 2123 | 8, |
| 2124 | i32::from(base_q_idx), |
| 2125 | 0, |
| 2126 | 0, |
| 2127 | TxType::DctDct, |
| 2128 | ); |
| 2129 | #[cfg(test)] |
| 2130 | stage_since(2, t); |
| 2131 | let reconstruction: Vec<u8> = if coded.is_empty() { |
| 2132 | prediction.to_vec() |
| 2133 | } else { |
| 2134 | prediction |
| 2135 | .iter() |
| 2136 | .zip(&coded) |
| 2137 | .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) |
| 2138 | .collect() |
| 2139 | }; |
| 2140 | let sse = self.block_sse(x, y, side, &reconstruction); |
| 2141 | // A 64-point transform codes only its top-left 32x32 corner (spec |
| 2142 | // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the |
| 2143 | // key frame writer takes a 32x32 level grid for one). The inverse |
| 2144 | // above reads the whole 64x64 array, but the price below and the |
| 2145 | // levels the writer takes are that corner. |
| 2146 | let levels = if side > BLOCK { |
| 2147 | coded_corner(&levels, side, BLOCK) |
| 2148 | } else { |
| 2149 | levels |
| 2150 | }; |
| 2151 | #[cfg(test)] |
| 2152 | let t = stage_start(); |
| 2153 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 2154 | levels |
| 2155 | .iter() |
| 2156 | .filter(|&&level| level != 0) |
| 2157 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 2158 | .sum() |
| 2159 | } else { |
| 2160 | { |
| 2161 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); |
| 2162 | crate::tile::coeff_bits( |
| 2163 | &levels, |
| 2164 | set, |
| 2165 | crate::decode::q_ctx_of(base_q_idx), |
| 2166 | skip_ctx, |
| 2167 | sign_ctx, |
| 2168 | ) |
| 2169 | } |
| 2170 | }; |
| 2171 | #[cfg(test)] |
| 2172 | stage_since(3, t); |
| 2173 | Trial { |
| 2174 | levels, |
| 2175 | reconstruction, |
| 2176 | sse, |
| 2177 | bits, |
| 2178 | } |
| 2179 | } |
| 2180 | |
| 2181 | /// Codes this block's luma at transform depth `depth`: the |
| 2182 | /// `(side >> depth)^2` transform units in raster order, each predicted |
| 2183 | /// from the reconstruction the units before it left behind -- exactly |
| 2184 | /// what the decoder's multi-transform-unit branch does (decode.rs |
| 2185 | /// `decode_block`, `tu_reach`) -- and each transformed, quantised and |
| 2186 | /// reconstructed on its own. Commits the result and hands back the |
| 2187 | /// block-coordinate levels, the block's squared error and what its |
| 2188 | /// coefficients cost. |
| 2189 | #[allow(clippy::too_many_arguments)] |
| 2190 | fn code_tx_depth( |
| 2191 | &mut self, |
| 2192 | at: At, |
| 2193 | mode: u8, |
| 2194 | angle_delta: i32, |
| 2195 | depth: usize, |
| 2196 | // This block's `filter_intra_mode` when it is coded with one, in |
| 2197 | // which case every transform unit predicts recursively off the |
| 2198 | // reconstruction the units before it left -- what the decoder does |
| 2199 | // per unit (decode.rs `decode_block`, `push_intra_rect`'s |
| 2200 | // `filter_intra`), not once over the whole block. |
| 2201 | filter_intra: Option<u8>, |
| 2202 | search: &Search, fctx: &crate::decode::FrameCtx, |
| 2203 | ) -> (Vec<i32>, f64, f64) { |
| 2204 | let At { x, y, side, reach, .. } = at; |
| 2205 | let tx = side >> depth; |
| 2206 | let n = 1usize << depth; |
| 2207 | let set = match tx { |
| 2208 | 32 => TxbSet::Luma32, |
| 2209 | 16 => TxbSet::Luma16, |
| 2210 | 8 => TxbSet::Luma8, |
| 2211 | _ => TxbSet::Luma4, |
| 2212 | }; |
| 2213 | let mut levels = vec![0i32; side * side]; |
| 2214 | census_add(4, n * n); |
| 2215 | // A unit smaller than its block reads the neighbour magnitude table |
| 2216 | // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]). |
| 2217 | self.ctx.tu_split = n > 1; |
| 2218 | let (mut sse, mut bits) = (0.0, 0.0); |
| 2219 | for tu_row in 0..n { |
| 2220 | for tu_col in 0..n { |
| 2221 | let (col_off, row_off) = (tu_col * tx, tu_row * tx); |
| 2222 | let tu = At { |
| 2223 | x: x + col_off, |
| 2224 | y: y + row_off, |
| 2225 | side: tx, |
| 2226 | reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach), |
| 2227 | set, |
| 2228 | }; |
| 2229 | let trial = match filter_intra { |
| 2230 | Some(fi) => { |
| 2231 | let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); |
| 2232 | let (above, left, corner) = |
| 2233 | self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf); |
| 2234 | let mut prediction = vec![0u8; tx * tx]; |
| 2235 | filter_intra_predict_u8( |
| 2236 | usize::from(fi), |
| 2237 | above, |
| 2238 | left, |
| 2239 | corner, |
| 2240 | tx, |
| 2241 | &mut prediction, |
| 2242 | fctx, |
| 2243 | ); |
| 2244 | self.code_from_prediction( |
| 2245 | tu.x, |
| 2246 | tu.y, |
| 2247 | tx, |
| 2248 | &prediction, |
| 2249 | false, |
| 2250 | search.base_q_idx, |
| 2251 | search.deadzone, |
| 2252 | set, |
| 2253 | ) |
| 2254 | } |
| 2255 | None => { |
| 2256 | self.trial(tu, mode, angle_delta, search.base_q_idx, search.deadzone, fctx) |
| 2257 | } |
| 2258 | }; |
| 2259 | sse += trial.sse; |
| 2260 | bits += trial.bits; |
| 2261 | self.commit(tu.x, tu.y, tx, &trial); |
| 2262 | for row in 0..tx { |
| 2263 | levels[(row_off + row) * side + col_off..][..tx] |
| 2264 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 2265 | } |
| 2266 | } |
| 2267 | } |
| 2268 | self.ctx.tu_split = false; |
| 2269 | (levels, sse, bits) |
| 2270 | } |
| 2271 | |
| 2272 | /// Writes a trial's reconstruction back into the plane, and the |
| 2273 | /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]). |
| 2274 | fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { |
| 2275 | for row in 0..side { |
| 2276 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 2277 | .copy_from_slice(&trial.reconstruction[row * side..][..side]); |
| 2278 | } |
| 2279 | self.commit_ctx(x, y, side, &trial.levels); |
| 2280 | } |
| 2281 | |
| 2282 | /// Publishes one committed transform's own context over every 4x4 cell it |
| 2283 | /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`, |
| 2284 | /// which is what the writer will read when it reaches the next block. |
| 2285 | fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) { |
| 2286 | if self.ctx.cells.is_empty() { |
| 2287 | self.ctx.stride = self.width.div_ceil(4); |
| 2288 | self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)]; |
| 2289 | } |
| 2290 | let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8; |
| 2291 | let state = CoefCtx { |
| 2292 | level: cul, |
| 2293 | dc: match levels[0].signum() { |
| 2294 | 0 => 0, |
| 2295 | -1 => -1, |
| 2296 | _ => 1, |
| 2297 | }, |
| 2298 | }; |
| 2299 | let n = (side / 4).max(1); |
| 2300 | // Only up to the frame's TRUE extent: the writer's own |
| 2301 | // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high` |
| 2302 | // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`) |
| 2303 | // and leaves the cells past it uncoded even mid-block, so a |
| 2304 | // straddling block publishes context for its inside part only. |
| 2305 | let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4)); |
| 2306 | let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4)); |
| 2307 | for row in 0..rows { |
| 2308 | let start = (y / 4 + row) * self.ctx.stride + x / 4; |
| 2309 | let end = (start + cols).min(self.ctx.cells.len()); |
| 2310 | if start < end { |
| 2311 | self.ctx.cells[start..end].fill(state); |
| 2312 | } |
| 2313 | } |
| 2314 | } |
| 2315 | |
| 2316 | /// A block committed without any residual at all ([`ibc_commit`]): the |
| 2317 | /// cells it covers coded nothing, and leaving an earlier trial's state |
| 2318 | /// there would price its neighbours off a block that was never coded. |
| 2319 | fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) { |
| 2320 | self.commit_ctx(x, y, side, &[0i32]); |
| 2321 | } |
| 2322 | |
| 2323 | /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this |
| 2324 | /// plane reads, off what the blocks before it in coding order committed |
| 2325 | /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether |
| 2326 | /// the above/left neighbours coded anything (tile.rs |
| 2327 | /// `write_block_planes`), luma reads context 0 when its transform covers |
| 2328 | /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour |
| 2329 | /// magnitude tiers when it does not (tile.rs `write_luma_tus` / |
| 2330 | /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of |
| 2331 | /// the same neighbours (tile.rs `dc_sign_ctx`). |
| 2332 | /// |
| 2333 | /// A neighbour outside this plane's own TILE does not exist, exactly as |
| 2334 | /// the writer's per-tile `Neighbours` bands start blank. |
| 2335 | /// |
| 2336 | /// CLOSED (lane-av1straddle): the decisions this price changes used to |
| 2337 | /// make `decode_stream_round_trips_an_odd_size_gop` and |
| 2338 | /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction` |
| 2339 | /// fail at 216x96. Never this map: the writer coded the phantom |
| 2340 | /// transform units of a right-edge-straddling 32x32 (tile.rs |
| 2341 | /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows` |
| 2342 | /// like decode.rs and libaom), which libdav1d and libaom both refused |
| 2343 | /// outright while a decision change was what first walked into it. |
| 2344 | fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) { |
| 2345 | if self.ctx.cells.is_empty() { |
| 2346 | return (0, 0); |
| 2347 | } |
| 2348 | let n = (side / 4).max(1); |
| 2349 | let (cx, cy) = (x / 4, y / 4); |
| 2350 | let (mut top, mut left) = (0u8, 0u8); |
| 2351 | let mut vote = 0i32; |
| 2352 | if y > self.tile_y0 && cy > 0 { |
| 2353 | for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] { |
| 2354 | top |= cell.level; |
| 2355 | vote += i32::from(cell.dc); |
| 2356 | } |
| 2357 | } |
| 2358 | if x > self.tile_x0 && cx > 0 { |
| 2359 | for row in 0..n { |
| 2360 | let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1]; |
| 2361 | left |= cell.level; |
| 2362 | vote += i32::from(cell.dc); |
| 2363 | } |
| 2364 | } |
| 2365 | let skip_ctx = if set.is_chroma() { |
| 2366 | usize::from(top != 0) + usize::from(left != 0) |
| 2367 | } else if self.ctx.tu_split { |
| 2368 | crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] |
| 2369 | } else { |
| 2370 | 0 |
| 2371 | }; |
| 2372 | let sign_ctx = match vote.signum() { |
| 2373 | 0 => 0, |
| 2374 | -1 => 1, |
| 2375 | _ => 2, |
| 2376 | }; |
| 2377 | (skip_ctx, sign_ctx) |
| 2378 | } |
| 2379 | |
| 2380 | /// The source samples of one square, contiguous — what a motion search |
| 2381 | /// compares its candidates' predictions against ([`motion::search`]'s |
| 2382 | /// `source`), since [`Self::source`] itself is the whole plane, strided |
| 2383 | /// by [`Self::width`]. |
| 2384 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 2385 | rows_of(self.source, self.width, x, y, side) |
| 2386 | } |
| 2387 | |
| 2388 | /// The reconstructed samples of one square, so that a partition trial can |
| 2389 | /// be undone. |
| 2390 | /// The reconstructed samples of one square AND the coefficient contexts |
| 2391 | /// its cells hold, so that a partition trial can be undone whole: a |
| 2392 | /// losing trial that left its own nz/DC state behind would price the |
| 2393 | /// blocks after it off a block the tile writer never codes. |
| 2394 | fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) { |
| 2395 | ( |
| 2396 | rows_of(&self.reconstruction, self.width, x, y, side), |
| 2397 | self.ctx_rows(x, y, side), |
| 2398 | ) |
| 2399 | } |
| 2400 | |
| 2401 | fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> { |
| 2402 | if self.ctx.cells.is_empty() { |
| 2403 | return Vec::new(); |
| 2404 | } |
| 2405 | let n = (side / 4).max(1); |
| 2406 | (0..n) |
| 2407 | .flat_map(|row| { |
| 2408 | let start = (y / 4 + row) * self.ctx.stride + x / 4; |
| 2409 | self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec() |
| 2410 | }) |
| 2411 | .collect() |
| 2412 | } |
| 2413 | |
| 2414 | /// Puts a snapshot back. |
| 2415 | fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) { |
| 2416 | for row in 0..side { |
| 2417 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 2418 | .copy_from_slice(&saved.0[row * side..][..side]); |
| 2419 | } |
| 2420 | if saved.1.is_empty() { |
| 2421 | return; |
| 2422 | } |
| 2423 | let n = (side / 4).max(1); |
| 2424 | for row in 0..n { |
| 2425 | let start = (y / 4 + row) * self.ctx.stride + x / 4; |
| 2426 | let end = (start + n).min(self.ctx.cells.len()); |
| 2427 | if start < end { |
| 2428 | self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]); |
| 2429 | } |
| 2430 | } |
| 2431 | } |
| 2432 | |
| 2433 | /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates |
| 2434 | /// by, exposed so [`search_inter_block`]'s intra-candidate loop can |
| 2435 | /// prescreen by the identical rule rather than a second one that could |
| 2436 | /// drift from it. |
| 2437 | fn intra_scores( |
| 2438 | &self, |
| 2439 | at: At, |
| 2440 | modes: &[u8], |
| 2441 | mode_bits: &[f64; 13], |
| 2442 | lambda: f64, fctx: &crate::decode::FrameCtx, |
| 2443 | ) -> Vec<(f64, u8)> { |
| 2444 | let At { |
| 2445 | x, y, side, reach, .. |
| 2446 | } = at; |
| 2447 | let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); |
| 2448 | let (above, left, corner) = |
| 2449 | self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); |
| 2450 | modes |
| 2451 | .iter() |
| 2452 | .map(|&mode| { |
| 2453 | let mut prediction = vec![0u8; side * side]; |
| 2454 | intra_predict_u8( |
| 2455 | mode, |
| 2456 | 0, |
| 2457 | above, |
| 2458 | left, |
| 2459 | corner, |
| 2460 | side, |
| 2461 | side, |
| 2462 | false, |
| 2463 | false, |
| 2464 | &mut prediction, fctx, |
| 2465 | ); |
| 2466 | let sad = self.block_sad(x, y, side, &prediction); |
| 2467 | (sad + lambda * mode_bits[usize::from(mode)], mode) |
| 2468 | }) |
| 2469 | .collect() |
| 2470 | } |
| 2471 | |
| 2472 | /// Codes one block under every mode the search offers (or, when |
| 2473 | /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD |
| 2474 | /// pre-pass plus DC) and commits the one whose squared error and |
| 2475 | /// estimated rate come out cheapest. |
| 2476 | /// |
| 2477 | /// The prediction is built once per mode regardless -- the full RD trial |
| 2478 | /// needs it too -- so ranking modes by SAD on that same prediction before |
| 2479 | /// running the expensive part (forward transform, quantize, reconstruct, |
| 2480 | /// `coeff_bits`) on only the survivors costs nothing extra to predict, |
| 2481 | /// only to sum. |
| 2482 | fn search_block( |
| 2483 | &mut self, |
| 2484 | at: At, |
| 2485 | search: &Search, |
| 2486 | mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, |
| 2487 | ) -> (Vec<Coeff>, u8, i32, f64) { |
| 2488 | let At { |
| 2489 | x, y, side, reach, .. |
| 2490 | } = at; |
| 2491 | let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); |
| 2492 | let (above, left, corner) = |
| 2493 | self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); |
| 2494 | // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or |
| 2495 | // the census reports it), so summing it under the default unpruned |
| 2496 | // search is `side * side` absolute differences per mode spent on a |
| 2497 | // number no one reads. |
| 2498 | let want_sad = search.top_k.is_some() || census_on(); |
| 2499 | let mut scored: Vec<(f64, u8, Vec<u8>)> = search |
| 2500 | .modes |
| 2501 | .iter() |
| 2502 | .map(|&mode| { |
| 2503 | let mut prediction = vec![0u8; side * side]; |
| 2504 | intra_predict_u8( |
| 2505 | mode, |
| 2506 | 0, |
| 2507 | above, |
| 2508 | left, |
| 2509 | corner, |
| 2510 | side, |
| 2511 | side, |
| 2512 | false, |
| 2513 | false, |
| 2514 | &mut prediction, fctx, |
| 2515 | ); |
| 2516 | let sad = if want_sad { |
| 2517 | self.block_sad(x, y, side, &prediction) |
| 2518 | } else { |
| 2519 | 0.0 |
| 2520 | }; |
| 2521 | ( |
| 2522 | sad + search.lambda * mode_bits[usize::from(mode)], |
| 2523 | mode, |
| 2524 | prediction, |
| 2525 | ) |
| 2526 | }) |
| 2527 | .collect(); |
| 2528 | if let Some(k) = search.top_k { |
| 2529 | if k < scored.len() { |
| 2530 | let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); |
| 2531 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 2532 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 2533 | scored.truncate(if dc_entry.is_some() { |
| 2534 | k.saturating_sub(1) |
| 2535 | } else { |
| 2536 | k |
| 2537 | }); |
| 2538 | if let Some(dc_entry) = dc_entry { |
| 2539 | scored.push(dc_entry); |
| 2540 | } |
| 2541 | } |
| 2542 | } |
| 2543 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 2544 | scored.iter().map(|&(score, mode, _)| (score, mode)).collect() |
| 2545 | } else { |
| 2546 | Vec::new() |
| 2547 | }; |
| 2548 | census_add(0, 1); |
| 2549 | census_add(1, scored.len()); |
| 2550 | let mut best: Option<(f64, u8, Trial)> = None; |
| 2551 | for (_, mode, prediction) in scored { |
| 2552 | let trial = self.code_from_prediction( |
| 2553 | x, |
| 2554 | y, |
| 2555 | side, |
| 2556 | &prediction, |
| 2557 | false, |
| 2558 | search.base_q_idx, |
| 2559 | search.deadzone, |
| 2560 | at.set, |
| 2561 | ); |
| 2562 | let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); |
| 2563 | if best |
| 2564 | .as_ref() |
| 2565 | .is_none_or(|(best_cost, _, _)| cost < *best_cost) |
| 2566 | { |
| 2567 | best = Some((cost, mode, trial)); |
| 2568 | } |
| 2569 | } |
| 2570 | let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode"); |
| 2571 | // `angle_delta_y` (spec `read_intra_angle_info`): the eight |
| 2572 | // directional modes each carry a -3..=3 delta, three degrees a step, |
| 2573 | // which the writer has always coded as ZERO because nothing searched |
| 2574 | // it. Refined on the winning mode only -- libaom's own ordering, and |
| 2575 | // six extra trials on the directional blocks instead of on every |
| 2576 | // block times every mode. The edges are the ones the base angle |
| 2577 | // already read (`enable_intra_edge_filter` is off in this encoder's |
| 2578 | // sequence header, so no delta changes which samples exist), and the |
| 2579 | // predictor is the decoder's, `angle_delta` argument and all. |
| 2580 | let mut angle_delta = 0i32; |
| 2581 | // Not on a screen frame: measured on the 5-row native gate, the |
| 2582 | // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the |
| 2583 | // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture -- |
| 2584 | // synthetic edges land on the base angles, so every delta there buys |
| 2585 | // a symbol and no prediction. Same `search.screen` gate palette and |
| 2586 | // intrabc already stand behind. |
| 2587 | if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) { |
| 2588 | let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)]; |
| 2589 | let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO); |
| 2590 | let mut prediction = vec![0u8; side * side]; |
| 2591 | for delta in [-3i32, -2, -1, 1, 2, 3] { |
| 2592 | intra_predict_u8( |
| 2593 | mode, |
| 2594 | delta, |
| 2595 | above, |
| 2596 | left, |
| 2597 | corner, |
| 2598 | side, |
| 2599 | side, |
| 2600 | false, |
| 2601 | false, |
| 2602 | &mut prediction, fctx, |
| 2603 | ); |
| 2604 | let candidate = self.code_from_prediction( |
| 2605 | x, |
| 2606 | y, |
| 2607 | side, |
| 2608 | &prediction, |
| 2609 | false, |
| 2610 | search.base_q_idx, |
| 2611 | search.deadzone, |
| 2612 | at.set, |
| 2613 | ); |
| 2614 | let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize) |
| 2615 | - zero_bits; |
| 2616 | let cost_d = candidate.sse |
| 2617 | + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits); |
| 2618 | if cost_d < cost { |
| 2619 | cost = cost_d; |
| 2620 | angle_delta = delta; |
| 2621 | trial = candidate; |
| 2622 | } |
| 2623 | } |
| 2624 | ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize] |
| 2625 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2626 | } |
| 2627 | if census_on() { |
| 2628 | LUMA_RANK[sad_rank(&ranking, mode).min(12)] |
| 2629 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2630 | } |
| 2631 | self.commit(x, y, side, &trial); |
| 2632 | (coeffs(&trial.levels, side), mode, angle_delta, cost) |
| 2633 | } |
| 2634 | } |
| 2635 | |
| 2636 | /// Where one block sits in its plane, and how far past its own edges its |
| 2637 | /// prediction may read. |
| 2638 | #[derive(Clone, Copy)] |
| 2639 | struct At { |
| 2640 | x: usize, |
| 2641 | y: usize, |
| 2642 | side: usize, |
| 2643 | reach: Reach, |
| 2644 | /// Which of the tile writer's coefficient tables this block's levels are |
| 2645 | /// coded with, and so which the search prices them through. |
| 2646 | set: TxbSet, |
| 2647 | } |
| 2648 | |
| 2649 | /// Which of the samples past a block's own edges the decoder has decoded by |
| 2650 | /// the time it predicts the block, and so which a directional mode may read. |
| 2651 | /// |
| 2652 | /// The decoder derives these from its `BlockDecoded` flags, which are cleared |
| 2653 | /// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry |
| 2654 | /// that map, this reads the answer the same way libaom and rav1e do: for a |
| 2655 | /// block whose transform covers it whole, whether the samples above its right |
| 2656 | /// (or below its left) are decoded depends only on where the block sits inside |
| 2657 | /// its 64x64 superblock, which is a pinned table per block size. |
| 2658 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 2659 | pub(crate) struct Reach { |
| 2660 | pub(crate) above_right: bool, |
| 2661 | pub(crate) below_left: bool, |
| 2662 | } |
| 2663 | |
| 2664 | /// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in |
| 2665 | /// libaom): for a block that is neither in the superblock's top row nor its |
| 2666 | /// rightmost column, whether the block above and to its right is coded before |
| 2667 | /// it. Indexed by the block's position in the superblock, in blocks of its own |
| 2668 | /// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's |
| 2669 | /// 128, not this crate's 64 superblock -- bit by bit from the low end. |
| 2670 | const HAS_TOP_RIGHT: [&[u8]; 4] = [ |
| 2671 | &[255, 85, 119, 85, 127, 85, 119, 85], |
| 2672 | &[95, 87], |
| 2673 | // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16 |
| 2674 | // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes. |
| 2675 | &[ |
| 2676 | 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, |
| 2677 | 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, |
| 2678 | ], |
| 2679 | |
| 2680 | // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) -- |
| 2681 | // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128 |
| 2682 | // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here |
| 2683 | // with side 4 outside a TX4 split; without their own row they clamped |
| 2684 | // into the 8x8 table and read above-right samples the decoder has not |
| 2685 | // written yet (all-zero pixels in the bottom-right triangle of a |
| 2686 | // directional 4x4 leaf). |
| 2687 | &[ |
| 2688 | 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, |
| 2689 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, |
| 2690 | 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, |
| 2691 | 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, |
| 2692 | 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, |
| 2693 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, |
| 2694 | 119, 119, 119, 119, 85, 85, 85, 85, |
| 2695 | ], |
| 2696 | ]; |
| 2697 | |
| 2698 | /// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the |
| 2699 | /// left. |
| 2700 | const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ |
| 2701 | &[84, 16, 84, 0, 84, 16, 84, 0], |
| 2702 | &[4, 4], |
| 2703 | // has_bl_8x8 (libaom av1/common/reconintra.c) |
| 2704 | &[ |
| 2705 | 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, |
| 2706 | 84, 85, 16, 17, 84, 85, 0, 0, |
| 2707 | ], |
| 2708 | |
| 2709 | // has_bl_4x4 (same source, same order). |
| 2710 | &[ |
| 2711 | 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, |
| 2712 | 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, |
| 2713 | 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, |
| 2714 | 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, |
| 2715 | 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, |
| 2716 | 85, 85, 0, 0, 0, 0, |
| 2717 | ], |
| 2718 | ]; |
| 2719 | |
| 2720 | /// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by |
| 2721 | /// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a |
| 2722 | /// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR |
| 2723 | /// rather than in raster order, so the bottom-left square's top-right |
| 2724 | /// neighbour is the partition's own right-hand rectangle -- not yet decoded. |
| 2725 | /// libaom switches tables on the partition type (`get_has_tr_table`); the |
| 2726 | /// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0: |
| 2727 | /// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case |
| 2728 | /// lane-part32 r5 caught reading undecoded samples. |
| 2729 | const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [ |
| 2730 | // has_tr_vert_16x16 |
| 2731 | &[255, 0, 119, 0, 127, 0, 119, 0], |
| 2732 | // has_tr_vert_32x32 |
| 2733 | &[15, 7], |
| 2734 | // has_tr_vert_8x8 |
| 2735 | &[ |
| 2736 | 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119, |
| 2737 | 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, |
| 2738 | ], |
| 2739 | ]; |
| 2740 | |
| 2741 | /// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`. |
| 2742 | const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [ |
| 2743 | // has_bl_vert_16x16 |
| 2744 | &[254, 16, 254, 0, 254, 16, 254, 0], |
| 2745 | // has_bl_vert_32x32 |
| 2746 | &[14, 14], |
| 2747 | // has_bl_vert_8x8 |
| 2748 | &[ |
| 2749 | 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254, |
| 2750 | 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, |
| 2751 | ], |
| 2752 | ]; |
| 2753 | |
| 2754 | thread_local! { |
| 2755 | /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks |
| 2756 | /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition |
| 2757 | /// type down into `has_top_right`/`has_bottom_left` as an argument, and |
| 2758 | /// threading one bool through this crate's already twenty-argument |
| 2759 | /// `decode_block` would touch every call site instead of the two arms |
| 2760 | /// that need it. |
| 2761 | static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 2762 | } |
| 2763 | |
| 2764 | /// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made. |
| 2765 | pub(crate) struct VertAbGuard(bool); |
| 2766 | |
| 2767 | impl Drop for VertAbGuard { |
| 2768 | fn drop(&mut self) { |
| 2769 | VERT_AB_PARTITION.with(|c| c.set(self.0)); |
| 2770 | } |
| 2771 | } |
| 2772 | |
| 2773 | /// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this |
| 2774 | /// decoder codes (libaom `reconintra.c`, generated from the oracle's source |
| 2775 | /// so no byte is retyped). Each is indexed by |
| 2776 | /// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride |
| 2777 | /// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel |
| 2778 | /// superblock grid; on this crate's 64-pixel superblock the highest index a |
| 2779 | /// shape can reach stays inside its own table, so no wrap is involved. |
| 2780 | /// |
| 2781 | /// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/ |
| 2782 | /// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed |
| 2783 | /// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at |
| 2784 | /// 10 of the 21 reachable superblock positions for above-right and 7 for |
| 2785 | /// below-left. |
| 2786 | /// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`). |
| 2787 | const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119]; |
| 2788 | /// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`). |
| 2789 | const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0]; |
| 2790 | /// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`). |
| 2791 | const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0]; |
| 2792 | /// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`). |
| 2793 | const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0]; |
| 2794 | /// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). |
| 2795 | const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119]; |
| 2796 | /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). |
| 2797 | const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; |
| 2798 | /// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). |
| 2799 | const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; |
| 2800 | /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). |
| 2801 | const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0]; |
| 2802 | /// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`). |
| 2803 | const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; |
| 2804 | /// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`). |
| 2805 | const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; |
| 2806 | /// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`). |
| 2807 | const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; |
| 2808 | /// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`). |
| 2809 | const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; |
| 2810 | /// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`). |
| 2811 | const HAS_TR_32X64: [u8; 1] = [127]; |
| 2812 | /// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`). |
| 2813 | const HAS_BL_32X64: [u8; 1] = [0]; |
| 2814 | /// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`). |
| 2815 | const HAS_TR_64X32: [u8; 1] = [19]; |
| 2816 | /// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`). |
| 2817 | const HAS_BL_64X32: [u8; 1] = [34]; |
| 2818 | /// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`). |
| 2819 | const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127]; |
| 2820 | /// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`). |
| 2821 | const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0]; |
| 2822 | /// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`). |
| 2823 | const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0]; |
| 2824 | /// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`). |
| 2825 | const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0]; |
| 2826 | /// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`). |
| 2827 | const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; |
| 2828 | /// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`). |
| 2829 | const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; |
| 2830 | /// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`). |
| 2831 | const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; |
| 2832 | /// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`). |
| 2833 | const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; |
| 2834 | /// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`). |
| 2835 | const HAS_TR_16X64: [u8; 2] = [255, 127]; |
| 2836 | /// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`). |
| 2837 | const HAS_BL_16X64: [u8; 2] = [0, 0]; |
| 2838 | /// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`). |
| 2839 | const HAS_TR_64X16: [u8; 2] = [3, 1]; |
| 2840 | /// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`). |
| 2841 | const HAS_BL_64X16: [u8; 2] = [42, 42]; |
| 2842 | |
| 2843 | /// The `has_tr_*`/`has_bl_*` row for one rectangular block shape. |
| 2844 | fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { |
| 2845 | match (bw, bh) { |
| 2846 | (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), |
| 2847 | (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), |
| 2848 | (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), |
| 2849 | (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), |
| 2850 | (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), |
| 2851 | (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), |
| 2852 | (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), |
| 2853 | (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), |
| 2854 | (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), |
| 2855 | (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), |
| 2856 | (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), |
| 2857 | (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), |
| 2858 | (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), |
| 2859 | (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), |
| 2860 | _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), |
| 2861 | } |
| 2862 | } |
| 2863 | |
| 2864 | impl Reach { |
| 2865 | /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a |
| 2866 | /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose |
| 2867 | /// own answer is `block` -- a different rule from the standalone-block |
| 2868 | /// tables, because a unit's neighbours are mostly its own block's |
| 2869 | /// already-reconstructed units: |
| 2870 | /// * top-right: available while the unit to the right is still inside |
| 2871 | /// the block (`col_off + tx < bw`); otherwise only the block's top row |
| 2872 | /// of units reaches past it, through the block-level answer |
| 2873 | /// (libaom's `row_off > 0` branch returns exactly |
| 2874 | /// `col_off + txw < plane_bw`). |
| 2875 | /// * bottom-left: a unit outside the block's left column has none |
| 2876 | /// (libaom returns 0 for `col_off > 0`); inside the block |
| 2877 | /// (`row_off + tx < bh`) they are the left unit's, already |
| 2878 | /// reconstructed; the bottom row falls back to the block-level answer. |
| 2879 | pub(crate) fn of_tu( |
| 2880 | bw: usize, |
| 2881 | bh: usize, |
| 2882 | col_off: usize, |
| 2883 | row_off: usize, |
| 2884 | // The unit's own width and height in pixels; equal for a square |
| 2885 | // transform, different for the rect unit a 1:4 strip's first split |
| 2886 | // produces (lane-rectsplitx r1). |
| 2887 | tx_w: usize, |
| 2888 | tx_h: usize, |
| 2889 | block: Self, |
| 2890 | ) -> Self { |
| 2891 | // A block wider than 64 is coded in 64x64 "mu" chunks in raster |
| 2892 | // order, so both libaom predicates special-case it (lane-sb128c r10); |
| 2893 | // without this the last unit column of every chunk of a 128x64 block |
| 2894 | // predicts from a chunk libaom has not decoded yet. |
| 2895 | let wide = bw > 64; |
| 2896 | Self { |
| 2897 | above_right: if row_off > 0 { |
| 2898 | // `has_top_right`'s `row_off > 0` branch: the offset is taken |
| 2899 | // modulo the 64-wide chunk, except for the one unit whose |
| 2900 | // top-right corner is the centre of a 128x128 block. |
| 2901 | if wide { |
| 2902 | (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64 |
| 2903 | } else { |
| 2904 | col_off + tx_w < bw |
| 2905 | } |
| 2906 | } else if col_off + tx_w < bw { |
| 2907 | true |
| 2908 | } else { |
| 2909 | block.above_right |
| 2910 | }, |
| 2911 | below_left: if wide && col_off > 0 && col_off % 64 == 0 { |
| 2912 | // `has_bottom_left`: at the left edge of a right-hand chunk |
| 2913 | // the bottom-left pixels are in the already-coded left chunk, |
| 2914 | // provided they stay inside it. |
| 2915 | (row_off % 64) + tx_h < bh.min(64) |
| 2916 | } else if col_off > 0 { |
| 2917 | false |
| 2918 | } else if row_off + tx_h < bh { |
| 2919 | true |
| 2920 | } else { |
| 2921 | block.below_left |
| 2922 | }, |
| 2923 | } |
| 2924 | } |
| 2925 | |
| 2926 | /// What a block of `side` samples at `(x, y)` may read past its own edges, |
| 2927 | /// in a frame of `width` by `height`. |
| 2928 | pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self { |
| 2929 | Self { |
| 2930 | above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx), |
| 2931 | below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx), |
| 2932 | } |
| 2933 | } |
| 2934 | |
| 2935 | /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp |
| 2936 | /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the |
| 2937 | /// block's own width for the row stride and by its own height for the |
| 2938 | /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`), |
| 2939 | /// unlike the square [`Self::of`] which uses one `side` for everything. |
| 2940 | pub(crate) fn of_rect( |
| 2941 | bw: usize, |
| 2942 | bh: usize, |
| 2943 | x: usize, |
| 2944 | y: usize, |
| 2945 | width: usize, |
| 2946 | height: usize, fctx: &crate::decode::FrameCtx, |
| 2947 | ) -> Self { |
| 2948 | Self { |
| 2949 | above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx), |
| 2950 | below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx), |
| 2951 | } |
| 2952 | } |
| 2953 | |
| 2954 | /// [`Self::of`] for one transform unit of a square block whose transform |
| 2955 | /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with |
| 2956 | /// non-zero `row_off`/`col_off`): interior units answer from the block's |
| 2957 | /// own geometry, and only a unit on the block's top row (resp. left |
| 2958 | /// column) reaches the table -- which is the BLOCK's table read at the |
| 2959 | /// BLOCK's position, never a table row for the transform's size. Letting |
| 2960 | /// the unit stand in for a block of its own size agrees with libaom for |
| 2961 | /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has |
| 2962 | /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4 |
| 2963 | /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a |
| 2964 | /// real `--enable-tx-size-search=1` stream (lane-ab16 r2). |
| 2965 | /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0, |
| 2966 | /// the transform covering the whole block, luma): everything before the |
| 2967 | /// table lookup is that function's own early-exit ladder. |
| 2968 | fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2969 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 2970 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 2971 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 2972 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 2973 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 2974 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 2975 | // Top row of the superblock: the top-right pixels are in the (already |
| 2976 | // decoded) superblock above. |
| 2977 | if blk_row == 0 { |
| 2978 | return true; |
| 2979 | } |
| 2980 | // Rightmost column: they fall in the superblock to the right. |
| 2981 | if ((blk_col + 1) << bw_log2) >= sb_mi { |
| 2982 | return false; |
| 2983 | } |
| 2984 | let table = rect_reach_tables(bw, bh).0; |
| 2985 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 2986 | } |
| 2987 | |
| 2988 | /// libaom `has_top_right`'s own index arithmetic: |
| 2989 | /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and |
| 2990 | /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a |
| 2991 | /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5: |
| 2992 | /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but |
| 2993 | /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a |
| 2994 | /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main). |
| 2995 | /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it. |
| 2996 | fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { |
| 2997 | (blk_row << (5 - bw_log2)) + blk_col |
| 2998 | } |
| 2999 | |
| 3000 | /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`]. |
| 3001 | fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 3002 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 3003 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 3004 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 3005 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 3006 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 3007 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 3008 | // Leftmost column of the superblock: the bottom-left pixels are in |
| 3009 | // the left superblock iff they stay inside its height. |
| 3010 | if blk_col == 0 { |
| 3011 | return (blk_row << bh_log2) + (bh / 4) < sb_mi; |
| 3012 | } |
| 3013 | // Bottom row (and not the leftmost column): they fall in the |
| 3014 | // superblock below, which is not decoded yet. |
| 3015 | if ((blk_row + 1) << bh_log2) >= sb_mi { |
| 3016 | return false; |
| 3017 | } |
| 3018 | let table = rect_reach_tables(bw, bh).1; |
| 3019 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 3020 | } |
| 3021 | |
| 3022 | /// Marks every [`Reach::of`] made until the returned guard drops as being |
| 3023 | /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` / |
| 3024 | /// `get_has_bl_table` partition argument). Rectangular sub-blocks are |
| 3025 | /// unaffected: libaom's own comment says vertical rectangles keep their |
| 3026 | /// non-vert table, which is what [`Reach::of_rect`] already reads. |
| 3027 | /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded |
| 3028 | /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller |
| 3029 | /// can count the sub-block work that partition creates (lane-ab16). |
| 3030 | pub(crate) fn in_vert_ab() -> bool { |
| 3031 | VERT_AB_PARTITION.with(std::cell::Cell::get) |
| 3032 | } |
| 3033 | |
| 3034 | pub(crate) fn vert_ab_partition() -> VertAbGuard { |
| 3035 | VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) |
| 3036 | } |
| 3037 | |
| 3038 | /// Neither, which is all a mode that reads no further than its own edges |
| 3039 | /// needs. |
| 3040 | pub(crate) fn none() -> Self { |
| 3041 | Self { |
| 3042 | above_right: false, |
| 3043 | below_left: false, |
| 3044 | } |
| 3045 | } |
| 3046 | |
| 3047 | /// `has_top_right` for a block whose transform covers it whole: the top |
| 3048 | /// row of a superblock reads into the superblock above, which is decoded; |
| 3049 | /// the rightmost column would read into the superblock to the right, which |
| 3050 | /// is not; and everything between is the table's to answer. |
| 3051 | fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 3052 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 3053 | if row == 0 { |
| 3054 | return true; |
| 3055 | } |
| 3056 | if col + 1 == per_side { |
| 3057 | return false; |
| 3058 | } |
| 3059 | // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row |
| 3060 | // (the clamp corner-cut that used to live here is gone); sides |
| 3061 | // 16/32/64 share row 0 exactly as libaom's tables repeat. |
| 3062 | // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block |
| 3063 | // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table |
| 3064 | // -- a reach over-estimate (extra above-right reference pixels), |
| 3065 | // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` / |
| 3066 | // `has_bl_vert_4x4` and extend the VERT tables to four rows. |
| 3067 | // NB: named `table_row`, not `row` -- `row` above is the block's |
| 3068 | // position inside the superblock and is what the bit index below |
| 3069 | // steps by (a merge that shadowed it desynced every block size). |
| 3070 | let table_row = Self::table(side); |
| 3071 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { |
| 3072 | HAS_TOP_RIGHT_VERT[table_row] |
| 3073 | } else { |
| 3074 | HAS_TOP_RIGHT[table_row] |
| 3075 | }; |
| 3076 | Self::bit( |
| 3077 | table, |
| 3078 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 3079 | ) |
| 3080 | } |
| 3081 | |
| 3082 | /// `has_bottom_left` for such a block: the leftmost column of a superblock |
| 3083 | /// reads into the superblock to its left, which is decoded only as far |
| 3084 | /// down as its own bottom; the bottom row would read into the superblock |
| 3085 | /// below, which is not decoded at all; and the table answers the rest. |
| 3086 | fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 3087 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 3088 | if col == 0 { |
| 3089 | return row * side + side < reach_sb_px(fctx); |
| 3090 | } |
| 3091 | if row + 1 == per_side { |
| 3092 | return false; |
| 3093 | } |
| 3094 | // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row |
| 3095 | // (the clamp corner-cut that used to live here is gone); sides |
| 3096 | // 16/32/64 share row 0 exactly as libaom's tables repeat. |
| 3097 | // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block |
| 3098 | // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table |
| 3099 | // -- a reach over-estimate (extra above-right reference pixels), |
| 3100 | // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` / |
| 3101 | // `has_bl_vert_4x4` and extend the VERT tables to four rows. |
| 3102 | // NB: named `table_row`, not `row` -- `row` above is the block's |
| 3103 | // position inside the superblock and is what the bit index below |
| 3104 | // steps by (a merge that shadowed it desynced every block size). |
| 3105 | let table_row = Self::table(side); |
| 3106 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { |
| 3107 | HAS_BOTTOM_LEFT_VERT[table_row] |
| 3108 | } else { |
| 3109 | HAS_BOTTOM_LEFT[table_row] |
| 3110 | }; |
| 3111 | Self::bit( |
| 3112 | table, |
| 3113 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 3114 | ) |
| 3115 | } |
| 3116 | |
| 3117 | /// Where a block sits inside its superblock, in blocks of its own size, |
| 3118 | /// and how many of them a superblock is across. |
| 3119 | fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) { |
| 3120 | let sb = reach_sb_px(fctx); |
| 3121 | ((y % sb) / side, (x % sb) / side, sb / side) |
| 3122 | } |
| 3123 | |
| 3124 | /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins |
| 3125 | /// these tables to its compile-time maximum superblock (128, spec |
| 3126 | /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock |
| 3127 | /// size an encode actually uses, so a block's row in the bit index steps |
| 3128 | /// by 128 / `side` even though this crate only ever codes a 64 |
| 3129 | /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative) |
| 3130 | /// here instead indexes the wrong bit for every block size but the one |
| 3131 | /// where 64 and 128 give the same stride. |
| 3132 | fn table_stride(side: usize) -> usize { |
| 3133 | 128 / side |
| 3134 | } |
| 3135 | |
| 3136 | /// Which of the three block sizes the encoder codes a table row is for. |
| 3137 | fn table(side: usize) -> usize { |
| 3138 | if side == BLOCK { |
| 3139 | 1 |
| 3140 | } else if side == 8 { |
| 3141 | 2 |
| 3142 | } else if side == 4 { |
| 3143 | 3 |
| 3144 | } else { |
| 3145 | 0 |
| 3146 | } |
| 3147 | } |
| 3148 | |
| 3149 | /// One bit of a table, counting from the low end of its first byte. |
| 3150 | fn bit(table: &[u8], index: usize) -> bool { |
| 3151 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 3152 | } |
| 3153 | } |
| 3154 | |
| 3155 | /// What one symbol costs against a CDF, in bits. |
| 3156 | /// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the |
| 3157 | /// search, the frame header's `allow_warped_motion` and the sequence's |
| 3158 | /// `enable_warped_motion`, all three together. ON by default since |
| 3159 | /// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at |
| 3160 | /// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header |
| 3161 | /// bits -- back off for an A/B on one build. |
| 3162 | pub(crate) fn warp_on() -> bool { |
| 3163 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 3164 | crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off")) |
| 3165 | }); |
| 3166 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP)) |
| 3167 | } |
| 3168 | |
| 3169 | /// The smallest LEAF an OBMC candidate is offered for, so the census can |
| 3170 | /// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 -- |
| 3171 | /// every leaf; 16 or 32 turn the smaller leaves off). Only read when |
| 3172 | /// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate. |
| 3173 | /// |
| 3174 | /// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e |
| 3175 | /// (12 frames, four quantizers, the standing keep table): |
| 3176 | /// |
| 3177 | /// | min side | film 1080p | film 2160p | screen | |
| 3178 | /// |---|---|---|---| |
| 3179 | /// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 | |
| 3180 | /// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 | |
| 3181 | /// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 | |
| 3182 | /// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 | |
| 3183 | /// |
| 3184 | /// So the leaves are not the thing that was holding OBMC back: at 8x8 the |
| 3185 | /// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p |
| 3186 | /// film -- 85% of them, far past libaom's own rate -- and costs another 0.3 |
| 3187 | /// BD points on top of the 0.4 the 32x32 candidate already costs. A tool |
| 3188 | /// that wins the local RD on five blocks in six and loses ladder bytes is |
| 3189 | /// the `local-RD-on-references` class again, not a missing footprint. |
| 3190 | /// |
| 3191 | /// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8): |
| 3192 | /// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with |
| 3193 | /// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point |
| 3194 | /// loss on the 1080p film became a 0.3-point win and the other two rows went |
| 3195 | /// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half |
| 3196 | /// of the "local win, ladder loss" it was charged with was the rate weight. |
| 3197 | /// It still does not meet the keep rule (two down, one flat, both columns). |
| 3198 | /// The tool stays OFF by default; the upgrade path is the price, not the size |
| 3199 | /// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8 |
| 3200 | /// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the |
| 3201 | /// 1080p film up, i.e. the same disagreement between the two gates). |
| 3202 | /// |
| 3203 | /// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept |
| 3204 | /// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1, |
| 3205 | /// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads |
| 3206 | /// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p |
| 3207 | /// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference |
| 3208 | /// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at |
| 3209 | /// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and |
| 3210 | /// the margin's gain are the same bytes. It stays OFF. |
| 3211 | fn obmc_min_side() -> usize { |
| 3212 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 3213 | *N.get_or_init(|| { |
| 3214 | std::env::var("EC_AV1_OBMC_MIN") |
| 3215 | .ok() |
| 3216 | .and_then(|v| v.parse().ok()) |
| 3217 | .unwrap_or(8) |
| 3218 | }) |
| 3219 | } |
| 3220 | |
| 3221 | /// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables |
| 3222 | /// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the |
| 3223 | /// same frame-CDF price the coefficients of a non-screen frame are estimated |
| 3224 | /// with, not the static default table. |
| 3225 | /// The same price for whichever alphabet the writer will really use for this |
| 3226 | /// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice |
| 3227 | /// (`allow_warped_motion` and at least one warp sample), otherwise the |
| 3228 | /// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the |
| 3229 | /// search pay it, so the alphabet cancels out of a comparison and only its |
| 3230 | /// per-value spread decides. |
| 3231 | fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 { |
| 3232 | let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else { |
| 3233 | return 0.0; |
| 3234 | }; |
| 3235 | match warp_alphabet { |
| 3236 | true => crate::tile::motion_mode_symbol_bits(row, motion), |
| 3237 | false => crate::tile::obmc_symbol_bits(row, motion == 1), |
| 3238 | } |
| 3239 | } |
| 3240 | |
| 3241 | /// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the |
| 3242 | /// candidate, the header's `allow_warped_motion` and the sequence's |
| 3243 | /// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing |
| 3244 | /// native keep table, against the same build with the knob off: |
| 3245 | /// |
| 3246 | /// | clip | warp on | off | |
| 3247 | /// |---|---|---| |
| 3248 | /// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 | |
| 3249 | /// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 | |
| 3250 | /// | screen | +59.2 / -9.9 | +59.4 / -10.0 | |
| 3251 | /// |
| 3252 | /// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and |
| 3253 | /// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so |
| 3254 | /// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2 |
| 3255 | /// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool |
| 3256 | /// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol |
| 3257 | /// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so |
| 3258 | /// this is a measured loss, not an inert knob. Same shape as the OBMC |
| 3259 | /// candidate above it (`obmc_min_side`): a local RD win that does not convert |
| 3260 | /// into ladder bytes. |
| 3261 | /// |
| 3262 | /// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, |
| 3263 | /// because a tool whose gain is local and whose cost is the rate it adds is |
| 3264 | /// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN: |
| 3265 | /// |
| 3266 | /// | clip | warp on | off (both at lambda 0.05) | |
| 3267 | /// |---|---|---| |
| 3268 | /// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 | |
| 3269 | /// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 | |
| 3270 | /// | screen | +51.3 / -14.3 | +51.6 / -14.2 | |
| 3271 | /// |
| 3272 | /// two rows down against libaom (0.3 each) with the third flat, and the rav1e |
| 3273 | /// column inside 0.1 everywhere -- which reads as a keep rather than the |
| 3274 | /// 0.7/0.9 loss it was. |
| 3275 | /// |
| 3276 | /// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table |
| 3277 | /// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5, |
| 3278 | /// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and |
| 3279 | /// ran the conformance shape the lambda lane deferred: every warp stream |
| 3280 | /// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1` |
| 3281 | /// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside |
| 3282 | /// a 16-tile frame, sample walk and all), and tile bytes still do not depend |
| 3283 | /// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks |
| 3284 | /// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it, |
| 3285 | /// `allow_warped_motion` and `enable_warped_motion` back off together. |
| 3286 | /// |
| 3287 | /// The WARPED_CAUSAL prediction of one square single-reference block: the |
| 3288 | /// decoder's own warp-sample walk (`decode::find_samples` + |
| 3289 | /// `warp::select_samples`), least-squares model (`warp::find_projection`) and |
| 3290 | /// affine predictor (`warp::warp_affine`), driven off the encoder's own mi |
| 3291 | /// grid -- never a second implementation of any of the three. `None` when the |
| 3292 | /// block would code no motion_mode symbol at all, when it has no warp sample |
| 3293 | /// (the writer then codes the 2-symbol alphabet, which has no WARPED value), |
| 3294 | /// or when the projection is not filter-representable (the decoder would then |
| 3295 | /// predict translationally, so the mode is pure cost). |
| 3296 | #[allow(clippy::too_many_arguments)] |
| 3297 | fn warp_prediction( |
| 3298 | grid: &MiGrid, |
| 3299 | (mi_row, mi_col): (usize, usize), |
| 3300 | (mi_rows, mi_cols): (usize, usize), |
| 3301 | (x, y): (usize, usize), |
| 3302 | side: usize, |
| 3303 | mv: (i32, i32), |
| 3304 | ref_frame: i8, |
| 3305 | ref_planes: [(&[u16], usize, usize, usize); 3], |
| 3306 | fctx: &crate::decode::FrameCtx, |
| 3307 | ) -> Option<[Vec<u8>; 3]> { |
| 3308 | let n4 = side / 4; |
| 3309 | if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) { |
| 3310 | return None; |
| 3311 | } |
| 3312 | let mut samples = crate::decode::find_samples( |
| 3313 | grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx, |
| 3314 | ); |
| 3315 | if samples.is_empty() { |
| 3316 | return None; |
| 3317 | } |
| 3318 | if samples.len() > 1 { |
| 3319 | crate::warp::select_samples(mv, &mut samples, side as i32, side as i32); |
| 3320 | } |
| 3321 | let params = crate::warp::find_projection( |
| 3322 | &samples, |
| 3323 | side as i32, |
| 3324 | side as i32, |
| 3325 | mv.1, |
| 3326 | mv.0, |
| 3327 | mi_row as i32, |
| 3328 | mi_col as i32, |
| 3329 | )?; |
| 3330 | let mut pred = [ |
| 3331 | vec![0u16; side * side], |
| 3332 | vec![0u16; side * side / 4], |
| 3333 | vec![0u16; side * side / 4], |
| 3334 | ]; |
| 3335 | // The translational prediction first, exactly as the decoder builds it, |
| 3336 | // then the affine one over the planes whose OWN block is at least 8x8 |
| 3337 | // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's |
| 3338 | // 4x4 chroma stays translational). |
| 3339 | for (i, r) in ref_planes.into_iter().enumerate() { |
| 3340 | let luma_plane = i == 0; |
| 3341 | let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) }; |
| 3342 | let s = if luma_plane { side } else { side / 2 }; |
| 3343 | mc::predict( |
| 3344 | r.0, |
| 3345 | r.1, |
| 3346 | r.2, |
| 3347 | r.3, |
| 3348 | mv_to_q4(px, mv.1, luma_plane), |
| 3349 | mv_to_q4(py, mv.0, luma_plane), |
| 3350 | s, |
| 3351 | s, |
| 3352 | &mut pred[i], |
| 3353 | fctx, |
| 3354 | ); |
| 3355 | if crate::decode::warp_plane_allowed(s, s) { |
| 3356 | let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32); |
| 3357 | crate::warp::warp_affine( |
| 3358 | ¶ms, |
| 3359 | r.0, |
| 3360 | r.2 as i32, |
| 3361 | r.3 as i32, |
| 3362 | r.1 as i32, |
| 3363 | &mut pred[i], |
| 3364 | px as i32, |
| 3365 | py as i32, |
| 3366 | cside, |
| 3367 | cside, |
| 3368 | cside, |
| 3369 | sub, |
| 3370 | sub, |
| 3371 | fctx, |
| 3372 | ); |
| 3373 | } |
| 3374 | } |
| 3375 | let [py_buf, pu_buf, pv_buf] = pred; |
| 3376 | let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>(); |
| 3377 | Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)]) |
| 3378 | } |
| 3379 | |
| 3380 | pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { |
| 3381 | let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; |
| 3382 | let width = cdf[symbol] - low; |
| 3383 | // lane-av1speed: a CDF interval is a 15-bit width, so there are only |
| 3384 | // 32769 prices a symbol can carry; the `log2` behind each is computed |
| 3385 | // once instead of per call (libm's `__log2_fma` was 5% of the encoder's |
| 3386 | // profile -- this function is called for every symbol of every candidate |
| 3387 | // the RD search prices). Each entry is exactly the expression this used |
| 3388 | // to evaluate, so every price is bit-identical. |
| 3389 | static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new(); |
| 3390 | PRICES.get_or_init(|| { |
| 3391 | (0..=32768u32) |
| 3392 | .map(|w| -(f64::from(w) / 32768.0).log2()) |
| 3393 | .collect() |
| 3394 | })[usize::from(width)] |
| 3395 | } |
| 3396 | |
| 3397 | /// What the tile writer spends to say a block is coded in each of the thirteen |
| 3398 | /// modes, given the modes of the blocks above it and to its left: the luma mode |
| 3399 | /// symbol against the CDF those two neighbours pick, the angle delta a |
| 3400 | /// directional mode carries, and the chroma mode symbol, whose CDF the luma |
| 3401 | /// mode itself indexes. |
| 3402 | /// |
| 3403 | /// Without this the search is blind to what a mode costs to name, which is not |
| 3404 | /// a rounding error: a directional mode on a picture that does not run that way |
| 3405 | /// is a rate loss the squared error never sees. |
| 3406 | /// Codes one square of the picture as a single block: searches the luma mode, |
| 3407 | /// codes both chroma planes DC, and hands back the block and what it cost -- |
| 3408 | /// squared error plus lambda times the bits its symbols spend. |
| 3409 | /// How many halvings of a `side`-square block's transform the `tx_depth` |
| 3410 | /// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two |
| 3411 | /// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform. |
| 3412 | fn max_tx_depth(side: usize) -> usize { |
| 3413 | match side { |
| 3414 | 8 => 1, |
| 3415 | 16 | 32 => 2, |
| 3416 | _ => 0, |
| 3417 | } |
| 3418 | } |
| 3419 | |
| 3420 | /// What the `tx_depth` symbol itself costs, off the size category's own CDF. |
| 3421 | /// Priced at context row 0 -- the writer picks the real row from its |
| 3422 | /// neighbours' transform sizes, which the search has no view of; the term is |
| 3423 | /// the same for every depth of one block either way, so it only shifts the |
| 3424 | /// depth-0-versus-split margin, never the ordering between two splits. |
| 3425 | fn tx_depth_bits(side: usize, depth: usize) -> f64 { |
| 3426 | match side { |
| 3427 | 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth), |
| 3428 | 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth), |
| 3429 | 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth), |
| 3430 | _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth), |
| 3431 | } |
| 3432 | } |
| 3433 | |
| 3434 | /// How many blocks resolved to each `tx_depth`, the fire count that says |
| 3435 | /// whether the depth search below reaches its candidates at all. |
| 3436 | static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = |
| 3437 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 3438 | |
| 3439 | /// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts |
| 3440 | /// to its own encode. |
| 3441 | #[cfg(test)] |
| 3442 | pub(crate) fn take_tx_depth_hits() -> [usize; 3] { |
| 3443 | std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 3444 | } |
| 3445 | |
| 3446 | /// How many inter blocks resolved to each var-tx depth (0 = one transform |
| 3447 | /// over the whole block, 1 = its four halves), the fire count a gate prints |
| 3448 | /// to see the split search reach its candidates at all. Indexed |
| 3449 | /// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census |
| 3450 | /// says which of the four block classes the split reaches -- the 32x32 root |
| 3451 | /// and the compound blocks are this lane's two new ones. |
| 3452 | static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 3453 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 3454 | |
| 3455 | /// Whether a 32x32 inter winner searches its own var-tx depth (the four |
| 3456 | /// 16x16 units against the flat transform) instead of coding depth 0 blind. |
| 3457 | /// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off. |
| 3458 | /// |
| 3459 | /// Rejected three times on the bars rows of the native gate (flat to +0.3). |
| 3460 | /// lane-av1resweep re-judged it on the two REAL film crops at |
| 3461 | /// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file |
| 3462 | /// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`): |
| 3463 | /// |
| 3464 | /// | clip | shipped | tx32 depth | + [`compound_var_tx`] | |
| 3465 | /// |---|---|---|---| |
| 3466 | /// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 | |
| 3467 | /// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 | |
| 3468 | /// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 | |
| 3469 | /// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 | |
| 3470 | /// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 | |
| 3471 | /// |
| 3472 | /// The bars rows are ~90% zero-intra-cost cells, so the split never had |
| 3473 | /// residual to reach there -- the tool was being judged on content that |
| 3474 | /// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`. |
| 3475 | fn tx32_depth_search() -> bool { |
| 3476 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 3477 | crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off")) |
| 3478 | }); |
| 3479 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH)) |
| 3480 | } |
| 3481 | |
| 3482 | /// Whether a COMPOUND inter winner is offered the var-tx split at all: its |
| 3483 | /// trial units have to be predicted from BOTH references |
| 3484 | /// ([`mc_trial_compound`]) or the split would re-predict them by single- |
| 3485 | /// reference translation, which is not what the decoder reconstructs. |
| 3486 | /// ON by default (the table on [`tx32_depth_search`]: on real film it is |
| 3487 | /// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the |
| 3488 | /// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off. |
| 3489 | /// `EC_AV1_COMP_VARTX`. |
| 3490 | fn compound_var_tx() -> bool { |
| 3491 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 3492 | crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off")) |
| 3493 | }); |
| 3494 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX)) |
| 3495 | } |
| 3496 | |
| 3497 | /// How many 32x32-and-below inter blocks each reference frame won, indexed by |
| 3498 | /// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the |
| 3499 | /// fire count a gate prints to see an extra reference reach a block at all |
| 3500 | /// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never |
| 3501 | /// chosen is a pyramid that costs bytes and buys nothing). |
| 3502 | static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 3503 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 3504 | |
| 3505 | /// Reads [`REF_FRAME_HITS`] and zeroes it. |
| 3506 | #[cfg(test)] |
| 3507 | pub(crate) fn take_ref_frame_hits() -> [usize; 8] { |
| 3508 | std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 3509 | } |
| 3510 | |
| 3511 | /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it. |
| 3512 | #[cfg(test)] |
| 3513 | pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] { |
| 3514 | std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 3515 | } |
| 3516 | |
| 3517 | /// What the `txfm_split` symbols of one inter block cost at `depth`, priced |
| 3518 | /// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0 |
| 3519 | /// is one flag, depth 1 is a split root plus one unsplit flag per child |
| 3520 | /// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH` |
| 3521 | /// or a 4x4 sub-size). |
| 3522 | fn txfm_split_bits(side: usize, depth: usize) -> f64 { |
| 3523 | let max_tx = side.min(64); |
| 3524 | let ctx = |tx: usize| { |
| 3525 | crate::decode::txfm_partition_ctx_rect( |
| 3526 | crate::decode::TXFM_CTX_INIT, |
| 3527 | crate::decode::TXFM_CTX_INIT, |
| 3528 | side, |
| 3529 | tx, |
| 3530 | tx, |
| 3531 | ) |
| 3532 | }; |
| 3533 | if depth == 0 { |
| 3534 | return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0); |
| 3535 | } |
| 3536 | symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1) |
| 3537 | + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0) |
| 3538 | } |
| 3539 | |
| 3540 | /// The inter block's own var-tx decision, once its motion vector is settled: |
| 3541 | /// its residual as ONE transform over the whole block, or as the four |
| 3542 | /// transforms of half the side the tree's first halving names. The prediction |
| 3543 | /// is the same motion compensation either way, so the split trial |
| 3544 | /// re-transforms the identical residual in four pieces -- it wins where four |
| 3545 | /// small transforms carry a locally varying residual cheaper than one big |
| 3546 | /// one. Commits the winner into `luma` and hands back its block-coordinate |
| 3547 | /// levels, the depth the writer codes and the cost the winner adds to (or |
| 3548 | /// takes off) the caller's already-computed flat cost. |
| 3549 | /// |
| 3550 | /// Only for a block wholly inside the frame: past the true edge the reader's |
| 3551 | /// var-tx recursion skips the units that fall outside |
| 3552 | /// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would |
| 3553 | /// leave the residual units this writes unpaired. |
| 3554 | #[allow(clippy::too_many_arguments)] |
| 3555 | fn commit_inter_luma( |
| 3556 | luma: &mut Plane, |
| 3557 | (x, y): (usize, usize), |
| 3558 | side: usize, |
| 3559 | mv: (i32, i32), |
| 3560 | reference: (&[u16], usize, usize, usize), |
| 3561 | search: &Search, |
| 3562 | flat: &Trial, |
| 3563 | skip: bool, |
| 3564 | // A COMPOUND winner's second half: the vector and reference planes the |
| 3565 | // trial units are blended from ([`mc_trial_compound`], the decoder's own |
| 3566 | // `comp_group_idx == 0` average). `None` is the single-reference block. |
| 3567 | second: Option<((i32, i32), (&[u16], usize, usize, usize))>, |
| 3568 | fctx: &crate::decode::FrameCtx, |
| 3569 | ) -> (Vec<i32>, u8, f64) { |
| 3570 | let eligible = tx_select() |
| 3571 | && tx_select_inter() |
| 3572 | && !skip |
| 3573 | && side >= 16 |
| 3574 | && (second.is_none() || compound_var_tx()) |
| 3575 | && (side != BLOCK || tx32_depth_search()) |
| 3576 | && x + side <= luma.true_width |
| 3577 | && y + side <= luma.true_height; |
| 3578 | if !eligible { |
| 3579 | luma.commit(x, y, side, flat); |
| 3580 | return (flat.levels.clone(), 0, 0.0); |
| 3581 | } |
| 3582 | let tx = side / 2; |
| 3583 | let set = if tx >= 32 { |
| 3584 | // lane-b64b: the 64x64 root's halved transform is TX_32X32. |
| 3585 | TxbSet::Luma32Inter |
| 3586 | } else if tx >= 16 { |
| 3587 | TxbSet::Luma16Inter |
| 3588 | } else { |
| 3589 | TxbSet::Luma8Inter |
| 3590 | }; |
| 3591 | let mut levels = vec![0i32; side * side]; |
| 3592 | let (mut sse, mut bits) = (0.0, 0.0); |
| 3593 | let mut units = Vec::with_capacity(4); |
| 3594 | // The split units are smaller than their block, so their `txb_skip` |
| 3595 | // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and |
| 3596 | // each unit's own commit publishes what the next one reads, coding order. |
| 3597 | luma.ctx.tu_split = true; |
| 3598 | for tu_row in 0..2 { |
| 3599 | for tu_col in 0..2 { |
| 3600 | let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); |
| 3601 | let trial = match second { |
| 3602 | Some((mv1, ref1)) => mc_trial_compound( |
| 3603 | luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1, |
| 3604 | search.base_q_idx, search.deadzone, set, fctx, |
| 3605 | ), |
| 3606 | None => mc_trial( |
| 3607 | luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, |
| 3608 | reference.3, false, search.base_q_idx, search.deadzone, set, fctx, |
| 3609 | ), |
| 3610 | }; |
| 3611 | sse += trial.sse; |
| 3612 | bits += trial.bits; |
| 3613 | for row in 0..tx { |
| 3614 | levels[(tu_row * tx + row) * side + tu_col * tx..][..tx] |
| 3615 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 3616 | } |
| 3617 | units.push((tu_x, tu_y, trial)); |
| 3618 | } |
| 3619 | } |
| 3620 | luma.ctx.tu_split = false; |
| 3621 | let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); |
| 3622 | let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); |
| 3623 | let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2; |
| 3624 | // The depth census has a leaf row and a 32x32 row and no 64 one, so the |
| 3625 | // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing |
| 3626 | // in the leaf row (class `gate-blind-to-feature`). |
| 3627 | let counted = side <= BLOCK; |
| 3628 | if split_cost < flat_cost { |
| 3629 | for (tu_x, tu_y, trial) in &units { |
| 3630 | luma.commit(*tu_x, *tu_y, tx, trial); |
| 3631 | } |
| 3632 | if counted { |
| 3633 | INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3634 | } |
| 3635 | return (levels, 1, split_cost - flat_cost); |
| 3636 | } |
| 3637 | if counted { |
| 3638 | INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3639 | } |
| 3640 | luma.commit(x, y, side, flat); |
| 3641 | (flat.levels.clone(), 0, 0.0) |
| 3642 | } |
| 3643 | |
| 3644 | /// The largest distinct-colour count a block may hold and still be offered a |
| 3645 | /// palette candidate at all: past it the k-means quantisation costs more |
| 3646 | /// error than the map saves rate, and every trial is wasted wall. |
| 3647 | /// |
| 3648 | /// Swept on the gate's own screen capture (lane-av1pal2, the |
| 3649 | /// `unswept-decision-constants` class): 32 (the value this lane inherited) |
| 3650 | /// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64 |
| 3651 | /// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores |
| 3652 | /// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound |
| 3653 | /// binds on nothing this content holds. 128 ships: best BD against both |
| 3654 | /// references and no wall cost at all (6.1s, the same as at 32, because the |
| 3655 | /// blocks it newly admits are ones the RD then keeps). |
| 3656 | /// `EC_AV1_PAL_MAXCOLORS`. |
| 3657 | fn palette_max_colors() -> usize { |
| 3658 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 3659 | *N.get_or_init(|| { |
| 3660 | std::env::var("EC_AV1_PAL_MAXCOLORS") |
| 3661 | .ok() |
| 3662 | .and_then(|v| v.parse().ok()) |
| 3663 | .unwrap_or(128) |
| 3664 | }) |
| 3665 | } |
| 3666 | |
| 3667 | /// The palettes worth trying for one block's luma, in the shape libaom's |
| 3668 | /// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE` |
| 3669 | /// distinct colours takes them ALL (the prediction is then exact and the |
| 3670 | /// residual empty), and a busier one is quantised to 8 and to 4 colours by a |
| 3671 | /// one-dimensional Lloyd iteration seeded evenly across its range -- both |
| 3672 | /// offered, because which wins is an RD question the caller answers. |
| 3673 | /// `block` is `side*side` source samples, row-major. |
| 3674 | fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> { |
| 3675 | let mut histogram = [0u32; 256]; |
| 3676 | for &v in block { |
| 3677 | histogram[usize::from(v)] += 1; |
| 3678 | } |
| 3679 | let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect(); |
| 3680 | if present.len() < 2 { |
| 3681 | return Vec::new(); |
| 3682 | } |
| 3683 | let exact = |colors: &[u16]| -> crate::tile::PaletteY { |
| 3684 | let mut base = [0u16; 8]; |
| 3685 | base[..colors.len()].copy_from_slice(colors); |
| 3686 | let map = block |
| 3687 | .iter() |
| 3688 | .map(|&v| { |
| 3689 | colors |
| 3690 | .iter() |
| 3691 | .enumerate() |
| 3692 | .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) |
| 3693 | .map(|(i, _)| i as u8) |
| 3694 | .expect("a palette holds at least two colours") |
| 3695 | }) |
| 3696 | .collect(); |
| 3697 | crate::tile::PaletteY { size: colors.len() as u8, colors: base, map } |
| 3698 | }; |
| 3699 | if present.len() <= 8 { |
| 3700 | return vec![exact(&present)]; |
| 3701 | } |
| 3702 | if present.len() > palette_max_colors() { |
| 3703 | return Vec::new(); |
| 3704 | } |
| 3705 | let (lo, hi) = ( |
| 3706 | i32::from(present[0]), |
| 3707 | i32::from(present[present.len() - 1]), |
| 3708 | ); |
| 3709 | let mut out = Vec::with_capacity(2); |
| 3710 | for n in [8usize, 4] { |
| 3711 | // Even seeding across the block's own range, then four Lloyd passes |
| 3712 | // over the histogram (256 bins, not `side*side` pixels). |
| 3713 | let mut centres: Vec<f64> = (0..n) |
| 3714 | .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) |
| 3715 | .collect(); |
| 3716 | for _ in 0..4 { |
| 3717 | let mut sums = vec![0f64; n]; |
| 3718 | let mut counts = vec![0u32; n]; |
| 3719 | for (v, &count) in histogram.iter().enumerate() { |
| 3720 | if count == 0 { |
| 3721 | continue; |
| 3722 | } |
| 3723 | let k = (0..n) |
| 3724 | .min_by(|&a, &b| { |
| 3725 | (centres[a] - v as f64) |
| 3726 | .abs() |
| 3727 | .total_cmp(&(centres[b] - v as f64).abs()) |
| 3728 | }) |
| 3729 | .expect("n >= 2"); |
| 3730 | sums[k] += (v as u32 * count) as f64; |
| 3731 | counts[k] += count; |
| 3732 | } |
| 3733 | for k in 0..n { |
| 3734 | if counts[k] > 0 { |
| 3735 | centres[k] = sums[k] / f64::from(counts[k]); |
| 3736 | } |
| 3737 | } |
| 3738 | } |
| 3739 | let mut colors: Vec<u16> = centres |
| 3740 | .iter() |
| 3741 | .map(|&c| c.round().clamp(0.0, 255.0) as u16) |
| 3742 | .collect(); |
| 3743 | colors.sort_unstable(); |
| 3744 | colors.dedup(); |
| 3745 | if colors.len() >= 2 { |
| 3746 | out.push(exact(&colors)); |
| 3747 | } |
| 3748 | } |
| 3749 | out |
| 3750 | } |
| 3751 | |
| 3752 | #[allow(clippy::too_many_arguments)] |
| 3753 | // --------------------------------------------------------------------------- |
| 3754 | // lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV |
| 3755 | // validity). A key frame that detected screen content and finds enough exact |
| 3756 | // repeats in its own source sets `allow_intrabc`, which the spec forces every |
| 3757 | // in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns |
| 3758 | // its place when the copied blocks pay back the deblock/CDEF/LR the frame |
| 3759 | // gives up. `EC_AV1_INTRABC=0` turns the whole arm off. |
| 3760 | // --------------------------------------------------------------------------- |
| 3761 | |
| 3762 | /// Whether intra block copy is offered at all. **Off by default** -- |
| 3763 | /// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against |
| 3764 | /// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`), |
| 3765 | /// but on the gate's real screen capture it MEASURED WORSE: setting |
| 3766 | /// `allow_intrabc` costs the key frame its deblocking, CDEF and loop |
| 3767 | /// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay |
| 3768 | /// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc, |
| 3769 | /// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame |
| 3770 | /// that detected no screen content. |
| 3771 | fn intrabc_enabled() -> bool { |
| 3772 | if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) { |
| 3773 | return forced; |
| 3774 | } |
| 3775 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 3776 | *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1")) |
| 3777 | } |
| 3778 | |
| 3779 | thread_local! { |
| 3780 | /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation |
| 3781 | /// probe runs both arms in one process, and the suite is one process, so |
| 3782 | /// an environment variable cannot separate them (same reason |
| 3783 | /// [`SCREEN_FORCE`] exists). |
| 3784 | static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 3785 | } |
| 3786 | |
| 3787 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 3788 | pub(crate) fn force_intrabc(value: Option<bool>) { |
| 3789 | INTRABC_FORCE.with(|c| c.set(value)); |
| 3790 | } |
| 3791 | |
| 3792 | /// How many of a screen frame's 16x16 blocks must have an exact repeat |
| 3793 | /// somewhere else in the source before `allow_intrabc` is worth the in-loop |
| 3794 | /// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision- |
| 3795 | /// constant class: `probe_intrabc_threshold` measures the arm at several |
| 3796 | /// values. |
| 3797 | fn intrabc_pct() -> usize { |
| 3798 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 3799 | *N.get_or_init(|| { |
| 3800 | std::env::var("EC_AV1_INTRABC_PCT") |
| 3801 | .ok() |
| 3802 | .and_then(|v| v.parse().ok()) |
| 3803 | .unwrap_or(10) |
| 3804 | }) |
| 3805 | } |
| 3806 | |
| 3807 | /// The pixel grid intrabc source positions are hashed on |
| 3808 | /// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it, |
| 3809 | /// which keeps the block-hash table (and so the search) linear in the frame |
| 3810 | /// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies |
| 3811 | /// at `dv / 2` full pel, so an odd DV would land half-pel and need the |
| 3812 | /// bilinear interpolation decode.rs applies but this encoder does not. |
| 3813 | fn intrabc_step() -> usize { |
| 3814 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 3815 | *N.get_or_init(|| { |
| 3816 | let n: usize = std::env::var("EC_AV1_INTRABC_STEP") |
| 3817 | .ok() |
| 3818 | .and_then(|v| v.parse().ok()) |
| 3819 | .unwrap_or(4); |
| 3820 | if n % 2 == 0 { n.max(2) } else { 4 } |
| 3821 | }) |
| 3822 | } |
| 3823 | |
| 3824 | /// The side of the luma square the block-hash table is keyed on. |
| 3825 | const IBC_HASH: usize = 16; |
| 3826 | |
| 3827 | /// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind |
| 3828 | /// the current one the source's bottom-right corner must already be. |
| 3829 | const INTRABC_DELAY_SB64: i32 = 4; |
| 3830 | |
| 3831 | /// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`. |
| 3832 | fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 { |
| 3833 | let mut h: u64 = 0xcbf2_9ce4_8422_2325; |
| 3834 | for row in 0..IBC_HASH { |
| 3835 | let base = (y + row) * width + x; |
| 3836 | for &v in &plane[base..base + IBC_HASH] { |
| 3837 | h ^= u64::from(v); |
| 3838 | h = h.wrapping_mul(0x100_0000_01b3); |
| 3839 | } |
| 3840 | } |
| 3841 | h |
| 3842 | } |
| 3843 | |
| 3844 | /// Every `intrabc_step()`-aligned position of `plane` inside |
| 3845 | /// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`]. |
| 3846 | fn ibc_index( |
| 3847 | table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>, |
| 3848 | plane: &[u8], |
| 3849 | width: usize, |
| 3850 | (x0, y0): (usize, usize), |
| 3851 | (x1, y1): (usize, usize), |
| 3852 | ) { |
| 3853 | let step = intrabc_step(); |
| 3854 | if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH { |
| 3855 | return; |
| 3856 | } |
| 3857 | let mut y = y0.next_multiple_of(step); |
| 3858 | while y + IBC_HASH <= y1 { |
| 3859 | let mut x = x0.next_multiple_of(step); |
| 3860 | while x + IBC_HASH <= x1 { |
| 3861 | table |
| 3862 | .entry(ibc_hash(plane, width, x, y)) |
| 3863 | .or_default() |
| 3864 | .push((x as u32, y as u32)); |
| 3865 | x += step; |
| 3866 | } |
| 3867 | y += step; |
| 3868 | } |
| 3869 | } |
| 3870 | |
| 3871 | /// Whether `screen`-detected source `y` repeats itself enough to be worth |
| 3872 | /// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact |
| 3873 | /// content appears at some other position, against [`intrabc_pct`]. Returns |
| 3874 | /// the share as well, for the gate's own print. |
| 3875 | fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) { |
| 3876 | if true_width < 4 * 64 || true_height < 2 * 64 { |
| 3877 | return (false, 0.0); |
| 3878 | } |
| 3879 | let mut table = std::collections::HashMap::new(); |
| 3880 | ibc_index(&mut table, y, width, (0, 0), (true_width, true_height)); |
| 3881 | let (mut total, mut matched) = (0usize, 0usize); |
| 3882 | let mut by = 0; |
| 3883 | while by + IBC_HASH <= true_height { |
| 3884 | let mut bx = 0; |
| 3885 | while bx + IBC_HASH <= true_width { |
| 3886 | total += 1; |
| 3887 | if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) { |
| 3888 | if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) { |
| 3889 | matched += 1; |
| 3890 | } |
| 3891 | } |
| 3892 | bx += IBC_HASH; |
| 3893 | } |
| 3894 | by += IBC_HASH; |
| 3895 | } |
| 3896 | let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 }; |
| 3897 | (share * 100.0 >= intrabc_pct() as f64, share) |
| 3898 | } |
| 3899 | |
| 3900 | /// One tile's intrabc search state: a block-hash table over the part of the |
| 3901 | /// tile's own reconstruction that is already final (whole superblock rows -- |
| 3902 | /// the in-loop filters are off on this frame, so a coded superblock row never |
| 3903 | /// changes again), plus the last DV chosen, which the RD price uses as its |
| 3904 | /// predictor estimate. |
| 3905 | struct Ibc { |
| 3906 | /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the |
| 3907 | /// source repeats exactly where a lossily coded reconstruction only |
| 3908 | /// nearly does, so an exact-match table over the reconstruction finds |
| 3909 | /// almost nothing. The candidate is then SCORED against the |
| 3910 | /// reconstruction ([`ibc_sse`]), which is what a decoder will copy. |
| 3911 | table: std::collections::HashMap<u64, Vec<(u32, u32)>>, |
| 3912 | /// The tile's own luma rect, in samples. |
| 3913 | tile: (usize, usize, usize, usize), |
| 3914 | /// The DV the previous intrabc block of this tile took -- the *estimate* |
| 3915 | /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken |
| 3916 | /// against. The writer computes the true predictor off its own mi grid |
| 3917 | /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost |
| 3918 | /// a slightly mispriced candidate, never a wrong bitstream. |
| 3919 | last_dv: Option<(i32, i32)>, |
| 3920 | /// How many blocks took intrabc, and how many hash lookups found at least |
| 3921 | /// one valid candidate -- the gate's own fire counts. |
| 3922 | hits: usize, |
| 3923 | lookups: usize, |
| 3924 | found: usize, |
| 3925 | } |
| 3926 | |
| 3927 | impl Ibc { |
| 3928 | fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self { |
| 3929 | let mut table = std::collections::HashMap::new(); |
| 3930 | ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3)); |
| 3931 | Self { |
| 3932 | table, |
| 3933 | tile, |
| 3934 | last_dv: None, |
| 3935 | hits: 0, |
| 3936 | lookups: 0, |
| 3937 | found: 0, |
| 3938 | } |
| 3939 | } |
| 3940 | |
| 3941 | /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv` |
| 3942 | /// (1/8 pel), with this lane's own extra restriction on top: the source |
| 3943 | /// must lie entirely in a COMPLETED superblock row, which is exactly the |
| 3944 | /// region [`Self::fill_to`] indexes and a strict subset of what the spec |
| 3945 | /// allows. corner-cut, ceiling named: same-superblock-row sources (the |
| 3946 | /// wavefront's own diagonal) are legal and not searched; the upgrade path |
| 3947 | /// is to index the current row's finished superblocks too. |
| 3948 | fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool { |
| 3949 | let (dr, dc) = (dv.0 / 8, dv.1 / 8); |
| 3950 | if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 { |
| 3951 | return false; |
| 3952 | } |
| 3953 | let (tx0, ty0, tx1, ty1) = ( |
| 3954 | self.tile.0 as i32, |
| 3955 | self.tile.1 as i32, |
| 3956 | self.tile.2 as i32, |
| 3957 | self.tile.3 as i32, |
| 3958 | ); |
| 3959 | let (sx, sy) = (x as i32 + dc, y as i32 + dr); |
| 3960 | let (w, h) = (w as i32, h as i32); |
| 3961 | if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 { |
| 3962 | return false; |
| 3963 | } |
| 3964 | let active_sb_row = (y as i32 - ty0) >> 6; |
| 3965 | let active_sb_col = (x as i32 - tx0) >> 6; |
| 3966 | let src_sb_row = (sy + h - 1 - ty0) >> 6; |
| 3967 | let src_sb_col = (sx + w - 1 - tx0) >> 6; |
| 3968 | // This lane's own restriction (see the doc comment). |
| 3969 | if src_sb_row >= active_sb_row { |
| 3970 | return false; |
| 3971 | } |
| 3972 | let total = ((tx1 - tx0 - 1) >> 6) + 1; |
| 3973 | if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64 |
| 3974 | { |
| 3975 | return false; |
| 3976 | } |
| 3977 | // libaom's wavefront: only the top-left cone of the frame is legal. |
| 3978 | let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row); |
| 3979 | src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf |
| 3980 | } |
| 3981 | } |
| 3982 | |
| 3983 | /// How many block searches ran, how many found at least one VALID candidate, |
| 3984 | /// and how many won on rate-distortion -- the hash hit rate a gate prints |
| 3985 | /// (class `gate-blind-to-feature`: "the search ran" and "the search found |
| 3986 | /// something" and "the block took it" are three different claims). |
| 3987 | static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] = |
| 3988 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 3989 | |
| 3990 | impl Drop for Ibc { |
| 3991 | fn drop(&mut self) { |
| 3992 | for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() { |
| 3993 | IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 3994 | } |
| 3995 | } |
| 3996 | } |
| 3997 | |
| 3998 | /// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to |
| 3999 | /// its own encode. |
| 4000 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 4001 | pub(crate) fn take_intrabc_search() -> [usize; 3] { |
| 4002 | std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4003 | } |
| 4004 | |
| 4005 | /// [`crate::tile::write_dv_component`]'s static price -- the same shape as |
| 4006 | /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv` |
| 4007 | /// infers rather than codes. |
| 4008 | fn dv_component_bits(diff: i32) -> f64 { |
| 4009 | let z = diff.unsigned_abs() as i32 - 1; |
| 4010 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 4011 | let class = mv_class_of(z); |
| 4012 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 4013 | let local = z - mv_class_base(class); |
| 4014 | if class == 0 { |
| 4015 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize); |
| 4016 | } else { |
| 4017 | let d = local >> 3; |
| 4018 | for i in 0..class { |
| 4019 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 4020 | } |
| 4021 | } |
| 4022 | bits |
| 4023 | } |
| 4024 | |
| 4025 | /// What one block vector costs against `pred`, plus the `skip` and |
| 4026 | /// `use_intrabc` flags the block carries and the ordinary intra block does |
| 4027 | /// not pay in this currency. |
| 4028 | fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 { |
| 4029 | let diff = (dv.0 - pred.0, dv.1 - pred.1); |
| 4030 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 4031 | (false, false) => 0, |
| 4032 | (false, true) => 1, |
| 4033 | (true, false) => 2, |
| 4034 | (true, true) => 3, |
| 4035 | }; |
| 4036 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0; |
| 4037 | if diff.0 != 0 { |
| 4038 | bits += dv_component_bits(diff.0); |
| 4039 | } |
| 4040 | if diff.1 != 0 { |
| 4041 | bits += dv_component_bits(diff.1); |
| 4042 | } |
| 4043 | bits |
| 4044 | } |
| 4045 | |
| 4046 | /// The squared error of copying the `side`-square block at `(sx, sy)` of each |
| 4047 | /// plane's reconstruction onto the source block at `(x, y)`, luma and both |
| 4048 | /// chroma planes together -- what an intrabc block's whole (residual-free) |
| 4049 | /// distortion is. |
| 4050 | fn ibc_sse( |
| 4051 | luma: &Plane, |
| 4052 | chroma: &[Plane; 2], |
| 4053 | (x, y): (usize, usize), |
| 4054 | (sx, sy): (usize, usize), |
| 4055 | side: usize, |
| 4056 | ) -> f64 { |
| 4057 | // Inside the true frame only, for the reason [`Plane::block_sse`] is |
| 4058 | // (lane-sse): an intrabc block at the edge would otherwise be ranked by |
| 4059 | // how well it copies the padding. |
| 4060 | let mut sse = 0.0f64; |
| 4061 | let clip = |whole: usize, inside: usize| match edge_sse() { |
| 4062 | true => whole.min(inside), |
| 4063 | false => whole, |
| 4064 | }; |
| 4065 | let rows = clip(side, luma.true_height.saturating_sub(y)); |
| 4066 | let cols = clip(side, luma.true_width.saturating_sub(x)); |
| 4067 | for row in 0..rows { |
| 4068 | let src = &luma.source[(y + row) * luma.width + x..][..cols]; |
| 4069 | let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols]; |
| 4070 | for (&s, &r) in src.iter().zip(rec) { |
| 4071 | let d = f64::from(i32::from(s) - i32::from(r)); |
| 4072 | sse += d * d; |
| 4073 | } |
| 4074 | } |
| 4075 | let half = side / 2; |
| 4076 | for plane in chroma { |
| 4077 | let rows = clip(half, plane.true_height.saturating_sub(y / 2)); |
| 4078 | let cols = clip(half, plane.true_width.saturating_sub(x / 2)); |
| 4079 | for row in 0..rows { |
| 4080 | let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols]; |
| 4081 | let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols]; |
| 4082 | for (&s, &r) in src.iter().zip(rec) { |
| 4083 | let d = f64::from(i32::from(s) - i32::from(r)); |
| 4084 | sse += d * d; |
| 4085 | } |
| 4086 | } |
| 4087 | } |
| 4088 | sse |
| 4089 | } |
| 4090 | |
| 4091 | /// Copies the `side`-square block at `(sx, sy)` of each plane's |
| 4092 | /// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction, |
| 4093 | /// since it carries no residual (`skip`). Full-pel in both planes by |
| 4094 | /// construction ([`intrabc_step`] keeps every DV even), which is what makes |
| 4095 | /// this a plain copy where decode.rs runs the bilinear kernel over the same |
| 4096 | /// samples. |
| 4097 | fn ibc_commit( |
| 4098 | luma: &mut Plane, |
| 4099 | chroma: &mut [Plane; 2], |
| 4100 | (x, y): (usize, usize), |
| 4101 | (sx, sy): (usize, usize), |
| 4102 | side: usize, |
| 4103 | ) { |
| 4104 | for row in 0..side { |
| 4105 | let from = (sy + row) * luma.width + sx; |
| 4106 | let to = (y + row) * luma.width + x; |
| 4107 | let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec(); |
| 4108 | luma.reconstruction[to..to + side].copy_from_slice(&copied); |
| 4109 | } |
| 4110 | let half = side / 2; |
| 4111 | for plane in chroma { |
| 4112 | for row in 0..half { |
| 4113 | let from = (sy / 2 + row) * plane.width + sx / 2; |
| 4114 | let to = (y / 2 + row) * plane.width + x / 2; |
| 4115 | let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec(); |
| 4116 | plane.reconstruction[to..to + half].copy_from_slice(&copied); |
| 4117 | } |
| 4118 | plane.commit_ctx_zero(x / 2, y / 2, half); |
| 4119 | } |
| 4120 | luma.commit_ctx_zero(x, y, side); |
| 4121 | } |
| 4122 | |
| 4123 | /// Searches this block's own DV: every hash-table position whose 16x16 luma |
| 4124 | /// square equals the block's source square, plus the previous block's DV as a |
| 4125 | /// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns |
| 4126 | /// the winning `(dv, cost)`, or `None` when nothing valid was found. |
| 4127 | fn ibc_search( |
| 4128 | ibc: &mut Ibc, |
| 4129 | luma: &Plane, |
| 4130 | chroma: &[Plane; 2], |
| 4131 | (x, y): (usize, usize), |
| 4132 | side: usize, |
| 4133 | lambda: f64, |
| 4134 | ) -> Option<((i32, i32), f64, (usize, usize))> { |
| 4135 | let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8)); |
| 4136 | let mut best: Option<((i32, i32), f64, (usize, usize))> = None; |
| 4137 | let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| { |
| 4138 | let dv = ( |
| 4139 | (sy as i32 - y as i32) * 8, |
| 4140 | (sx as i32 - x as i32) * 8, |
| 4141 | ); |
| 4142 | if !ibc.dv_valid(x, y, side, side, dv) { |
| 4143 | return; |
| 4144 | } |
| 4145 | let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred); |
| 4146 | if best.as_ref().is_none_or(|b| cost < b.1) { |
| 4147 | *best = Some((dv, cost, (sx, sy))); |
| 4148 | } |
| 4149 | }; |
| 4150 | ibc.lookups += 1; |
| 4151 | let key = ibc_hash(luma.source, luma.width, x, y); |
| 4152 | // The table is filled in raster order, so the entries BEFORE this block's |
| 4153 | // own position are exactly the already-coded ones -- and the nearest of |
| 4154 | // them costs the fewest DV bits. Walking backwards from the block's own |
| 4155 | // slot is what makes the search look up-and-left; taking the newest |
| 4156 | // entries outright only ever finds candidates below and to the right, |
| 4157 | // every one of which `dv_valid` rejects. |
| 4158 | let hits: Vec<(u32, u32)> = ibc |
| 4159 | .table |
| 4160 | .get(&key) |
| 4161 | .map(|h| { |
| 4162 | let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32)); |
| 4163 | h[..end].iter().rev().take(32).copied().collect() |
| 4164 | }) |
| 4165 | .unwrap_or_default(); |
| 4166 | for (hx, hy) in hits { |
| 4167 | consider(&*ibc, hx as usize, hy as usize, &mut best); |
| 4168 | } |
| 4169 | if let Some(dv) = ibc.last_dv { |
| 4170 | let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8); |
| 4171 | if sx >= 0 && sy >= 0 { |
| 4172 | consider(&*ibc, sx as usize, sy as usize, &mut best); |
| 4173 | } |
| 4174 | } |
| 4175 | if best.is_some() { |
| 4176 | ibc.found += 1; |
| 4177 | } |
| 4178 | best |
| 4179 | } |
| 4180 | |
| 4181 | fn code_square( |
| 4182 | luma: &mut Plane, |
| 4183 | chroma: &mut [Plane; 2], |
| 4184 | (x, y): (usize, usize), |
| 4185 | side: usize, |
| 4186 | search: &Search, |
| 4187 | mode_bits: &[f64; 13], |
| 4188 | // The frame header's `tx_mode == TxMode::Select`: the block then searches |
| 4189 | // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one |
| 4190 | // transform over its whole side. |
| 4191 | tx_select: bool, |
| 4192 | // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose |
| 4193 | // header did not set `allow_intrabc`. |
| 4194 | ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx, |
| 4195 | ) -> (BlockCoeffs, f64) { |
| 4196 | let (luma_set, chroma_set) = if side == BLOCK { |
| 4197 | (TxbSet::Luma32, TxbSet::Chroma16) |
| 4198 | } else if side == 8 { |
| 4199 | // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction: |
| 4200 | // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is |
| 4201 | // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at |
| 4202 | // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet |
| 4203 | // (this branch is still unreached), so leaving `Chroma8` here would |
| 4204 | // silently wire the wrong table the moment one does; `Chroma4` is |
| 4205 | // what a real caller needs. |
| 4206 | (TxbSet::Luma8, TxbSet::Chroma4) |
| 4207 | } else { |
| 4208 | (TxbSet::Luma16, TxbSet::Chroma8) |
| 4209 | }; |
| 4210 | let at = At { |
| 4211 | x, |
| 4212 | y, |
| 4213 | side, |
| 4214 | reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), |
| 4215 | set: luma_set, |
| 4216 | }; |
| 4217 | let (mut luma_coeffs, mode, angle_delta, mut cost) = |
| 4218 | luma.search_block(at, search, mode_bits, fctx); |
| 4219 | // The depth search runs on the mode the whole-block transform picked -- |
| 4220 | // libaom's own ordering, and the reason it costs one extra pass per depth |
| 4221 | // rather than one per (mode, depth) pair. |
| 4222 | let mut tx_depth = 0u8; |
| 4223 | if tx_select && max_tx_depth(side) > 0 { |
| 4224 | let mut best = ( |
| 4225 | cost + search.lambda * tx_depth_bits(side, 0), |
| 4226 | 0usize, |
| 4227 | luma.snapshot(x, y, side), |
| 4228 | luma_coeffs, |
| 4229 | ); |
| 4230 | for depth in 1..=max_tx_depth(side) { |
| 4231 | let (levels, sse, bits) = luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx); |
| 4232 | let cost_d = sse |
| 4233 | + search.lambda |
| 4234 | * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth)); |
| 4235 | if cost_d < best.0 { |
| 4236 | best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side)); |
| 4237 | } |
| 4238 | } |
| 4239 | luma.restore(x, y, side, &best.2); |
| 4240 | cost = best.0; |
| 4241 | tx_depth = best.1 as u8; |
| 4242 | luma_coeffs = best.3; |
| 4243 | TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4244 | } |
| 4245 | // The palette candidate is priced against the mode the luma search (and |
| 4246 | // its transform-depth search) already settled on, so a block only takes |
| 4247 | // one when it beats the best ordinary intra coding of the same pixels. |
| 4248 | // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its |
| 4249 | // prediction is the colour map, not the DC of its neighbours. |
| 4250 | let mut mode = mode; |
| 4251 | let mut angle_delta = angle_delta; |
| 4252 | let mut palette = None; |
| 4253 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 4254 | let source: Vec<u8> = (y..y + side) |
| 4255 | .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) |
| 4256 | .collect(); |
| 4257 | let kept = luma.snapshot(x, y, side); |
| 4258 | for pal in palette_candidates(&source) { |
| 4259 | let n = usize::from(pal.size); |
| 4260 | let prediction: Vec<u8> = pal |
| 4261 | .map |
| 4262 | .iter() |
| 4263 | .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) |
| 4264 | .collect(); |
| 4265 | let trial = luma.code_from_prediction( |
| 4266 | x, |
| 4267 | y, |
| 4268 | side, |
| 4269 | &prediction, |
| 4270 | false, |
| 4271 | search.base_q_idx, |
| 4272 | search.deadzone, |
| 4273 | luma_set, |
| 4274 | ); |
| 4275 | let cost_p = trial.sse |
| 4276 | + search.lambda |
| 4277 | * (trial.bits |
| 4278 | + mode_bits[DC_PRED as usize] |
| 4279 | + crate::tile::palette_bits(&pal, side) |
| 4280 | + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); |
| 4281 | if cost_p < cost { |
| 4282 | cost = cost_p; |
| 4283 | mode = DC_PRED as u8; |
| 4284 | angle_delta = 0; |
| 4285 | tx_depth = 0; |
| 4286 | luma_coeffs = coeffs(&trial.levels, side); |
| 4287 | luma.commit(x, y, side, &trial); |
| 4288 | palette = Some(pal); |
| 4289 | } |
| 4290 | } |
| 4291 | if palette.is_none() { |
| 4292 | luma.restore(x, y, side, &kept); |
| 4293 | } |
| 4294 | } |
| 4295 | |
| 4296 | // The five recursive filter-intra modes (spec 5.11.14), priced against |
| 4297 | // whatever the mode, transform-depth and palette searches settled on -- |
| 4298 | // the same "one candidate loop after the incumbent is known" shape the |
| 4299 | // palette above uses. A block that takes one is `DC_PRED` with no palette |
| 4300 | // by construction (`av1_filter_intra_allowed`), and its luma transform |
| 4301 | // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`). |
| 4302 | // |
| 4303 | // lane-fitu: on a SCREEN frame the candidate is priced at every transform |
| 4304 | // depth the ordinary intra search runs, each unit predicting recursively |
| 4305 | // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra` |
| 4306 | // arm), so a block whose ordinary winner wanted a split transform is |
| 4307 | // compared against a filter arm that may split too. |
| 4308 | // |
| 4309 | // Measured (native BD table, lane-fitu): searching the depths on EVERY |
| 4310 | // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves |
| 4311 | // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a |
| 4312 | // locally cheaper reconstruction that the film rows go on to predict from |
| 4313 | // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen |
| 4314 | // content is where it pays, and a non-screen frame keeps the depth-0-only |
| 4315 | // arm, byte for byte. |
| 4316 | let mut filter_intra: Option<u8> = None; |
| 4317 | if filter_intra_on() |
| 4318 | && palette.is_none() |
| 4319 | && let Some(class) = crate::decode::filter_intra_size_class(side) |
| 4320 | { |
| 4321 | let row = &cdf::FILTER_INTRA[class]; |
| 4322 | // With the sequence bit on, EVERY `DC_PRED` block without a luma |
| 4323 | // palette carries the flag, so the incumbent pays its zero before the |
| 4324 | // comparison -- otherwise the candidate is charged a bit the block |
| 4325 | // spends either way (class `price-the-narrowing-not-the-table`). |
| 4326 | if mode == DC_PRED { |
| 4327 | cost += search.lambda * symbol_bits(row, 0); |
| 4328 | } |
| 4329 | let one_bits = symbol_bits(row, 1); |
| 4330 | let kept = luma.snapshot(x, y, side); |
| 4331 | let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 }; |
| 4332 | let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None; |
| 4333 | for fi in 0..5u8 { |
| 4334 | for depth in 0..=max_depth { |
| 4335 | let (levels, sse, bits) = |
| 4336 | luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx); |
| 4337 | let cost_f = sse |
| 4338 | + search.lambda |
| 4339 | * (bits |
| 4340 | + mode_bits[DC_PRED as usize] |
| 4341 | + one_bits |
| 4342 | + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi)) |
| 4343 | + if tx_select { tx_depth_bits(side, depth) } else { 0.0 }); |
| 4344 | if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) { |
| 4345 | best = Some(( |
| 4346 | cost_f, |
| 4347 | fi, |
| 4348 | depth, |
| 4349 | luma.snapshot(x, y, side), |
| 4350 | coeffs(&levels, side), |
| 4351 | )); |
| 4352 | } |
| 4353 | } |
| 4354 | } |
| 4355 | if let Some((cost_f, fi, depth, snapshot, levels)) = best { |
| 4356 | cost = cost_f; |
| 4357 | mode = DC_PRED; |
| 4358 | angle_delta = 0; |
| 4359 | tx_depth = depth as u8; |
| 4360 | luma_coeffs = levels; |
| 4361 | luma.restore(x, y, side, &snapshot); |
| 4362 | filter_intra = Some(fi); |
| 4363 | } else { |
| 4364 | luma.restore(x, y, side, &kept); |
| 4365 | } |
| 4366 | } |
| 4367 | |
| 4368 | // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both |
| 4369 | // planes; what it costs still counts towards the partition decision. |
| 4370 | let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) = |
| 4371 | search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx); |
| 4372 | cost += chroma_cost; |
| 4373 | |
| 4374 | // The intrabc arm is priced against the WHOLE block -- luma and both |
| 4375 | // chroma planes, residual-free -- so it is compared after the chroma |
| 4376 | // search has added its own cost, not against the luma decision alone. |
| 4377 | if let Some(ibc) = ibc { |
| 4378 | if let Some((dv, cost_ibc, src)) = |
| 4379 | ibc_search(ibc, luma, chroma, (x, y), side, search.lambda) |
| 4380 | { |
| 4381 | if cost_ibc < cost { |
| 4382 | ibc_commit(luma, chroma, (x, y), src, side); |
| 4383 | ibc.last_dv = Some(dv); |
| 4384 | ibc.hits += 1; |
| 4385 | return ( |
| 4386 | BlockCoeffs { |
| 4387 | skip: true, |
| 4388 | dv: Some(dv), |
| 4389 | ..BlockCoeffs::default() |
| 4390 | }, |
| 4391 | cost_ibc, |
| 4392 | ); |
| 4393 | } |
| 4394 | } |
| 4395 | } |
| 4396 | ( |
| 4397 | BlockCoeffs { |
| 4398 | u, |
| 4399 | v, |
| 4400 | luma: luma_coeffs, |
| 4401 | mode, |
| 4402 | uv_mode, |
| 4403 | tx_depth, |
| 4404 | palette, |
| 4405 | palette_uv, |
| 4406 | filter_intra, |
| 4407 | cfl_alphas, |
| 4408 | angle_delta_y: angle_delta as i8, |
| 4409 | ..BlockCoeffs::default() |
| 4410 | }, |
| 4411 | cost, |
| 4412 | ) |
| 4413 | } |
| 4414 | |
| 4415 | /// The chroma modes the search offers, and the only ones it may offer: each |
| 4416 | /// predicts from the row directly above and the column directly to the left |
| 4417 | /// and nothing further, so none of them needs the above-right/below-left |
| 4418 | /// `Reach` a chroma block is coded with `Reach::none()` for. The eight |
| 4419 | /// directional modes do read past that, and `UV_CFL_PRED` needs the luma |
| 4420 | /// reconstruction and its own alpha syntax; both are left out here. |
| 4421 | const CHROMA_MODES: [u8; 7] = [ |
| 4422 | DC_PRED, |
| 4423 | V_PRED, |
| 4424 | H_PRED, |
| 4425 | SMOOTH_PRED, |
| 4426 | SMOOTH_V_PRED, |
| 4427 | SMOOTH_H_PRED, |
| 4428 | PAETH_PRED, |
| 4429 | ]; |
| 4430 | |
| 4431 | /// The thirteen intra mode names, for the chroma fire count's print. |
| 4432 | #[cfg(test)] |
| 4433 | const UV_MODE_NAMES: [&str; 14] = [ |
| 4434 | "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", |
| 4435 | "SMOOTH_H", "PAETH", "CFL", |
| 4436 | ]; |
| 4437 | |
| 4438 | /// How many blocks each chroma mode has won, indexed by the mode itself -- |
| 4439 | /// the fire count that says whether the search below reaches its candidates |
| 4440 | /// at all (the `gate-blind-to-feature` class), printed once per gate run. |
| 4441 | static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] = |
| 4442 | [const { std::sync::atomic::AtomicUsize::new(0) }; 14]; |
| 4443 | |
| 4444 | /// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has |
| 4445 | /// won, summed over both chroma planes -- the alpha histogram the gate prints |
| 4446 | /// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one |
| 4447 | /// magnitude only is a search that never left its first candidate). |
| 4448 | static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] = |
| 4449 | [const { std::sync::atomic::AtomicUsize::new(0) }; 17]; |
| 4450 | |
| 4451 | /// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha |
| 4452 | /// zero on a CfL block", `1..=16` the magnitudes. |
| 4453 | #[cfg(test)] |
| 4454 | pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] { |
| 4455 | std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4456 | } |
| 4457 | |
| 4458 | /// How many directional luma blocks won at each `angle_delta_y`, indexed |
| 4459 | /// `delta + 3` -- the histogram that says whether the refinement below ever |
| 4460 | /// leaves zero (`gate-blind-to-feature`). |
| 4461 | static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] = |
| 4462 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 4463 | |
| 4464 | /// Reads [`ANGLE_DELTA_HITS`] and zeroes it. |
| 4465 | #[cfg(test)] |
| 4466 | pub(crate) fn take_angle_delta_hits() -> [usize; 7] { |
| 4467 | std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4468 | } |
| 4469 | |
| 4470 | /// Whether the luma search refines a directional winner's `angle_delta_y` |
| 4471 | /// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair). |
| 4472 | fn angle_delta_on() -> bool { |
| 4473 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 4474 | crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0") |
| 4475 | }); |
| 4476 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE)) |
| 4477 | } |
| 4478 | |
| 4479 | /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0` |
| 4480 | /// switches it off, which is how the lane measured its own on/off pair). |
| 4481 | fn cfl_on() -> bool { |
| 4482 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 4483 | crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0") |
| 4484 | }); |
| 4485 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL)) |
| 4486 | } |
| 4487 | |
| 4488 | /// Whether the intra search offers the five recursive filter-intra modes at |
| 4489 | /// all, and with them whether the sequence header sets `enable_filter_intra` |
| 4490 | /// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured |
| 4491 | /// its own on/off pair -- and how every byte pin written before it still |
| 4492 | /// reproduces). It is also a speed lever: on at preset 0, off above it. |
| 4493 | pub(crate) fn filter_intra_on() -> bool { |
| 4494 | #[cfg(test)] |
| 4495 | if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) { |
| 4496 | return forced; |
| 4497 | } |
| 4498 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 4499 | crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0") |
| 4500 | }); |
| 4501 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA)) |
| 4502 | } |
| 4503 | |
| 4504 | /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts |
| 4505 | /// to its own encode. |
| 4506 | #[cfg(test)] |
| 4507 | pub(crate) fn take_uv_mode_hits() -> [usize; 14] { |
| 4508 | std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4509 | } |
| 4510 | |
| 4511 | /// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode -- |
| 4512 | /// `uv_mode` is a single symbol covering U and V -- and commits the cheapest. |
| 4513 | /// Returns each plane's levels, the mode, and what the pair cost (squared |
| 4514 | /// error plus lambda times bits, the same currency the luma search speaks). |
| 4515 | /// |
| 4516 | /// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`], |
| 4517 | /// which is what the luma mode decision was taken against, so what a |
| 4518 | /// candidate owes here is only the *difference* from that -- plus, for `V`/`H` |
| 4519 | /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the |
| 4520 | /// writer then has to code. |
| 4521 | #[allow(clippy::too_many_arguments)] |
| 4522 | /// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on, |
| 4523 | /// ranked by the SAD of their predictions summed over both planes (`DC_PRED` |
| 4524 | /// always kept, the same rule [`prune_by_sad`] applies to luma). `None` |
| 4525 | /// trials all seven, as before this lever. |
| 4526 | /// |
| 4527 | /// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was |
| 4528 | /// the search's largest trial population by far -- seven modes times two |
| 4529 | /// planes for every intra block, against 3.7 luma trials -- and the RD |
| 4530 | /// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three |
| 4531 | /// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build. |
| 4532 | fn chroma_top_k() -> Option<usize> { |
| 4533 | static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| { |
| 4534 | crate::envflags::var("EC_AV1_CHROMA_K") |
| 4535 | .ok() |
| 4536 | .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0)) |
| 4537 | }); |
| 4538 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K)) |
| 4539 | } |
| 4540 | |
| 4541 | /// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD |
| 4542 | /// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3): |
| 4543 | /// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/ |
| 4544 | /// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better) |
| 4545 | /// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The |
| 4546 | /// BD swings by about a point in either direction as near-tie chroma modes |
| 4547 | /// flip, which is the measurement's own sensitivity, not a trend: nothing |
| 4548 | /// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned. |
| 4549 | /// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: |
| 4550 | /// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's |
| 4551 | /// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`. |
| 4552 | pub(crate) const CHROMA_TOP_K: Option<usize> = None; |
| 4553 | |
| 4554 | fn search_chroma( |
| 4555 | chroma: &mut [Plane; 2], |
| 4556 | // The luma plane's RECONSTRUCTION under this block, already committed by |
| 4557 | // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales. |
| 4558 | luma: &Plane, |
| 4559 | (x, y): (usize, usize), |
| 4560 | side: usize, |
| 4561 | set: TxbSet, |
| 4562 | search: &Search, |
| 4563 | luma_mode: u8, |
| 4564 | fctx: &crate::decode::FrameCtx, |
| 4565 | ) -> ( |
| 4566 | [Vec<Coeff>; 2], |
| 4567 | u8, |
| 4568 | f64, |
| 4569 | Option<crate::tile::PaletteUv>, |
| 4570 | Option<(i32, i32)>, |
| 4571 | ) { |
| 4572 | let at = At { |
| 4573 | x: x / 2, |
| 4574 | y: y / 2, |
| 4575 | side: side / 2, |
| 4576 | reach: Reach::none(), |
| 4577 | set, |
| 4578 | }; |
| 4579 | // The census's cheap proxy for a chroma mode: the SAD of its prediction |
| 4580 | // summed over both planes, ranked by the same rule the luma histogram |
| 4581 | // uses. Only built under `EC_AV1_CENSUS`. |
| 4582 | // The SAD of each mode's prediction, summed over both planes -- the |
| 4583 | // census's ranking rule, and what [`chroma_top_k`] prunes by. |
| 4584 | let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> { |
| 4585 | let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 4586 | let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 4587 | u.iter() |
| 4588 | .zip(v.iter()) |
| 4589 | .map(|(&(us, mode), &(vs, _))| (us + vs, mode)) |
| 4590 | .collect() |
| 4591 | }; |
| 4592 | let modes: Vec<u8> = match chroma_top_k() { |
| 4593 | Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k), |
| 4594 | _ => CHROMA_MODES.to_vec(), |
| 4595 | }; |
| 4596 | let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; |
| 4597 | let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); |
| 4598 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 4599 | sad_scores(chroma) |
| 4600 | } else { |
| 4601 | Vec::new() |
| 4602 | }; |
| 4603 | census_add(2, 1); |
| 4604 | census_add(3, modes.len()); |
| 4605 | let mut best: Option<(f64, u8, Trial, Trial)> = None; |
| 4606 | for mode in modes { |
| 4607 | let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; |
| 4608 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 4609 | bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); |
| 4610 | } |
| 4611 | let tx_type = crate::decode::default_intra_tx_type(mode); |
| 4612 | let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 4613 | let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 4614 | let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits); |
| 4615 | if best.as_ref().is_none_or(|(b, ..)| cost < *b) { |
| 4616 | best = Some((cost, mode, u, v)); |
| 4617 | } |
| 4618 | } |
| 4619 | let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); |
| 4620 | // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over |
| 4621 | // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is |
| 4622 | // what keeps `u_colors` ascending and distinct the way |
| 4623 | // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as |
| 4624 | // each cluster's own mean, since the colour-index map is SHARED by the |
| 4625 | // two planes. Priced against the best ordinary chroma mode above, so a |
| 4626 | // block only takes one when it beats it; a palette block's chroma mode is |
| 4627 | // `UV_DC_PRED` by construction. |
| 4628 | let mut palette_uv = None; |
| 4629 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 4630 | debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); |
| 4631 | let plane_source = |p: &Plane| -> Vec<u8> { |
| 4632 | (at.y..at.y + at.side) |
| 4633 | .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) |
| 4634 | .collect() |
| 4635 | }; |
| 4636 | let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); |
| 4637 | for pal in palette_candidates(&u_source) { |
| 4638 | let n = usize::from(pal.size); |
| 4639 | // V's base colour per cluster: the mean of the samples the shared |
| 4640 | // map assigns to it (an empty cluster cannot happen -- every |
| 4641 | // colour `palette_candidates` returns is some pixel's nearest). |
| 4642 | let mut sums = [0u32; 8]; |
| 4643 | let mut counts = [0u32; 8]; |
| 4644 | for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { |
| 4645 | let k = usize::from(i).min(n - 1); |
| 4646 | sums[k] += u32::from(sample); |
| 4647 | counts[k] += 1; |
| 4648 | } |
| 4649 | let mut v_colors = [0u16; 8]; |
| 4650 | for k in 0..n { |
| 4651 | v_colors[k] = if counts[k] > 0 { |
| 4652 | ((sums[k] + counts[k] / 2) / counts[k]) as u16 |
| 4653 | } else { |
| 4654 | 0 |
| 4655 | }; |
| 4656 | } |
| 4657 | let candidate = crate::tile::PaletteUv { |
| 4658 | size: pal.size, |
| 4659 | u_colors: pal.colors, |
| 4660 | v_colors, |
| 4661 | map: pal.map, |
| 4662 | }; |
| 4663 | let predict = |colors: &[u16; 8]| -> Vec<u8> { |
| 4664 | candidate |
| 4665 | .map |
| 4666 | .iter() |
| 4667 | .map(|&i| colors[usize::from(i).min(n - 1)] as u8) |
| 4668 | .collect() |
| 4669 | }; |
| 4670 | let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); |
| 4671 | let u_trial = chroma[0].code_from_prediction( |
| 4672 | at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, |
| 4673 | ); |
| 4674 | let v_trial = chroma[1].code_from_prediction( |
| 4675 | at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, |
| 4676 | ); |
| 4677 | let cost_p = u_trial.sse |
| 4678 | + v_trial.sse |
| 4679 | + search.lambda |
| 4680 | * (u_trial.bits |
| 4681 | + v_trial.bits |
| 4682 | + crate::tile::palette_uv_bits(&candidate, side)); |
| 4683 | if cost_p < cost { |
| 4684 | cost = cost_p; |
| 4685 | mode = DC_PRED; |
| 4686 | u = u_trial; |
| 4687 | v = v_trial; |
| 4688 | palette_uv = Some(candidate); |
| 4689 | } |
| 4690 | } |
| 4691 | } |
| 4692 | // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`): |
| 4693 | // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then |
| 4694 | // nudges every sample by `alpha_q3` times the block's subsampled, |
| 4695 | // average-subtracted luma reconstruction. Offered only where |
| 4696 | // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 -- |
| 4697 | // and priced against the best ordinary chroma mode above, palette |
| 4698 | // included, so a block only takes it when it beats both. |
| 4699 | let mut cfl_alphas = None; |
| 4700 | if side <= 32 && cfl_on() { |
| 4701 | // The AC signal, through the decoder's own |
| 4702 | // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body. |
| 4703 | let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| { |
| 4704 | i32::from(luma.reconstruction[ly * luma.width + lx]) |
| 4705 | }); |
| 4706 | let dc_prediction = |plane: &Plane| -> Vec<u8> { |
| 4707 | let (mut above_buf, mut left_buf) = ([0u8; 2 * BLOCK], [0u8; 2 * BLOCK]); |
| 4708 | let (above, left, corner) = |
| 4709 | plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf); |
| 4710 | let mut prediction = vec![0u8; at.side * at.side]; |
| 4711 | intra_predict_u8( |
| 4712 | DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction, |
| 4713 | fctx, |
| 4714 | ); |
| 4715 | prediction |
| 4716 | }; |
| 4717 | let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])]; |
| 4718 | // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then |
| 4719 | // add the residual -- which is what [`Plane::code_from_prediction`] |
| 4720 | // does with what this returns. |
| 4721 | let apply = |base: &[u8], alpha: i32| -> Vec<u8> { |
| 4722 | base.iter() |
| 4723 | .zip(ac.iter()) |
| 4724 | .map(|(&b, &a)| { |
| 4725 | (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8 |
| 4726 | }) |
| 4727 | .collect() |
| 4728 | }; |
| 4729 | // The least-squares alpha, then its two neighbours: minimising |
| 4730 | // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one |
| 4731 | // dot-product ratio, and the quantised optimum is one of the two |
| 4732 | // integers around it (the clamp and the Q6 rounding are what the SSE |
| 4733 | // check below re-decides). libaom sweeps all sixteen magnitudes under |
| 4734 | // full RD; three predictions per plane buy nearly the same alpha for a |
| 4735 | // thirtieth of the search. |
| 4736 | let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 { |
| 4737 | let (mut num, mut den) = (0.0f64, 0.0f64); |
| 4738 | for row in 0..at.side { |
| 4739 | for col in 0..at.side { |
| 4740 | let i = row * at.side + col; |
| 4741 | let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col]) |
| 4742 | - f64::from(base[i]); |
| 4743 | num += d * f64::from(ac[i]); |
| 4744 | den += f64::from(ac[i]) * f64::from(ac[i]); |
| 4745 | } |
| 4746 | } |
| 4747 | if den == 0.0 { |
| 4748 | return 0; |
| 4749 | } |
| 4750 | let ideal = 64.0 * num / den; |
| 4751 | let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32); |
| 4752 | for alpha in [ideal.floor() as i64, ideal.ceil() as i64] { |
| 4753 | let alpha = alpha.clamp(-16, 16) as i32; |
| 4754 | if alpha == 0 { |
| 4755 | continue; |
| 4756 | } |
| 4757 | let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha)); |
| 4758 | if sse < best.0 { |
| 4759 | best = (sse, alpha); |
| 4760 | } |
| 4761 | } |
| 4762 | best.1 |
| 4763 | }; |
| 4764 | let picked = [ |
| 4765 | pick_alpha(&chroma[0], &bases[0]), |
| 4766 | pick_alpha(&chroma[1], &bases[1]), |
| 4767 | ]; |
| 4768 | if picked != [0, 0] { |
| 4769 | let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits; |
| 4770 | let trial = |plane_idx: usize, alpha: i32| -> Trial { |
| 4771 | let prediction = if alpha == 0 { |
| 4772 | bases[plane_idx].clone() |
| 4773 | } else { |
| 4774 | apply(&bases[plane_idx], alpha) |
| 4775 | }; |
| 4776 | chroma[plane_idx].code_from_prediction( |
| 4777 | at.x, |
| 4778 | at.y, |
| 4779 | at.side, |
| 4780 | &prediction, |
| 4781 | false, |
| 4782 | search.base_q_idx, |
| 4783 | search.deadzone, |
| 4784 | set, |
| 4785 | ) |
| 4786 | }; |
| 4787 | // At least one alpha must be nonzero: `cfl_alpha_signs` has no |
| 4788 | // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]). |
| 4789 | let combos: [(i32, i32); 3] = [ |
| 4790 | (picked[0], picked[1]), |
| 4791 | (picked[0], 0), |
| 4792 | (0, picked[1]), |
| 4793 | ]; |
| 4794 | for &(alpha_u, alpha_v) in &combos { |
| 4795 | if (alpha_u, alpha_v) == (0, 0) { |
| 4796 | continue; |
| 4797 | } |
| 4798 | let cu = trial(0, alpha_u); |
| 4799 | let cv = trial(1, alpha_v); |
| 4800 | let bits = |
| 4801 | cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits; |
| 4802 | let cost_cfl = cu.sse + cv.sse + search.lambda * bits; |
| 4803 | if cost_cfl < cost { |
| 4804 | cost = cost_cfl; |
| 4805 | mode = crate::tile::UV_CFL_PRED as u8; |
| 4806 | u = cu; |
| 4807 | v = cv; |
| 4808 | palette_uv = None; |
| 4809 | cfl_alphas = Some((alpha_u, alpha_v)); |
| 4810 | } |
| 4811 | } |
| 4812 | } |
| 4813 | } |
| 4814 | if let Some((alpha_u, alpha_v)) = cfl_alphas { |
| 4815 | for alpha in [alpha_u, alpha_v] { |
| 4816 | CFL_ALPHA_HITS[alpha.unsigned_abs() as usize] |
| 4817 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4818 | } |
| 4819 | } |
| 4820 | if census_on() { |
| 4821 | CHROMA_RANK[sad_rank(&ranking, mode).min(6)] |
| 4822 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4823 | } |
| 4824 | UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4825 | chroma[0].commit(at.x, at.y, at.side, &u); |
| 4826 | chroma[1].commit(at.x, at.y, at.side, &v); |
| 4827 | ( |
| 4828 | [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], |
| 4829 | mode, |
| 4830 | cost, |
| 4831 | palette_uv, |
| 4832 | cfl_alphas, |
| 4833 | ) |
| 4834 | } |
| 4835 | |
| 4836 | /// Codes one leaf of a straddling quadrant as whichever costs least of intra |
| 4837 | /// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at |
| 4838 | /// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`] |
| 4839 | /// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a |
| 4840 | /// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under |
| 4841 | /// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`] |
| 4842 | /// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not |
| 4843 | /// attempted here: these leaves only ever fill the sliver of real content a |
| 4844 | /// true edge lands in the middle of a larger block, not a leaf worth a full |
| 4845 | /// search, so `NEARESTMV`-or-intra is this function's deliberate first cut |
| 4846 | /// (see `write_inter_frame_leaf`'s doc comment). |
| 4847 | #[allow(clippy::too_many_arguments)] |
| 4848 | /// The compound MV stack of each `LAST` + extra-reference pair at one leaf, |
| 4849 | /// as [`code_square_inter`] wants them: empty on a frame that codes no |
| 4850 | /// `reference_select`, or when the leaf compound candidates are switched off. |
| 4851 | /// One helper because THREE leaf call sites need it -- the split quadrants |
| 4852 | /// and, since lane-av1comp4, both straddling-edge sites, which used to pass |
| 4853 | /// `&[]` and so coded no compound block anywhere along the frame's true edge. |
| 4854 | #[allow(clippy::too_many_arguments)] |
| 4855 | fn leaf_compound_stacks<'a>( |
| 4856 | grid: &MiGrid, |
| 4857 | mi_row: usize, |
| 4858 | mi_col: usize, |
| 4859 | bw4: usize, |
| 4860 | bh4: usize, |
| 4861 | mi_cols: usize, |
| 4862 | mi_rows: usize, |
| 4863 | reference_select: bool, |
| 4864 | golden: Option<&'a Picture>, |
| 4865 | altref: Option<&'a Picture>, |
| 4866 | ) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> { |
| 4867 | if !(reference_select && leaf_compound()) { |
| 4868 | return Vec::new(); |
| 4869 | } |
| 4870 | [ |
| 4871 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 4872 | (crate::mvstack::ALTREF_FRAME, altref), |
| 4873 | ] |
| 4874 | .into_iter() |
| 4875 | .filter_map(|(r, pic)| { |
| 4876 | pic.map(|p| { |
| 4877 | ( |
| 4878 | r, |
| 4879 | p, |
| 4880 | crate::mvstack::find_mv_stack_compound( |
| 4881 | grid, mi_row, mi_col, bw4, bh4, |
| 4882 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 4883 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 4884 | ), |
| 4885 | ) |
| 4886 | }) |
| 4887 | }) |
| 4888 | .collect() |
| 4889 | } |
| 4890 | |
| 4891 | /// The OBMC prediction of one square single-reference block: this block's own |
| 4892 | /// translation prediction (`mc::predict`) with every bordering above/left |
| 4893 | /// neighbour blended into the overlap strips by the DECODER's own plan and |
| 4894 | /// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what |
| 4895 | /// the search prices is what a decoder reconstructs -- never a second |
| 4896 | /// implementation of the blend. `None` when the block has no overlappable |
| 4897 | /// neighbour at all (the writer would then code no `motion_mode` symbol) or |
| 4898 | /// when the plan cannot be built (a neighbour naming a reference this encode |
| 4899 | /// does not hold). |
| 4900 | #[allow(clippy::too_many_arguments)] |
| 4901 | fn obmc_prediction( |
| 4902 | grid: &MiGrid, |
| 4903 | (mi_row, mi_col): (usize, usize), |
| 4904 | (mi_rows, mi_cols): (usize, usize), |
| 4905 | (x, y): (usize, usize), |
| 4906 | side: usize, |
| 4907 | mv: (i32, i32), |
| 4908 | refs: &[Option<&Picture>; 8], |
| 4909 | // This block's OWN reference planes, luma then both chroma, each as |
| 4910 | // (samples, stride, true width, true height). |
| 4911 | ref_planes: [(&[u16], usize, usize, usize); 3], |
| 4912 | frame_width: usize, |
| 4913 | fctx: &crate::decode::FrameCtx, |
| 4914 | ) -> Option<[Vec<u8>; 3]> { |
| 4915 | let n4 = side / 4; |
| 4916 | if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) { |
| 4917 | return None; |
| 4918 | } |
| 4919 | let refpix = crate::decode::RefPix::ready(*refs); |
| 4920 | let plan = crate::decode::obmc_plan( |
| 4921 | grid, |
| 4922 | &[], |
| 4923 | &[], |
| 4924 | mi_row, |
| 4925 | mi_col, |
| 4926 | n4, |
| 4927 | n4, |
| 4928 | mi_rows, |
| 4929 | mi_cols, |
| 4930 | side, |
| 4931 | side, |
| 4932 | side, |
| 4933 | side / 2, |
| 4934 | x, |
| 4935 | y, |
| 4936 | x / 2, |
| 4937 | y / 2, |
| 4938 | &refpix, |
| 4939 | Some(mc::InterpFilterKind::Regular), |
| 4940 | frame_width, |
| 4941 | ) |
| 4942 | .ok()?; |
| 4943 | let mut pred = [ |
| 4944 | vec![0u16; side * side], |
| 4945 | vec![0u16; side * side / 4], |
| 4946 | vec![0u16; side * side / 4], |
| 4947 | ]; |
| 4948 | for (i, r) in ref_planes.into_iter().enumerate() { |
| 4949 | let luma_plane = i == 0; |
| 4950 | let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) }; |
| 4951 | let s = if luma_plane { side } else { side / 2 }; |
| 4952 | mc::predict( |
| 4953 | r.0, |
| 4954 | r.1, |
| 4955 | r.2, |
| 4956 | r.3, |
| 4957 | mv_to_q4(px, mv.1, luma_plane), |
| 4958 | mv_to_q4(py, mv.0, luma_plane), |
| 4959 | s, |
| 4960 | s, |
| 4961 | &mut pred[i], |
| 4962 | fctx, |
| 4963 | ); |
| 4964 | } |
| 4965 | let [mut py_buf, mut pu_buf, mut pv_buf] = pred; |
| 4966 | crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx); |
| 4967 | let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>(); |
| 4968 | Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)]) |
| 4969 | } |
| 4970 | |
| 4971 | fn code_square_inter( |
| 4972 | luma: &mut Plane, |
| 4973 | chroma: &mut [Plane; 2], |
| 4974 | (x, y): (usize, usize), |
| 4975 | side: usize, |
| 4976 | search: &Search, |
| 4977 | mode_bits: &[f64; 13], |
| 4978 | reference: &Picture, |
| 4979 | stack: &MvStack, |
| 4980 | // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS |
| 4981 | // leaf's own `bw4`/`bh4` (empty on a frame that does not code |
| 4982 | // `reference_select`, and at the straddling call sites). |
| 4983 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 4984 | // lane-av1obmc2: the mi grid this leaf's neighbours were published into |
| 4985 | // (`record_mi`, in the writer's own coding order) and this leaf's place in |
| 4986 | // it -- what the OBMC candidate's eligibility walk and neighbour plan |
| 4987 | // read, the same state the tile writer reads when it codes the leaf's |
| 4988 | // `motion_mode` symbol. |
| 4989 | grid: &MiGrid, |
| 4990 | (mi_row, mi_col): (usize, usize), |
| 4991 | (mi_rows, mi_cols): (usize, usize), |
| 4992 | // Every picture an OBMC neighbour can name: a leaf only searches LAST, |
| 4993 | // but the neighbours it blends may be GOLDEN/ALTREF blocks. |
| 4994 | refs: &[Option<&Picture>; 8], |
| 4995 | fctx: &crate::decode::FrameCtx, |
| 4996 | ) -> (BlockCoeffs, f64) { |
| 4997 | let (intra_block, intra_cost) = |
| 4998 | code_square( |
| 4999 | luma, |
| 5000 | chroma, |
| 5001 | (x, y), |
| 5002 | side, |
| 5003 | search, |
| 5004 | mode_bits, |
| 5005 | tx_select() && tx_select_inter(), |
| 5006 | None, |
| 5007 | fctx, |
| 5008 | ); |
| 5009 | let luma_set = if side == 8 { |
| 5010 | TxbSet::Luma8Inter |
| 5011 | } else { |
| 5012 | TxbSet::Luma16Inter |
| 5013 | }; |
| 5014 | let chroma_set = if side == 8 { |
| 5015 | TxbSet::Chroma4 |
| 5016 | } else { |
| 5017 | TxbSet::Chroma8 |
| 5018 | }; |
| 5019 | |
| 5020 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 5021 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 5022 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 5023 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 5024 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 5025 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV |
| 5026 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero |
| 5027 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV |
| 5028 | |
| 5029 | let mv = stack.nearest_mv; |
| 5030 | let ref_luma = ( |
| 5031 | &reference.y, |
| 5032 | reference.width, |
| 5033 | luma.true_width, |
| 5034 | luma.true_height, |
| 5035 | ); |
| 5036 | let ref_u = ( |
| 5037 | &reference.u, |
| 5038 | reference.width / 2, |
| 5039 | chroma[0].true_width, |
| 5040 | chroma[0].true_height, |
| 5041 | ); |
| 5042 | let ref_v = ( |
| 5043 | &reference.v, |
| 5044 | reference.width / 2, |
| 5045 | chroma[1].true_width, |
| 5046 | chroma[1].true_height, |
| 5047 | ); |
| 5048 | let luma_trial = mc_trial( |
| 5049 | luma, |
| 5050 | x, |
| 5051 | y, |
| 5052 | side, |
| 5053 | mv, |
| 5054 | true, |
| 5055 | ref_luma.0, |
| 5056 | ref_luma.1, |
| 5057 | ref_luma.2, |
| 5058 | ref_luma.3, |
| 5059 | false, |
| 5060 | search.base_q_idx, |
| 5061 | search.deadzone, |
| 5062 | luma_set, fctx, |
| 5063 | ); |
| 5064 | let u = mc_trial( |
| 5065 | &chroma[0], |
| 5066 | x / 2, |
| 5067 | y / 2, |
| 5068 | side / 2, |
| 5069 | mv, |
| 5070 | false, |
| 5071 | ref_u.0, |
| 5072 | ref_u.1, |
| 5073 | ref_u.2, |
| 5074 | ref_u.3, |
| 5075 | false, |
| 5076 | search.base_q_idx, |
| 5077 | search.deadzone, |
| 5078 | chroma_set, fctx, |
| 5079 | ); |
| 5080 | let v = mc_trial( |
| 5081 | &chroma[1], |
| 5082 | x / 2, |
| 5083 | y / 2, |
| 5084 | side / 2, |
| 5085 | mv, |
| 5086 | false, |
| 5087 | ref_v.0, |
| 5088 | ref_v.1, |
| 5089 | ref_v.2, |
| 5090 | ref_v.3, |
| 5091 | false, |
| 5092 | search.base_q_idx, |
| 5093 | search.deadzone, |
| 5094 | chroma_set, fctx, |
| 5095 | ); |
| 5096 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 5097 | && u.levels.iter().all(|&l| l == 0) |
| 5098 | && v.levels.iter().all(|&l| l == 0); |
| 5099 | let inter_cost = luma_trial.sse |
| 5100 | + u.sse |
| 5101 | + v.sse |
| 5102 | + search.lambda |
| 5103 | * (skip_bits(skip) |
| 5104 | + intra_inter_bits(true) |
| 5105 | + single_ref_bits |
| 5106 | + mode_bits_inter |
| 5107 | + if skip { |
| 5108 | 0.0 |
| 5109 | } else { |
| 5110 | luma_trial.bits + u.bits + v.bits |
| 5111 | }); |
| 5112 | |
| 5113 | // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's |
| 5114 | // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's |
| 5115 | // extended row/col scan, invisible at 8-mi-only geometry (the immediate |
| 5116 | // scan's own coverage already reached as far) but a real gap at 4-mi |
| 5117 | // leaf geometry. r3 ported the extended scan and, while proving it a |
| 5118 | // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`, |
| 5119 | // `mvstack.rs`), found and fixed a second bug the extended scan's |
| 5120 | // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an |
| 5121 | // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/ |
| 5122 | // `scan_col_mbmi` advance coverage from any candidate's `bsize`, |
| 5123 | // regardless of whether it also casts a ref-frame-matching vote) -- |
| 5124 | // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else` |
| 5125 | // branches), which is what made 8-mi geometry a true no-op instead of |
| 5126 | // one that only held when every neighbour happened to be inter. |
| 5127 | // A motion search of this leaf's own (lane-av1rd2): before it, a leaf |
| 5128 | // only ever took the stack's NEARESTMV candidate or went intra, so a |
| 5129 | // 32x32 block splitting because its four quarters MOVE differently could |
| 5130 | // not code the movement it split for. Same candidate `search_inter_block` |
| 5131 | // prices for a whole block -- `motion::search` from `pred_mv`, rounded to |
| 5132 | // a vector the residual syntax can name -- at this leaf's own side. |
| 5133 | let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None); |
| 5134 | // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC |
| 5135 | // re-price below can hand it back as the winner's own mode info. |
| 5136 | let nearest_info = InterInfo { |
| 5137 | ref1: None, |
| 5138 | mv1: (0, 0), |
| 5139 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5140 | mode: InterMode::NearestMv, |
| 5141 | mv, |
| 5142 | ref_mv_idx: 0, |
| 5143 | }; |
| 5144 | // What the current SINGLE-REFERENCE winner pays in mode/reference/mv |
| 5145 | // syntax, apart from its residual: the OBMC candidate re-prices the same |
| 5146 | // syntax against a different prediction, so both sides of that comparison |
| 5147 | // carry it. |
| 5148 | let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter; |
| 5149 | // This leaf's own `NEWMV` vector, kept whether or not it won the |
| 5150 | // single-reference comparison: it seeds the compound half-new candidate |
| 5151 | // below, exactly as `search_inter_block` seeds its own from the searches |
| 5152 | // it already ran. |
| 5153 | let mut searched_new: Option<(i32, i32)> = None; |
| 5154 | // What that search cost, kept for the second reference's own early-out |
| 5155 | // below (`None` when this leaf ran no search at all). |
| 5156 | let mut searched_new_cost: Option<f64> = None; |
| 5157 | let source_block = luma.source_block(x, y, side); |
| 5158 | if leaf_new_mv() { |
| 5159 | let (seeds, seed_n) = mv_seeds(stack); |
| 5160 | let found = motion::search( |
| 5161 | ref_luma.0, |
| 5162 | ref_luma.1, |
| 5163 | ref_luma.2, |
| 5164 | ref_luma.3, |
| 5165 | &source_block, |
| 5166 | x, |
| 5167 | y, |
| 5168 | side, |
| 5169 | side, |
| 5170 | stack.pred_mv, |
| 5171 | &seeds[..seed_n], |
| 5172 | search.lambda, fctx, |
| 5173 | 1, |
| 5174 | ); |
| 5175 | let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 5176 | searched_new_cost = Some(found.cost); |
| 5177 | if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) { |
| 5178 | searched_new = Some(new_mv); |
| 5179 | // Same reuse as `search_inter_block`: a NEWMV equal to the |
| 5180 | // stack's NEARESTMV is the same three trials, already run above. |
| 5181 | let (luma_new, u_new, v_new) = if new_mv == mv { |
| 5182 | (luma_trial.clone(), u.clone(), v.clone()) |
| 5183 | } else { |
| 5184 | ( |
| 5185 | mc_trial( |
| 5186 | luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2, |
| 5187 | ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx, |
| 5188 | ), |
| 5189 | mc_trial( |
| 5190 | &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1, |
| 5191 | ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 5192 | fctx, |
| 5193 | ), |
| 5194 | mc_trial( |
| 5195 | &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1, |
| 5196 | ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 5197 | fctx, |
| 5198 | ), |
| 5199 | ) |
| 5200 | }; |
| 5201 | let skip_new = luma_new.levels.iter().all(|&l| l == 0) |
| 5202 | && u_new.levels.iter().all(|&l| l == 0) |
| 5203 | && v_new.levels.iter().all(|&l| l == 0); |
| 5204 | let drl_bits = if stack.entries.len() > 1 { |
| 5205 | symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) |
| 5206 | } else { |
| 5207 | 0.0 |
| 5208 | }; |
| 5209 | let cost_new = luma_new.sse |
| 5210 | + u_new.sse |
| 5211 | + v_new.sse |
| 5212 | + search.lambda |
| 5213 | * (skip_bits(skip_new) |
| 5214 | + intra_inter_bits(true) |
| 5215 | + single_ref_bits |
| 5216 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 5217 | + drl_bits |
| 5218 | + mv_bits |
| 5219 | + if skip_new { |
| 5220 | 0.0 |
| 5221 | } else { |
| 5222 | luma_new.bits + u_new.bits + v_new.bits |
| 5223 | }); |
| 5224 | if cost_new < best.0 { |
| 5225 | single_syntax = intra_inter_bits(true) |
| 5226 | + single_ref_bits |
| 5227 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 5228 | + drl_bits |
| 5229 | + mv_bits; |
| 5230 | best = ( |
| 5231 | cost_new, |
| 5232 | Some(( |
| 5233 | luma_new, |
| 5234 | u_new, |
| 5235 | v_new, |
| 5236 | skip_new, |
| 5237 | InterInfo { |
| 5238 | ref1: None, |
| 5239 | mv1: (0, 0), |
| 5240 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5241 | mode: InterMode::NewMv, |
| 5242 | mv: new_mv, |
| 5243 | ref_mv_idx: 0, |
| 5244 | }, |
| 5245 | )), |
| 5246 | ); |
| 5247 | } |
| 5248 | } |
| 5249 | } |
| 5250 | |
| 5251 | // The COMPOUND candidates at this leaf (lane-av1comp3), the same set |
| 5252 | // `search_inter_block` prices for a whole 32x32 block: |
| 5253 | // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector |
| 5254 | // this leaf already searched, and -- since lane-av1comp4 gave the leaf a |
| 5255 | // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV` |
| 5256 | // too. Priced with the same static-CDF approximation, plus the |
| 5257 | // compound-only syntax the writer emits. |
| 5258 | for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) { |
| 5259 | let (ref1, g) = (*ref1, *g); |
| 5260 | let uni = |
| 5261 | (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1); |
| 5262 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 5263 | + if uni { |
| 5264 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 5265 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 5266 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 5267 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 5268 | } else { |
| 5269 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 5270 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 5271 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 5272 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 5273 | }; |
| 5274 | let mode_ctx = |
| 5275 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 5276 | let mode_bits_of = |
| 5277 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 5278 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 5279 | ( |
| 5280 | cstack.nearest_mv, |
| 5281 | mode_bits_of(0), |
| 5282 | InterInfo { |
| 5283 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5284 | mode: InterMode::NearestNearestMv, |
| 5285 | mv: cstack.nearest_mv.0, |
| 5286 | mv1: cstack.nearest_mv.1, |
| 5287 | ref1: Some(ref1), |
| 5288 | ref_mv_idx: 0, |
| 5289 | }, |
| 5290 | ), |
| 5291 | ( |
| 5292 | ((0, 0), (0, 0)), |
| 5293 | mode_bits_of(6), |
| 5294 | InterInfo { |
| 5295 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5296 | mode: InterMode::GlobalGlobalMv, |
| 5297 | mv: (0, 0), |
| 5298 | mv1: (0, 0), |
| 5299 | ref1: Some(ref1), |
| 5300 | ref_mv_idx: 0, |
| 5301 | }, |
| 5302 | ), |
| 5303 | ]; |
| 5304 | // Every compound MV residual here is priced against compound stack |
| 5305 | // entry 0, which is what `assign_compound_mv` predicts from at |
| 5306 | // `ref_mv_idx = 0` -- so it is also what the second-reference search |
| 5307 | // below seeds from and rounds to, and no candidate it finds can then |
| 5308 | // fail `mv_residual_bits`. |
| 5309 | let cbase = cstack |
| 5310 | .entries |
| 5311 | .first() |
| 5312 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 5313 | // This leaf's SECOND-reference motion search (lane-av1comp4). Without |
| 5314 | // it a leaf could only name a stack vector for the second half, and |
| 5315 | // screen capture showed the consequence: every leaf compound block |
| 5316 | // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s |
| 5317 | // extra-reference `NEWMV`, when this reference's own |
| 5318 | // `NEAREST_NEARESTMV` vector already prices `margin` times better |
| 5319 | // than the `LAST` search of this same leaf did -- one candidate |
| 5320 | // evaluation standing in for a whole search. |
| 5321 | let margin = leaf_second_new_margin(); |
| 5322 | let mut second_new: Option<(i32, i32)> = None; |
| 5323 | if leaf_second_new_mv() { |
| 5324 | let skip = margin > 0.0 |
| 5325 | && searched_new_cost.is_some_and(|last| { |
| 5326 | motion::cost_at( |
| 5327 | &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, |
| 5328 | side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx, |
| 5329 | ) * margin |
| 5330 | <= last |
| 5331 | }); |
| 5332 | if !skip { |
| 5333 | let mut seeds = [(0, 0); 4]; |
| 5334 | let mut seed_n = 1; |
| 5335 | for e in cstack.entries.iter().take(3) { |
| 5336 | seeds[seed_n] = e.mv1; |
| 5337 | seed_n += 1; |
| 5338 | } |
| 5339 | let found = motion::search( |
| 5340 | &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side, |
| 5341 | side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1), |
| 5342 | ); |
| 5343 | second_new = Some(round_to_valid_mv(found.mv, cbase.1)); |
| 5344 | } |
| 5345 | } |
| 5346 | if let Some(new_mv) = searched_new { |
| 5347 | if let Some(b0) = mv_residual_bits(new_mv, cbase.0) { |
| 5348 | ccands.push(( |
| 5349 | (new_mv, cstack.nearest_mv.1), |
| 5350 | mode_bits_of(3) + b0, |
| 5351 | InterInfo { |
| 5352 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5353 | mode: InterMode::NewNearestMv, |
| 5354 | mv: new_mv, |
| 5355 | mv1: cstack.nearest_mv.1, |
| 5356 | ref1: Some(ref1), |
| 5357 | ref_mv_idx: 0, |
| 5358 | }, |
| 5359 | )); |
| 5360 | } |
| 5361 | } |
| 5362 | // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two |
| 5363 | // searches this leaf ran, each residual priced against `cbase`. |
| 5364 | if let Some(mv1) = second_new { |
| 5365 | if let Some(b1) = mv_residual_bits(mv1, cbase.1) { |
| 5366 | ccands.push(( |
| 5367 | (cstack.nearest_mv.0, mv1), |
| 5368 | mode_bits_of(2) + b1, |
| 5369 | InterInfo { |
| 5370 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5371 | mode: InterMode::NearestNewMv, |
| 5372 | mv: cstack.nearest_mv.0, |
| 5373 | mv1, |
| 5374 | ref1: Some(ref1), |
| 5375 | ref_mv_idx: 0, |
| 5376 | }, |
| 5377 | )); |
| 5378 | if let Some((new_mv, b0)) = |
| 5379 | searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b))) |
| 5380 | { |
| 5381 | ccands.push(( |
| 5382 | (new_mv, mv1), |
| 5383 | mode_bits_of(7) + b0 + b1, |
| 5384 | InterInfo { |
| 5385 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5386 | mode: InterMode::NewNewMv, |
| 5387 | mv: new_mv, |
| 5388 | mv1, |
| 5389 | ref1: Some(ref1), |
| 5390 | ref_mv_idx: 0, |
| 5391 | }, |
| 5392 | )); |
| 5393 | } |
| 5394 | } |
| 5395 | } |
| 5396 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 5397 | ccands.dedup_by_key(|c| c.0); |
| 5398 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 5399 | let g_u = ( |
| 5400 | g.u.as_slice(), |
| 5401 | g.width / 2, |
| 5402 | chroma[0].true_width, |
| 5403 | chroma[0].true_height, |
| 5404 | ); |
| 5405 | let g_v = ( |
| 5406 | g.v.as_slice(), |
| 5407 | g.width / 2, |
| 5408 | chroma[1].true_width, |
| 5409 | chroma[1].true_height, |
| 5410 | ); |
| 5411 | for (mvs, bits, info) in ccands { |
| 5412 | let luma_c = mc_trial_compound( |
| 5413 | luma, x, y, side, mvs, true, |
| 5414 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 5415 | search.base_q_idx, search.deadzone, luma_set, fctx, |
| 5416 | ); |
| 5417 | let u_c = mc_trial_compound( |
| 5418 | &chroma[0], x / 2, y / 2, side / 2, mvs, false, |
| 5419 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 5420 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 5421 | ); |
| 5422 | let v_c = mc_trial_compound( |
| 5423 | &chroma[1], x / 2, y / 2, side / 2, mvs, false, |
| 5424 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 5425 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 5426 | ); |
| 5427 | let skip_c = luma_c.levels.iter().all(|&l| l == 0) |
| 5428 | && u_c.levels.iter().all(|&l| l == 0) |
| 5429 | && v_c.levels.iter().all(|&l| l == 0); |
| 5430 | let cost_c = luma_c.sse |
| 5431 | + u_c.sse |
| 5432 | + v_c.sse |
| 5433 | + search.lambda |
| 5434 | * (skip_bits(skip_c) |
| 5435 | + intra_inter_bits(true) |
| 5436 | + bits |
| 5437 | + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits }); |
| 5438 | if cost_c < best.0 { |
| 5439 | best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info))); |
| 5440 | } |
| 5441 | } |
| 5442 | } |
| 5443 | |
| 5444 | // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec |
| 5445 | // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference |
| 5446 | // winner -- libaom's `motion_mode_allowed` refuses a compound block, and |
| 5447 | // the writer codes no symbol for one. The prediction is the decoder's own |
| 5448 | // plan and blend over the neighbours this leaf's `grid` already carries |
| 5449 | // (published by `record_mi` in the writer's coding order), so the |
| 5450 | // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc |
| 5451 | // offered this only at 32x32, which is not where libaom cashes its OBMC |
| 5452 | // gain. |
| 5453 | let mut motion_won = 0u8; |
| 5454 | let single = match &best.1 { |
| 5455 | None => Some(nearest_info), |
| 5456 | Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info), |
| 5457 | Some(_) => None, |
| 5458 | }; |
| 5459 | if let Some(info) = single.filter(|i| { |
| 5460 | (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on()) |
| 5461 | && i.ref_frame == crate::mvstack::LAST_FRAME |
| 5462 | }) { |
| 5463 | let planes = [ |
| 5464 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 5465 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 5466 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 5467 | ]; |
| 5468 | // Which alphabet this block's writer will code the symbol against |
| 5469 | // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the |
| 5470 | // 3-symbol one only under `allow_warped_motion` and at least one warp |
| 5471 | // sample. Mirrored here so the candidates are priced against the |
| 5472 | // table the tile really narrows. |
| 5473 | let warp_alphabet = warp_on() |
| 5474 | && crate::decode::num_proj_ref( |
| 5475 | grid, |
| 5476 | mi_row, |
| 5477 | mi_col, |
| 5478 | side / 4, |
| 5479 | side / 4, |
| 5480 | mi_cols, |
| 5481 | mi_rows, |
| 5482 | info.ref_frame, |
| 5483 | fctx, |
| 5484 | ) >= 1; |
| 5485 | let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet); |
| 5486 | let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new(); |
| 5487 | if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() { |
| 5488 | if let Some(pred) = obmc_prediction( |
| 5489 | grid, |
| 5490 | (mi_row, mi_col), |
| 5491 | (mi_rows, mi_cols), |
| 5492 | (x, y), |
| 5493 | side, |
| 5494 | info.mv, |
| 5495 | refs, |
| 5496 | planes, |
| 5497 | reference.width, |
| 5498 | fctx, |
| 5499 | ) { |
| 5500 | candidates.push((1, pred)); |
| 5501 | } |
| 5502 | } |
| 5503 | if warp_alphabet { |
| 5504 | if let Some(pred) = warp_prediction( |
| 5505 | grid, |
| 5506 | (mi_row, mi_col), |
| 5507 | (mi_rows, mi_cols), |
| 5508 | (x, y), |
| 5509 | side, |
| 5510 | info.mv, |
| 5511 | info.ref_frame, |
| 5512 | planes, |
| 5513 | fctx, |
| 5514 | ) { |
| 5515 | candidates.push((2, pred)); |
| 5516 | } |
| 5517 | } |
| 5518 | for (motion, pred) in candidates { |
| 5519 | let luma_o = luma.code_from_prediction( |
| 5520 | x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set, |
| 5521 | ); |
| 5522 | let u_o = chroma[0].code_from_prediction( |
| 5523 | x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone, |
| 5524 | chroma_set, |
| 5525 | ); |
| 5526 | let v_o = chroma[1].code_from_prediction( |
| 5527 | x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone, |
| 5528 | chroma_set, |
| 5529 | ); |
| 5530 | let skip_o = luma_o.levels.iter().all(|&l| l == 0) |
| 5531 | && u_o.levels.iter().all(|&l| l == 0) |
| 5532 | && v_o.levels.iter().all(|&l| l == 0); |
| 5533 | let cost_o = luma_o.sse |
| 5534 | + u_o.sse |
| 5535 | + v_o.sse |
| 5536 | + search.lambda |
| 5537 | * (skip_bits(skip_o) |
| 5538 | + single_syntax |
| 5539 | + mm(motion) |
| 5540 | + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits }); |
| 5541 | // The incumbent pays the motion_mode symbol IT would code, so |
| 5542 | // both sides of the comparison carry that syntax. |
| 5543 | if cost_o < best.0 + search.lambda * mm(motion_won) { |
| 5544 | motion_won = motion; |
| 5545 | best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info))); |
| 5546 | } |
| 5547 | } |
| 5548 | } |
| 5549 | |
| 5550 | if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best { |
| 5551 | if cost < intra_cost { |
| 5552 | // A compound winner commits the flat trial it was priced from: |
| 5553 | // `commit_inter_luma`'s var-tx trial set is single-reference |
| 5554 | // (`mc_trial`), so a compound leaf codes `tx_depth = 0`. |
| 5555 | // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma` |
| 5556 | // predicting each half-side trial from BOTH references, verified |
| 5557 | // byte-identical to this when its split is disabled) and MEASURED |
| 5558 | // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the |
| 5559 | // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/ |
| 5560 | // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A |
| 5561 | // compound block's residual is small enough that the four extra |
| 5562 | // per-unit txb_skip/eob symbols cost more ladder bytes than this |
| 5563 | // encoder's static-CDF estimate prices them at, so the local RD |
| 5564 | // win does not convert. lane-av1txbits REBUILT it on top of a |
| 5565 | // search that prices against the tables the frame is really |
| 5566 | // written with (`tile::arm_pricing_cdfs`, the estimate error on |
| 5567 | // these very blocks measured down from +31% to +3%) and measured |
| 5568 | // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/ |
| 5569 | // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the |
| 5570 | // same build without it. The static-CDF estimate was NOT what |
| 5571 | // held the compound var-tx trial back. The flat trial stays. |
| 5572 | // An OBMC winner commits the flat trial too: `commit_inter_luma` |
| 5573 | // re-predicts each var-tx unit by plain translation, which is not |
| 5574 | // the prediction this candidate was priced from. |
| 5575 | // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE |
| 5576 | // 0.05 (both rejections above were measured at 0.1, the weight |
| 5577 | // the lambda lane showed was 2x too heavy): a compound winner is |
| 5578 | // offered the same var-tx split, its units predicted from BOTH |
| 5579 | // references (`mc_trial_compound`). RE-MEASURED native: film |
| 5580 | // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4 |
| 5581 | // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off -- |
| 5582 | // one row 0.2 down, two flat, short of the two-down-one-flat keep |
| 5583 | // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF) |
| 5584 | // rather than change the default on a single 0.2 row. It fires: |
| 5585 | // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for |
| 5586 | // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against |
| 5587 | // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is |
| 5588 | // 1.3/1.2 down there, which is where the upgrade path is if this |
| 5589 | // is picked up again. |
| 5590 | let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| { |
| 5591 | refs[r as usize].map(|g| { |
| 5592 | ( |
| 5593 | info.mv1, |
| 5594 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 5595 | ) |
| 5596 | }) |
| 5597 | }); |
| 5598 | let (levels, tx_depth, dcost) = if motion_won != 0 |
| 5599 | || (info.ref1.is_some() && second.is_none()) |
| 5600 | { |
| 5601 | luma.commit(x, y, side, &luma_new); |
| 5602 | (luma_new.levels.clone(), 0, 0.0) |
| 5603 | } else { |
| 5604 | commit_inter_luma( |
| 5605 | luma, (x, y), side, info.mv, |
| 5606 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 5607 | search, &luma_new, skip_new, second, fctx, |
| 5608 | ) |
| 5609 | }; |
| 5610 | chroma[0].commit(x / 2, y / 2, side / 2, &u_new); |
| 5611 | chroma[1].commit(x / 2, y / 2, side / 2, &v_new); |
| 5612 | return ( |
| 5613 | BlockCoeffs { |
| 5614 | angle_delta_y: 0, |
| 5615 | cfl_alphas: None, |
| 5616 | filter_intra: None, |
| 5617 | luma: coeffs(&levels, side), |
| 5618 | u: coeffs(&u_new.levels, side / 2), |
| 5619 | v: coeffs(&v_new.levels, side / 2), |
| 5620 | mode: DC_PRED as u8, |
| 5621 | uv_mode: DC_PRED, |
| 5622 | skip: skip_new, |
| 5623 | eight: None, |
| 5624 | dv: None, |
| 5625 | palette: None, |
| 5626 | palette_uv: None, |
| 5627 | tx_depth, |
| 5628 | inter: Some(info), |
| 5629 | motion_mode: motion_won, |
| 5630 | }, |
| 5631 | cost + dcost, |
| 5632 | ); |
| 5633 | } |
| 5634 | } |
| 5635 | |
| 5636 | census_add(8, 1); |
| 5637 | if skip { |
| 5638 | census_add(10, 1); |
| 5639 | } |
| 5640 | if inter_cost >= intra_cost { |
| 5641 | census_add(9, 1); |
| 5642 | } |
| 5643 | if inter_cost < intra_cost { |
| 5644 | let (levels, tx_depth, dcost) = commit_inter_luma( |
| 5645 | luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, None, fctx, |
| 5646 | ); |
| 5647 | chroma[0].commit(x / 2, y / 2, side / 2, &u); |
| 5648 | chroma[1].commit(x / 2, y / 2, side / 2, &v); |
| 5649 | (BlockCoeffs { |
| 5650 | angle_delta_y: 0, |
| 5651 | cfl_alphas: None, |
| 5652 | filter_intra: None, |
| 5653 | luma: coeffs(&levels, side), |
| 5654 | u: coeffs(&u.levels, side / 2), |
| 5655 | v: coeffs(&v.levels, side / 2), |
| 5656 | mode: DC_PRED as u8, |
| 5657 | uv_mode: DC_PRED, |
| 5658 | skip, |
| 5659 | eight: None, |
| 5660 | dv: None, |
| 5661 | palette: None, |
| 5662 | palette_uv: None, |
| 5663 | tx_depth, |
| 5664 | motion_mode: 0, |
| 5665 | inter: Some(InterInfo { |
| 5666 | ref1: None, |
| 5667 | mv1: (0, 0), |
| 5668 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5669 | mode: InterMode::NearestMv, |
| 5670 | mv, |
| 5671 | ref_mv_idx: 0, |
| 5672 | }), |
| 5673 | }, inter_cost + dcost) |
| 5674 | } else { |
| 5675 | (intra_block, intra_cost) |
| 5676 | } |
| 5677 | } |
| 5678 | |
| 5679 | /// Publishes one coded inter-frame block into the `mi` grid the next block's |
| 5680 | /// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra |
| 5681 | /// block casts no vote but is still a coded cell (see `code_square_inter`'s |
| 5682 | /// note on `processed_rows`/`processed_cols`). |
| 5683 | fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) { |
| 5684 | let info = match inter { |
| 5685 | Some(info) => MiInfo { |
| 5686 | is_inter: true, |
| 5687 | ref_frame: info.ref_frame, |
| 5688 | // A COMPOUND block votes with BOTH of its references and both of |
| 5689 | // its vectors, exactly as the tile writer publishes it: recording |
| 5690 | // a compound block as a single-reference one here left the |
| 5691 | // encoder's own grid disagreeing with the writer's from the first |
| 5692 | // compound block on, so every later stack it searched against was |
| 5693 | // not the stack the decoder derives. |
| 5694 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 5695 | mv1: mv16(info.mv1), |
| 5696 | mv: mv16(info.mv), |
| 5697 | // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference |
| 5698 | // side, compound modes 2/3/7 on the other. |
| 5699 | is_new_mv: matches!( |
| 5700 | info.mode, |
| 5701 | InterMode::NewMv |
| 5702 | | InterMode::NewNewMv |
| 5703 | | InterMode::NearestNewMv |
| 5704 | | InterMode::NewNearestMv |
| 5705 | ), |
| 5706 | size, |
| 5707 | size_h: size, |
| 5708 | is_global_mv0: false, |
| 5709 | is_global_mv1: false, |
| 5710 | }, |
| 5711 | None => MiInfo { |
| 5712 | is_inter: false, |
| 5713 | ref_frame: -1, |
| 5714 | ref_frame1: NO_REF1, |
| 5715 | mv1: (0, 0), |
| 5716 | mv: (0, 0), |
| 5717 | is_new_mv: false, |
| 5718 | size, |
| 5719 | size_h: size, |
| 5720 | is_global_mv0: false, |
| 5721 | is_global_mv1: false, |
| 5722 | }, |
| 5723 | }; |
| 5724 | for dr in 0..usize::from(size) { |
| 5725 | for dc in 0..usize::from(size) { |
| 5726 | grid.set(mi_row + dr, mi_col + dc, info); |
| 5727 | } |
| 5728 | } |
| 5729 | } |
| 5730 | |
| 5731 | /// The reconstructed samples one 32x32 square covers in all three planes, so |
| 5732 | /// that a partition trial can be undone. |
| 5733 | /// One square of a plane, row-major, the inverse of [`Plane::restore`]. |
| 5734 | /// |
| 5735 | /// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces, |
| 5736 | /// which allocated and freed a `Vec` per row of every block it copied -- |
| 5737 | /// `Plane::snapshot` runs once per partition trial. |
| 5738 | fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 5739 | let mut out = vec![0u8; side * side]; |
| 5740 | for row in 0..side { |
| 5741 | out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]); |
| 5742 | } |
| 5743 | out |
| 5744 | } |
| 5745 | |
| 5746 | fn snapshot( |
| 5747 | luma: &Plane, |
| 5748 | chroma: &[Plane; 2], |
| 5749 | (x, y): (usize, usize), |
| 5750 | side: usize, |
| 5751 | ) -> [(Vec<u8>, Vec<CoefCtx>); 3] { |
| 5752 | [ |
| 5753 | luma.snapshot(x, y, side), |
| 5754 | chroma[0].snapshot(x / 2, y / 2, side / 2), |
| 5755 | chroma[1].snapshot(x / 2, y / 2, side / 2), |
| 5756 | ] |
| 5757 | } |
| 5758 | |
| 5759 | /// Puts such a snapshot back. |
| 5760 | fn restore( |
| 5761 | luma: &mut Plane, |
| 5762 | chroma: &mut [Plane; 2], |
| 5763 | (x, y): (usize, usize), |
| 5764 | side: usize, |
| 5765 | saved: &[(Vec<u8>, Vec<CoefCtx>); 3], |
| 5766 | ) { |
| 5767 | luma.restore(x, y, side, &saved[0]); |
| 5768 | chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); |
| 5769 | chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]); |
| 5770 | } |
| 5771 | |
| 5772 | /// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set |
| 5773 | /// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own |
| 5774 | /// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`] |
| 5775 | /// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one |
| 5776 | /// rule shared with the key-frame path, not a second one that could diverge. |
| 5777 | fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { |
| 5778 | let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); |
| 5779 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 5780 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 5781 | scored.truncate(if dc_entry.is_some() { |
| 5782 | top_k.saturating_sub(1) |
| 5783 | } else { |
| 5784 | top_k |
| 5785 | }); |
| 5786 | if let Some(dc_entry) = dc_entry { |
| 5787 | scored.push(dc_entry); |
| 5788 | } |
| 5789 | let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); |
| 5790 | modes.iter().copied().filter(|m| keep.contains(m)).collect() |
| 5791 | } |
| 5792 | |
| 5793 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 5794 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 5795 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| 5796 | std::array::from_fn(|mode| { |
| 5797 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 5798 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 5799 | } else { |
| 5800 | 0.0 |
| 5801 | }; |
| 5802 | symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 5803 | }) |
| 5804 | } |
| 5805 | |
| 5806 | /// What the luma mode search picks between, and under what terms. |
| 5807 | #[derive(Clone, Copy)] |
| 5808 | struct Search<'a> { |
| 5809 | /// This frame's `allow_screen_content_tools` ([`screen_content`]): the |
| 5810 | /// luma search then offers a palette candidate beside the intra modes. |
| 5811 | screen: bool, |
| 5812 | base_q_idx: u8, |
| 5813 | deadzone: f64, |
| 5814 | lambda: f64, |
| 5815 | modes: &'a [u8], |
| 5816 | /// How many of `modes` the full RD trial (forward transform, quantize, |
| 5817 | /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD |
| 5818 | /// pre-pass on the prediction residual alone plus DC (always kept, since |
| 5819 | /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s |
| 5820 | /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every |
| 5821 | /// mode through full RD, unchanged from before this lever. |
| 5822 | top_k: Option<usize>, |
| 5823 | } |
| 5824 | |
| 5825 | /// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged |
| 5826 | /// (the default, until a lever's quality gate justifies pruning by default); |
| 5827 | /// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers. |
| 5828 | fn prune_top_k() -> Option<usize> { |
| 5829 | #[cfg(test)] |
| 5830 | { |
| 5831 | if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { |
| 5832 | return k; |
| 5833 | } |
| 5834 | } |
| 5835 | let swept = std::env::var("EC_AV1_PRUNE_K") |
| 5836 | .ok() |
| 5837 | .and_then(|v| v.parse::<usize>().ok()); |
| 5838 | match swept { |
| 5839 | Some(k) if cfg!(test) => Some(k), |
| 5840 | _ => crate::speed::at(&crate::speed::PRUNE_K), |
| 5841 | } |
| 5842 | } |
| 5843 | |
| 5844 | // A per-thread override [`prune_top_k`] checks first, so one test can sweep |
| 5845 | // `top_k` in-process without mutating the environment (forbidden here -- |
| 5846 | // `#![forbid(unsafe_code)]` -- and racy across parallel tests besides). |
| 5847 | #[cfg(test)] |
| 5848 | thread_local! { |
| 5849 | static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = |
| 5850 | const { std::cell::Cell::new(None) }; |
| 5851 | } |
| 5852 | |
| 5853 | #[cfg(test)] |
| 5854 | fn set_test_top_k_override(value: Option<usize>) { |
| 5855 | TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); |
| 5856 | } |
| 5857 | |
| 5858 | /// The default: unpruned, thirteen full trials per block, same as before this |
| 5859 | /// lever. Set from the sweep in the lane report if the quality gate clears it. |
| 5860 | pub(crate) const PRUNE_TOP_K: Option<usize> = None; |
| 5861 | |
| 5862 | /// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop -- |
| 5863 | /// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths' |
| 5864 | /// quality gates were measured separately and may land on different |
| 5865 | /// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching |
| 5866 | /// [`EC_AV1_PRUNE_K`] or the key-frame path. |
| 5867 | fn prune_top_k_inter() -> Option<usize> { |
| 5868 | #[cfg(test)] |
| 5869 | { |
| 5870 | if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { |
| 5871 | return k; |
| 5872 | } |
| 5873 | } |
| 5874 | let swept = std::env::var("EC_AV1_PRUNE_K_INTER") |
| 5875 | .ok() |
| 5876 | .and_then(|v| v.parse::<usize>().ok()); |
| 5877 | match swept { |
| 5878 | Some(k) if cfg!(test) => Some(k), |
| 5879 | _ => crate::speed::at(&crate::speed::PRUNE_K_INTER), |
| 5880 | } |
| 5881 | } |
| 5882 | |
| 5883 | // A per-thread override [`prune_top_k_inter`] checks first, same reason as |
| 5884 | // [`TEST_TOP_K_OVERRIDE`]. |
| 5885 | #[cfg(test)] |
| 5886 | thread_local! { |
| 5887 | static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = |
| 5888 | const { std::cell::Cell::new(None) }; |
| 5889 | } |
| 5890 | |
| 5891 | #[cfg(test)] |
| 5892 | fn set_test_top_k_override_inter(value: Option<usize>) { |
| 5893 | TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); |
| 5894 | } |
| 5895 | |
| 5896 | /// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter` |
| 5897 | /// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the |
| 5898 | /// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes |
| 5899 | /// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest, |
| 5900 | /// `K=3`, ships as default. Unlike the key-frame path (still `None`), an |
| 5901 | /// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so |
| 5902 | /// pruning them costs less quality here. |
| 5903 | pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3); |
| 5904 | |
| 5905 | // Per-thread nanosecond counters `stage_timing_breakdown_inter` (and |
| 5906 | // [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an |
| 5907 | // inter frame's cost can be attributed to a bucket without changing what |
| 5908 | // the search actually does. Index: 0 = whole-call time inside |
| 5909 | // [`motion::search`] (includes bucket 1's time, run from inside it), 1 = |
| 5910 | // [`crate::mc::predict`] (every call, from the motion search's own |
| 5911 | // candidates and from a committed inter block's final prediction alike), |
| 5912 | // 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`. |
| 5913 | #[cfg(test)] |
| 5914 | thread_local! { |
| 5915 | static STAGE_NS: [std::cell::Cell<u64>; 4] = [ |
| 5916 | std::cell::Cell::new(0), |
| 5917 | std::cell::Cell::new(0), |
| 5918 | std::cell::Cell::new(0), |
| 5919 | std::cell::Cell::new(0), |
| 5920 | ]; |
| 5921 | } |
| 5922 | |
| 5923 | /// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and |
| 5924 | /// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran |
| 5925 | /// per transform trial and per `mc::predict` call whether or not anyone was |
| 5926 | /// reading the breakdown (the vdso clock was 1.7% of the encoder's profile). |
| 5927 | /// The clock is now read only when [`crate::par::stage_times`] is on, which |
| 5928 | /// is what prints the breakdown in the first place. |
| 5929 | #[cfg(test)] |
| 5930 | pub(crate) fn stage_start() -> Option<std::time::Instant> { |
| 5931 | crate::par::stage_times().then(std::time::Instant::now) |
| 5932 | } |
| 5933 | |
| 5934 | #[cfg(test)] |
| 5935 | pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) { |
| 5936 | if let Some(t) = t { |
| 5937 | stage_add(bucket, t.elapsed()); |
| 5938 | } |
| 5939 | } |
| 5940 | |
| 5941 | #[cfg(test)] |
| 5942 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 5943 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| 5944 | } |
| 5945 | |
| 5946 | #[cfg(test)] |
| 5947 | fn stage_reset() { |
| 5948 | crate::par::set_stage_times(true); |
| 5949 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 5950 | } |
| 5951 | |
| 5952 | #[cfg(test)] |
| 5953 | fn stage_read() -> [std::time::Duration; 4] { |
| 5954 | crate::par::set_stage_times(false); |
| 5955 | STAGE_NS.with(|c| { |
| 5956 | c.each_ref() |
| 5957 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| 5958 | }) |
| 5959 | } |
| 5960 | |
| 5961 | /// One mode's coding of one block, before it is committed. |
| 5962 | #[derive(Clone)] |
| 5963 | struct Trial { |
| 5964 | levels: Vec<i32>, |
| 5965 | reconstruction: Vec<u8>, |
| 5966 | sse: f64, |
| 5967 | bits: f64, |
| 5968 | } |
| 5969 | |
| 5970 | /// The top-left `to` x `to` corner of a `from`-sided level grid -- the part |
| 5971 | /// of a 64-point transform that is actually coded (everything outside it is |
| 5972 | /// zeroed by [`crate::transform::quantize`] already, so this only reshapes). |
| 5973 | fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> { |
| 5974 | let mut out = vec![0i32; to * to]; |
| 5975 | for row in 0..to { |
| 5976 | out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]); |
| 5977 | } |
| 5978 | out |
| 5979 | } |
| 5980 | |
| 5981 | /// The non-zero levels of a block, as the tile writer takes them. |
| 5982 | fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { |
| 5983 | levels |
| 5984 | .iter() |
| 5985 | .enumerate() |
| 5986 | .filter(|&(_, &level)| level != 0) |
| 5987 | .map(|(i, &level)| Coeff { |
| 5988 | row: (i / side) as u8, |
| 5989 | col: (i % side) as u8, |
| 5990 | level, |
| 5991 | }) |
| 5992 | .collect() |
| 5993 | } |
| 5994 | |
| 5995 | thread_local! { |
| 5996 | /// The tile grid the next frame is coded with, as `(TileColsLog2, |
| 5997 | /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its |
| 5998 | /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s |
| 5999 | /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is |
| 6000 | /// one tile per frame, what every caller that never arms anything gets |
| 6001 | /// and what every stream this crate wrote before tiles existed carries. |
| 6002 | static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) }; |
| 6003 | } |
| 6004 | |
| 6005 | /// Arms this thread's next frame encodes with a tile grid (log2 counts). |
| 6006 | pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) { |
| 6007 | TILE_LOG2.with(|c| c.set((cols_log2, rows_log2))); |
| 6008 | } |
| 6009 | |
| 6010 | fn armed_tiles() -> (u32, u32) { |
| 6011 | let armed = TILE_LOG2.with(std::cell::Cell::get); |
| 6012 | if armed != (0, 0) { |
| 6013 | return armed; |
| 6014 | } |
| 6015 | // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate |
| 6016 | // (which codes through `encode_sequence`, not the facade) can measure what |
| 6017 | // a tile grid costs without a knob of its own -- same shape as |
| 6018 | // `EC_AV1_LR`/`EC_AV1_PYRAMID`. |
| 6019 | match std::env::var("EC_AV1_TILES").ok() { |
| 6020 | Some(v) if cfg!(test) => { |
| 6021 | let mut f = v.split(':'); |
| 6022 | let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0); |
| 6023 | let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0); |
| 6024 | (cols, rows) |
| 6025 | } |
| 6026 | _ => armed, |
| 6027 | } |
| 6028 | } |
| 6029 | |
| 6030 | /// Codes a frame's `tiles` tiles, each entirely on its own (see |
| 6031 | /// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of |
| 6032 | /// the crate's own pool, and hands back their payloads in tile order plus |
| 6033 | /// whatever `code` returned for tile `store` -- the CDF state |
| 6034 | /// `context_update_tile_id` names. The result cannot depend on the thread |
| 6035 | /// count: each job writes one tile from the frame's own starting tables into |
| 6036 | /// its own slot. |
| 6037 | fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)> |
| 6038 | where |
| 6039 | F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send, |
| 6040 | { |
| 6041 | let _t = crate::par::timer(crate::par::S_TILE_WRITE); |
| 6042 | type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>; |
| 6043 | let threads = crate::par::tile_threads().min(tiles); |
| 6044 | let mut slots: Vec<Slot> = Vec::new(); |
| 6045 | if threads <= 1 { |
| 6046 | for index in 0..tiles { |
| 6047 | slots.push(Some(code(index))); |
| 6048 | } |
| 6049 | } else { |
| 6050 | let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 6051 | { |
| 6052 | let batch = crate::par::Batch::new("ec-av1-tile"); |
| 6053 | for (from, to) in crate::par::bands(tiles, threads) { |
| 6054 | let done = &done; |
| 6055 | let code = &code; |
| 6056 | batch.submit(move || { |
| 6057 | for index in from..to { |
| 6058 | let coded = code(index); |
| 6059 | done.lock().expect("tile slots")[index] = Some(coded); |
| 6060 | } |
| 6061 | }); |
| 6062 | } |
| 6063 | } |
| 6064 | slots = done.into_inner().expect("tile slots"); |
| 6065 | } |
| 6066 | let mut out = Vec::with_capacity(tiles); |
| 6067 | let mut stored = None; |
| 6068 | for (index, slot) in slots.into_iter().enumerate() { |
| 6069 | let (bytes, cdfs) = slot.expect("every tile was coded")?; |
| 6070 | if index == store { |
| 6071 | stored = cdfs; |
| 6072 | } |
| 6073 | out.push(bytes); |
| 6074 | } |
| 6075 | Ok((out, stored)) |
| 6076 | } |
| 6077 | |
| 6078 | /// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS` |
| 6079 | /// workers, and returns the results in tile order. The counterpart of |
| 6080 | /// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of |
| 6081 | /// state the search mutates (its own reconstruction planes, its own `MiGrid`, |
| 6082 | /// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and |
| 6083 | /// availability is already tile-relative (`clip_planes_to_tile`, |
| 6084 | /// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which |
| 6085 | /// other tiles have run -- gated by |
| 6086 | /// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now |
| 6087 | /// covers the search as well as the write. |
| 6088 | /// |
| 6089 | /// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync` |
| 6090 | /// by design) and moved into the worker, exactly as [`crate::par::run_bands`] |
| 6091 | /// does it for the decoder's filter bands. |
| 6092 | fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>> |
| 6093 | where |
| 6094 | T: Send, |
| 6095 | F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync, |
| 6096 | { |
| 6097 | let _t = crate::par::timer(crate::par::S_TILE_SEARCH); |
| 6098 | let threads = crate::par::tile_threads().min(tiles); |
| 6099 | if threads <= 1 { |
| 6100 | return (0..tiles).map(|index| job(index, fctx)).collect(); |
| 6101 | } |
| 6102 | type Slot<T> = Option<Result<T>>; |
| 6103 | let done: std::sync::Mutex<Vec<Slot<T>>> = |
| 6104 | std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 6105 | { |
| 6106 | let batch = crate::par::Batch::new("ec-av1-tile-search"); |
| 6107 | for (from, to) in crate::par::bands(tiles, threads) { |
| 6108 | let done = &done; |
| 6109 | let job = &job; |
| 6110 | let ctx = crate::decode::filter_ctx_copy(fctx); |
| 6111 | batch.submit(move || { |
| 6112 | for index in from..to { |
| 6113 | let searched = job(index, &ctx); |
| 6114 | done.lock().expect("tile slots")[index] = Some(searched); |
| 6115 | } |
| 6116 | }); |
| 6117 | } |
| 6118 | } |
| 6119 | done.into_inner() |
| 6120 | .expect("tile slots") |
| 6121 | .into_iter() |
| 6122 | .map(|slot| slot.expect("every tile was searched")) |
| 6123 | .collect() |
| 6124 | } |
| 6125 | |
| 6126 | /// One tile job's own copy of a plane: the frame's source, a blank |
| 6127 | /// reconstruction of the frame's size, and the frame's own bounds -- narrowed |
| 6128 | /// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy |
| 6129 | /// of the frame's reconstruction because a tile's prediction never reads a |
| 6130 | /// sample outside its own rectangle, and every sample inside it is written |
| 6131 | /// before it is read. |
| 6132 | fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> { |
| 6133 | Plane { |
| 6134 | source, |
| 6135 | reconstruction: vec![128; source.len()], |
| 6136 | width, |
| 6137 | height, |
| 6138 | true_width, |
| 6139 | true_height, |
| 6140 | tile_x0: 0, |
| 6141 | tile_y0: 0, |
| 6142 | tile_x1: width, |
| 6143 | tile_y1: height, |
| 6144 | ctx: CoefCtxMap::default(), |
| 6145 | } |
| 6146 | } |
| 6147 | |
| 6148 | /// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into |
| 6149 | /// the frame's plane, through the [`crate::par::Shared`] every job holds. |
| 6150 | /// |
| 6151 | /// corner-cut: the disjointness that makes the aliasing sound is the caller's |
| 6152 | /// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile |
| 6153 | /// rectangles partition it -- checked end-to-end by |
| 6154 | /// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow |
| 6155 | /// checker, exactly the contract `Shared`'s own doc names. Upgrade path is |
| 6156 | /// row-range `split_at_mut` plumbing through `Plane`, which would have to |
| 6157 | /// thread an origin offset through every prediction and transform call site |
| 6158 | /// for the same bytes. |
| 6159 | #[allow(unsafe_code)] |
| 6160 | fn copy_rect( |
| 6161 | dst: crate::par::Shared<'_, Vec<u8>>, |
| 6162 | src: &[u8], |
| 6163 | stride: usize, |
| 6164 | x0: usize, |
| 6165 | y0: usize, |
| 6166 | x1: usize, |
| 6167 | y1: usize, |
| 6168 | ) { |
| 6169 | // SAFETY: this job touches only its own tile rectangle (see above). |
| 6170 | let dst = unsafe { dst.get() }; |
| 6171 | for y in y0..y1 { |
| 6172 | let (a, b) = (y * stride + x0, y * stride + x1); |
| 6173 | dst[a..b].copy_from_slice(&src[a..b]); |
| 6174 | } |
| 6175 | } |
| 6176 | |
| 6177 | /// The frame header's `tile_info` (spec 5.9.15) for `layout`: |
| 6178 | /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF |
| 6179 | /// tables the frame stores (spec 7.20), which is what |
| 6180 | /// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops |
| 6181 | /// below publish. |
| 6182 | fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo { |
| 6183 | ec_av1_syntax::TileInfo { |
| 6184 | uniform_spacing: true, |
| 6185 | cols: layout.cols(), |
| 6186 | rows: layout.rows(), |
| 6187 | cols_log2: layout.cols_log2, |
| 6188 | rows_log2: layout.rows_log2, |
| 6189 | mi_col_starts: layout.mi_col_starts(), |
| 6190 | mi_row_starts: layout.mi_row_starts(), |
| 6191 | context_update_tile_id: layout.largest_tile() as u32, |
| 6192 | tile_size_bytes, |
| 6193 | } |
| 6194 | } |
| 6195 | |
| 6196 | /// Clips the three planes' intra edge reads to `rect`, the tile the |
| 6197 | /// superblock about to be searched belongs to (the encoder side of the |
| 6198 | /// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame |
| 6199 | /// raster order -- which is a linear extension of every tile's own coding |
| 6200 | /// order, so a block still only ever predicts from samples already |
| 6201 | /// reconstructed -- and only availability is tile-relative. |
| 6202 | fn clip_planes_to_tile( |
| 6203 | luma: &mut Plane<'_>, |
| 6204 | chroma: &mut [Plane<'_>; 2], |
| 6205 | rect: crate::tile::TileRect, |
| 6206 | ) { |
| 6207 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 6208 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 6209 | luma.set_tile(x0, y0, x1, y1); |
| 6210 | for plane in chroma.iter_mut() { |
| 6211 | plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); |
| 6212 | } |
| 6213 | } |
| 6214 | |
| 6215 | /// Encodes one picture as a key frame. |
| 6216 | /// |
| 6217 | /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer |
| 6218 | /// picks its coefficient CDFs from one of four q contexts by that index. |
| 6219 | /// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and |
| 6220 | /// smaller values trade fidelity for rate. |
| 6221 | /// |
| 6222 | /// The picture may be any even width and height: the encoder pads it by edge |
| 6223 | /// replication to a whole number of 32x32 blocks internally, and the frame it |
| 6224 | /// writes crops back to the picture's own size (`render_width`/ |
| 6225 | /// `render_height`), so [`Encoded::reconstruction`] is always the picture's |
| 6226 | /// own size, never the padded one. |
| 6227 | /// |
| 6228 | /// # Errors |
| 6229 | /// Returns an error when the picture's width or height is zero or odd, or |
| 6230 | /// when its planes are not 4:2:0 of that size. |
| 6231 | /// Codes one picture as a whole key frame, at `base_q_idx`, and returns its |
| 6232 | /// stream. The per-frame decode state this needs lives for exactly this call. |
| 6233 | /// |
| 6234 | /// # Errors |
| 6235 | /// Returns an error under the same conditions |
| 6236 | /// [`encode_key_frame_with_modes`] does. |
| 6237 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 6238 | encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new()) |
| 6239 | } |
| 6240 | |
| 6241 | /// [`encode_key_frame`] with the per-block intra modes given rather than |
| 6242 | /// searched. |
| 6243 | /// |
| 6244 | /// # Errors |
| 6245 | /// Returns an error when `picture`'s dimensions are odd or zero, when `modes` |
| 6246 | /// is empty, or when a block's coefficients do not fit the coded frame. |
| 6247 | pub fn encode_key_frame_with_modes( |
| 6248 | picture: &Picture, |
| 6249 | base_q_idx: u8, |
| 6250 | deadzone: f64, |
| 6251 | modes: &[u8], |
| 6252 | ) -> Result<Encoded> { |
| 6253 | encode_key_frame_with_modes_with_ctx( |
| 6254 | picture, |
| 6255 | base_q_idx, |
| 6256 | deadzone, |
| 6257 | modes, |
| 6258 | &crate::decode::FrameCtx::new(), |
| 6259 | ) |
| 6260 | } |
| 6261 | |
| 6262 | /// Codes `pictures` as one key frame followed by inter frames. |
| 6263 | /// |
| 6264 | /// Camera material is coded under [`crate::encoder::Pyramid::default`] since |
| 6265 | /// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a |
| 6266 | /// `show_existing_frame` header, so `stream` is in CODING order while |
| 6267 | /// `frames` stays in display order (`EncodedSequence::coding_order` is the |
| 6268 | /// map). Screen content codes flat, decided once per sequence by the same |
| 6269 | /// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0` |
| 6270 | /// puts every stream back on the flat path for an A/B. |
| 6271 | /// |
| 6272 | /// # Errors |
| 6273 | /// Returns an error under the same conditions [`encode_key_frame`] and the |
| 6274 | /// inter frame path do. |
| 6275 | pub fn encode_sequence( |
| 6276 | pictures: &[Picture], |
| 6277 | base_q_idx: u8, |
| 6278 | deadzone: f64, |
| 6279 | ) -> Result<EncodedSequence> { |
| 6280 | encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new()) |
| 6281 | } |
| 6282 | |
| 6283 | pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> { |
| 6284 | encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx) |
| 6285 | } |
| 6286 | |
| 6287 | /// Encodes one picture as a key frame, choosing each block's luma mode from |
| 6288 | /// `modes` alone. |
| 6289 | /// |
| 6290 | /// This is what an ablation measures against: `&[DC_PRED]` is the encoder |
| 6291 | /// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the |
| 6292 | /// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`] |
| 6293 | /// uses. |
| 6294 | /// |
| 6295 | /// # Errors |
| 6296 | /// The same as [`encode_key_frame`], and additionally when `modes` is empty or |
| 6297 | /// names a mode [`crate::intra::predict`] does not predict. |
| 6298 | pub(crate) fn encode_key_frame_with_modes_with_ctx( |
| 6299 | picture: &Picture, |
| 6300 | base_q_idx: u8, |
| 6301 | deadzone: f64, |
| 6302 | modes: &[u8], fctx: &crate::decode::FrameCtx, |
| 6303 | ) -> Result<Encoded> { |
| 6304 | picture.check_even()?; |
| 6305 | let padded = picture.padded_to(BLOCK); |
| 6306 | let encoded = encode_key_frame_inner( |
| 6307 | &padded, |
| 6308 | base_q_idx, |
| 6309 | deadzone, |
| 6310 | modes, |
| 6311 | split_blocks(), |
| 6312 | (picture.width, picture.height), |
| 6313 | unspecified_color_config(), fctx, |
| 6314 | )?; |
| 6315 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 6316 | } |
| 6317 | |
| 6318 | /// [`encode_key_frame_with_modes`] with the partition decision forced, which is |
| 6319 | /// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is |
| 6320 | /// already padded to a whole number of 32x32 blocks; `render` is the real |
| 6321 | /// (pre-pad) size the frame header tells a decoder to crop back to. |
| 6322 | pub(crate) fn encode_key_frame_inner( |
| 6323 | picture: &Picture, |
| 6324 | base_q_idx: u8, |
| 6325 | deadzone: f64, |
| 6326 | modes: &[u8], |
| 6327 | split_blocks: bool, |
| 6328 | render: (usize, usize), |
| 6329 | color_config: ColorConfig, fctx: &crate::decode::FrameCtx, |
| 6330 | ) -> Result<Encoded> { |
| 6331 | picture.check()?; |
| 6332 | if modes.is_empty() { |
| 6333 | return Err(Error::unsupported( |
| 6334 | "AV1 encode", |
| 6335 | "a mode search needs at least one mode to choose from", |
| 6336 | )); |
| 6337 | } |
| 6338 | if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { |
| 6339 | return Err(Error::unsupported( |
| 6340 | "AV1 encode", |
| 6341 | format!("intra mode {bad} is not one the encoder predicts"), |
| 6342 | )); |
| 6343 | } |
| 6344 | // The header carries the frame's true (unpadded) size as `frame_width`/ |
| 6345 | // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/ |
| 6346 | // `mi_rows` derived from that same true size (spec `compute_image_size`). |
| 6347 | // `render_width`/`render_height` come out equal to it too, so |
| 6348 | // `render_and_frame_size_different` is false and no render_size bits are |
| 6349 | // written, mirroring libaom/rav1e: the padded `picture` below is only the |
| 6350 | // internal coding surface, never what the header names. |
| 6351 | // Screen-content detection runs on the SOURCE luma, before any header is |
| 6352 | // built: it decides this sequence's `seq_force_screen_content_tools` (and |
| 6353 | // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as |
| 6354 | // this frame's own `allow_screen_content_tools`. |
| 6355 | let screen = screen_content( |
| 6356 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 6357 | picture.width, |
| 6358 | (picture.width).min(render.0), |
| 6359 | (picture.height).min(render.1), |
| 6360 | ); |
| 6361 | arm_seq_screen(screen); |
| 6362 | // A key frame's writer really does start from the defaults, and a search |
| 6363 | // worker may be carrying an inter frame's armed tables (lane-av1txbits): |
| 6364 | // disarm, or a key frame's bits would depend on which thread searched it. |
| 6365 | crate::tile::arm_pricing_cdfs(None, false); |
| 6366 | // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit |
| 6367 | // forces deblocking, CDEF and loop restoration OFF for this frame |
| 6368 | // (frame.rs:194/210/252/272), so it is only set when the source repeats |
| 6369 | // itself enough for the copied blocks to pay that back |
| 6370 | // ([`intrabc_worth_it`]). |
| 6371 | // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi |
| 6372 | // grid across every tile while this writer builds one per tile, so a |
| 6373 | // multi-tile allow_intrabc frame would predict its DVs off a different |
| 6374 | // grid than the decoder does. corner-cut, ceiling named: the upgrade |
| 6375 | // path is a frame-scoped grid shared by the tile writers. |
| 6376 | let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) { |
| 6377 | intrabc_worth_it( |
| 6378 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 6379 | picture.width, |
| 6380 | picture.width.min(render.0), |
| 6381 | picture.height.min(render.1), |
| 6382 | ) |
| 6383 | } else { |
| 6384 | (false, 0.0) |
| 6385 | }; |
| 6386 | IBC_SHARE.with(|c| c.set(ibc_share)); |
| 6387 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 6388 | header.allow_screen_content_tools = screen; |
| 6389 | header.allow_intrabc = allow_intrabc; |
| 6390 | header.render_width = render.0 as u32; |
| 6391 | header.render_height = render.1 as u32; |
| 6392 | // `TxMode::Select`: every block codes a `tx_depth` symbol and may split |
| 6393 | // its luma transform below its own side (`crate::tile::write_luma_select`). |
| 6394 | // Set here rather than in `key_frame_headers_colour` so the header |
| 6395 | // builders' other callers -- the hand-built tile writers, which code no |
| 6396 | // depth symbol -- keep the `TxMode::Largest` stream they are written for. |
| 6397 | let tx_select = tx_select(); |
| 6398 | if tx_select { |
| 6399 | header.tx_mode = TxMode::Select; |
| 6400 | } |
| 6401 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 6402 | |
| 6403 | // Prediction reads no further than this, in each plane's own units -- |
| 6404 | // see `Plane::true_width`/`true_height`. |
| 6405 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 6406 | // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's |
| 6407 | // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by |
| 6408 | // design (see `intra_predict_u8`'s doc comment), so narrow the source |
| 6409 | // once here. |
| 6410 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 6411 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 6412 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 6413 | let mut luma = Plane { |
| 6414 | source: &picture_y8, |
| 6415 | reconstruction: vec![128; picture_y8.len()], |
| 6416 | width: picture.width, |
| 6417 | height: picture.height, |
| 6418 | true_width, |
| 6419 | true_height, |
| 6420 | tile_x0: 0, |
| 6421 | tile_y0: 0, |
| 6422 | tile_x1: picture.width, |
| 6423 | tile_y1: picture.height, |
| 6424 | ctx: CoefCtxMap::default(), |
| 6425 | }; |
| 6426 | let mut chroma = [ |
| 6427 | Plane { |
| 6428 | source: &picture_u8, |
| 6429 | reconstruction: vec![128; picture_u8.len()], |
| 6430 | width: picture.width / 2, |
| 6431 | height: picture.height / 2, |
| 6432 | true_width: true_width / 2, |
| 6433 | true_height: true_height / 2, |
| 6434 | tile_x0: 0, |
| 6435 | tile_y0: 0, |
| 6436 | tile_x1: picture.width / 2, |
| 6437 | tile_y1: picture.height / 2, |
| 6438 | ctx: CoefCtxMap::default(), |
| 6439 | }, |
| 6440 | Plane { |
| 6441 | source: &picture_v8, |
| 6442 | reconstruction: vec![128; picture_v8.len()], |
| 6443 | width: picture.width / 2, |
| 6444 | height: picture.height / 2, |
| 6445 | true_width: true_width / 2, |
| 6446 | true_height: true_height / 2, |
| 6447 | tile_x0: 0, |
| 6448 | tile_y0: 0, |
| 6449 | tile_x1: picture.width / 2, |
| 6450 | tile_y1: picture.height / 2, |
| 6451 | ctx: CoefCtxMap::default(), |
| 6452 | }, |
| 6453 | ]; |
| 6454 | |
| 6455 | // The search trades a bit for the squared error it saves, in the units the |
| 6456 | // reconstruction is measured in: one step of the quantizer, squared. |
| 6457 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 6458 | let search = Search { |
| 6459 | base_q_idx, |
| 6460 | deadzone, |
| 6461 | lambda: lambda_scale() * key_lambda_factor() * step * step, |
| 6462 | modes, |
| 6463 | top_k: prune_top_k(), |
| 6464 | screen, |
| 6465 | }; |
| 6466 | |
| 6467 | // The block grid this frame is coded over: [`crate::tile::block_grid`]'s |
| 6468 | // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`, |
| 6469 | // which may be fewer columns/rows than the padded picture has room for |
| 6470 | // -- a block whose origin sits past the true bound is not coded at all, |
| 6471 | // matching what a decoder derives from `frame_width`/`frame_height` and |
| 6472 | // so never visits either. |
| 6473 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 6474 | let (cols, rows) = (cols as usize, rows as usize); |
| 6475 | // The luma mode of the block above and of the block to the left, which is |
| 6476 | // what picks the CDF the next block's mode is coded against -- the same |
| 6477 | // bookkeeping the tile writer keeps, so that the search is costing the |
| 6478 | // symbol the writer will actually write. |
| 6479 | // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on, |
| 6480 | // because a 32x32 block may be split into four 16x16 ones. |
| 6481 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 6482 | // This frame's tile grid (one tile unless the facade armed more). |
| 6483 | let layout = |
| 6484 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 6485 | header.tile_info = tile_info_of(&layout, 1); |
| 6486 | // The filter search re-decodes this frame's tiles; the decoder derives |
| 6487 | // every tile's own rect from this same `tile_info` (its `mi_col_starts`/ |
| 6488 | // `mi_row_starts`), which is what makes the writer's rects and the |
| 6489 | // reader's the same rects. |
| 6490 | let header_tile_info = header.tile_info.clone(); |
| 6491 | // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not |
| 6492 | // once over the whole frame. Each tile job builds its own reconstruction |
| 6493 | // planes and its own `above_mode`/`left_mode` bands, which is also what |
| 6494 | // the tile writer reads -- a tile resets its neighbour contexts (spec |
| 6495 | // 5.11.1), so a block at a tile's left edge must cost its mode against |
| 6496 | // the default context, not against whatever the tile to its west left in |
| 6497 | // that row. At one tile the bands are the frame's, exactly as before. |
| 6498 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 6499 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 6500 | let [cb, cr] = &mut chroma; |
| 6501 | let chroma_out = [ |
| 6502 | crate::par::Shared::new(&mut cb.reconstruction), |
| 6503 | crate::par::Shared::new(&mut cr.reconstruction), |
| 6504 | ]; |
| 6505 | let search_tile = |index: usize, |
| 6506 | fctx: &crate::decode::FrameCtx| |
| 6507 | -> Result<Vec<(usize, Superblock, Vec<u8>)>> { |
| 6508 | crate::tile::arm_pricing_cdfs(None, false); |
| 6509 | let rect = layout.rect(index); |
| 6510 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 6511 | let mut chroma = [ |
| 6512 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 6513 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 6514 | ]; |
| 6515 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 6516 | let mut above_mode = vec![DC_PRED; cols * 2]; |
| 6517 | let mut left_mode = vec![DC_PRED; rows * 2]; |
| 6518 | let mut ibc = allow_intrabc.then(|| { |
| 6519 | Ibc::new( |
| 6520 | ( |
| 6521 | rect.mi_col0 as usize * 4, |
| 6522 | rect.mi_row0 as usize * 4, |
| 6523 | (rect.mi_col1 as usize * 4).min(true_width), |
| 6524 | (rect.mi_row1 as usize * 4).min(true_height), |
| 6525 | ), |
| 6526 | &picture_y8, |
| 6527 | frame_width, |
| 6528 | ) |
| 6529 | }); |
| 6530 | let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new(); |
| 6531 | for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 6532 | for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 6533 | let mut modes = Vec::with_capacity(4); |
| 6534 | // The quadrants of a superblock are coded in the order the decoder |
| 6535 | // walks them, which for a 64x64 split into 32x32 blocks is raster |
| 6536 | // order among the quadrants that are inside the frame. |
| 6537 | let mut blocks = Vec::with_capacity(4); |
| 6538 | for quadrant in 0..4 { |
| 6539 | let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); |
| 6540 | if col >= cols || row >= rows { |
| 6541 | continue; |
| 6542 | } |
| 6543 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 6544 | let (c0, r0) = (col * 2, row * 2); |
| 6545 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 6546 | |
| 6547 | // spec `decode_partition`'s hasRows/hasCols recomputed at this |
| 6548 | // 32x32 block's own half (see `crate::tile::has_half`): the |
| 6549 | // true frame edge can fall inside a quadrant a superblock-level |
| 6550 | // check already let through. A quadrant that fails either may |
| 6551 | // not be left whole; a 16x16 sub-block that fails either (once |
| 6552 | // split) is a leaf this writer has no rectangular transform |
| 6553 | // for, so the search must not pick a split that would need one. |
| 6554 | let (has_cols32, has_rows32) = ( |
| 6555 | crate::tile::has_half( |
| 6556 | col as u32 * crate::tile::BLOCK_MI, |
| 6557 | crate::tile::BLOCK_MI, |
| 6558 | header.mi_cols, |
| 6559 | ), |
| 6560 | crate::tile::has_half( |
| 6561 | row as u32 * crate::tile::BLOCK_MI, |
| 6562 | crate::tile::BLOCK_MI, |
| 6563 | header.mi_rows, |
| 6564 | ), |
| 6565 | ); |
| 6566 | let whole_legal = has_cols32 && has_rows32; |
| 6567 | // A 16x16 sub-block's own hasCols/hasRows (spec |
| 6568 | // `decode_partition`, recomputed at this leaf's own half): |
| 6569 | // either axis false is a straddling leaf this writer codes as |
| 6570 | // the 8x8 leaves that are inside it |
| 6571 | // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes |
| 6572 | // false is the same split with the partition symbol inferred |
| 6573 | // rather than coded -- no rectangular transform is needed |
| 6574 | // (lane-av1rect). |
| 6575 | let sub_half = |sr: usize, sc: usize| { |
| 6576 | ( |
| 6577 | crate::tile::has_half( |
| 6578 | sc as u32 * crate::tile::SUB_MI, |
| 6579 | crate::tile::SUB_MI, |
| 6580 | header.mi_cols, |
| 6581 | ), |
| 6582 | crate::tile::has_half( |
| 6583 | sr as u32 * crate::tile::SUB_MI, |
| 6584 | crate::tile::SUB_MI, |
| 6585 | header.mi_rows, |
| 6586 | ), |
| 6587 | ) |
| 6588 | }; |
| 6589 | // What the whole 32x32 costs, including the partition symbol |
| 6590 | // that says it is not split. |
| 6591 | let (whole, mut cost_whole) = code_square( |
| 6592 | &mut luma, |
| 6593 | &mut chroma, |
| 6594 | (x, y), |
| 6595 | BLOCK, |
| 6596 | &search, |
| 6597 | &mode_bits(above_mode[c0], left_mode[r0]), |
| 6598 | tx_select, |
| 6599 | ibc.as_mut(), fctx, |
| 6600 | ); |
| 6601 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 6602 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 6603 | |
| 6604 | // What four 16x16 blocks cost instead, each searched against |
| 6605 | // the reconstruction the ones before it left. |
| 6606 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 6607 | let mut split = Vec::with_capacity(4); |
| 6608 | let mut cost_split = search.lambda |
| 6609 | * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); |
| 6610 | let mut split_modes = Vec::with_capacity(4); |
| 6611 | for sub in 0..4 { |
| 6612 | let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); |
| 6613 | // Same filter as the writer's `sub_positions` (spec |
| 6614 | // `decode_partition`'s `r >= MiRows || c >= MiCols` early |
| 6615 | // return): a sub-block whose own origin sits past the |
| 6616 | // true frame is never coded, so it must not be searched |
| 6617 | // or pushed onto `split` either, or the writer's block |
| 6618 | // count will not match what it is prepared to name. |
| 6619 | if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows |
| 6620 | || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols |
| 6621 | { |
| 6622 | continue; |
| 6623 | } |
| 6624 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 6625 | if has_cols16 && has_rows16 { |
| 6626 | let (block, cost) = code_square( |
| 6627 | &mut luma, |
| 6628 | &mut chroma, |
| 6629 | (x + (sub % 2) * SUB, y + (sub / 2) * SUB), |
| 6630 | SUB, |
| 6631 | &search, |
| 6632 | &mode_bits(above_mode[sc], left_mode[sr]), |
| 6633 | tx_select, |
| 6634 | ibc.as_mut(), fctx, |
| 6635 | ); |
| 6636 | cost_split += cost; |
| 6637 | split_modes.push(block.mode); |
| 6638 | above_mode[sc] = block.mode; |
| 6639 | left_mode[sr] = block.mode; |
| 6640 | split.push(block); |
| 6641 | } else { |
| 6642 | // A straddling 16x16: two (or, at a true corner, one) |
| 6643 | // 8x8 leaves, in the raster order `write_leaf8`'s |
| 6644 | // caller expects. Both leaves cost against the SAME |
| 6645 | // enclosing-slot mode context (see |
| 6646 | // `crate::tile::write_leaf8`'s doc), and neither |
| 6647 | // updates `above_mode`/`left_mode` at this SUB slot -- |
| 6648 | // the writer never does either, so the search must |
| 6649 | // not diverge from what it will actually read next. |
| 6650 | let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); |
| 6651 | let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); |
| 6652 | let mut leaves = Vec::with_capacity(2); |
| 6653 | for i in 0..4 { |
| 6654 | let leaf_x = x_sub + (i % 2) * 8; |
| 6655 | let leaf_y = y_sub + (i / 2) * 8; |
| 6656 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 6657 | continue; |
| 6658 | } |
| 6659 | let (leaf, cost) = code_square( |
| 6660 | &mut luma, |
| 6661 | &mut chroma, |
| 6662 | (leaf_x, leaf_y), |
| 6663 | 8, |
| 6664 | &search, |
| 6665 | &leaf_mode_bits, |
| 6666 | tx_select, |
| 6667 | None, fctx, |
| 6668 | ); |
| 6669 | cost_split += cost; |
| 6670 | split_modes.push(leaf.mode); |
| 6671 | leaves.push(leaf); |
| 6672 | } |
| 6673 | split.push(BlockCoeffs { |
| 6674 | eight: Some(leaves), |
| 6675 | ..BlockCoeffs::default() |
| 6676 | }); |
| 6677 | } |
| 6678 | } |
| 6679 | |
| 6680 | // A split whose subs are all whole 16x16 is a real quality |
| 6681 | // alternative to `whole`, exactly as before. Through r14, a |
| 6682 | // split carrying an 8x8-leaf sub was only ever forced |
| 6683 | // (`!whole_legal`), never chosen on cost, because the leaf |
| 6684 | // path was not yet proven against a real decoder; r15 proved |
| 6685 | // it against ffmpeg, and lane-av1dec r5 taught crate::decode |
| 6686 | // the read path (`decode_leaf8`), so leaf8 can now win on |
| 6687 | // cost anywhere, same as any other split. |
| 6688 | if !whole_legal || (split_blocks && cost_split < cost_whole) { |
| 6689 | modes.extend_from_slice(&split_modes); |
| 6690 | blocks.push(Quadrant::Split(split)); |
| 6691 | } else { |
| 6692 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 6693 | for cell in 0..2 { |
| 6694 | above_mode[c0 + cell] = whole.mode; |
| 6695 | left_mode[r0 + cell] = whole.mode; |
| 6696 | } |
| 6697 | modes.push(whole.mode); |
| 6698 | blocks.push(Quadrant::Whole(whole)); |
| 6699 | } |
| 6700 | } |
| 6701 | coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes)); |
| 6702 | } |
| 6703 | } |
| 6704 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 6705 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 6706 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 6707 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 6708 | copy_rect( |
| 6709 | out, |
| 6710 | &tile.reconstruction, |
| 6711 | frame_width / 2, |
| 6712 | x0 / 2, |
| 6713 | y0 / 2, |
| 6714 | x1.div_ceil(2), |
| 6715 | y1.div_ceil(2), |
| 6716 | ); |
| 6717 | } |
| 6718 | Ok(coded) |
| 6719 | }; |
| 6720 | let searched = search_tiles(layout.count(), fctx, search_tile)?; |
| 6721 | // Back into frame raster order: the tile writer indexes `superblocks` by |
| 6722 | // the frame's own superblock index, and `modes` is the coding order the |
| 6723 | // ablation drivers read. |
| 6724 | let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect(); |
| 6725 | for (at, superblock, block_modes) in searched.into_iter().flatten() { |
| 6726 | in_order[at] = Some((superblock, block_modes)); |
| 6727 | } |
| 6728 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 6729 | let mut modes = Vec::with_capacity(cols * rows); |
| 6730 | for slot in in_order { |
| 6731 | let (superblock, block_modes) = slot.expect("every superblock belongs to a tile"); |
| 6732 | superblocks.push(superblock); |
| 6733 | modes.extend_from_slice(&block_modes); |
| 6734 | } |
| 6735 | |
| 6736 | #[cfg(test)] |
| 6737 | record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); |
| 6738 | // A key frame always starts from the defaults (`primary_ref_frame` is |
| 6739 | // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf` |
| 6740 | // set, so what it stores into the slots it refreshes is exactly those |
| 6741 | // defaults again (spec 7.20's `started_from` arm) -- the first inter |
| 6742 | // frame after it therefore starts from the defaults too. |
| 6743 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 6744 | let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); |
| 6745 | let start_cdfs = CdfSnapshot(cdfs); |
| 6746 | // The luma restoration-unit grid this frame's `lr_params` implies |
| 6747 | // (`av1_lr_count_units` rounds to nearest, so a short last unit is |
| 6748 | // swallowed by the one before it), for the tile writer's own per-unit |
| 6749 | // walk. |
| 6750 | let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; |
| 6751 | let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; |
| 6752 | // Every tile is coded from this frame's OWN starting tables and leaves |
| 6753 | // its own end state behind (spec 5.11.1: each tile resets the CDFs, the |
| 6754 | // loop-restoration reference and its neighbour contexts), so the tiles |
| 6755 | // are independent of each other and of the order they are written in. |
| 6756 | let code_tiles = |bits: u8, |
| 6757 | sb_cols: usize, |
| 6758 | grid: &[u8], |
| 6759 | units: &[Option<crate::restoration::WienerInfo>]| |
| 6760 | -> Result<Vec<Vec<u8>>> { |
| 6761 | let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { |
| 6762 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 6763 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 6764 | let mut cdfs = start_cdfs.0.clone(); |
| 6765 | crate::tile::arm_screen(screen); |
| 6766 | crate::tile::arm_filter_intra(filter_intra_on()); |
| 6767 | crate::tile::arm_intrabc(allow_intrabc); |
| 6768 | crate::tile::arm_pricing_cdfs(None, false); |
| 6769 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 6770 | mi_cols, |
| 6771 | mi_rows, |
| 6772 | base_q_idx, |
| 6773 | &superblocks, |
| 6774 | tx_select, |
| 6775 | &mut cdfs, |
| 6776 | layout.rect(index), |
| 6777 | )?; |
| 6778 | Ok((bytes, None)) |
| 6779 | })?; |
| 6780 | Ok(out) |
| 6781 | }; |
| 6782 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 6783 | // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing |
| 6784 | // the tile just coded back to the decoder under each candidate (see |
| 6785 | // `crate::filter_search`), and keep the filtered picture that wins as |
| 6786 | // the reconstruction -- what a decoder outputs, and what the next |
| 6787 | // frame predicts from. |
| 6788 | pick_and_apply_filters( |
| 6789 | &mut header, |
| 6790 | &mut luma, |
| 6791 | &mut chroma, |
| 6792 | [&picture_y8, &picture_u8, &picture_v8], |
| 6793 | // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF |
| 6794 | // and loop restoration off and codes none of their parameters |
| 6795 | // (frame.rs:194/210/252/272) -- there is no filter to search for, and |
| 6796 | // the encoder's reconstruction is already what a decoder produces. |
| 6797 | !allow_intrabc, |
| 6798 | &mut tiles, |
| 6799 | search.lambda, |
| 6800 | fctx, |
| 6801 | // Every re-code starts from this frame's OWN starting tables, never |
| 6802 | // from where the first write left them: the second tile is the same |
| 6803 | // symbol sequence plus new ones, so it must adapt from the same |
| 6804 | // point the decoder will. |
| 6805 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 6806 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 6807 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 6808 | crate::decode::decode_key_frame_tiles_lr( |
| 6809 | &payloads, |
| 6810 | &header_tile_info, |
| 6811 | h.mi_cols, |
| 6812 | h.mi_rows, |
| 6813 | base_q_idx, |
| 6814 | h.frame_width, |
| 6815 | h.frame_height, |
| 6816 | seq.enable_filter_intra, |
| 6817 | cdef, |
| 6818 | lf, |
| 6819 | tx_select, |
| 6820 | h.reduced_tx_set, |
| 6821 | h.allow_screen_content_tools, |
| 6822 | h.allow_intrabc, |
| 6823 | lr, |
| 6824 | fctx, |
| 6825 | ) |
| 6826 | }, |
| 6827 | )?; |
| 6828 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 6829 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 6830 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 6831 | let mut stream = temporal_delimiter(); |
| 6832 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 6833 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 6834 | |
| 6835 | let [u, v] = chroma; |
| 6836 | Ok(Encoded { |
| 6837 | stream, |
| 6838 | modes, |
| 6839 | inter_block_share: 0.0, |
| 6840 | reconstruction: Picture { |
| 6841 | width: luma.width, |
| 6842 | height: luma.height, |
| 6843 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6844 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6845 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6846 | }, |
| 6847 | tile, |
| 6848 | mi_cols: header.mi_cols, |
| 6849 | mi_rows: header.mi_rows, |
| 6850 | base_q_idx, |
| 6851 | tx_select, |
| 6852 | // A key frame codes no inter block, so no motion_mode symbol. |
| 6853 | switchable_motion_mode: false, |
| 6854 | screen, |
| 6855 | next_cdfs: start_cdfs.clone(), |
| 6856 | start_cdfs, |
| 6857 | loop_filter: header.loop_filter, |
| 6858 | cdef: header.cdef, |
| 6859 | loop_restoration: header.loop_restoration, |
| 6860 | allow_intrabc, |
| 6861 | }) |
| 6862 | } |
| 6863 | |
| 6864 | /// Chooses this frame's deblocking levels and CDEF strengths, writes them |
| 6865 | /// into `header` and |
| 6866 | /// replaces the frame's own region of the encoder's reconstruction with the |
| 6867 | /// filtered picture the decoder produced under them |
| 6868 | /// ([`crate::filter_search::pick_deblock`]). |
| 6869 | /// |
| 6870 | /// `search == false` leaves the header at level 0 (deblocking off) and the |
| 6871 | /// reconstruction untouched: the caller's stream is one this crate's own |
| 6872 | /// decoder cannot read back, so there is nothing to search against. |
| 6873 | /// |
| 6874 | /// # Errors |
| 6875 | /// The decoder's own error, when it refuses the tile the encoder just wrote |
| 6876 | /// -- that is an encoder defect, not a filter one, so it is propagated |
| 6877 | /// rather than swallowed into "no deblocking". |
| 6878 | fn pick_and_apply_filters( |
| 6879 | header: &mut FrameHeader, |
| 6880 | luma: &mut Plane<'_>, |
| 6881 | chroma: &mut [Plane<'_>; 2], |
| 6882 | source: [&[u8]; 3], |
| 6883 | search: bool, |
| 6884 | // The coded tiles, one payload per tile of the frame's grid, replaced in |
| 6885 | // place when the search chooses a per-64x64 `cdef_idx` list |
| 6886 | // (`cdef_bits > 0`): those literals live in the tile payloads, so every |
| 6887 | // tile is written a second time under `recode` and the winner |
| 6888 | // re-decoded from them. |
| 6889 | tiles: &mut Vec<Vec<u8>>, |
| 6890 | lambda: f64, |
| 6891 | fctx: &crate::decode::FrameCtx, |
| 6892 | recode: impl Fn( |
| 6893 | u8, |
| 6894 | usize, |
| 6895 | &[u8], |
| 6896 | &[Option<crate::restoration::WienerInfo>], |
| 6897 | ) -> Result<Vec<Vec<u8>>>, |
| 6898 | decode: impl Fn( |
| 6899 | &LoopFilterParams, |
| 6900 | &CdefParams, |
| 6901 | &FrameHeader, |
| 6902 | &[Vec<u8>], |
| 6903 | &LoopRestorationParams, |
| 6904 | ) -> Result<Picture>, |
| 6905 | ) -> Result<()> { |
| 6906 | if !search { |
| 6907 | return Ok(()); |
| 6908 | } |
| 6909 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 6910 | let hdr = header.clone(); |
| 6911 | // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: |
| 6912 | // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. |
| 6913 | let damping = 3 + (header.quantization.base_q_idx >> 6); |
| 6914 | let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 6915 | let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); |
| 6916 | let none_lr = LoopRestorationParams::default(); |
| 6917 | // Every candidate scores the same coded tile: decode it once and re-run |
| 6918 | // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of |
| 6919 | // the encoder's profile before this). The per-64x64 error the CDEF |
| 6920 | // preset search reads comes off the REPLAYED picture, which is the same |
| 6921 | // picture a decode produces -- that is what the replay is pinned on. |
| 6922 | crate::decode::clear_filter_replay(); |
| 6923 | // lane-av1fpar: the per-tile search is over, so every core is idle from |
| 6924 | // here to the end of the frame -- band each candidate's deblock/CDEF |
| 6925 | // replay, the capture decode's own filter chain and the loop-restoration |
| 6926 | // passes across the same workers the search used. |
| 6927 | let _bands = crate::par::override_filter_threads(crate::par::tile_threads()); |
| 6928 | let ft = crate::par::timer(crate::par::S_FILTER); |
| 6929 | let search_result = crate::filter_search::pick_filters( |
| 6930 | |lf, cdef| { |
| 6931 | if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { |
| 6932 | return Ok(picture); |
| 6933 | } |
| 6934 | crate::decode::arm_filter_replay(); |
| 6935 | let _t = crate::par::timer(crate::par::S_FIRST); |
| 6936 | decode(lf, cdef, &hdr, tiles, &none_lr) |
| 6937 | }, |
| 6938 | source, |
| 6939 | luma.width, |
| 6940 | (fw, fh), |
| 6941 | damping, |
| 6942 | (sb_cols, sb_rows), |
| 6943 | lambda, |
| 6944 | ); |
| 6945 | drop(ft); |
| 6946 | let (lf, cdef, idx_grid, picture) = search_result?; |
| 6947 | header.loop_filter = lf; |
| 6948 | header.cdef = cdef; |
| 6949 | // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not |
| 6950 | // in the frame header, so a re-decode under candidate parameters cannot |
| 6951 | // search them the way deblocking and CDEF are searched above. What the |
| 6952 | // decoder hands back instead is its own filter chain's intermediates |
| 6953 | // (`crate::decode::FrameCtx::capture_stages`), and the search runs on |
| 6954 | // those, through the decoder's own Wiener kernel. |
| 6955 | // |
| 6956 | // The capture rides the decode this stage was already going to do: the |
| 6957 | // re-decode of the `cdef_idx` tile when there is one, and otherwise one |
| 6958 | // decode of the tile as it stands. That decode's header still says |
| 6959 | // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the |
| 6960 | // post-CDEF picture stands in for it at LR's 3-row stripe borders -- |
| 6961 | // an approximation inside the SEARCH only; the reconstruction this |
| 6962 | // function ends up splicing is always a real decode of the real tile. |
| 6963 | let lr_on = restoration_enabled(); |
| 6964 | // The `cdef_idx` literals live in the tile payload, so a frame that |
| 6965 | // chose a per-64x64 preset list codes its tiles a second time. |
| 6966 | if !idx_grid.is_empty() { |
| 6967 | *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?; |
| 6968 | } |
| 6969 | // lane-av1cap: that re-coded tile used to be DECODED here as well -- |
| 6970 | // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop |
| 6971 | // restoration search reads (`crate::decode::FrameCtx::capture_stages`) |
| 6972 | // and the picture this function splices. Both come out of ONE more |
| 6973 | // replay of the winning parameters on the same captured pre-filter |
| 6974 | // planes every candidate was scored on: the same two filter kernels, on |
| 6975 | // the same input, in the same order, so the same bytes. Re-coding the |
| 6976 | // tile does not move the reconstruction the replay holds -- `cdef_idx` |
| 6977 | // is an equiprobable literal, so it adapts no CDF and changes no |
| 6978 | // residual. |
| 6979 | let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx); |
| 6980 | #[cfg(test)] |
| 6981 | let replay_was_used = replayed.is_some(); |
| 6982 | let (mut filtered, mut stages) = match replayed { |
| 6983 | Some((picture, stages)) => (picture, stages), |
| 6984 | // Nothing captured (the shapes [`crate::decode::FilterReplay`] |
| 6985 | // refuses): every candidate was a full decode, so the winner's own |
| 6986 | // picture stands, and the stages still need a capturing decode. |
| 6987 | None => { |
| 6988 | fctx.capture_stages.set(lr_on); |
| 6989 | let picture = if idx_grid.is_empty() && !lr_on { |
| 6990 | picture |
| 6991 | } else { |
| 6992 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 6993 | decode(&lf, &cdef, &hdr, tiles, &none_lr)? |
| 6994 | }; |
| 6995 | fctx.capture_stages.set(false); |
| 6996 | (picture, crate::decode::take_filter_stages(fctx)) |
| 6997 | } |
| 6998 | }; |
| 6999 | #[cfg(test)] |
| 7000 | if crate::decode::verify_final_replay() && replay_was_used { |
| 7001 | fctx.capture_stages.set(lr_on); |
| 7002 | let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?; |
| 7003 | fctx.capture_stages.set(false); |
| 7004 | let want_stages = crate::decode::take_filter_stages(fctx); |
| 7005 | assert!( |
| 7006 | (want.width, want.height) == (filtered.width, filtered.height) |
| 7007 | && want.y == filtered.y |
| 7008 | && want.u == filtered.u |
| 7009 | && want.v == filtered.v, |
| 7010 | "the final filter replay is not the capture decode it stands in for", |
| 7011 | ); |
| 7012 | // Only the frame's own cropped region: the plane is padded to the |
| 7013 | // superblock grid and the columns past the mi extent are written by |
| 7014 | // nothing (the decoder's plane pool leaves whatever the last frame |
| 7015 | // put there), while the restoration search reads strictly inside |
| 7016 | // `fw x fh` -- `restoration::lr_sample` clamps its column to |
| 7017 | // `plane_w - 1` and its row to the frame's, and |
| 7018 | // `filter_search::pick_restoration`'s own SSE walk never leaves the |
| 7019 | // crop either. |
| 7020 | let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| { |
| 7021 | for row in 0..h { |
| 7022 | let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]); |
| 7023 | assert!( |
| 7024 | x == y, |
| 7025 | "{what}: the replayed filter stages are not the ones the capture \ |
| 7026 | decode returns (row {row} of {h}, width {w}, stride {stride})", |
| 7027 | ); |
| 7028 | } |
| 7029 | }; |
| 7030 | match (&want_stages, &stages) { |
| 7031 | (Some(a), Some(b)) => { |
| 7032 | assert_eq!(a.stride, b.stride, "the captured plane strides moved"); |
| 7033 | let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); |
| 7034 | for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() { |
| 7035 | region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked"); |
| 7036 | region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed"); |
| 7037 | } |
| 7038 | } |
| 7039 | (None, None) => {} |
| 7040 | _ => panic!("one path captured filter stages and the other did not"), |
| 7041 | } |
| 7042 | } |
| 7043 | // lane-av1cap2: the capture stays live past the restoration search -- |
| 7044 | // `crate::decode::replay_restoration` filters the same post-CDEF plane |
| 7045 | // rather than decoding the re-coded tile. Cleared at the end instead. |
| 7046 | let mut lr = LoopRestorationParams::default(); |
| 7047 | if lr_on { |
| 7048 | let mut want = LoopRestorationParams { |
| 7049 | loop_restoration_size: [64, 64, 64], |
| 7050 | uses_lr: true, |
| 7051 | ..LoopRestorationParams::default() |
| 7052 | }; |
| 7053 | want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; |
| 7054 | let lrt = crate::par::timer(crate::par::S_LR); |
| 7055 | let units = match stages.take() { |
| 7056 | Some(stages) => crate::filter_search::pick_restoration( |
| 7057 | &stages, |
| 7058 | source[0], |
| 7059 | luma.width, |
| 7060 | (fw, fh), |
| 7061 | &want, |
| 7062 | lambda, |
| 7063 | fctx, |
| 7064 | ), |
| 7065 | None => Vec::new(), |
| 7066 | }; |
| 7067 | // A frame no unit restores keeps `RESTORE_NONE` on every plane |
| 7068 | // rather than paying ~1 bit per 64x64 for a tile full of |
| 7069 | // `restore_wiener = 0` symbols (the BD gate saw exactly that on the |
| 7070 | // clip whose units never take a filter). |
| 7071 | drop(lrt); |
| 7072 | if units.iter().any(Option::is_some) { |
| 7073 | let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; |
| 7074 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 7075 | // lane-av1cap2: that re-coded tile used to be DECODED here to |
| 7076 | // reach the restored reference frame -- 5.6% of a 4K frame, |
| 7077 | // for a filter that reads nothing of the tile but the per-unit |
| 7078 | // Wiener filters this stage just chose. Run the decoder's own |
| 7079 | // restoration kernel on the replay's post-CDEF plane instead |
| 7080 | // (`crate::decode::replay_restoration`), with the real |
| 7081 | // post-deblock stripe borders. |
| 7082 | match crate::decode::replay_restoration(&want, &units, fctx) { |
| 7083 | Some(y) => { |
| 7084 | #[cfg(test)] |
| 7085 | let margin = fctx |
| 7086 | .last_frame_wide_margin |
| 7087 | .with(|m| m.borrow().as_ref().map(|p| p.y.clone())); |
| 7088 | #[cfg(test)] |
| 7089 | if crate::decode::verify_final_replay() { |
| 7090 | let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?; |
| 7091 | assert!( |
| 7092 | (want_pic.width, want_pic.height) == (filtered.width, filtered.height) |
| 7093 | && want_pic.u == filtered.u |
| 7094 | && want_pic.v == filtered.v, |
| 7095 | "the restoration replay moved a chroma plane or the picture size", |
| 7096 | ); |
| 7097 | assert!( |
| 7098 | want_pic.y == y, |
| 7099 | "the restoration replay is not the decode of the re-coded tile", |
| 7100 | ); |
| 7101 | assert!( |
| 7102 | fctx.last_frame_wide_margin |
| 7103 | .with(|m| m.borrow().as_ref().map(|p| p.y.clone())) |
| 7104 | == margin, |
| 7105 | "the restoration replay's wide-margin luma is not the decode's", |
| 7106 | ); |
| 7107 | } |
| 7108 | filtered.y = y; |
| 7109 | } |
| 7110 | // Nothing captured: the winner came out of a full decode, |
| 7111 | // so this one does too. |
| 7112 | None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?, |
| 7113 | } |
| 7114 | *tiles = coded; |
| 7115 | lr = want; |
| 7116 | } |
| 7117 | } |
| 7118 | crate::decode::clear_filter_replay(); |
| 7119 | header.loop_restoration = lr; |
| 7120 | let dec_cw = filtered.width.div_ceil(2); |
| 7121 | let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); |
| 7122 | crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); |
| 7123 | crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch); |
| 7124 | crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch); |
| 7125 | Ok(()) |
| 7126 | } |
| 7127 | |
| 7128 | /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only |
| 7129 | /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`), |
| 7130 | /// since every block this crate's inter tile writer codes is 32x32. |
| 7131 | const SIZE_GROUP_32: usize = 3; |
| 7132 | |
| 7133 | /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference |
| 7134 | /// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV |
| 7135 | /// stack this encoder builds is ever asked to predict against. |
| 7136 | const LAST_FRAME: i8 = 1; |
| 7137 | |
| 7138 | /// What an inter frame's intra branch spends to name each of the thirteen |
| 7139 | /// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour |
| 7140 | /// context, since an inter frame's intra blocks do not read their |
| 7141 | /// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s |
| 7142 | /// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour |
| 7143 | /// state, so it is built once per frame. |
| 7144 | fn inter_mode_bits() -> [f64; 13] { |
| 7145 | std::array::from_fn(|mode| { |
| 7146 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 7147 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 7148 | } else { |
| 7149 | 0.0 |
| 7150 | }; |
| 7151 | symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) |
| 7152 | + angle |
| 7153 | + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 7154 | }) |
| 7155 | } |
| 7156 | |
| 7157 | /// A 1/8-pel motion vector component, converted to the 1/16-pel offset |
| 7158 | /// [`mc::predict`] takes, in the units of the plane it predicts into. |
| 7159 | /// |
| 7160 | /// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is |
| 7161 | /// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same |
| 7162 | /// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel |
| 7163 | /// domain. `luma` picks which. |
| 7164 | fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { |
| 7165 | (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } |
| 7166 | } |
| 7167 | |
| 7168 | /// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to |
| 7169 | /// that module): the magnitude an `MV_CLASS_n` component's own bits start |
| 7170 | /// counting from. |
| 7171 | fn mv_class_base(class: usize) -> i32 { |
| 7172 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 7173 | } |
| 7174 | |
| 7175 | /// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring |
| 7176 | /// `tile::mv_class_of`. |
| 7177 | fn mv_class_of(z: i32) -> usize { |
| 7178 | let mut class = 0; |
| 7179 | while class < 10 && mv_class_base(class + 1) <= z { |
| 7180 | class += 1; |
| 7181 | } |
| 7182 | class |
| 7183 | } |
| 7184 | |
| 7185 | /// What [`crate::tile::write_mv_component`] (private to that module) would |
| 7186 | /// spend coding one non-zero motion vector component, against the same |
| 7187 | /// static default CDFs the writer starts a frame from — the same |
| 7188 | /// static-table approximation [`mode_bits`] costs the luma mode symbol |
| 7189 | /// through, not the tile writer's own adapting state, which this encoder has |
| 7190 | /// no way to read without duplicating it block for block. |
| 7191 | /// |
| 7192 | /// Returns `None` when `diff` needs the eighth-pel precision this crate's |
| 7193 | /// frames never carry (`allow_high_precision_mv` is always off), which is |
| 7194 | /// what [`round_to_valid_mv`] exists to avoid ever happening. |
| 7195 | fn mv_component_bits(diff: i32) -> Option<f64> { |
| 7196 | let mag = diff.unsigned_abs() as i32; |
| 7197 | let z = mag - 1; |
| 7198 | if z & 1 == 0 { |
| 7199 | return None; |
| 7200 | } |
| 7201 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 7202 | let class = mv_class_of(z); |
| 7203 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 7204 | let local = z - mv_class_base(class); |
| 7205 | if class == 0 { |
| 7206 | let bit = (local >> 3) & 1; |
| 7207 | let fr = (local >> 1) & 3; |
| 7208 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); |
| 7209 | bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); |
| 7210 | } else { |
| 7211 | let d = local >> 3; |
| 7212 | let fr = (local >> 1) & 3; |
| 7213 | for i in 0..class { |
| 7214 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 7215 | } |
| 7216 | bits += symbol_bits(&cdf::MV_FR, fr as usize); |
| 7217 | } |
| 7218 | Some(bits) |
| 7219 | } |
| 7220 | |
| 7221 | /// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its |
| 7222 | /// own -- a second motion search per block against that reference's picture, |
| 7223 | /// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it |
| 7224 | /// off in a test build (what the lane measured both arms with). |
| 7225 | fn extra_ref_new_mv() -> bool { |
| 7226 | match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() { |
| 7227 | Some(v) if cfg!(test) => v != "0", |
| 7228 | _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW), |
| 7229 | } |
| 7230 | } |
| 7231 | |
| 7232 | /// The seven `ref_frame_idx` order hints of a frame coded on this crate's own |
| 7233 | /// flat slot plan (`inter_frame_headers_slots`): every reference but |
| 7234 | /// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded, |
| 7235 | /// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the |
| 7236 | /// frame two back when there is one (otherwise it, too, names the key frame's |
| 7237 | /// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes. |
| 7238 | pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] { |
| 7239 | let last = order_hint.wrapping_sub(1) & 0x7f; |
| 7240 | let alt = if has_altref { |
| 7241 | order_hint.wrapping_sub(2) & 0x7f |
| 7242 | } else { |
| 7243 | key_hint |
| 7244 | }; |
| 7245 | [last, last, last, key_hint, last, last, alt] |
| 7246 | } |
| 7247 | |
| 7248 | /// Whether an inter frame carries `reference_select` (spec 5.9.22): the |
| 7249 | /// header bit that lets each block choose between a single and a compound |
| 7250 | /// reference. Off by default until compound prediction is measured to pay; |
| 7251 | /// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate |
| 7252 | /// runs as), and every block still codes SINGLE, so the only cost is one |
| 7253 | /// `comp_mode` symbol per inter block. |
| 7254 | pub(crate) const REFERENCE_SELECT: bool = true; |
| 7255 | |
| 7256 | /// [`REFERENCE_SELECT`], with the test-build environment override. |
| 7257 | pub(crate) fn reference_select() -> bool { |
| 7258 | match std::env::var("EC_AV1_COMPOUND").ok() { |
| 7259 | Some(v) if cfg!(test) => v != "0", |
| 7260 | _ => crate::speed::at(&crate::speed::COMPOUND), |
| 7261 | } |
| 7262 | } |
| 7263 | |
| 7264 | /// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol |
| 7265 | /// per entry past `start`, `1` to advance and `0` to stop, at most two. |
| 7266 | fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { |
| 7267 | let mut bits = 0.0; |
| 7268 | let mut idx = start; |
| 7269 | while idx < start + 2 && stack.entries.len() > idx + 1 { |
| 7270 | let advance = idx < target; |
| 7271 | bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); |
| 7272 | if !advance { |
| 7273 | break; |
| 7274 | } |
| 7275 | idx += 1; |
| 7276 | } |
| 7277 | bits |
| 7278 | } |
| 7279 | |
| 7280 | /// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off |
| 7281 | /// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10 |
| 7282 | /// `assign_mv`), so the same vector costs a different residual from each. |
| 7283 | fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { |
| 7284 | let mut best: Option<(f64, u8)> = None; |
| 7285 | for idx in 0..3usize { |
| 7286 | if idx > 0 && stack.entries.len() <= idx { |
| 7287 | break; |
| 7288 | } |
| 7289 | let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); |
| 7290 | if let Some(b) = mv_residual_bits(mv, base) { |
| 7291 | let total = b + drl_bits_for(stack, 0, idx); |
| 7292 | if best.is_none_or(|(t, _)| total < t) { |
| 7293 | best = Some((total, idx as u8)); |
| 7294 | } |
| 7295 | } |
| 7296 | } |
| 7297 | best |
| 7298 | } |
| 7299 | |
| 7300 | /// The starting points [`motion::search`] gets besides `stack.pred_mv`: the |
| 7301 | /// zero vector and the stack's own candidates. A neighbour block's vector is |
| 7302 | /// where this block's motion most often already is, which is what pays for |
| 7303 | /// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points |
| 7304 | /// vs libaom for 0.2 s off a 6 s ladder). |
| 7305 | fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { |
| 7306 | let mut seeds = [(0, 0); 4]; |
| 7307 | let mut n = 1; |
| 7308 | for e in stack.entries.iter().take(3) { |
| 7309 | seeds[n] = e.mv; |
| 7310 | n += 1; |
| 7311 | } |
| 7312 | (seeds, n) |
| 7313 | } |
| 7314 | |
| 7315 | /// What [`crate::tile::write_mv`] (private to that module) would spend |
| 7316 | /// coding `mv` as a residual against `pred`: the joint symbol naming which |
| 7317 | /// components differ, then each differing component. `None` under the same |
| 7318 | /// condition [`mv_component_bits`] returns `None`. |
| 7319 | /// How many frames back `ref_frame` sits from the frame being coded, off the |
| 7320 | /// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is |
| 7321 | /// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is |
| 7322 | /// what [`crate::motion::search`] scales its starting step by. |
| 7323 | fn ref_distance(ref_frame: i8) -> u32 { |
| 7324 | let (bits, order_hint, hints) = crate::tile::order_hints(); |
| 7325 | let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize; |
| 7326 | let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i]) |
| 7327 | .unsigned_abs() |
| 7328 | .max(1); |
| 7329 | if crate::envflags::env_flag!("EC_TRACE_DIST") { |
| 7330 | eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]); |
| 7331 | } |
| 7332 | d |
| 7333 | } |
| 7334 | |
| 7335 | fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> { |
| 7336 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 7337 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 7338 | (false, false) => 0, |
| 7339 | (false, true) => 1, |
| 7340 | (true, false) => 2, |
| 7341 | (true, true) => 3, |
| 7342 | }; |
| 7343 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint); |
| 7344 | for d in [diff.0, diff.1] { |
| 7345 | if d != 0 { |
| 7346 | bits += mv_component_bits(d)?; |
| 7347 | } |
| 7348 | } |
| 7349 | Some(bits) |
| 7350 | } |
| 7351 | |
| 7352 | /// Rounds `mv` so that its residual against `pred` is one |
| 7353 | /// [`crate::tile::write_mv_component`] can actually code: each component's |
| 7354 | /// difference is either zero or has an even magnitude (the eighth-pel bit |
| 7355 | /// `allow_high_precision_mv` off always infers as one forces the coded |
| 7356 | /// magnitude odd one step further in, which comes out even here since this |
| 7357 | /// crate's motion search works in whole units of that same step). Rounding |
| 7358 | /// down keeps every coded MV — and so every `nearest_mv` a later block's |
| 7359 | /// stack votes with — built from an even displacement from `(0, 0)`, so the |
| 7360 | /// invariant holds without this function seeing the whole stack. |
| 7361 | fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { |
| 7362 | let round = |m: i32, p: i32| { |
| 7363 | let diff = m - p; |
| 7364 | let mag = diff.unsigned_abs() as i32; |
| 7365 | let even = mag - mag % 2; |
| 7366 | if even == 0 { |
| 7367 | p |
| 7368 | } else { |
| 7369 | p + even * diff.signum() |
| 7370 | } |
| 7371 | }; |
| 7372 | (round(mv.0, pred.0), round(mv.1, pred.1)) |
| 7373 | } |
| 7374 | |
| 7375 | /// Predicts one `side`-square block by motion compensation from `reference` |
| 7376 | /// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`]. |
| 7377 | #[allow(clippy::too_many_arguments)] |
| 7378 | fn mc_trial( |
| 7379 | plane: &Plane, |
| 7380 | x: usize, |
| 7381 | y: usize, |
| 7382 | side: usize, |
| 7383 | mv: (i32, i32), |
| 7384 | luma: bool, |
| 7385 | reference: &[u16], |
| 7386 | stride: usize, |
| 7387 | ref_width: usize, |
| 7388 | ref_height: usize, |
| 7389 | skip: bool, |
| 7390 | base_q_idx: u8, |
| 7391 | deadzone: f64, |
| 7392 | set: TxbSet, fctx: &crate::decode::FrameCtx, |
| 7393 | ) -> Trial { |
| 7394 | let x_q4 = mv_to_q4(x, mv.1, luma); |
| 7395 | let y_q4 = mv_to_q4(y, mv.0, luma); |
| 7396 | // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that |
| 7397 | // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is |
| 7398 | // 8-bit only this round, see `intra_predict_u8`'s doc comment). |
| 7399 | // lane-av1speed: both buffers are per-candidate scratch on the hottest |
| 7400 | // path in the encoder, so they live on the stack -- `side` is at most |
| 7401 | // `BLOCK` (32) for luma and half that for chroma. Two heap allocations |
| 7402 | // per motion-compensated trial otherwise. |
| 7403 | let mut prediction16 = [0u16; BLOCK * BLOCK]; |
| 7404 | let prediction16 = &mut prediction16[..side * side]; |
| 7405 | mc::predict( |
| 7406 | reference, |
| 7407 | stride, |
| 7408 | ref_width, |
| 7409 | ref_height, |
| 7410 | x_q4, |
| 7411 | y_q4, |
| 7412 | side, |
| 7413 | side, |
| 7414 | prediction16, fctx, |
| 7415 | ); |
| 7416 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 7417 | let prediction = &mut prediction[..side * side]; |
| 7418 | for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) { |
| 7419 | *dst = src as u8; |
| 7420 | } |
| 7421 | plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set) |
| 7422 | } |
| 7423 | |
| 7424 | /// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both |
| 7425 | /// references predict into the `CONV_BUF` intermediate domain |
| 7426 | /// ([`mc::predict_compound_intermediate`]) and are blended by |
| 7427 | /// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly |
| 7428 | /// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1` |
| 7429 | /// block, so the encoder's reconstruction is the decoder's. |
| 7430 | #[allow(clippy::too_many_arguments)] |
| 7431 | fn mc_trial_compound( |
| 7432 | plane: &Plane, |
| 7433 | x: usize, |
| 7434 | y: usize, |
| 7435 | side: usize, |
| 7436 | (mv0, mv1): ((i32, i32), (i32, i32)), |
| 7437 | luma: bool, |
| 7438 | ref0: (&[u16], usize, usize, usize), |
| 7439 | ref1: (&[u16], usize, usize, usize), |
| 7440 | base_q_idx: u8, |
| 7441 | deadzone: f64, |
| 7442 | set: TxbSet, fctx: &crate::decode::FrameCtx, |
| 7443 | ) -> Trial { |
| 7444 | let mut inter0 = [0i32; BLOCK * BLOCK]; |
| 7445 | let mut inter1 = [0i32; BLOCK * BLOCK]; |
| 7446 | let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]); |
| 7447 | for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] { |
| 7448 | mc::predict_compound_intermediate( |
| 7449 | r.0, |
| 7450 | r.1, |
| 7451 | r.2, |
| 7452 | r.3, |
| 7453 | mv_to_q4(x, mv.1, luma), |
| 7454 | mv_to_q4(y, mv.0, luma), |
| 7455 | mc::REF_NO_SCALE, |
| 7456 | side, |
| 7457 | side, |
| 7458 | mc::InterpFilterKind::Regular, |
| 7459 | mc::InterpFilterKind::Regular, |
| 7460 | dst, |
| 7461 | ); |
| 7462 | } |
| 7463 | let mut blended16 = [0u16; BLOCK * BLOCK]; |
| 7464 | let blended16 = &mut blended16[..side * side]; |
| 7465 | mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx); |
| 7466 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 7467 | let prediction = &mut prediction[..side * side]; |
| 7468 | for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { |
| 7469 | *dst = src as u8; |
| 7470 | } |
| 7471 | plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set) |
| 7472 | } |
| 7473 | |
| 7474 | /// Codes one 32x32 block of an inter frame as whichever costs least of: each |
| 7475 | /// intra mode [`Search::modes`] offers (predicted exactly as a key frame's |
| 7476 | /// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by |
| 7477 | /// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates |
| 7478 | /// coding a real residual (`skip: false`) whenever one prices out cheaper |
| 7479 | /// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s |
| 7480 | /// missing inter `tx_type` symbol (the desync this function's candidates |
| 7481 | /// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is |
| 7482 | /// fixed. |
| 7483 | /// |
| 7484 | /// The symbol costs this ranks candidates by use fixed contexts (0) for |
| 7485 | /// `skip`, `intra_inter` and `single_ref` — the tile writer's actual |
| 7486 | /// contexts for those come from its own neighbour bookkeeping |
| 7487 | /// (`tile::Neighbours`), which is private to that module and not worth |
| 7488 | /// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/ |
| 7489 | /// `drl_mode` contexts come straight from `stack`, which is exact, because |
| 7490 | /// [`find_mv_stack`] is public and this function is handed the same `MvStack` |
| 7491 | /// the tile writer derives from the same grid state. |
| 7492 | #[allow(clippy::too_many_arguments)] |
| 7493 | /// One prediction of `side` x `side` samples from `reference`, as `u8` -- |
| 7494 | /// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is |
| 7495 | /// four times the stack scratch that function sizes for [`BLOCK`]. |
| 7496 | fn predict_u8( |
| 7497 | reference: &[u16], |
| 7498 | stride: usize, |
| 7499 | ref_width: usize, |
| 7500 | ref_height: usize, |
| 7501 | (x, y): (usize, usize), |
| 7502 | side: usize, |
| 7503 | mv: (i32, i32), |
| 7504 | luma: bool, |
| 7505 | fctx: &crate::decode::FrameCtx, |
| 7506 | ) -> Vec<u8> { |
| 7507 | let mut prediction = vec![0u16; side * side]; |
| 7508 | mc::predict( |
| 7509 | reference, |
| 7510 | stride, |
| 7511 | ref_width, |
| 7512 | ref_height, |
| 7513 | mv_to_q4(x, mv.1, luma), |
| 7514 | mv_to_q4(y, mv.0, luma), |
| 7515 | side, |
| 7516 | side, |
| 7517 | &mut prediction, |
| 7518 | fctx, |
| 7519 | ); |
| 7520 | prediction.iter().map(|&v| v as u8).collect() |
| 7521 | } |
| 7522 | |
| 7523 | /// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's |
| 7524 | /// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both |
| 7525 | /// references predict into the `CONV_BUF` intermediate domain and are blended |
| 7526 | /// at the simple-average split `(8, 8)`, the same path (and so the same |
| 7527 | /// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes. |
| 7528 | fn predict_compound_u8( |
| 7529 | ref0: (&[u16], usize, usize, usize), |
| 7530 | ref1: (&[u16], usize, usize, usize), |
| 7531 | (x, y): (usize, usize), |
| 7532 | side: usize, |
| 7533 | (mv0, mv1): ((i32, i32), (i32, i32)), |
| 7534 | luma: bool, |
| 7535 | fctx: &crate::decode::FrameCtx, |
| 7536 | ) -> Vec<u8> { |
| 7537 | let mut inter = [vec![0i32; side * side], vec![0i32; side * side]]; |
| 7538 | for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) { |
| 7539 | mc::predict_compound_intermediate( |
| 7540 | r.0, |
| 7541 | r.1, |
| 7542 | r.2, |
| 7543 | r.3, |
| 7544 | mv_to_q4(x, mv.1, luma), |
| 7545 | mv_to_q4(y, mv.0, luma), |
| 7546 | mc::REF_NO_SCALE, |
| 7547 | side, |
| 7548 | side, |
| 7549 | mc::InterpFilterKind::Regular, |
| 7550 | mc::InterpFilterKind::Regular, |
| 7551 | dst, |
| 7552 | ); |
| 7553 | } |
| 7554 | let mut blended = vec![0u16; side * side]; |
| 7555 | mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx); |
| 7556 | blended.iter().map(|&v| v as u8).collect() |
| 7557 | } |
| 7558 | |
| 7559 | /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]): |
| 7560 | /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded |
| 7561 | /// SKIP, priced through the same `symbol_bits` path every other candidate |
| 7562 | /// uses. The winner's prediction is committed to the planes (it IS the |
| 7563 | /// reconstruction -- a skip block has no residual); the caller restores them |
| 7564 | /// if the four quadrants come out cheaper. |
| 7565 | /// |
| 7566 | /// `None` when no candidate could be coded at all (a `NEWMV` residual the |
| 7567 | /// writer cannot name is simply not offered, and the other modes always are, |
| 7568 | /// so this only happens if every candidate is refused). |
| 7569 | fn search_skip_64( |
| 7570 | luma: &mut Plane, |
| 7571 | chroma: &mut [Plane; 2], |
| 7572 | (x, y): (usize, usize), |
| 7573 | search: &Search, |
| 7574 | // Whether the non-skip arm is priced at all ([`b64_residual`], and off on |
| 7575 | // screen content -- see that function's doc). |
| 7576 | residual: bool, |
| 7577 | reference: &Picture, |
| 7578 | stack: &MvStack, |
| 7579 | // The COMPOUND stack of each `LAST` + extra-reference pair at THIS |
| 7580 | // superblock's 16x16-mi window, built off the same grid the tile writer |
| 7581 | // rebuilds it from (empty unless the frame carries `reference_select`). |
| 7582 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 7583 | fctx: &crate::decode::FrameCtx, |
| 7584 | ) -> Option<(f64, BlockCoeffs)> { |
| 7585 | let side = SUPERBLOCK; |
| 7586 | let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 7587 | let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 7588 | let ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 7589 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 7590 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 7591 | // What every candidate pays whatever its vector: `skip` coded 1, then |
| 7592 | // `is_inter` coded 1, then the LAST chain above. |
| 7593 | let fixed = symbol_bits(&cdf::SKIP[0], 1) + symbol_bits(&cdf::INTRA_INTER[0], 1) + ref_bits; |
| 7594 | let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo { |
| 7595 | ref1: None, |
| 7596 | mv1: (0, 0), |
| 7597 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7598 | mode, |
| 7599 | mv, |
| 7600 | ref_mv_idx, |
| 7601 | }; |
| 7602 | let mut cands: Vec<(f64, InterInfo)> = vec![ |
| 7603 | ( |
| 7604 | not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 7605 | info_of(InterMode::NearestMv, stack.nearest_mv, 0), |
| 7606 | ), |
| 7607 | ( |
| 7608 | not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), |
| 7609 | info_of(InterMode::GlobalMv, (0, 0), 0), |
| 7610 | ), |
| 7611 | ]; |
| 7612 | let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); |
| 7613 | for idx in 1..=2usize { |
| 7614 | if let Some(e) = stack.entries.get(idx) { |
| 7615 | cands.push(( |
| 7616 | near_bits + drl_bits_for(stack, 1, idx), |
| 7617 | info_of(InterMode::NearMv, e.mv, idx as u8), |
| 7618 | )); |
| 7619 | } |
| 7620 | } |
| 7621 | // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV` |
| 7622 | // candidate below to pair with the second reference's NEAREST half. |
| 7623 | let mut last_new_mv: Option<(i32, i32)> = None; |
| 7624 | if leaf_new_mv() { |
| 7625 | let source_block = luma.source_block(x, y, side); |
| 7626 | let (seeds, seed_n) = mv_seeds(stack); |
| 7627 | let found = motion::search( |
| 7628 | &reference.y, |
| 7629 | reference.width, |
| 7630 | luma.true_width, |
| 7631 | luma.true_height, |
| 7632 | &source_block, |
| 7633 | x, |
| 7634 | y, |
| 7635 | side, |
| 7636 | side, |
| 7637 | stack.pred_mv, |
| 7638 | &seeds[..seed_n], |
| 7639 | search.lambda, |
| 7640 | fctx, |
| 7641 | 1, |
| 7642 | ); |
| 7643 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 7644 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 7645 | last_new_mv = Some(mv); |
| 7646 | cands.push(( |
| 7647 | symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, |
| 7648 | info_of(InterMode::NewMv, mv, ref_mv_idx), |
| 7649 | )); |
| 7650 | } |
| 7651 | } |
| 7652 | |
| 7653 | let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None; |
| 7654 | for (bits, info) in cands { |
| 7655 | let trials = [ |
| 7656 | (0usize, x, y, side, true), |
| 7657 | (1, x / 2, y / 2, side / 2, false), |
| 7658 | (2, x / 2, y / 2, side / 2, false), |
| 7659 | ] |
| 7660 | .map(|(plane, px, py, s, is_luma)| { |
| 7661 | let (samples, stride, w, h) = match plane { |
| 7662 | 0 => (&reference.y, reference.width, luma.true_width, luma.true_height), |
| 7663 | 1 => ( |
| 7664 | &reference.u, |
| 7665 | reference.width / 2, |
| 7666 | chroma[0].true_width, |
| 7667 | chroma[0].true_height, |
| 7668 | ), |
| 7669 | _ => ( |
| 7670 | &reference.v, |
| 7671 | reference.width / 2, |
| 7672 | chroma[1].true_width, |
| 7673 | chroma[1].true_height, |
| 7674 | ), |
| 7675 | }; |
| 7676 | let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx); |
| 7677 | let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] }; |
| 7678 | // `skip` true: the trial is the prediction itself plus its SSE, |
| 7679 | // so no transform of any size is involved (the reason a 64x64 |
| 7680 | // root can be coded at all before a forward TX_64X64 exists). |
| 7681 | target.code_from_prediction( |
| 7682 | px, |
| 7683 | py, |
| 7684 | s, |
| 7685 | &prediction, |
| 7686 | true, |
| 7687 | search.base_q_idx, |
| 7688 | search.deadzone, |
| 7689 | TxbSet::Luma32Inter, |
| 7690 | ) |
| 7691 | }); |
| 7692 | let cost = trials[0].sse |
| 7693 | + trials[1].sse |
| 7694 | + trials[2].sse |
| 7695 | + search.lambda * (fixed + bits); |
| 7696 | if best.as_ref().is_none_or(|b| cost < b.0) { |
| 7697 | best = Some((cost, fixed + bits, info, trials)); |
| 7698 | } |
| 7699 | } |
| 7700 | |
| 7701 | // lane-b64b: the COMPOUND candidates at the 64 root, the same three a |
| 7702 | // superblock can form without a second motion search ([`b64_compound`]), |
| 7703 | // priced through the same `symbol_bits` path -- `fixed` minus the single |
| 7704 | // reference's tree, plus the pair tree and the compound mode. |
| 7705 | for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) { |
| 7706 | let (ref1, g) = (*ref1, *g); |
| 7707 | let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1); |
| 7708 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 7709 | + if uni { |
| 7710 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 7711 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 7712 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 7713 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 7714 | } else { |
| 7715 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 7716 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 7717 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 7718 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 7719 | }; |
| 7720 | let mode_ctx = |
| 7721 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 7722 | let mode_bits_of = |
| 7723 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 7724 | let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo { |
| 7725 | ref1: Some(ref1), |
| 7726 | mv1: mvs.1, |
| 7727 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7728 | mode, |
| 7729 | mv: mvs.0, |
| 7730 | ref_mv_idx: 0, |
| 7731 | }; |
| 7732 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 7733 | ( |
| 7734 | cstack.nearest_mv, |
| 7735 | mode_bits_of(0), |
| 7736 | compound_info(InterMode::NearestNearestMv, cstack.nearest_mv), |
| 7737 | ), |
| 7738 | ( |
| 7739 | ((0, 0), (0, 0)), |
| 7740 | mode_bits_of(6), |
| 7741 | compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))), |
| 7742 | ), |
| 7743 | ]; |
| 7744 | // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search |
| 7745 | // above, its residual priced against compound stack entry 0 -- what |
| 7746 | // `assign_compound_mv` predicts from at `ref_mv_idx = 0`. |
| 7747 | let cbase = cstack |
| 7748 | .entries |
| 7749 | .first() |
| 7750 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 7751 | if let Some(new_mv) = last_new_mv |
| 7752 | && let Some(b0) = mv_residual_bits(new_mv, cbase.0) |
| 7753 | { |
| 7754 | let mvs = (new_mv, cstack.nearest_mv.1); |
| 7755 | ccands.push(( |
| 7756 | mvs, |
| 7757 | mode_bits_of(3) + b0, |
| 7758 | compound_info(InterMode::NewNearestMv, mvs), |
| 7759 | )); |
| 7760 | } |
| 7761 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 7762 | ccands.dedup_by_key(|c| c.0); |
| 7763 | for (mvs, bits, info) in ccands { |
| 7764 | let trials = [ |
| 7765 | (0usize, x, y, side, true), |
| 7766 | (1, x / 2, y / 2, side / 2, false), |
| 7767 | (2, x / 2, y / 2, side / 2, false), |
| 7768 | ] |
| 7769 | .map(|(plane, px, py, s, is_luma)| { |
| 7770 | let (r0, r1) = match plane { |
| 7771 | 0 => ( |
| 7772 | (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height), |
| 7773 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 7774 | ), |
| 7775 | 1 => ( |
| 7776 | ( |
| 7777 | reference.u.as_slice(), |
| 7778 | reference.width / 2, |
| 7779 | chroma[0].true_width, |
| 7780 | chroma[0].true_height, |
| 7781 | ), |
| 7782 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 7783 | ), |
| 7784 | _ => ( |
| 7785 | ( |
| 7786 | reference.v.as_slice(), |
| 7787 | reference.width / 2, |
| 7788 | chroma[1].true_width, |
| 7789 | chroma[1].true_height, |
| 7790 | ), |
| 7791 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 7792 | ), |
| 7793 | }; |
| 7794 | let prediction = |
| 7795 | predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx); |
| 7796 | let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] }; |
| 7797 | target.code_from_prediction( |
| 7798 | px, |
| 7799 | py, |
| 7800 | s, |
| 7801 | &prediction, |
| 7802 | true, |
| 7803 | search.base_q_idx, |
| 7804 | search.deadzone, |
| 7805 | TxbSet::Luma32Inter, |
| 7806 | ) |
| 7807 | }); |
| 7808 | let syntax = fixed - ref_bits + bits; |
| 7809 | let cost = |
| 7810 | trials[0].sse + trials[1].sse + trials[2].sse + search.lambda * syntax; |
| 7811 | if best.as_ref().is_none_or(|b| cost < b.0) { |
| 7812 | best = Some((cost, syntax, info, trials)); |
| 7813 | } |
| 7814 | } |
| 7815 | } |
| 7816 | |
| 7817 | let (skip_cost, syntax, info, skip_trials) = best?; |
| 7818 | |
| 7819 | // The winner's prediction coded with a REAL residual (lane-tx64): one |
| 7820 | // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the |
| 7821 | // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per |
| 7822 | // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv |
| 7823 | // the skip arm already chose is re-coded: the prediction with the lowest |
| 7824 | // SSE is also the cheapest residual to code, and a second 64x64 motion |
| 7825 | // search per superblock is the wall this root was taken to SAVE. |
| 7826 | // |
| 7827 | // Priced against the skip arm through the same `symbol_bits` path, so the |
| 7828 | // two numbers are comparable: `fixed` charged `skip` coded 1, and this |
| 7829 | // arm charges 0 instead and adds its three planes' coefficient bits. |
| 7830 | let mut chosen = (skip_cost, true, skip_trials); |
| 7831 | // Set when [`commit_inter_luma`] already wrote the residual arm's luma |
| 7832 | // into the plane, so the tail below does not commit over its units. |
| 7833 | let mut luma_committed = false; |
| 7834 | // The residual arm's luma levels and the `txfm_split` depth the writer |
| 7835 | // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is |
| 7836 | // four TX_32X32 units in 64x64 ones. |
| 7837 | let mut luma_levels: Option<(Vec<i32>, u8)> = None; |
| 7838 | if residual { |
| 7839 | let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; |
| 7840 | let residual_trials = [0usize, 1, 2].map(|plane| { |
| 7841 | let (target, px, py, s) = if plane == 0 { |
| 7842 | (&*luma, x, y, side) |
| 7843 | } else { |
| 7844 | (&chroma[plane - 1], x / 2, y / 2, side / 2) |
| 7845 | }; |
| 7846 | target.code_from_prediction( |
| 7847 | px, |
| 7848 | py, |
| 7849 | s, |
| 7850 | &chosen.2[plane].reconstruction, |
| 7851 | false, |
| 7852 | search.base_q_idx, |
| 7853 | search.deadzone, |
| 7854 | sets[plane], |
| 7855 | ) |
| 7856 | }); |
| 7857 | let unskip = symbol_bits(&cdf::SKIP[0], 0) - symbol_bits(&cdf::SKIP[0], 1); |
| 7858 | let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum(); |
| 7859 | // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the |
| 7860 | // four TX_32X32 units of `txfm_split = 1`, taken by the same |
| 7861 | // `commit_inter_luma` every other inter block's is (it commits the |
| 7862 | // winner and hands back the cost it took off the flat arm). |
| 7863 | let (levels, depth, gain) = if b64_var_tx() { |
| 7864 | let second = info.ref1.and_then(|r1| { |
| 7865 | compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| { |
| 7866 | ( |
| 7867 | info.mv1, |
| 7868 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 7869 | ) |
| 7870 | }) |
| 7871 | }); |
| 7872 | luma_committed = true; |
| 7873 | commit_inter_luma( |
| 7874 | luma, |
| 7875 | (x, y), |
| 7876 | side, |
| 7877 | info.mv, |
| 7878 | (&reference.y, reference.width, luma.true_width, luma.true_height), |
| 7879 | search, |
| 7880 | &residual_trials[0], |
| 7881 | false, |
| 7882 | second, |
| 7883 | fctx, |
| 7884 | ) |
| 7885 | } else { |
| 7886 | (residual_trials[0].levels.clone(), 0, 0.0) |
| 7887 | }; |
| 7888 | let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>() |
| 7889 | + search.lambda * (syntax + unskip + coeff_bits) |
| 7890 | + gain; |
| 7891 | if cost < skip_cost { |
| 7892 | B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 7893 | if depth == 1 { |
| 7894 | B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 7895 | } |
| 7896 | luma_levels = Some((levels, depth)); |
| 7897 | chosen = (cost, false, residual_trials); |
| 7898 | } |
| 7899 | } |
| 7900 | |
| 7901 | let (cost, skip, trials) = chosen; |
| 7902 | // `commit_inter_luma` already wrote the residual arm's luma (its four |
| 7903 | // split units are not one 64-sided trial); a skip winner overwrites it. |
| 7904 | if skip || !luma_committed { |
| 7905 | luma.commit(x, y, side, &trials[0]); |
| 7906 | } |
| 7907 | chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]); |
| 7908 | chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]); |
| 7909 | Some(( |
| 7910 | cost, |
| 7911 | BlockCoeffs { |
| 7912 | skip, |
| 7913 | inter: Some(info), |
| 7914 | // The chroma grids are whole TX_32X32; the luma one is the |
| 7915 | // 64-point transform's coded 32x32 corner at depth 0 and the |
| 7916 | // whole 64-sided block at depth 1 (lane-b64b). |
| 7917 | tx_depth: luma_levels.as_ref().map_or(0, |&(_, d)| d), |
| 7918 | luma: match (skip, &luma_levels) { |
| 7919 | (true, _) => Vec::new(), |
| 7920 | (false, Some((levels, 1))) => coeffs(levels, SUPERBLOCK), |
| 7921 | (false, Some((levels, _))) => coeffs(levels, BLOCK), |
| 7922 | (false, None) => coeffs(&trials[0].levels, BLOCK), |
| 7923 | }, |
| 7924 | u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) }, |
| 7925 | v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) }, |
| 7926 | ..BlockCoeffs::default() |
| 7927 | }, |
| 7928 | )) |
| 7929 | } |
| 7930 | |
| 7931 | fn search_inter_block( |
| 7932 | luma: &mut Plane, |
| 7933 | chroma: &mut [Plane; 2], |
| 7934 | (x, y): (usize, usize), |
| 7935 | search: &Search, |
| 7936 | mode_bits: &[f64; 13], |
| 7937 | reference: &Picture, |
| 7938 | stack: &MvStack, |
| 7939 | // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1 |
| 7940 | // for the whole GOP, with the stack this block derives against it. Only |
| 7941 | // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a |
| 7942 | // second motion search would double the wall of the stage that already |
| 7943 | // owns most of it. |
| 7944 | extra: &[(i8, &Picture, &MvStack)], |
| 7945 | // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by |
| 7946 | // the caller off the same MI grid the tile writer will (empty unless the |
| 7947 | // frame carries `reference_select`). |
| 7948 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 7949 | // lane-av1obmc: the mi grid this search's neighbours were published into |
| 7950 | // (`record_mi`) and this block's own place in it -- what the OBMC |
| 7951 | // candidate's eligibility walk and neighbour plan read, the same state |
| 7952 | // the tile writer will read when it codes the `motion_mode` symbol. |
| 7953 | grid: &MiGrid, |
| 7954 | (mi_row, mi_col): (usize, usize), |
| 7955 | (mi_rows, mi_cols): (usize, usize), |
| 7956 | fctx: &crate::decode::FrameCtx, |
| 7957 | ) -> (BlockCoeffs, f64) { |
| 7958 | // `luma_set` is the INTRA candidates' table; the two inter candidates |
| 7959 | // below price their coefficients through `TxbSet::Luma32Inter`, which is |
| 7960 | // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries |
| 7961 | // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1). |
| 7962 | let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); |
| 7963 | let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx); |
| 7964 | |
| 7965 | // skip / intra_inter symbol costs at a fixed context -- see this |
| 7966 | // function's doc comment. |
| 7967 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 7968 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 7969 | // `write_single_ref`'s own tree, at the fixed context this pricer uses |
| 7970 | // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN |
| 7971 | // p1=0,p3=1,p5=1. |
| 7972 | let single_ref_bits = |ref_frame: i8| { |
| 7973 | symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 7974 | + if ref_frame == crate::mvstack::GOLDEN_FRAME { |
| 7975 | symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) |
| 7976 | } else { |
| 7977 | symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0) |
| 7978 | } |
| 7979 | }; |
| 7980 | |
| 7981 | struct Candidate { |
| 7982 | cost: f64, |
| 7983 | luma: Trial, |
| 7984 | u: Trial, |
| 7985 | v: Trial, |
| 7986 | mode: u8, |
| 7987 | skip: bool, |
| 7988 | inter: Option<InterInfo>, |
| 7989 | /// The mode/mv syntax this candidate pays for, apart from its |
| 7990 | /// residual -- what the OBMC candidate below has to re-pay when it |
| 7991 | /// re-prices the winner's prediction. |
| 7992 | mode_bits: f64, |
| 7993 | } |
| 7994 | let mut best: Option<Candidate> = None; |
| 7995 | let mut consider = |candidate: Candidate| { |
| 7996 | if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { |
| 7997 | best = Some(candidate); |
| 7998 | } |
| 7999 | }; |
| 8000 | |
| 8001 | // The chroma trial an intra candidate prices does not depend on `mode` |
| 8002 | // at all -- both planes always code `DC_PRED` here (a coding choice this |
| 8003 | // search inherited, not this loop's to second-guess) at the same `reach: |
| 8004 | // Reach::none()` -- so it is the same call with the same inputs on every |
| 8005 | // one of the thirteen iterations below; run it once and reuse the result |
| 8006 | // rather than repeat an already-priced transform/quantize/entropy call |
| 8007 | // twelve times for nothing (bit-identical: the value each iteration |
| 8008 | // reads back is exactly what it used to recompute). |
| 8009 | let u_trial = chroma[0].trial( |
| 8010 | At { |
| 8011 | x: x / 2, |
| 8012 | y: y / 2, |
| 8013 | side: BLOCK / 2, |
| 8014 | reach: Reach::none(), |
| 8015 | set: chroma_set, |
| 8016 | }, |
| 8017 | DC_PRED, |
| 8018 | 0, |
| 8019 | search.base_q_idx, |
| 8020 | search.deadzone, fctx, |
| 8021 | ); |
| 8022 | let v_trial = chroma[1].trial( |
| 8023 | At { |
| 8024 | x: x / 2, |
| 8025 | y: y / 2, |
| 8026 | side: BLOCK / 2, |
| 8027 | reach: Reach::none(), |
| 8028 | set: chroma_set, |
| 8029 | }, |
| 8030 | DC_PRED, |
| 8031 | 0, |
| 8032 | search.base_q_idx, |
| 8033 | search.deadzone, fctx, |
| 8034 | ); |
| 8035 | |
| 8036 | let intra_modes: Vec<u8> = match search.top_k { |
| 8037 | Some(k) if k < search.modes.len() => { |
| 8038 | let scored = luma.intra_scores( |
| 8039 | At { |
| 8040 | x, |
| 8041 | y, |
| 8042 | side: BLOCK, |
| 8043 | reach, |
| 8044 | set: luma_set, |
| 8045 | }, |
| 8046 | search.modes, |
| 8047 | mode_bits, |
| 8048 | search.lambda, fctx, |
| 8049 | ); |
| 8050 | prune_by_sad(search.modes, scored, k) |
| 8051 | } |
| 8052 | _ => search.modes.to_vec(), |
| 8053 | }; |
| 8054 | census_add(5, 1); |
| 8055 | census_add(6, intra_modes.len()); |
| 8056 | for &mode in &intra_modes { |
| 8057 | let luma_trial = luma.trial( |
| 8058 | At { |
| 8059 | x, |
| 8060 | y, |
| 8061 | side: BLOCK, |
| 8062 | reach, |
| 8063 | set: luma_set, |
| 8064 | }, |
| 8065 | mode, |
| 8066 | 0, |
| 8067 | search.base_q_idx, |
| 8068 | search.deadzone, fctx, |
| 8069 | ); |
| 8070 | let u = u_trial.clone(); |
| 8071 | let v = v_trial.clone(); |
| 8072 | let cost = luma_trial.sse |
| 8073 | + u.sse |
| 8074 | + v.sse |
| 8075 | + search.lambda |
| 8076 | * (luma_trial.bits |
| 8077 | + u.bits |
| 8078 | + v.bits |
| 8079 | + mode_bits[usize::from(mode)] |
| 8080 | + skip_bits(false) |
| 8081 | + intra_inter_bits(false)); |
| 8082 | consider(Candidate { |
| 8083 | cost, |
| 8084 | luma: luma_trial, |
| 8085 | u, |
| 8086 | v, |
| 8087 | mode, |
| 8088 | skip: false, |
| 8089 | inter: None, |
| 8090 | mode_bits: mode_bits[usize::from(mode)], |
| 8091 | }); |
| 8092 | } |
| 8093 | |
| 8094 | // The reference frame buffer a spec decoder holds is exactly the true |
| 8095 | // (unpadded) coded extent -- a superblock whose partition stops early at |
| 8096 | // `has_cols`/`has_rows` never codes syntax for the padding columns/rows |
| 8097 | // beyond it, so those samples are never part of the decoded picture. |
| 8098 | // Motion compensation clamps reads to that true extent (spec 7.11.3.4's |
| 8099 | // reference sample position clamp), not to this crate's own |
| 8100 | // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height |
| 8101 | // here would let a fractional-pel read past the true edge pick up this |
| 8102 | // encoder's own uncoded padding instead of the true edge's replicated |
| 8103 | // value a decoder computes. |
| 8104 | let ref_luma = ( |
| 8105 | &reference.y, |
| 8106 | reference.width, |
| 8107 | luma.true_width, |
| 8108 | luma.true_height, |
| 8109 | ); |
| 8110 | let ref_u = ( |
| 8111 | &reference.u, |
| 8112 | reference.width / 2, |
| 8113 | chroma[0].true_width, |
| 8114 | chroma[0].true_height, |
| 8115 | ); |
| 8116 | let ref_v = ( |
| 8117 | &reference.v, |
| 8118 | reference.width / 2, |
| 8119 | chroma[1].true_width, |
| 8120 | chroma[1].true_height, |
| 8121 | ); |
| 8122 | // Every single-reference mode the writer can code (spec 5.11.24's symbol |
| 8123 | // chain, mirrored by `tile::write_inter_mode`), priced with the static |
| 8124 | // CDFs at this block's own stack contexts. A candidate is a motion |
| 8125 | // vector plus the cheapest syntax that reaches it, so two modes landing |
| 8126 | // on the same vector share one set of trials: the added modes cost |
| 8127 | // mode-bit arithmetic, not another motion compensation. |
| 8128 | let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 8129 | let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 8130 | // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry |
| 8131 | // past `start`, `1` to advance and `0` to stop, at most two. A `target` |
| 8132 | // the loop cannot reach is never offered below -- every candidate's |
| 8133 | // index is one this same loop walks to. |
| 8134 | let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); |
| 8135 | let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); |
| 8136 | let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ |
| 8137 | ( |
| 8138 | stack.nearest_mv, |
| 8139 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 8140 | InterInfo { |
| 8141 | ref1: None, |
| 8142 | mv1: (0, 0), |
| 8143 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8144 | mode: InterMode::NearestMv, |
| 8145 | mv: stack.nearest_mv, |
| 8146 | ref_mv_idx: 0, |
| 8147 | }, |
| 8148 | ), |
| 8149 | // GLOBALMV is the identity model's zero vector -- this encoder writes |
| 8150 | // no `gm_params` -- and the cheapest syntax of the four on the static |
| 8151 | // content where that vector is also the right one. |
| 8152 | ( |
| 8153 | (0, 0), |
| 8154 | last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), |
| 8155 | InterInfo { |
| 8156 | ref1: None, |
| 8157 | mv1: (0, 0), |
| 8158 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8159 | mode: InterMode::GlobalMv, |
| 8160 | mv: (0, 0), |
| 8161 | ref_mv_idx: 0, |
| 8162 | }, |
| 8163 | ), |
| 8164 | ]; |
| 8165 | let near_bits = |
| 8166 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); |
| 8167 | for idx in 1..=2usize { |
| 8168 | if let Some(e) = stack.entries.get(idx) { |
| 8169 | cands.push(( |
| 8170 | e.mv, |
| 8171 | near_bits + drl_bits(1, idx), |
| 8172 | InterInfo { |
| 8173 | ref1: None, |
| 8174 | mv1: (0, 0), |
| 8175 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8176 | mode: InterMode::NearMv, |
| 8177 | mv: e.mv, |
| 8178 | ref_mv_idx: idx as u8, |
| 8179 | }, |
| 8180 | )); |
| 8181 | } |
| 8182 | } |
| 8183 | |
| 8184 | let source_block = luma.source_block(x, y, BLOCK); |
| 8185 | let (seeds, seed_n) = mv_seeds(stack); |
| 8186 | #[cfg(test)] |
| 8187 | let t = stage_start(); |
| 8188 | let found = motion::search( |
| 8189 | ref_luma.0, |
| 8190 | ref_luma.1, |
| 8191 | ref_luma.2, |
| 8192 | ref_luma.3, |
| 8193 | &source_block, |
| 8194 | x, |
| 8195 | y, |
| 8196 | BLOCK, |
| 8197 | BLOCK, |
| 8198 | stack.pred_mv, |
| 8199 | &seeds[..seed_n], |
| 8200 | search.lambda, fctx, |
| 8201 | 1, |
| 8202 | ); |
| 8203 | #[cfg(test)] |
| 8204 | stage_since(0, t); |
| 8205 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 8206 | // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so |
| 8207 | // the same vector costs a different residual from each: take the index |
| 8208 | // whose residual plus DRL bits is cheapest, not entry 0 by default. |
| 8209 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 8210 | cands.push(( |
| 8211 | mv, |
| 8212 | last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, |
| 8213 | InterInfo { |
| 8214 | ref1: None, |
| 8215 | mv1: (0, 0), |
| 8216 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8217 | mode: InterMode::NewMv, |
| 8218 | mv, |
| 8219 | ref_mv_idx, |
| 8220 | }, |
| 8221 | )); |
| 8222 | } |
| 8223 | |
| 8224 | // Each extra reference's own `NEWMV` vector, for the compound |
| 8225 | // `NEW_NEWMV` candidate below to pair with `LAST`'s. |
| 8226 | let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new(); |
| 8227 | for &(ref_frame, g, gstack) in extra { |
| 8228 | let g_ref_bits = single_ref_bits(ref_frame); |
| 8229 | let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); |
| 8230 | cands.push(( |
| 8231 | gstack.nearest_mv, |
| 8232 | g_ref_bits |
| 8233 | + g_not_new |
| 8234 | + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) |
| 8235 | + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), |
| 8236 | InterInfo { |
| 8237 | ref1: None, |
| 8238 | mv1: (0, 0), |
| 8239 | ref_frame, |
| 8240 | mode: InterMode::NearestMv, |
| 8241 | mv: gstack.nearest_mv, |
| 8242 | ref_mv_idx: 0, |
| 8243 | }, |
| 8244 | )); |
| 8245 | cands.push(( |
| 8246 | (0, 0), |
| 8247 | g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), |
| 8248 | InterInfo { |
| 8249 | ref1: None, |
| 8250 | mv1: (0, 0), |
| 8251 | ref_frame, |
| 8252 | mode: InterMode::GlobalMv, |
| 8253 | mv: (0, 0), |
| 8254 | ref_mv_idx: 0, |
| 8255 | }, |
| 8256 | )); |
| 8257 | // A motion search of this reference's own: without it, GOLDEN/ALTREF |
| 8258 | // can only be coded at a vector some neighbour already found, which |
| 8259 | // is why they carried a third of the inter blocks at their two |
| 8260 | // search-free modes alone. |
| 8261 | // The search is skipped when this reference's own NEARESTMV already |
| 8262 | // prices out `margin` times better than LAST's best vector does -- |
| 8263 | // one candidate evaluation (`motion::cost_at`) standing in for a |
| 8264 | // whole search of ~50. |
| 8265 | let margin = extra_new_skip_margin(); |
| 8266 | let skip_search = extra_ref_new_mv() |
| 8267 | && margin > 0.0 |
| 8268 | && motion::cost_at( |
| 8269 | &g.y, |
| 8270 | g.width, |
| 8271 | luma.true_width, |
| 8272 | luma.true_height, |
| 8273 | &source_block, |
| 8274 | x, |
| 8275 | y, |
| 8276 | BLOCK, |
| 8277 | BLOCK, |
| 8278 | gstack.nearest_mv, |
| 8279 | gstack.pred_mv, |
| 8280 | search.lambda, |
| 8281 | fctx, |
| 8282 | ) * margin |
| 8283 | <= found.cost; |
| 8284 | if extra_ref_new_mv() && !skip_search { |
| 8285 | let (gseeds, gn) = mv_seeds(gstack); |
| 8286 | #[cfg(test)] |
| 8287 | let t = stage_start(); |
| 8288 | let gfound = motion::search( |
| 8289 | &g.y, |
| 8290 | g.width, |
| 8291 | luma.true_width, |
| 8292 | luma.true_height, |
| 8293 | &source_block, |
| 8294 | x, |
| 8295 | y, |
| 8296 | BLOCK, |
| 8297 | BLOCK, |
| 8298 | gstack.pred_mv, |
| 8299 | &gseeds[..gn], |
| 8300 | search.lambda, fctx, |
| 8301 | ref_distance(ref_frame), |
| 8302 | ); |
| 8303 | #[cfg(test)] |
| 8304 | stage_since(0, t); |
| 8305 | let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); |
| 8306 | extra_new_mvs.push((ref_frame, gmv)); |
| 8307 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { |
| 8308 | cands.push(( |
| 8309 | gmv, |
| 8310 | g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, |
| 8311 | InterInfo { |
| 8312 | ref1: None, |
| 8313 | mv1: (0, 0), |
| 8314 | ref_frame, |
| 8315 | mode: InterMode::NewMv, |
| 8316 | mv: gmv, |
| 8317 | ref_mv_idx, |
| 8318 | }, |
| 8319 | )); |
| 8320 | } |
| 8321 | } |
| 8322 | } |
| 8323 | |
| 8324 | // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one |
| 8325 | // trial set each: both references predict the block and the two |
| 8326 | // predictions are averaged, which is what pays on content where neither |
| 8327 | // reference alone is right. Priced with the same static-CDF approximation |
| 8328 | // the single-reference candidates use, plus the compound-only symbols |
| 8329 | // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`). |
| 8330 | // The two compound-mode arms, each measured alone on the BD gate before |
| 8331 | // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8 |
| 8332 | // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not |
| 8333 | // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`. |
| 8334 | // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on: |
| 8335 | // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, |
| 8336 | // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of |
| 8337 | // the keep rule. Still behind the knob. |
| 8338 | let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR"); |
| 8339 | let half_new = true; |
| 8340 | for (ref1, g, cstack) in compound { |
| 8341 | let (ref1, g) = (*ref1, *g); |
| 8342 | let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME) |
| 8343 | .contains(&ref1); |
| 8344 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 8345 | + if uni { |
| 8346 | // LAST + a backward reference: `comp_ref_type` = bidirectional, |
| 8347 | // `comp_ref` LAST, `comp_bwdref` ALTREF. |
| 8348 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 8349 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 8350 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 8351 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 8352 | } else { |
| 8353 | // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2. |
| 8354 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 8355 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 8356 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 8357 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 8358 | }; |
| 8359 | let mode_ctx = |
| 8360 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 8361 | let mode_bits_of = |
| 8362 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 8363 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 8364 | ( |
| 8365 | cstack.nearest_mv, |
| 8366 | mode_bits_of(0), |
| 8367 | InterInfo { |
| 8368 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8369 | mode: InterMode::NearestNearestMv, |
| 8370 | mv: cstack.nearest_mv.0, |
| 8371 | mv1: cstack.nearest_mv.1, |
| 8372 | ref1: Some(ref1), |
| 8373 | ref_mv_idx: 0, |
| 8374 | }, |
| 8375 | ), |
| 8376 | ( |
| 8377 | ((0, 0), (0, 0)), |
| 8378 | mode_bits_of(6), |
| 8379 | InterInfo { |
| 8380 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8381 | mode: InterMode::GlobalGlobalMv, |
| 8382 | mv: (0, 0), |
| 8383 | mv1: (0, 0), |
| 8384 | ref1: Some(ref1), |
| 8385 | ref_mv_idx: 0, |
| 8386 | }, |
| 8387 | ), |
| 8388 | ]; |
| 8389 | // `NEAR_NEARMV`: both halves off compound stack entry 1 (the |
| 8390 | // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever |
| 8391 | // the stack is deep enough for that walk to read one. |
| 8392 | if let Some(e) = cstack.entries.get(1).filter(|_| near_near) { |
| 8393 | let drl = if cstack.entries.len() > 2 { |
| 8394 | symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0) |
| 8395 | } else { |
| 8396 | 0.0 |
| 8397 | }; |
| 8398 | ccands.push(( |
| 8399 | (e.mv0, e.mv1), |
| 8400 | mode_bits_of(1) + drl, |
| 8401 | InterInfo { |
| 8402 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8403 | mode: InterMode::NearNearMv, |
| 8404 | mv: e.mv0, |
| 8405 | mv1: e.mv1, |
| 8406 | ref1: Some(ref1), |
| 8407 | ref_mv_idx: 0, |
| 8408 | }, |
| 8409 | )); |
| 8410 | } |
| 8411 | // The half-new modes and `NEW_NEWMV`, all seeded from the two |
| 8412 | // single-reference searches this block already ran -- no joint search |
| 8413 | // of its own. Every residual is priced against stack entry 0, which |
| 8414 | // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`. |
| 8415 | let cbase = cstack |
| 8416 | .entries |
| 8417 | .first() |
| 8418 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 8419 | if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) { |
| 8420 | ccands.push(( |
| 8421 | (mv, cstack.nearest_mv.1), |
| 8422 | mode_bits_of(3) + b0, |
| 8423 | InterInfo { |
| 8424 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8425 | mode: InterMode::NewNearestMv, |
| 8426 | mv, |
| 8427 | mv1: cstack.nearest_mv.1, |
| 8428 | ref1: Some(ref1), |
| 8429 | ref_mv_idx: 0, |
| 8430 | }, |
| 8431 | )); |
| 8432 | } |
| 8433 | if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) { |
| 8434 | if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) { |
| 8435 | ccands.push(( |
| 8436 | (cstack.nearest_mv.0, mv1), |
| 8437 | mode_bits_of(2) + b1, |
| 8438 | InterInfo { |
| 8439 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8440 | mode: InterMode::NearestNewMv, |
| 8441 | mv: cstack.nearest_mv.0, |
| 8442 | mv1, |
| 8443 | ref1: Some(ref1), |
| 8444 | ref_mv_idx: 0, |
| 8445 | }, |
| 8446 | )); |
| 8447 | } |
| 8448 | let base = cbase; |
| 8449 | if let (Some(b0), Some(b1)) = ( |
| 8450 | mv_residual_bits(mv, base.0), |
| 8451 | mv_residual_bits(mv1, base.1), |
| 8452 | ) { |
| 8453 | ccands.push(( |
| 8454 | (mv, mv1), |
| 8455 | mode_bits_of(7) + b0 + b1, |
| 8456 | InterInfo { |
| 8457 | ref_frame: crate::mvstack::LAST_FRAME, |
| 8458 | mode: InterMode::NewNewMv, |
| 8459 | mv, |
| 8460 | mv1, |
| 8461 | ref1: Some(ref1), |
| 8462 | ref_mv_idx: 0, |
| 8463 | }, |
| 8464 | )); |
| 8465 | } |
| 8466 | } |
| 8467 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 8468 | ccands.dedup_by_key(|c| c.0); |
| 8469 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 8470 | let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height); |
| 8471 | let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height); |
| 8472 | for (mvs, bits, info) in ccands { |
| 8473 | let luma_trial = mc_trial_compound( |
| 8474 | luma, x, y, BLOCK, mvs, true, |
| 8475 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 8476 | search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, |
| 8477 | ); |
| 8478 | let u = mc_trial_compound( |
| 8479 | &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 8480 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 8481 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 8482 | ); |
| 8483 | let v = mc_trial_compound( |
| 8484 | &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 8485 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 8486 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 8487 | ); |
| 8488 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 8489 | && u.levels.iter().all(|&l| l == 0) |
| 8490 | && v.levels.iter().all(|&l| l == 0); |
| 8491 | let cost = luma_trial.sse |
| 8492 | + u.sse |
| 8493 | + v.sse |
| 8494 | + search.lambda |
| 8495 | * (skip_bits(skip) |
| 8496 | + intra_inter_bits(true) |
| 8497 | + bits |
| 8498 | + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); |
| 8499 | consider(Candidate { |
| 8500 | cost, |
| 8501 | luma: luma_trial, |
| 8502 | u, |
| 8503 | v, |
| 8504 | mode: DC_PRED, |
| 8505 | skip, |
| 8506 | mode_bits: bits, |
| 8507 | inter: Some(info), |
| 8508 | }); |
| 8509 | } |
| 8510 | } |
| 8511 | |
| 8512 | // One trial set per distinct (reference, vector) pair: sort, cheapest |
| 8513 | // syntax first, and drop the rest of each pair's run. |
| 8514 | cands.sort_by(|a, b| { |
| 8515 | (a.2.ref_frame, a.0) |
| 8516 | .cmp(&(b.2.ref_frame, b.0)) |
| 8517 | .then(a.1.total_cmp(&b.1)) |
| 8518 | }); |
| 8519 | cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); |
| 8520 | census_add(7, cands.len()); |
| 8521 | { |
| 8522 | for (mv, mode_bits_inter, info) in cands { |
| 8523 | let (ref_luma, ref_u, ref_v) = match extra |
| 8524 | .iter() |
| 8525 | .find(|(r, _, _)| *r == info.ref_frame) |
| 8526 | { |
| 8527 | Some(&(_, g, _)) => ( |
| 8528 | (&g.y, g.width, luma.true_width, luma.true_height), |
| 8529 | (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 8530 | (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 8531 | ), |
| 8532 | None => (ref_luma, ref_u, ref_v), |
| 8533 | }; |
| 8534 | let luma_trial = mc_trial( |
| 8535 | luma, |
| 8536 | x, |
| 8537 | y, |
| 8538 | BLOCK, |
| 8539 | mv, |
| 8540 | true, |
| 8541 | ref_luma.0, |
| 8542 | ref_luma.1, |
| 8543 | ref_luma.2, |
| 8544 | ref_luma.3, |
| 8545 | false, |
| 8546 | search.base_q_idx, |
| 8547 | search.deadzone, |
| 8548 | TxbSet::Luma32Inter, fctx, |
| 8549 | ); |
| 8550 | let u = mc_trial( |
| 8551 | &chroma[0], |
| 8552 | x / 2, |
| 8553 | y / 2, |
| 8554 | BLOCK / 2, |
| 8555 | mv, |
| 8556 | false, |
| 8557 | ref_u.0, |
| 8558 | ref_u.1, |
| 8559 | ref_u.2, |
| 8560 | ref_u.3, |
| 8561 | false, |
| 8562 | search.base_q_idx, |
| 8563 | search.deadzone, |
| 8564 | chroma_set, fctx, |
| 8565 | ); |
| 8566 | let v = mc_trial( |
| 8567 | &chroma[1], |
| 8568 | x / 2, |
| 8569 | y / 2, |
| 8570 | BLOCK / 2, |
| 8571 | mv, |
| 8572 | false, |
| 8573 | ref_v.0, |
| 8574 | ref_v.1, |
| 8575 | ref_v.2, |
| 8576 | ref_v.3, |
| 8577 | false, |
| 8578 | search.base_q_idx, |
| 8579 | search.deadzone, |
| 8580 | chroma_set, fctx, |
| 8581 | ); |
| 8582 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 8583 | && u.levels.iter().all(|&l| l == 0) |
| 8584 | && v.levels.iter().all(|&l| l == 0); |
| 8585 | let cost = luma_trial.sse |
| 8586 | + u.sse |
| 8587 | + v.sse |
| 8588 | + search.lambda |
| 8589 | * (skip_bits(skip) |
| 8590 | + intra_inter_bits(true) |
| 8591 | + mode_bits_inter |
| 8592 | + if skip { |
| 8593 | 0.0 |
| 8594 | } else { |
| 8595 | luma_trial.bits + u.bits + v.bits |
| 8596 | }); |
| 8597 | consider(Candidate { |
| 8598 | cost, |
| 8599 | luma: luma_trial, |
| 8600 | u, |
| 8601 | v, |
| 8602 | mode: DC_PRED, |
| 8603 | skip, |
| 8604 | mode_bits: mode_bits_inter, |
| 8605 | inter: Some(info), |
| 8606 | }); |
| 8607 | } |
| 8608 | } |
| 8609 | |
| 8610 | let best = best.expect("the search offers at least the intra modes"); |
| 8611 | // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`), |
| 8612 | // offered to the SINGLE-REFERENCE winner only -- libaom's |
| 8613 | // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a |
| 8614 | // compound block, so the writer codes no symbol for one. The prediction |
| 8615 | // is built by the DECODER's own plan and blend |
| 8616 | // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`], |
| 8617 | // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs |
| 8618 | // this search's `grid` already carries, so what is priced here is what a |
| 8619 | // decoder reconstructs -- never a second implementation of the blend. |
| 8620 | // |
| 8621 | // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it |
| 8622 | // on). Native crop BD, the standing recipe, with it on against the same |
| 8623 | // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p |
| 8624 | // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against |
| 8625 | // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and |
| 8626 | // one UP -- the keep rule wants two down and one flat, so it stays off. |
| 8627 | // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and |
| 8628 | // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two |
| 8629 | // things bound it and are the upgrade path: only the 32x32 winner is |
| 8630 | // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and |
| 8631 | // that is where libaom cashes most of its OBMC gain), and the symbol/ |
| 8632 | // residual price here is the static-CDF estimate. |
| 8633 | let mut best = best; |
| 8634 | let mut motion_won = 0u8; |
| 8635 | if let Some(info) = best.inter.filter(|i| { |
| 8636 | i.ref1.is_none() |
| 8637 | && (crate::envflags::env_flag!("EC_AV1_OBMC") |
| 8638 | || warp_on()) |
| 8639 | }) { |
| 8640 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 8641 | refs[LAST_FRAME as usize] = Some(reference); |
| 8642 | for &(r, p, _) in extra { |
| 8643 | refs[r as usize] = Some(p); |
| 8644 | } |
| 8645 | // This block's OWN reference planes: the single-reference winner may |
| 8646 | // be one of the extra references, not LAST. |
| 8647 | let planes: [(&[u16], usize, usize, usize); 3] = |
| 8648 | match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { |
| 8649 | Some(&(_, g, _)) => [ |
| 8650 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 8651 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 8652 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 8653 | ], |
| 8654 | None => [ |
| 8655 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 8656 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 8657 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 8658 | ], |
| 8659 | }; |
| 8660 | // The alphabet `tile::write_motion_mode` will code this block's |
| 8661 | // symbol against, mirrored term for term (libaom |
| 8662 | // `motion_mode_allowed`). |
| 8663 | let warp_alphabet = warp_on() |
| 8664 | && crate::decode::num_proj_ref( |
| 8665 | grid, |
| 8666 | mi_row, |
| 8667 | mi_col, |
| 8668 | 8, |
| 8669 | 8, |
| 8670 | mi_cols, |
| 8671 | mi_rows, |
| 8672 | info.ref_frame, |
| 8673 | fctx, |
| 8674 | ) >= 1; |
| 8675 | let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet); |
| 8676 | let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new(); |
| 8677 | if crate::envflags::env_flag!("EC_AV1_OBMC") { |
| 8678 | if let Some(pred) = obmc_prediction( |
| 8679 | grid, |
| 8680 | (mi_row, mi_col), |
| 8681 | (mi_rows, mi_cols), |
| 8682 | (x, y), |
| 8683 | BLOCK, |
| 8684 | info.mv, |
| 8685 | &refs, |
| 8686 | planes, |
| 8687 | reference.width, |
| 8688 | fctx, |
| 8689 | ) { |
| 8690 | candidates.push((1, pred)); |
| 8691 | } |
| 8692 | } |
| 8693 | if warp_alphabet { |
| 8694 | if let Some(pred) = warp_prediction( |
| 8695 | grid, |
| 8696 | (mi_row, mi_col), |
| 8697 | (mi_rows, mi_cols), |
| 8698 | (x, y), |
| 8699 | BLOCK, |
| 8700 | info.mv, |
| 8701 | info.ref_frame, |
| 8702 | planes, |
| 8703 | fctx, |
| 8704 | ) { |
| 8705 | candidates.push((2, pred)); |
| 8706 | } |
| 8707 | } |
| 8708 | for (motion, pred) in candidates { |
| 8709 | let luma_trial = luma.code_from_prediction( |
| 8710 | x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone, |
| 8711 | TxbSet::Luma32Inter, |
| 8712 | ); |
| 8713 | let u = chroma[0].code_from_prediction( |
| 8714 | x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone, |
| 8715 | chroma_set, |
| 8716 | ); |
| 8717 | let v = chroma[1].code_from_prediction( |
| 8718 | x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone, |
| 8719 | chroma_set, |
| 8720 | ); |
| 8721 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 8722 | && u.levels.iter().all(|&l| l == 0) |
| 8723 | && v.levels.iter().all(|&l| l == 0); |
| 8724 | let cost = luma_trial.sse |
| 8725 | + u.sse |
| 8726 | + v.sse |
| 8727 | + search.lambda |
| 8728 | * (skip_bits(skip) |
| 8729 | + intra_inter_bits(true) |
| 8730 | + best.mode_bits |
| 8731 | + mm(motion) |
| 8732 | + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); |
| 8733 | if cost < best.cost + search.lambda * mm(motion_won) { |
| 8734 | motion_won = motion; |
| 8735 | best = Candidate { |
| 8736 | cost, |
| 8737 | luma: luma_trial, |
| 8738 | u, |
| 8739 | v, |
| 8740 | mode: DC_PRED, |
| 8741 | skip, |
| 8742 | mode_bits: best.mode_bits, |
| 8743 | inter: best.inter, |
| 8744 | }; |
| 8745 | } |
| 8746 | } |
| 8747 | } |
| 8748 | // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`, |
| 8749 | // default OFF): the four 16x16 units of `commit_inter_luma` against the |
| 8750 | // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured |
| 8751 | // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and |
| 8752 | // RE-MEASURED it at 0.05, where the rate weight is half of what rejected |
| 8753 | // it, and it is worse again on the deciding native table: film 1080p |
| 8754 | // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the |
| 8755 | // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off -- |
| 8756 | // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1 |
| 8757 | // up against rav1e. (640x384 reads it slightly the other way, +70.0/ |
| 8758 | // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and |
| 8759 | // +28.4/+47.4/-4.0 -- the native table decides.) |
| 8760 | // |
| 8761 | // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks, |
| 8762 | // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing |
| 8763 | // either, and the census names the row: the split units' own set |
| 8764 | // `Luma16Inter` is priced within 1.4% of what it is written at in every |
| 8765 | // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced |
| 8766 | // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting, |
| 8767 | // so a perfect pricer would split even more, and more splitting is what |
| 8768 | // measured worse. The four extra txb_skip/eob symbols simply cost more |
| 8769 | // ladder bytes than the local RD saves. The flat 32x32 transform stays. |
| 8770 | // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection |
| 8771 | // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the |
| 8772 | // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp |
| 8773 | // winner still commits flat: `commit_inter_luma` re-predicts each unit by |
| 8774 | // plain translation, which is not the prediction it was priced from. |
| 8775 | let (levels, tx_depth, dcost) = match best.inter.filter(|_| motion_won == 0) { |
| 8776 | Some(info) => { |
| 8777 | let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { |
| 8778 | Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 8779 | None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 8780 | }; |
| 8781 | let second = info.ref1.and_then(|r| { |
| 8782 | compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| { |
| 8783 | ( |
| 8784 | info.mv1, |
| 8785 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 8786 | ) |
| 8787 | }) |
| 8788 | }); |
| 8789 | match info.ref1.is_some() && second.is_none() { |
| 8790 | true => { |
| 8791 | luma.commit(x, y, BLOCK, &best.luma); |
| 8792 | (best.luma.levels.clone(), 0, 0.0) |
| 8793 | } |
| 8794 | false => commit_inter_luma( |
| 8795 | luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second, |
| 8796 | fctx, |
| 8797 | ), |
| 8798 | } |
| 8799 | } |
| 8800 | None => { |
| 8801 | luma.commit(x, y, BLOCK, &best.luma); |
| 8802 | (best.luma.levels.clone(), 0, 0.0) |
| 8803 | } |
| 8804 | }; |
| 8805 | chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); |
| 8806 | chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); |
| 8807 | ( |
| 8808 | BlockCoeffs { |
| 8809 | angle_delta_y: 0, |
| 8810 | cfl_alphas: None, |
| 8811 | filter_intra: None, |
| 8812 | luma: coeffs(&levels, BLOCK), |
| 8813 | u: coeffs(&best.u.levels, BLOCK / 2), |
| 8814 | v: coeffs(&best.v.levels, BLOCK / 2), |
| 8815 | mode: best.mode, |
| 8816 | uv_mode: DC_PRED, |
| 8817 | skip: best.skip, |
| 8818 | inter: best.inter, |
| 8819 | motion_mode: motion_won, |
| 8820 | eight: None, |
| 8821 | dv: None, |
| 8822 | palette: None, |
| 8823 | palette_uv: None, |
| 8824 | tx_depth, |
| 8825 | }, |
| 8826 | best.cost + dcost, |
| 8827 | ) |
| 8828 | } |
| 8829 | |
| 8830 | /// lane-av1tpl: the strength `k` of the temporal lambda weighting |
| 8831 | /// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which |
| 8832 | /// is what every measurement before this lane was taken on. Swept by |
| 8833 | /// `EC_AV1_TPL=<k>`. |
| 8834 | /// |
| 8835 | /// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs |
| 8836 | /// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane |
| 8837 | /// baseline exactly, which is the control the rest of the table is read |
| 8838 | /// against: |
| 8839 | /// |
| 8840 | /// | k | film 1080p | film 2160p | screen | |
| 8841 | /// |---|---|---|---| |
| 8842 | /// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 | |
| 8843 | /// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 | |
| 8844 | /// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** | |
| 8845 | /// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 | |
| 8846 | /// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 | |
| 8847 | /// |
| 8848 | /// 0.5 is the only arm that is at least flat on every row and down on five of |
| 8849 | /// the six columns, so it ships as the default. The lookahead pass that feeds |
| 8850 | /// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%). |
| 8851 | const TPL_STRENGTH: f64 = 0.5; |
| 8852 | |
| 8853 | fn tpl_strength() -> f64 { |
| 8854 | std::env::var("EC_AV1_TPL") |
| 8855 | .ok() |
| 8856 | .and_then(|v| v.parse::<f64>().ok()) |
| 8857 | .filter(|k| k.is_finite() && *k >= 0.0) |
| 8858 | .unwrap_or(TPL_STRENGTH) |
| 8859 | } |
| 8860 | |
| 8861 | /// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting |
| 8862 | /// the frame being coded. 1 turns the weighting off; 2 is the shipped |
| 8863 | /// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under |
| 8864 | /// [`tpl_propagating`], which is the map that can actually use them and is |
| 8865 | /// the default since lane-av1tpl3, so the default window is 8. Swept by |
| 8866 | /// `EC_AV1_TPL_D=<d>`. |
| 8867 | /// |
| 8868 | /// The streaming facade holds `depth - 1` pictures back so it feeds |
| 8869 | /// `encode_inter_frame` the same window `encode_sequence` does; both read |
| 8870 | /// THIS function, so the two paths cannot disagree about the window. |
| 8871 | pub(crate) const TPL_DEPTH: usize = 8; |
| 8872 | |
| 8873 | /// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]). |
| 8874 | /// 0.5 is libaom's own square-root compression of its dependence ratio. |
| 8875 | const TPL_POWER: f64 = 0.5; |
| 8876 | |
| 8877 | /// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the |
| 8878 | /// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`. |
| 8879 | /// |
| 8880 | /// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom |
| 8881 | /// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map |
| 8882 | /// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]: |
| 8883 | /// |
| 8884 | /// | k | D | p | film 1080p | film 2160p | screen | |
| 8885 | /// |---|---|---|---|---|---| |
| 8886 | /// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 | |
| 8887 | /// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 | |
| 8888 | /// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 | |
| 8889 | /// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 | |
| 8890 | /// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 | |
| 8891 | /// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 | |
| 8892 | /// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 | |
| 8893 | /// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 | |
| 8894 | /// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 | |
| 8895 | /// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** | |
| 8896 | /// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 | |
| 8897 | /// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 | |
| 8898 | /// |
| 8899 | /// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of |
| 8900 | /// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside |
| 8901 | /// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p |
| 8902 | /// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was |
| 8903 | /// 0.1..0.4 UP on film 2160p, so it shipped off. |
| 8904 | /// |
| 8905 | /// lane-av1tpl3 found why and turned it on. The denominator is the cell's own |
| 8906 | /// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour |
| 8907 | /// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of |
| 8908 | /// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1 |
| 8909 | /// wherever the window leans on a flat bar, which is exactly where coding is |
| 8910 | /// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio |
| 8911 | /// (libaom's own granularity) puts a busy cell's denominator next to the flat |
| 8912 | /// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed |
| 8913 | /// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on |
| 8914 | /// the same native gate (baseline = the shipped one-frame map): |
| 8915 | /// |
| 8916 | /// | arm | film 1080p | film 2160p | screen | |
| 8917 | /// |---|---|---|---| |
| 8918 | /// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 | |
| 8919 | /// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 | |
| 8920 | /// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 | |
| 8921 | /// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 | |
| 8922 | /// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 | |
| 8923 | /// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 | |
| 8924 | /// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 | |
| 8925 | /// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 | |
| 8926 | /// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 | |
| 8927 | /// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** | |
| 8928 | /// |
| 8929 | /// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4, |
| 8930 | /// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships |
| 8931 | /// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The |
| 8932 | /// floor is a real effect on the ratio and never a win once the aggregation |
| 8933 | /// is in -- the aggregation is the same fix, done where libaom does it. |
| 8934 | fn tpl_propagating() -> bool { |
| 8935 | std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0") |
| 8936 | } |
| 8937 | |
| 8938 | pub(crate) fn tpl_depth() -> usize { |
| 8939 | std::env::var("EC_AV1_TPL_D") |
| 8940 | .ok() |
| 8941 | .and_then(|v| v.parse::<usize>().ok()) |
| 8942 | .filter(|d| *d >= 1) |
| 8943 | .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH)) |
| 8944 | .max(1) |
| 8945 | } |
| 8946 | |
| 8947 | /// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this |
| 8948 | /// process, so the gate can price it against the encode it rides on. |
| 8949 | static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 8950 | |
| 8951 | /// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell, |
| 8952 | /// the winning displacement and its SAD. |
| 8953 | /// |
| 8954 | /// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at |
| 8955 | /// the left/above winners, first-best tie-break. Built once on the frame's |
| 8956 | /// own thread and read-only afterwards, so it cannot make a tile's bytes |
| 8957 | /// depend on the thread count. |
| 8958 | fn tpl_coarse_pass( |
| 8959 | cur: &[u8], |
| 8960 | next: &[u8], |
| 8961 | width: usize, |
| 8962 | height: usize, |
| 8963 | ) -> Vec<((i32, i32), u32)> { |
| 8964 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 8965 | let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 { |
| 8966 | let (sx, sy) = (bx as i32 + mx, by as i32 + my); |
| 8967 | if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height { |
| 8968 | return u32::MAX; |
| 8969 | } |
| 8970 | let (sx, sy) = (sx as usize, sy as usize); |
| 8971 | let mut sum = 0u32; |
| 8972 | for r in 0..16 { |
| 8973 | let a = &next[(by + r) * width + bx..][..16]; |
| 8974 | let b = &cur[(sy + r) * width + sx..][..16]; |
| 8975 | sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>(); |
| 8976 | } |
| 8977 | sum |
| 8978 | }; |
| 8979 | let mut out = Vec::with_capacity(cells_x * cells_y); |
| 8980 | let mut above = vec![(0i32, 0i32); cells_x]; |
| 8981 | for cy in 0..cells_y { |
| 8982 | let mut left = (0i32, 0i32); |
| 8983 | for cx in 0..cells_x { |
| 8984 | let (bx, by) = (cx * 16, cy * 16); |
| 8985 | let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32)); |
| 8986 | for cand in [left, above[cx]] { |
| 8987 | if cand != (0, 0) { |
| 8988 | let s = sad(bx, by, cand); |
| 8989 | if s < best.0 { |
| 8990 | best = (s, cand); |
| 8991 | } |
| 8992 | } |
| 8993 | } |
| 8994 | for step in [8i32, 4, 2, 1] { |
| 8995 | let centre = best.1; |
| 8996 | for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { |
| 8997 | let mv = (centre.0 + dx, centre.1 + dy); |
| 8998 | if mv.0.abs() > 32 || mv.1.abs() > 32 { |
| 8999 | continue; |
| 9000 | } |
| 9001 | let s = sad(bx, by, mv); |
| 9002 | if s < best.0 { |
| 9003 | best = (s, mv); |
| 9004 | } |
| 9005 | } |
| 9006 | } |
| 9007 | left = best.1; |
| 9008 | above[cx] = best.1; |
| 9009 | out.push((best.1, best.0)); |
| 9010 | } |
| 9011 | } |
| 9012 | out |
| 9013 | } |
| 9014 | |
| 9015 | /// The intra-cost proxy libaom's tpl gets from a DC prediction plus a |
| 9016 | /// transform: here, the mean absolute deviation of the cell from its own DC. |
| 9017 | /// It is the denominator every propagated cost is read against, so only its |
| 9018 | /// SHAPE across the frame matters, not its scale. |
| 9019 | fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> { |
| 9020 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 9021 | let mut out = Vec::with_capacity(cells_x * cells_y); |
| 9022 | for cy in 0..cells_y { |
| 9023 | for cx in 0..cells_x { |
| 9024 | let (bx, by) = (cx * 16, cy * 16); |
| 9025 | let mut sum = 0u32; |
| 9026 | for r in 0..16 { |
| 9027 | sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>(); |
| 9028 | } |
| 9029 | let dc = ((sum + 128) / 256) as u8; |
| 9030 | let mut cost = 0u32; |
| 9031 | for r in 0..16 { |
| 9032 | cost += frame[(by + r) * width + bx..][..16] |
| 9033 | .iter() |
| 9034 | .map(|&p| u32::from(p.abs_diff(dc))) |
| 9035 | .sum::<u32>(); |
| 9036 | } |
| 9037 | out.push(cost); |
| 9038 | } |
| 9039 | } |
| 9040 | out |
| 9041 | } |
| 9042 | |
| 9043 | /// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS |
| 9044 | /// frame the next one predicts from, per 16x16 cell -- each cell of `next` |
| 9045 | /// splats its own area, at its winning displacement, onto the (at most four) |
| 9046 | /// cells of `cur` it lands on. 1.0 is "referenced exactly once". |
| 9047 | fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> { |
| 9048 | let start = std::time::Instant::now(); |
| 9049 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 9050 | let pass = tpl_coarse_pass(cur, next, width, height); |
| 9051 | let mut area = vec![0.0f64; cells_x * cells_y]; |
| 9052 | for cy in 0..cells_y { |
| 9053 | for cx in 0..cells_x { |
| 9054 | let (mv, _) = pass[cy * cells_x + cx]; |
| 9055 | let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); |
| 9056 | let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); |
| 9057 | for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) { |
| 9058 | let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16); |
| 9059 | for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) { |
| 9060 | let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16); |
| 9061 | area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0; |
| 9062 | } |
| 9063 | } |
| 9064 | } |
| 9065 | } |
| 9066 | TPL_NANOS.fetch_add( |
| 9067 | start.elapsed().as_nanos() as u64, |
| 9068 | std::sync::atomic::Ordering::Relaxed, |
| 9069 | ); |
| 9070 | area |
| 9071 | } |
| 9072 | |
| 9073 | /// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda |
| 9074 | /// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where |
| 9075 | /// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean. |
| 9076 | /// Decreasing in referenced-ness (a block the next frame leans on is coded |
| 9077 | /// more distortion-averse) and 1.0 at the frame's own mean, so the frame's |
| 9078 | /// total lambda scale is only redistributed, never moved -- a global move is |
| 9079 | /// the thing lane-av1lambda already measured inert. |
| 9080 | fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> { |
| 9081 | let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4); |
| 9082 | let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6); |
| 9083 | let mut out = Vec::with_capacity(sb_cols * sb_rows); |
| 9084 | for sr in 0..sb_rows { |
| 9085 | for sc in 0..sb_cols { |
| 9086 | let mut sum = 0.0; |
| 9087 | for r in 0..4 { |
| 9088 | for c in 0..4 { |
| 9089 | sum += map[(sr * 4 + r) * cells_x + sc * 4 + c]; |
| 9090 | } |
| 9091 | } |
| 9092 | let w_rel = sum / 16.0 / mean; |
| 9093 | out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0)); |
| 9094 | } |
| 9095 | } |
| 9096 | if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { |
| 9097 | let mut hist = [0usize; 8]; |
| 9098 | for w in map { |
| 9099 | hist[((w / mean * 2.0) as usize).min(7)] += 1; |
| 9100 | } |
| 9101 | let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); |
| 9102 | eprintln!( |
| 9103 | "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \ |
| 9104 | sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative", |
| 9105 | map.len(), |
| 9106 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 9107 | ); |
| 9108 | } |
| 9109 | out |
| 9110 | } |
| 9111 | |
| 9112 | /// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda |
| 9113 | /// factor per 16x16 cell of `frames[0]` (the frame being coded), from how |
| 9114 | /// much of the WHOLE lookahead window leans on that cell. |
| 9115 | /// |
| 9116 | /// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the |
| 9117 | /// coarse pass gives a displacement and an inter cost; a cell's own |
| 9118 | /// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that |
| 9119 | /// cell well saves the frames that predict from it -- and it is splatted, |
| 9120 | /// area-weighted, onto the (at most four) cells of `frames[f-1]` its |
| 9121 | /// displacement lands on. Walking `f` from the far end of the window back to |
| 9122 | /// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame |
| 9123 | /// area map could not do at all. |
| 9124 | /// |
| 9125 | /// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean |
| 9126 | /// factor over the frame is exactly 1: a cell the window leans on is coded |
| 9127 | /// more distortion-averse (smaller lambda), and the frame's TOTAL lambda |
| 9128 | /// scale only moves around, never up or down -- a global move is what |
| 9129 | /// lane-av1lambda already measured inert. |
| 9130 | fn tpl_lambda_factors(frames: &[&[u8]], width: usize, height: usize, k: f64) -> Vec<f64> { |
| 9131 | let start = std::time::Instant::now(); |
| 9132 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 9133 | let cells = cells_x * cells_y; |
| 9134 | let levels = frames.len(); |
| 9135 | let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect(); |
| 9136 | let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels) |
| 9137 | .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height)) |
| 9138 | .collect(); |
| 9139 | let mut mc_dep = vec![vec![0.0f64; cells]; levels]; |
| 9140 | for f in (1..levels).rev() { |
| 9141 | for cy in 0..cells_y { |
| 9142 | for cx in 0..cells_x { |
| 9143 | let ci = cy * cells_x + cx; |
| 9144 | let (mv, inter) = passes[f - 1][ci]; |
| 9145 | let saved = f64::from(intra[f][ci].saturating_sub(inter)); |
| 9146 | let propagate = saved + mc_dep[f][ci]; |
| 9147 | if propagate <= 0.0 { |
| 9148 | continue; |
| 9149 | } |
| 9150 | // The 16x16 window of the PREVIOUS frame this cell predicted |
| 9151 | // from, spread over the cells it overlaps. |
| 9152 | let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); |
| 9153 | let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); |
| 9154 | for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) { |
| 9155 | let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16); |
| 9156 | for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) { |
| 9157 | let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16); |
| 9158 | mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0; |
| 9159 | } |
| 9160 | } |
| 9161 | } |
| 9162 | } |
| 9163 | } |
| 9164 | // The tail compression `p`: `mc_dep/intra` is a ratio with a very long |
| 9165 | // tail (a nearly flat cell the window leans on has a tiny denominator), |
| 9166 | // and at p = 1 that tail slams into the clamp. libaom reads its own |
| 9167 | // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P` |
| 9168 | // sweeps the exponent, 1 being the raw ratio. |
| 9169 | let power = std::env::var("EC_AV1_TPL_P") |
| 9170 | .ok() |
| 9171 | .and_then(|v| v.parse::<f64>().ok()) |
| 9172 | .filter(|p| p.is_finite() && *p > 0.0) |
| 9173 | .unwrap_or(TPL_POWER); |
| 9174 | // lane-av1tpl3, the three shape fixes, each its own knob so the gate can |
| 9175 | // read them apart. `SB` and `LOG` are the shipped shape (set the knob to |
| 9176 | // `0` to take either back out); `FLOOR` defaults to off. |
| 9177 | // |
| 9178 | // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the |
| 9179 | // frame's own mean intra cost. A cell of flat content has a near-zero |
| 9180 | // MAD, so its ratio explodes exactly where coding is cheap. |
| 9181 | // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra |
| 9182 | // and mc_dep are summed over the 64x64 superblock first -- libaom's |
| 9183 | // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not |
| 9184 | // per-16x16 numbers), which is also what makes the ratio survive one |
| 9185 | // flat cell next to a busy one. |
| 9186 | // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through |
| 9187 | // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail |
| 9188 | // harder than the `p` exponent alone can. |
| 9189 | let floor_frac = std::env::var("EC_AV1_TPL_FLOOR") |
| 9190 | .ok() |
| 9191 | .and_then(|v| v.parse::<f64>().ok()) |
| 9192 | .filter(|f| f.is_finite() && *f >= 0.0) |
| 9193 | .unwrap_or(0.0); |
| 9194 | let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0"); |
| 9195 | let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0"); |
| 9196 | let intra_mean = |
| 9197 | intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64; |
| 9198 | let floor = floor_frac * intra_mean; |
| 9199 | let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0); |
| 9200 | // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by |
| 9201 | // every cell under it. The edge groups are partial and summed as they are. |
| 9202 | let ratio: Vec<f64> = if sb_agg { |
| 9203 | let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4)); |
| 9204 | let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows]; |
| 9205 | for cy in 0..cells_y { |
| 9206 | for cx in 0..cells_x { |
| 9207 | let e = &mut sb[(cy / 4) * sb_cols + cx / 4]; |
| 9208 | e.0 += mc_dep[0][cy * cells_x + cx]; |
| 9209 | e.1 += denom(cy * cells_x + cx); |
| 9210 | } |
| 9211 | } |
| 9212 | (0..cells) |
| 9213 | .map(|c| { |
| 9214 | let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4]; |
| 9215 | dep / den.max(1.0) |
| 9216 | }) |
| 9217 | .collect() |
| 9218 | } else { |
| 9219 | (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect() |
| 9220 | }; |
| 9221 | let mut out: Vec<f64> = ratio |
| 9222 | .iter() |
| 9223 | .map(|&r| { |
| 9224 | let r = if log_beta { (1.0 + r).log2() } else { r }; |
| 9225 | (1.0 + k * r).powf(-power) |
| 9226 | }) |
| 9227 | .collect(); |
| 9228 | let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9); |
| 9229 | for f in &mut out { |
| 9230 | *f = (*f / mean).clamp(0.25, 4.0); |
| 9231 | } |
| 9232 | TPL_NANOS.fetch_add( |
| 9233 | start.elapsed().as_nanos() as u64, |
| 9234 | std::sync::atomic::Ordering::Relaxed, |
| 9235 | ); |
| 9236 | if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { |
| 9237 | let mut hist = [0usize; 8]; |
| 9238 | for &f in &out { |
| 9239 | hist[((f * 4.0) as usize).min(7)] += 1; |
| 9240 | } |
| 9241 | let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); |
| 9242 | let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count(); |
| 9243 | eprintln!( |
| 9244 | "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \ |
| 9245 | range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative", |
| 9246 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 9247 | ); |
| 9248 | } |
| 9249 | out |
| 9250 | } |
| 9251 | |
| 9252 | /// Where one inter frame sits in a coding-order pyramid: which DPB slots its |
| 9253 | /// references name, which slot it refreshes, whether it is shown when it is |
| 9254 | /// coded, and the `ref_frame_sign_bias` that follows from all of it. `None` |
| 9255 | /// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot |
| 9256 | /// 0/2 alternation, every frame shown, every reference in the past). |
| 9257 | /// |
| 9258 | /// The sign bias is carried rather than derived here because only the caller |
| 9259 | /// knows what order hint each slot holds; it is armed onto the tile writer |
| 9260 | /// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so |
| 9261 | /// the writer scans the same stacks the decoder will. |
| 9262 | #[derive(Debug, Clone, Copy)] |
| 9263 | pub(crate) struct PyramidFrame { |
| 9264 | /// The slot `LAST_FRAME` (and every reference this encoder does not name |
| 9265 | /// apart) reads. |
| 9266 | pub last_slot: u8, |
| 9267 | /// The single slot `refresh_frame_flags` sets. |
| 9268 | pub self_slot: u8, |
| 9269 | /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a |
| 9270 | /// pyramid, which is what makes `sign_bias`'s last entry true. |
| 9271 | pub altref_slot: u8, |
| 9272 | /// `show_frame`: false for a hidden frame, output later by a |
| 9273 | /// `show_existing_frame` header. |
| 9274 | pub show_frame: bool, |
| 9275 | /// This frame's `ref_frame_sign_bias` (spec 5.9.2). |
| 9276 | pub sign_bias: crate::mvstack::SignBiasTable, |
| 9277 | } |
| 9278 | |
| 9279 | /// Encodes one picture as an inter frame predicting from `reference`'s |
| 9280 | /// reconstruction, which the caller decoded (or, for the frame right after |
| 9281 | /// the key frame, is the key frame's own reconstruction). |
| 9282 | pub(crate) fn encode_inter_frame( |
| 9283 | picture: &Picture, |
| 9284 | reference: &Picture, |
| 9285 | base_q_idx: u8, |
| 9286 | deadzone: f64, |
| 9287 | order_hint: u32, |
| 9288 | // The order hint each of the seven `ref_frame_idx` entries names, which a |
| 9289 | // decoder reads out of its own reference state -- only spec 5.9.22's |
| 9290 | // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only |
| 9291 | // on a `reference_select` frame. [`flat_order_hints`] builds it for the |
| 9292 | // callers that follow this crate's own flat slot plan. |
| 9293 | order_hints: [u32; 7], |
| 9294 | render: (usize, usize), |
| 9295 | // The tables this frame's writer starts from: what the previous frame |
| 9296 | // stored into the slot this one's `primary_ref_frame` names. `None` |
| 9297 | // starts from the defaults, which is right only for the frame straight |
| 9298 | // after a key frame. |
| 9299 | start_cdfs: Option<&crate::cdf_state::Cdfs>, |
| 9300 | // The key frame's own (padded) reconstruction, which every frame of the |
| 9301 | // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame |
| 9302 | // with `LAST_FRAME` alone, exactly as before. |
| 9303 | golden: Option<&Picture>, |
| 9304 | // The frame two back, held in the slot this frame is about to refresh |
| 9305 | // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two |
| 9306 | // inter frames of a GOP, where the frame two back IS the key frame. |
| 9307 | altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, |
| 9308 | // Where this frame sits in the coding-order pyramid; `None` is the flat |
| 9309 | // one-shown-frame-per-picture stream this encoder wrote before. |
| 9310 | pyramid: Option<PyramidFrame>, |
| 9311 | // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of |
| 9312 | // them), padded like this one -- the lookahead window the per-block |
| 9313 | // lambda weighting propagates back through ([`tpl_lambda_factors`]). An |
| 9314 | // EMPTY slice codes the frame at one lambda, as before. |
| 9315 | lookahead: &[Picture], |
| 9316 | ) -> Result<Encoded> { |
| 9317 | picture.check()?; |
| 9318 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 9319 | return Err(Error::unsupported( |
| 9320 | "AV1 encode", |
| 9321 | "an inter frame is coded only for a picture that is a whole number \ |
| 9322 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 9323 | superblock's partition below that", |
| 9324 | )); |
| 9325 | } |
| 9326 | if reference.width != picture.width || reference.height != picture.height { |
| 9327 | return Err(Error::unsupported( |
| 9328 | "AV1 encode", |
| 9329 | "the reference picture must be the same size as the one being coded", |
| 9330 | )); |
| 9331 | } |
| 9332 | |
| 9333 | // The single slot this crate's inter frames ever predict from or |
| 9334 | // refresh (`inter_frame_headers`'s contract): every frame both reads and |
| 9335 | // overwrites slot 0, so the frame just coded is always what the next one |
| 9336 | // predicts against. |
| 9337 | const LAST_SLOT: u8 = 0; |
| 9338 | // Slot 0 and slot 2 alternate so the frame two back survives one more |
| 9339 | // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2) |
| 9340 | // and the picture this frame names as `ALTREF_FRAME` is the one sitting |
| 9341 | // in the very slot it will overwrite. |
| 9342 | let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot); |
| 9343 | let last_slot = pyramid.map_or( |
| 9344 | if order_hint <= 1 { |
| 9345 | LAST_SLOT |
| 9346 | } else if (order_hint - 1) % 2 == 1 { |
| 9347 | 0 |
| 9348 | } else { |
| 9349 | 2 |
| 9350 | }, |
| 9351 | |p| p.last_slot, |
| 9352 | ); |
| 9353 | // `render`, not `picture.width`/`picture.height`: `picture` here is |
| 9354 | // already padded to a whole number of superblocks (`encode_sequence`'s |
| 9355 | // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so |
| 9356 | // every true-edge clamp downstream) must come from the frame's real, |
| 9357 | // unpadded size, same as `key_frame_headers_colour` takes `render` and |
| 9358 | // not the padded picture in `encode_key_frame_inner`. |
| 9359 | let (seq, mut header) = inter_frame_headers_slots( |
| 9360 | render.0, |
| 9361 | render.1, |
| 9362 | base_q_idx, |
| 9363 | order_hint, |
| 9364 | last_slot, |
| 9365 | self_slot, |
| 9366 | match pyramid { |
| 9367 | Some(p) => p.altref_slot, |
| 9368 | None if altref.is_some() => self_slot, |
| 9369 | None => GOLDEN_SLOT, |
| 9370 | }, |
| 9371 | )?; |
| 9372 | header.render_width = render.0 as u32; |
| 9373 | header.render_height = render.1 as u32; |
| 9374 | let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); |
| 9375 | // The order hint behind each `ref_frame_idx` entry. The flat path's own |
| 9376 | // slot plan (`inter_frame_headers_slots`) is: every reference but |
| 9377 | // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except |
| 9378 | // `ALTREF_FRAME`, which reads the frame two back when there is one; |
| 9379 | // `GOLDEN_FRAME` is the key frame, order hint 0. Only |
| 9380 | // `frame::write_frame_header`'s `skipModeAllowed` reads this. |
| 9381 | header.order_hints = order_hints; |
| 9382 | header.reference_select = reference_select(); |
| 9383 | // Armed HERE, not only beside the tile write below: `ref_distance`'s own |
| 9384 | // per-reference order-hint distance is read by the block SEARCH, which |
| 9385 | // runs long before the writer arms these (the distance-scaled search step |
| 9386 | // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob |
| 9387 | // never reached the tool). |
| 9388 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 9389 | if let Some(p) = pyramid { |
| 9390 | header.show_frame = p.show_frame; |
| 9391 | header.showable_frame = !p.show_frame; |
| 9392 | header.ref_frame_sign_bias = p.sign_bias; |
| 9393 | } |
| 9394 | // `TxMode::Select` here too: an inter block then codes one `txfm_split` |
| 9395 | // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA |
| 9396 | // block inside this frame codes and searches its own `tx_depth`, the same |
| 9397 | // as in a key frame (`crate::tile::write_tx_syntax_inter`). |
| 9398 | let tx_select = tx_select() && tx_select_inter(); |
| 9399 | if tx_select { |
| 9400 | header.tx_mode = TxMode::Select; |
| 9401 | } |
| 9402 | |
| 9403 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 9404 | // lane-hbd r4: encoder stays 8-bit by design; narrow the source once |
| 9405 | // here (see `encode_key_frame_inner`). |
| 9406 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 9407 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 9408 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 9409 | // This frame's own `allow_screen_content_tools`. It can only be set when |
| 9410 | // the SEQUENCE offers the bit at all, which is the key frame's decision |
| 9411 | // ([`SEQ_SCREEN`]): a frame header that contradicts |
| 9412 | // `seq_force_screen_content_tools` is a corrupt stream, not a tighter |
| 9413 | // encode. |
| 9414 | let screen = seq_screen() |
| 9415 | && screen_content(&picture_y8, picture.width, true_width, true_height); |
| 9416 | header.allow_screen_content_tools = screen; |
| 9417 | // The search prices coefficients against the tables this frame's writer |
| 9418 | // starts from, not against the defaults (lane-av1txbits) -- but only on a |
| 9419 | // frame the screen detector said no to (lane-av1price2): armed HERE, after |
| 9420 | // `screen` exists, and again on every search/tile worker below. |
| 9421 | crate::tile::arm_pricing_cdfs(start_cdfs, screen); |
| 9422 | let mut luma = Plane { |
| 9423 | source: &picture_y8, |
| 9424 | reconstruction: vec![128; picture_y8.len()], |
| 9425 | width: picture.width, |
| 9426 | height: picture.height, |
| 9427 | true_width, |
| 9428 | true_height, |
| 9429 | tile_x0: 0, |
| 9430 | tile_y0: 0, |
| 9431 | tile_x1: picture.width, |
| 9432 | tile_y1: picture.height, |
| 9433 | ctx: CoefCtxMap::default(), |
| 9434 | }; |
| 9435 | let mut chroma = [ |
| 9436 | Plane { |
| 9437 | source: &picture_u8, |
| 9438 | reconstruction: vec![128; picture_u8.len()], |
| 9439 | width: picture.width / 2, |
| 9440 | height: picture.height / 2, |
| 9441 | true_width: true_width / 2, |
| 9442 | true_height: true_height / 2, |
| 9443 | tile_x0: 0, |
| 9444 | tile_y0: 0, |
| 9445 | tile_x1: picture.width / 2, |
| 9446 | tile_y1: picture.height / 2, |
| 9447 | ctx: CoefCtxMap::default(), |
| 9448 | }, |
| 9449 | Plane { |
| 9450 | source: &picture_v8, |
| 9451 | reconstruction: vec![128; picture_v8.len()], |
| 9452 | width: picture.width / 2, |
| 9453 | height: picture.height / 2, |
| 9454 | true_width: true_width / 2, |
| 9455 | true_height: true_height / 2, |
| 9456 | tile_x0: 0, |
| 9457 | tile_y0: 0, |
| 9458 | tile_x1: picture.width / 2, |
| 9459 | tile_y1: picture.height / 2, |
| 9460 | ctx: CoefCtxMap::default(), |
| 9461 | }, |
| 9462 | ]; |
| 9463 | |
| 9464 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 9465 | let search = Search { |
| 9466 | base_q_idx, |
| 9467 | deadzone, |
| 9468 | lambda: lambda_scale() |
| 9469 | * match pyramid { |
| 9470 | Some(p) if !p.show_frame => hidden_lambda_factor(), |
| 9471 | _ => 1.0, |
| 9472 | } |
| 9473 | * step |
| 9474 | * step, |
| 9475 | modes: &KEY_FRAME_MODES, |
| 9476 | top_k: prune_top_k_inter(), |
| 9477 | screen, |
| 9478 | }; |
| 9479 | let mode_bits_table = inter_mode_bits(); |
| 9480 | // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of |
| 9481 | // this frame the NEXT one predicts from. Off (`None`) without a |
| 9482 | // lookahead picture or at strength 0. |
| 9483 | let tpl_k = tpl_strength(); |
| 9484 | let window: Vec<&Picture> = lookahead |
| 9485 | .iter() |
| 9486 | .take_while(|n| n.width == picture.width && n.height == picture.height) |
| 9487 | .collect(); |
| 9488 | let tpl_sources: Vec<Vec<u8>> = |
| 9489 | window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect(); |
| 9490 | let tpl_cells_x = picture.width / 16; |
| 9491 | let tpl_factors: Option<Vec<f64>> = (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { |
| 9492 | if tpl_propagating() { |
| 9493 | let mut frames: Vec<&[u8]> = vec![&picture_y8]; |
| 9494 | frames.extend(tpl_sources.iter().map(Vec::as_slice)); |
| 9495 | tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k) |
| 9496 | } else { |
| 9497 | // The shipped map is one factor per 64x64; it is spread over that |
| 9498 | // superblock's own 16 cells so the application site below (which |
| 9499 | // averages the four cells of a 32x32 block) reads exactly the |
| 9500 | // superblock factor, whichever map fed it. |
| 9501 | let map = |
| 9502 | tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height); |
| 9503 | let cells_y = picture.height / 16; |
| 9504 | let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k); |
| 9505 | (0..tpl_cells_x * cells_y) |
| 9506 | .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4]) |
| 9507 | .collect() |
| 9508 | } |
| 9509 | }); |
| 9510 | |
| 9511 | // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded |
| 9512 | // coding surface's: `blocks` carries one entry per 32x32 block the tile |
| 9513 | // writer will actually visit, same count it checks `blocks.len()` |
| 9514 | // against, which is fewer than the padded surface's own block count |
| 9515 | // whenever the true size is not a 64x64 multiple. |
| 9516 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 9517 | let (cols, rows) = (cols as usize, rows as usize); |
| 9518 | let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 9519 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 9520 | // This frame's tile grid, as in `encode_key_frame_inner`. |
| 9521 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 9522 | let layout = |
| 9523 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 9524 | header.tile_info = tile_info_of(&layout, 1); |
| 9525 | let header_tile_info = header.tile_info.clone(); |
| 9526 | // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is |
| 9527 | // integer-`u8`-scale), so the DPB reference plane is narrowed for it -- |
| 9528 | // once per frame (lane-av1rd2), not once per block, which is a whole |
| 9529 | // plane's map per 32x32 block and now per leaf too. |
| 9530 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 9531 | // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour |
| 9532 | // availability -- intra edges and the MV stack's scans alike -- already |
| 9533 | // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`, |
| 9534 | // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote; |
| 9535 | // giving each job its own planes and its own `MiGrid` therefore leaves |
| 9536 | // every decision, and so every coded bit, exactly where the whole-frame |
| 9537 | // loop left it, at any tile count and any thread count. |
| 9538 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 9539 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 9540 | let [cb, cr] = &mut chroma; |
| 9541 | let chroma_out = [ |
| 9542 | crate::par::Shared::new(&mut cb.reconstruction), |
| 9543 | crate::par::Shared::new(&mut cr.reconstruction), |
| 9544 | ]; |
| 9545 | let search_tile = |index: usize, |
| 9546 | fctx: &crate::decode::FrameCtx| |
| 9547 | -> Result<Vec<(usize, Quadrant)>> { |
| 9548 | // Thread-local, and this job may be running on a `search_tiles` |
| 9549 | // worker: `ref_distance`'s order-hint distance (the scaled motion |
| 9550 | // search step) is read by the SEARCH, so every worker arms it or the |
| 9551 | // tile's bits depend on the thread count. |
| 9552 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 9553 | crate::tile::arm_pricing_cdfs(start_cdfs, screen); |
| 9554 | let rect = layout.rect(index); |
| 9555 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 9556 | let mut chroma = [ |
| 9557 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 9558 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 9559 | ]; |
| 9560 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 9561 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 9562 | grid.set_sign_bias(sign_bias); |
| 9563 | // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name, |
| 9564 | // built once per tile job (`obmc_prediction`). |
| 9565 | let mut obmc_refs: [Option<&Picture>; 8] = [None; 8]; |
| 9566 | obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference); |
| 9567 | obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden; |
| 9568 | obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref; |
| 9569 | grid.set_tile_bounds( |
| 9570 | rect.mi_row0 as usize, |
| 9571 | rect.mi_col0 as usize, |
| 9572 | rect.mi_row1 as usize, |
| 9573 | rect.mi_col1 as usize, |
| 9574 | ); |
| 9575 | let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); |
| 9576 | for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 9577 | for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 9578 | // lane-b64: the whole superblock as ONE 64x64 block, tried before |
| 9579 | // its quadrants are (`search_skip_64`) and compared against the |
| 9580 | // four of them below. Only a superblock wholly inside the true |
| 9581 | // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the |
| 9582 | // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask |
| 9583 | // only that the block's half is inside, and the trial is ranked |
| 9584 | // over the inside part alone ([`Plane::block_sse`]). |
| 9585 | let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK); |
| 9586 | let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols |
| 9587 | && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows |
| 9588 | && x64 + SUPERBLOCK <= luma.true_width |
| 9589 | && y64 + SUPERBLOCK <= luma.true_height; |
| 9590 | let edge_inside = b64_edge() |
| 9591 | && crate::tile::has_half( |
| 9592 | sb_c as u32 * crate::tile::SB_MI, |
| 9593 | crate::tile::SB_MI, |
| 9594 | header.mi_cols, |
| 9595 | ) |
| 9596 | && crate::tile::has_half( |
| 9597 | sb_r as u32 * crate::tile::SB_MI, |
| 9598 | crate::tile::SB_MI, |
| 9599 | header.mi_rows, |
| 9600 | ); |
| 9601 | let sb64_legal = b64_root() |
| 9602 | && sb_r * 2 + 1 < rows |
| 9603 | && sb_c * 2 + 1 < cols |
| 9604 | && (whole_inside || edge_inside); |
| 9605 | // One lambda for the whole superblock, the same mean the 32x32 |
| 9606 | // level takes over its own four tpl cells: the 64-vs-four-32 |
| 9607 | // comparison below weighs one cost against four, so both sides |
| 9608 | // have to be priced at the same lambda. |
| 9609 | let sb_search = match &tpl_factors { |
| 9610 | Some(f) if sb64_legal => { |
| 9611 | let mean = (0..16) |
| 9612 | .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) |
| 9613 | .sum::<f64>() |
| 9614 | / 16.0; |
| 9615 | Search { lambda: search.lambda * mean, ..search } |
| 9616 | } |
| 9617 | _ => search, |
| 9618 | }; |
| 9619 | let mark = blocks.len(); |
| 9620 | let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None; |
| 9621 | let mut sb_cost = 0.0f64; |
| 9622 | if sb64_legal { |
| 9623 | let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 9624 | let (mi_row, mi_col) = (sb_r * 16, sb_c * 16); |
| 9625 | let stack = |
| 9626 | find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows); |
| 9627 | // lane-b64b: the `LAST` + extra-reference pairs at this |
| 9628 | // superblock's own 16x16-mi window, the same stacks the tile |
| 9629 | // writer's `Whole64` arm rebuilds. Empty unless the frame |
| 9630 | // codes `reference_select`, which is what gates the syntax. |
| 9631 | // `!screen` for the same reason the residual arm is gated |
| 9632 | // there ([`b64_residual`]): a desktop capture's superblocks |
| 9633 | // are flat runs the skip arm already codes for nothing, and |
| 9634 | // MEASURED, compound at the root cost it +33.4/-23.8 -> |
| 9635 | // +33.7/-23.6 while both film rows gained (step 1's table). |
| 9636 | let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 9637 | if header.reference_select && b64_compound() && !screen { |
| 9638 | [ |
| 9639 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 9640 | (crate::mvstack::ALTREF_FRAME, altref), |
| 9641 | ] |
| 9642 | .into_iter() |
| 9643 | .filter_map(|(r, pic)| { |
| 9644 | pic.map(|p| { |
| 9645 | ( |
| 9646 | r, |
| 9647 | p, |
| 9648 | crate::mvstack::find_mv_stack_compound( |
| 9649 | &grid, |
| 9650 | mi_row, |
| 9651 | mi_col, |
| 9652 | 16, |
| 9653 | 16, |
| 9654 | (crate::mvstack::LAST_FRAME, r), |
| 9655 | mi_cols, |
| 9656 | mi_rows, |
| 9657 | grid.sign_bias_table(), |
| 9658 | &[(0, 0); 7], |
| 9659 | None, |
| 9660 | ), |
| 9661 | ) |
| 9662 | }) |
| 9663 | }) |
| 9664 | .collect() |
| 9665 | } else { |
| 9666 | Vec::new() |
| 9667 | }; |
| 9668 | if let Some((cost, block)) = search_skip_64( |
| 9669 | &mut luma, |
| 9670 | &mut chroma, |
| 9671 | (x64, y64), |
| 9672 | &sb_search, |
| 9673 | b64_residual() && !screen, |
| 9674 | reference, |
| 9675 | &stack, |
| 9676 | &sb_compound, |
| 9677 | fctx, |
| 9678 | ) { |
| 9679 | let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 9680 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base); |
| 9681 | let cost = cost |
| 9682 | + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false); |
| 9683 | sb64 = Some((cost, block, after)); |
| 9684 | } |
| 9685 | } |
| 9686 | // A superblock whose 64x64 trial already codes almost nothing per |
| 9687 | // pixel is taken outright and its quadrants are never searched -- |
| 9688 | // the same `split_rd_breakout` shape the 32x32 level uses one |
| 9689 | // size up, and where this lever BUYS wall instead of spending it. |
| 9690 | let early64 = sb64.as_ref().is_some_and(|(c, _, _)| { |
| 9691 | split_rd_breakout_at( |
| 9692 | b64_breakout_threshold(), |
| 9693 | *c, |
| 9694 | SUPERBLOCK, |
| 9695 | sb_search.lambda, |
| 9696 | ) |
| 9697 | }); |
| 9698 | for quadrant in 0..if early64 { 0 } else { 4 } { |
| 9699 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 9700 | // lane-av1tpl2: this 32x32 block's own lambda -- every RD |
| 9701 | // decision under it (partition, mode, tx, motion) reads |
| 9702 | // `search.lambda`, so scaling the one field here scales all |
| 9703 | // of them. 32x32 and not the 16x16 the map is built at |
| 9704 | // because the whole-vs-split comparison right below weighs |
| 9705 | // one 32x32 cost against four 16x16 ones: a per-leaf lambda |
| 9706 | // would make those two numbers incomparable. |
| 9707 | let search = match &tpl_factors { |
| 9708 | Some(f) => { |
| 9709 | let mean = (0..4) |
| 9710 | .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2]) |
| 9711 | .sum::<f64>() |
| 9712 | / 4.0; |
| 9713 | Search { lambda: search.lambda * mean, ..search } |
| 9714 | } |
| 9715 | None => search, |
| 9716 | }; |
| 9717 | // Same filter as the tile writer's: a quadrant whose own mi |
| 9718 | // origin is not inside the true frame is never coded. |
| 9719 | if r32 >= rows || c32 >= cols { |
| 9720 | continue; |
| 9721 | } |
| 9722 | // spec `decode_partition`'s hasRows/hasCols recomputed at this |
| 9723 | // 32x32 block's own half (`crate::tile::has_half`), same as |
| 9724 | // the key frame search: the true frame edge can fall inside a |
| 9725 | // quadrant a superblock-level check already let through, and |
| 9726 | // such a quadrant cannot be left whole -- it must split into |
| 9727 | // the 16x16 leaves that are actually inside the true frame |
| 9728 | // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split` |
| 9729 | // arm). |
| 9730 | let (has_cols32, has_rows32) = ( |
| 9731 | crate::tile::has_half( |
| 9732 | c32 as u32 * crate::tile::BLOCK_MI, |
| 9733 | crate::tile::BLOCK_MI, |
| 9734 | header.mi_cols, |
| 9735 | ), |
| 9736 | crate::tile::has_half( |
| 9737 | r32 as u32 * crate::tile::BLOCK_MI, |
| 9738 | crate::tile::BLOCK_MI, |
| 9739 | header.mi_rows, |
| 9740 | ), |
| 9741 | ); |
| 9742 | if has_cols32 && has_rows32 { |
| 9743 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 9744 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 9745 | let stack = |
| 9746 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 9747 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ |
| 9748 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 9749 | (crate::mvstack::ALTREF_FRAME, altref), |
| 9750 | ] |
| 9751 | .into_iter() |
| 9752 | .filter_map(|(r, pic)| { |
| 9753 | pic.map(|p| { |
| 9754 | ( |
| 9755 | r, |
| 9756 | p, |
| 9757 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), |
| 9758 | ) |
| 9759 | }) |
| 9760 | }) |
| 9761 | .collect(); |
| 9762 | let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks |
| 9763 | .iter() |
| 9764 | .map(|(r, p, st)| (*r, *p, st)) |
| 9765 | .collect(); |
| 9766 | // The COMPOUND stack of each `LAST` + extra pair, off the |
| 9767 | // same grid (and the same armed sign bias) the tile writer |
| 9768 | // rebuilds it from. Empty unless this frame codes |
| 9769 | // `reference_select`, which is what gates the syntax. |
| 9770 | let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 9771 | if header.reference_select { |
| 9772 | extra_stacks |
| 9773 | .iter() |
| 9774 | .map(|&(r, p, _)| { |
| 9775 | ( |
| 9776 | r, |
| 9777 | p, |
| 9778 | crate::mvstack::find_mv_stack_compound( |
| 9779 | &grid, |
| 9780 | mi_row, |
| 9781 | mi_col, |
| 9782 | 8, |
| 9783 | 8, |
| 9784 | (crate::mvstack::LAST_FRAME, r), |
| 9785 | mi_cols, |
| 9786 | mi_rows, |
| 9787 | grid.sign_bias_table(), |
| 9788 | &[(0, 0); 7], |
| 9789 | None, |
| 9790 | ), |
| 9791 | ) |
| 9792 | }) |
| 9793 | .collect() |
| 9794 | } else { |
| 9795 | Vec::new() |
| 9796 | }; |
| 9797 | |
| 9798 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 9799 | let (block, mut cost_whole) = search_inter_block( |
| 9800 | &mut luma, |
| 9801 | &mut chroma, |
| 9802 | (x, y), |
| 9803 | &search, |
| 9804 | &mode_bits_table, |
| 9805 | reference, |
| 9806 | &stack, |
| 9807 | &extra, |
| 9808 | &compound, |
| 9809 | &grid, |
| 9810 | (mi_row, mi_col), |
| 9811 | (mi_rows, mi_cols), |
| 9812 | fctx, |
| 9813 | ); |
| 9814 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 9815 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 9816 | |
| 9817 | // What four 16x16 leaves cost instead (spec |
| 9818 | // PARTITION_SPLIT at BLOCK_32X32, which |
| 9819 | // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm |
| 9820 | // already writes for a straddling quadrant). Each leaf is |
| 9821 | // searched against the reconstruction -- and the `mi` |
| 9822 | // grid -- the ones before it left, exactly as the writer |
| 9823 | // and the decoder will read them. |
| 9824 | // |
| 9825 | // A block the whole-32 search left skipped (no residual |
| 9826 | // at all) is not offered the split: libaom prunes the |
| 9827 | // same way at cpu-used 6, and it is where the wall would |
| 9828 | // otherwise go on static content. |
| 9829 | let leaf_positions: Vec<(usize, usize)> = (0..4) |
| 9830 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 9831 | .collect(); |
| 9832 | let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| { |
| 9833 | crate::tile::has_half( |
| 9834 | sc as u32 * crate::tile::SUB_MI, |
| 9835 | crate::tile::SUB_MI, |
| 9836 | header.mi_cols, |
| 9837 | ) && crate::tile::has_half( |
| 9838 | sr as u32 * crate::tile::SUB_MI, |
| 9839 | crate::tile::SUB_MI, |
| 9840 | header.mi_rows, |
| 9841 | ) |
| 9842 | }); |
| 9843 | // The breakout above: a 32x32 block that codes almost |
| 9844 | // nothing is not offered the split at all. |
| 9845 | let breakout = split_breakout_coeffs(); |
| 9846 | let split = (!block.skip |
| 9847 | && !split_rd_breakout(cost_whole, BLOCK, search.lambda) |
| 9848 | && (breakout == 0 || block.luma.len() > 4 * breakout) |
| 9849 | && leaves_legal |
| 9850 | && split_inter_blocks()) |
| 9851 | .then(|| { |
| 9852 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 9853 | let mut cost = search.lambda * partition_bits(BLOCK, true); |
| 9854 | let mut leaves = Vec::with_capacity(4); |
| 9855 | for &(sr, sc) in &leaf_positions { |
| 9856 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 9857 | let (lx, ly) = (sc * SUB, sr * SUB); |
| 9858 | let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 9859 | let stack = find_mv_stack( |
| 9860 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 9861 | ); |
| 9862 | let cstacks = leaf_compound_stacks( |
| 9863 | &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows, |
| 9864 | header.reference_select, golden, altref, |
| 9865 | ); |
| 9866 | let (leaf, leaf_cost) = code_square_inter( |
| 9867 | &mut luma, |
| 9868 | &mut chroma, |
| 9869 | (lx, ly), |
| 9870 | SUB, |
| 9871 | &search, |
| 9872 | &mode_bits_table, |
| 9873 | reference, |
| 9874 | &stack, |
| 9875 | &cstacks, |
| 9876 | &grid, |
| 9877 | (mi_row, mi_col), |
| 9878 | (mi_rows, mi_cols), |
| 9879 | &obmc_refs, |
| 9880 | fctx, |
| 9881 | ); |
| 9882 | let leaf_cost = leaf_cost |
| 9883 | + search.lambda * partition_bits(SUB, false); |
| 9884 | let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 9885 | |
| 9886 | // And what four 8x8 leaves cost instead -- |
| 9887 | // the same tree one step further down, which |
| 9888 | // the writer codes as a real PARTITION_SPLIT |
| 9889 | // at BLOCK_16X16 (lane-av1rd2). Same |
| 9890 | // skipped-block prune as the level above. |
| 9891 | let eight = (!leaf.skip |
| 9892 | && !split_rd_breakout(leaf_cost, SUB, search.lambda) |
| 9893 | && (breakout == 0 || leaf.luma.len() > breakout) |
| 9894 | && split_inter_8()) |
| 9895 | .then(|| { |
| 9896 | restore( |
| 9897 | &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base, |
| 9898 | ); |
| 9899 | let mut cost8 = search.lambda |
| 9900 | * (partition_bits(SUB, true) |
| 9901 | + 4.0 * partition_bits(8, false)); |
| 9902 | let mut eight = Vec::with_capacity(4); |
| 9903 | for i in 0..4 { |
| 9904 | let (mr, mc) = |
| 9905 | (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2); |
| 9906 | let stack8 = find_mv_stack( |
| 9907 | &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 9908 | ); |
| 9909 | let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 9910 | if header.reference_select && leaf_compound() { |
| 9911 | [ |
| 9912 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 9913 | (crate::mvstack::ALTREF_FRAME, altref), |
| 9914 | ] |
| 9915 | .into_iter() |
| 9916 | .filter_map(|(r, pic)| { |
| 9917 | pic.map(|p| { |
| 9918 | ( |
| 9919 | r, |
| 9920 | p, |
| 9921 | crate::mvstack::find_mv_stack_compound( |
| 9922 | &grid, mr, mc, 2, 2, |
| 9923 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 9924 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 9925 | ), |
| 9926 | ) |
| 9927 | }) |
| 9928 | }) |
| 9929 | .collect() |
| 9930 | } else { |
| 9931 | Vec::new() |
| 9932 | }; |
| 9933 | let (leaf8, cost) = code_square_inter( |
| 9934 | &mut luma, |
| 9935 | &mut chroma, |
| 9936 | (lx + (i % 2) * 8, ly + (i / 2) * 8), |
| 9937 | 8, |
| 9938 | &search, |
| 9939 | &mode_bits_table, |
| 9940 | reference, |
| 9941 | &stack8, |
| 9942 | &cstacks8, |
| 9943 | &grid, |
| 9944 | (mr, mc), |
| 9945 | (mi_rows, mi_cols), |
| 9946 | &obmc_refs, |
| 9947 | fctx, |
| 9948 | ); |
| 9949 | cost8 += cost; |
| 9950 | record_mi(&mut grid, mr, mc, 2, leaf8.inter); |
| 9951 | eight.push(leaf8); |
| 9952 | } |
| 9953 | (eight, cost8) |
| 9954 | }); |
| 9955 | match eight { |
| 9956 | Some((eight, cost8)) if cost8 < leaf_cost => { |
| 9957 | partition_hit(3); |
| 9958 | cost += cost8; |
| 9959 | leaves.push(BlockCoeffs { |
| 9960 | eight: Some(eight), |
| 9961 | ..BlockCoeffs::default() |
| 9962 | }); |
| 9963 | continue; |
| 9964 | } |
| 9965 | Some(_) => restore( |
| 9966 | &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf, |
| 9967 | ), |
| 9968 | None => {} |
| 9969 | } |
| 9970 | partition_hit(2); |
| 9971 | cost += leaf_cost; |
| 9972 | record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter); |
| 9973 | leaves.push(leaf); |
| 9974 | } |
| 9975 | (leaves, cost) |
| 9976 | }); |
| 9977 | if let Some((leaves, cost)) = split { |
| 9978 | if cost < cost_whole { |
| 9979 | // The leaves' own `mi` cells are already in the |
| 9980 | // grid, and their reconstruction is what the |
| 9981 | // planes hold. |
| 9982 | partition_hit(1); |
| 9983 | sb_cost += cost; |
| 9984 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 9985 | continue; |
| 9986 | } |
| 9987 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 9988 | } |
| 9989 | partition_hit(0); |
| 9990 | sb_cost += cost_whole; |
| 9991 | record_mi(&mut grid, mi_row, mi_col, 8, block.inter); |
| 9992 | blocks.push((r32 * cols + c32, Quadrant::Whole(block))); |
| 9993 | } else { |
| 9994 | // The sub-positions actually inside the true frame, same |
| 9995 | // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`. |
| 9996 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 9997 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 9998 | .filter(|&(sr, sc)| { |
| 9999 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 10000 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 10001 | }) |
| 10002 | .collect(); |
| 10003 | // Each leaf searches intra against its own `NEARESTMV` |
| 10004 | // candidate (`code_square_inter`), same real-inter choice |
| 10005 | // `search_inter_block` makes for a whole 32x32 block, at |
| 10006 | // this leaf's own 4x4-mi mv-stack window -- unless the |
| 10007 | // leaf's own half itself straddles the true edge, which |
| 10008 | // it codes as two (or one, at a true corner) 8x8 leaves |
| 10009 | // (`crate::tile::write_leaf8`'s inter counterpart), |
| 10010 | // mirroring the key frame search's straddling-16x16 |
| 10011 | // handling above (lane-av1inter8). |
| 10012 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 10013 | for (sr, sc) in sub_positions { |
| 10014 | let (has_cols16, has_rows16) = ( |
| 10015 | crate::tile::has_half( |
| 10016 | sc as u32 * crate::tile::SUB_MI, |
| 10017 | crate::tile::SUB_MI, |
| 10018 | header.mi_cols, |
| 10019 | ), |
| 10020 | crate::tile::has_half( |
| 10021 | sr as u32 * crate::tile::SUB_MI, |
| 10022 | crate::tile::SUB_MI, |
| 10023 | header.mi_rows, |
| 10024 | ), |
| 10025 | ); |
| 10026 | if has_cols16 && has_rows16 { |
| 10027 | let (x, y) = (sc * SUB, sr * SUB); |
| 10028 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 10029 | let stack = find_mv_stack( |
| 10030 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 10031 | ); |
| 10032 | let cstacks = leaf_compound_stacks( |
| 10033 | &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows, |
| 10034 | header.reference_select, golden, altref, |
| 10035 | ); |
| 10036 | let (block, _) = code_square_inter( |
| 10037 | &mut luma, |
| 10038 | &mut chroma, |
| 10039 | (x, y), |
| 10040 | SUB, |
| 10041 | &search, |
| 10042 | &mode_bits_table, |
| 10043 | reference, |
| 10044 | &stack, |
| 10045 | &cstacks, |
| 10046 | &grid, |
| 10047 | (mi_row, mi_col), |
| 10048 | (mi_rows, mi_cols), |
| 10049 | &obmc_refs, |
| 10050 | fctx, |
| 10051 | ); |
| 10052 | // One publication point for every coded leaf |
| 10053 | // (`record_mi`): this site used to spell the vote |
| 10054 | // out with `ref_frame` pinned to LAST and `mv1` |
| 10055 | // to (0,0), which is the encoder-grid-drift class |
| 10056 | // -- correct only for as long as a leaf can never |
| 10057 | // be compound. |
| 10058 | record_mi(&mut grid, mi_row, mi_col, 4, block.inter); |
| 10059 | leaves.push(block); |
| 10060 | } else { |
| 10061 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 10062 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 10063 | let mut eight = Vec::with_capacity(2); |
| 10064 | for i in 0..4 { |
| 10065 | let leaf_x = x_sub + (i % 2) * 8; |
| 10066 | let leaf_y = y_sub + (i / 2) * 8; |
| 10067 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 10068 | continue; |
| 10069 | } |
| 10070 | let (mi_row, mi_col) = |
| 10071 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 10072 | let stack = find_mv_stack( |
| 10073 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 10074 | ); |
| 10075 | let cstacks = leaf_compound_stacks( |
| 10076 | &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows, |
| 10077 | header.reference_select, golden, altref, |
| 10078 | ); |
| 10079 | let (leaf, _) = code_square_inter( |
| 10080 | &mut luma, |
| 10081 | &mut chroma, |
| 10082 | (leaf_x, leaf_y), |
| 10083 | 8, |
| 10084 | &search, |
| 10085 | &mode_bits_table, |
| 10086 | reference, |
| 10087 | &stack, |
| 10088 | &cstacks, |
| 10089 | &grid, |
| 10090 | (mi_row, mi_col), |
| 10091 | (mi_rows, mi_cols), |
| 10092 | &obmc_refs, |
| 10093 | fctx, |
| 10094 | ); |
| 10095 | // Same publication point as the 16x16 |
| 10096 | // straddling leaf above (`record_mi`). |
| 10097 | record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter); |
| 10098 | eight.push(leaf); |
| 10099 | } |
| 10100 | leaves.push(BlockCoeffs { |
| 10101 | eight: Some(eight), |
| 10102 | ..BlockCoeffs::default() |
| 10103 | }); |
| 10104 | } |
| 10105 | } |
| 10106 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 10107 | } |
| 10108 | } |
| 10109 | // The 64x64 root against what its four quadrants really cost. |
| 10110 | if let Some((cost64, block, after)) = sb64 |
| 10111 | && (early64 |
| 10112 | || cost64 |
| 10113 | < sb_cost |
| 10114 | + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true)) |
| 10115 | { |
| 10116 | B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10117 | if block.inter.is_some_and(|i| i.ref1.is_some()) { |
| 10118 | B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10119 | } |
| 10120 | if !whole_inside { |
| 10121 | B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10122 | } |
| 10123 | blocks.truncate(mark); |
| 10124 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after); |
| 10125 | // Overwrites every 16x16 mi cell the quadrant searches |
| 10126 | // published under this superblock, so the next block's stack |
| 10127 | // is built off the block that was really coded. |
| 10128 | record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter); |
| 10129 | blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block))); |
| 10130 | for q in 1..4 { |
| 10131 | let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2); |
| 10132 | blocks.push((r32 * cols + c32, Quadrant::Covered)); |
| 10133 | } |
| 10134 | } |
| 10135 | } |
| 10136 | } |
| 10137 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 10138 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 10139 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 10140 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 10141 | copy_rect( |
| 10142 | out, |
| 10143 | &tile.reconstruction, |
| 10144 | frame_width / 2, |
| 10145 | x0 / 2, |
| 10146 | y0 / 2, |
| 10147 | x1.div_ceil(2), |
| 10148 | y1.div_ceil(2), |
| 10149 | ); |
| 10150 | } |
| 10151 | Ok(blocks) |
| 10152 | }; |
| 10153 | for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)? |
| 10154 | .into_iter() |
| 10155 | .flatten() |
| 10156 | { |
| 10157 | blocks[at] = quadrant; |
| 10158 | } |
| 10159 | |
| 10160 | let modes = blocks |
| 10161 | .iter() |
| 10162 | .flat_map(Quadrant::blocks) |
| 10163 | .map(|b| b.mode) |
| 10164 | .collect::<Vec<_>>(); |
| 10165 | let inter_block_share = blocks |
| 10166 | .iter() |
| 10167 | .flat_map(Quadrant::blocks) |
| 10168 | .filter(|b| b.inter.is_some()) |
| 10169 | .count() as f64 |
| 10170 | / modes.len() as f64; |
| 10171 | for block in blocks.iter().flat_map(Quadrant::blocks) { |
| 10172 | if let Some(info) = block.inter { |
| 10173 | let r = (info.ref_frame as usize).min(7); |
| 10174 | REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10175 | } |
| 10176 | } |
| 10177 | #[cfg(test)] |
| 10178 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 10179 | // This frame's header leaves `disable_frame_end_update_cdf` off, so it |
| 10180 | // stores its end-of-tile tables with the counts reset (spec 7.20) and the |
| 10181 | // next frame's writer starts from them -- exactly what |
| 10182 | // `crate::stream::stored_cdfs_for` hands the decoder. |
| 10183 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 10184 | let cdfs = start_cdfs |
| 10185 | .cloned() |
| 10186 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); |
| 10187 | let start_cdfs = CdfSnapshot(cdfs); |
| 10188 | let reference_select_bit = header.reference_select; |
| 10189 | let switchable_motion_mode = header.is_motion_mode_switchable; |
| 10190 | let warped_motion = header.allow_warped_motion; |
| 10191 | let order_hint_bits = seq.order_hint_bits; |
| 10192 | let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; |
| 10193 | let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; |
| 10194 | // What this frame stores is the LARGEST tile's end-of-tile tables -- |
| 10195 | // its own header's `context_update_tile_id` (spec 7.20), which |
| 10196 | // `tile_info_of` set to exactly that tile. |
| 10197 | let store_tile = layout.largest_tile(); |
| 10198 | let end_cdfs = std::cell::RefCell::new(None); |
| 10199 | // As in `encode_key_frame_inner`: every tile starts from this frame's |
| 10200 | // own tables, so no tile depends on any other. |
| 10201 | let code_tiles = |bits: u8, |
| 10202 | sb_cols: usize, |
| 10203 | cdef_grid: &[u8], |
| 10204 | units: &[Option<crate::restoration::WienerInfo>]| |
| 10205 | -> Result<Vec<Vec<u8>>> { |
| 10206 | let (out, stored) = write_tiles(layout.count(), store_tile, |index| { |
| 10207 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); |
| 10208 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 10209 | crate::tile::arm_sign_bias(sign_bias); |
| 10210 | // Thread-locals: every tile job arms its own worker. |
| 10211 | crate::tile::arm_reference_select(reference_select_bit); |
| 10212 | crate::tile::arm_motion_mode(switchable_motion_mode); |
| 10213 | crate::tile::arm_warped_motion(warped_motion); |
| 10214 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 10215 | crate::tile::arm_screen(screen); |
| 10216 | crate::tile::arm_filter_intra(filter_intra_on()); |
| 10217 | let mut cdfs = start_cdfs.0.clone(); |
| 10218 | crate::tile::arm_pricing_cdfs(Some(&cdfs), screen); |
| 10219 | // Each tile's own MV grid: a candidate scan never reaches past |
| 10220 | // the tile's bounds, so a grid holding only this tile's own |
| 10221 | // blocks reads exactly as the decoder's frame-wide one does |
| 10222 | // under `MiGrid::set_tile_bounds`. |
| 10223 | let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 10224 | mv_grid.set_sign_bias(sign_bias); |
| 10225 | let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 10226 | mi_cols, |
| 10227 | mi_rows, |
| 10228 | base_q_idx, |
| 10229 | &blocks, |
| 10230 | tx_select, |
| 10231 | &mut cdfs, |
| 10232 | layout.rect(index), |
| 10233 | &mut mv_grid, |
| 10234 | )?; |
| 10235 | Ok((bytes, Some(cdfs))) |
| 10236 | })?; |
| 10237 | if let Some(cdfs) = stored { |
| 10238 | *end_cdfs.borrow_mut() = Some(cdfs); |
| 10239 | } |
| 10240 | Ok(out) |
| 10241 | }; |
| 10242 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 10243 | // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs |
| 10244 | // this tile against the same single-slot reference this encoder predicted |
| 10245 | // from, under each candidate level. |
| 10246 | // The reference a DECODER holds is this frame's cropped size, not the |
| 10247 | // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a |
| 10248 | // reference whose height is not the header's own `frame_height` (spec |
| 10249 | // 7.9's compatible-size rule), and the chained-decode round trips prove |
| 10250 | // the two predict identically. |
| 10251 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 10252 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { |
| 10253 | reference.clone() |
| 10254 | } else { |
| 10255 | Picture { |
| 10256 | width: fw, |
| 10257 | height: fh, |
| 10258 | y: crop_plane(&reference.y, reference.width, fw, fh), |
| 10259 | u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), |
| 10260 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), |
| 10261 | } |
| 10262 | }; |
| 10263 | // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1, |
| 10264 | // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose |
| 10265 | // blocks may name GOLDEN needs that plane too, cropped the same way. |
| 10266 | let trial_golden = golden.map(|g| { |
| 10267 | if (g.width, g.height) == (fw, fh) { |
| 10268 | g.clone() |
| 10269 | } else { |
| 10270 | Picture { |
| 10271 | width: fw, |
| 10272 | height: fh, |
| 10273 | y: crop_plane(&g.y, g.width, fw, fh), |
| 10274 | u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), |
| 10275 | v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), |
| 10276 | } |
| 10277 | } |
| 10278 | }); |
| 10279 | let trial_altref = altref.map(|a| { |
| 10280 | if (a.width, a.height) == (fw, fh) { |
| 10281 | a.clone() |
| 10282 | } else { |
| 10283 | Picture { |
| 10284 | width: fw, |
| 10285 | height: fh, |
| 10286 | y: crop_plane(&a.y, a.width, fw, fh), |
| 10287 | u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), |
| 10288 | v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), |
| 10289 | } |
| 10290 | } |
| 10291 | }); |
| 10292 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 10293 | refs[1] = Some(&trial_ref); |
| 10294 | refs[4] = trial_golden.as_ref(); |
| 10295 | refs[7] = trial_altref.as_ref(); |
| 10296 | let refpix = crate::decode::RefPix::ready(refs); |
| 10297 | pick_and_apply_filters( |
| 10298 | &mut header, |
| 10299 | &mut luma, |
| 10300 | &mut chroma, |
| 10301 | [&picture_y8, &picture_u8, &picture_v8], |
| 10302 | // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes |
| 10303 | // this frame's own `tx_select`, so the search runs under inter |
| 10304 | // `TxMode::Select` too (it used to skip and leave every inter frame |
| 10305 | // unfiltered once Select became the default). |
| 10306 | true, |
| 10307 | &mut tiles, |
| 10308 | search.lambda, |
| 10309 | fctx, |
| 10310 | // As in `encode_key_frame_inner`, but this frame's end-of-tile tables |
| 10311 | // are what the NEXT frame writes from, so the winning re-code |
| 10312 | // publishes its own into `end_cdfs` -- the first write's are stale |
| 10313 | // the moment a second tile is coded. |
| 10314 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 10315 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 10316 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 10317 | crate::decode::decode_inter_frame_tiles_lr( |
| 10318 | &payloads, |
| 10319 | &header_tile_info, |
| 10320 | h.mi_cols, |
| 10321 | h.mi_rows, |
| 10322 | base_q_idx, |
| 10323 | h.frame_width, |
| 10324 | h.frame_height, |
| 10325 | &refpix, |
| 10326 | cdef, |
| 10327 | lf, |
| 10328 | h.allow_high_precision_mv, |
| 10329 | h.force_integer_mv, |
| 10330 | Some(mc::InterpFilterKind::Regular), |
| 10331 | seq.enable_dual_filter, |
| 10332 | h.reference_select, |
| 10333 | tx_select, |
| 10334 | lr, |
| 10335 | // The trial decode re-reads the tile the writer just wrote, |
| 10336 | // so it starts from the same tables the writer did (this |
| 10337 | // frame's `start_cdfs`), not from the defaults. |
| 10338 | Some(start_cdfs.0.clone()), |
| 10339 | sign_bias, |
| 10340 | h.allow_screen_content_tools, |
| 10341 | switchable_motion_mode, |
| 10342 | h.allow_warped_motion, |
| 10343 | seq.enable_filter_intra, |
| 10344 | fctx, |
| 10345 | ) |
| 10346 | }, |
| 10347 | )?; |
| 10348 | let mut cdfs = end_cdfs |
| 10349 | .into_inner() |
| 10350 | .unwrap_or_else(|| start_cdfs.0.clone()); |
| 10351 | cdfs.reset_counts(); |
| 10352 | let next_cdfs = CdfSnapshot(cdfs); |
| 10353 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 10354 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 10355 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 10356 | let mut stream = temporal_delimiter(); |
| 10357 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 10358 | |
| 10359 | let [u, v] = chroma; |
| 10360 | Ok(Encoded { |
| 10361 | stream, |
| 10362 | modes, |
| 10363 | inter_block_share, |
| 10364 | reconstruction: Picture { |
| 10365 | width: luma.width, |
| 10366 | height: luma.height, |
| 10367 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 10368 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 10369 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 10370 | }, |
| 10371 | tile, |
| 10372 | mi_cols: header.mi_cols, |
| 10373 | mi_rows: header.mi_rows, |
| 10374 | base_q_idx, |
| 10375 | tx_select, |
| 10376 | switchable_motion_mode, |
| 10377 | screen, |
| 10378 | start_cdfs, |
| 10379 | next_cdfs, |
| 10380 | loop_filter: header.loop_filter, |
| 10381 | cdef: header.cdef, |
| 10382 | loop_restoration: header.loop_restoration, |
| 10383 | // An inter frame never allows intrabc (spec 5.9.2 codes the bit on |
| 10384 | // intra frames only). |
| 10385 | allow_intrabc: false, |
| 10386 | }) |
| 10387 | } |
| 10388 | |
| 10389 | /// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key |
| 10390 | /// frame's temporal unit followed by one inter frame's temporal unit per |
| 10391 | /// remaining picture, all sharing the key frame's sequence header -- and |
| 10392 | /// each frame's own [`Encoded`], in coding order. |
| 10393 | #[derive(Clone, Debug)] |
| 10394 | pub struct EncodedSequence { |
| 10395 | /// The whole stream: `frames[0].stream` (a temporal delimiter, the |
| 10396 | /// sequence header and the key frame) followed by each later frame's |
| 10397 | /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses |
| 10398 | /// the sequence header the key frame carried). |
| 10399 | pub stream: Vec<u8>, |
| 10400 | /// One entry per picture, in DISPLAY order — the order a decoder outputs |
| 10401 | /// them and the order `pictures` came in. Without a pyramid that is also |
| 10402 | /// the coding order; with one the two differ, and `coding_order` is the |
| 10403 | /// map between them. |
| 10404 | pub frames: Vec<Encoded>, |
| 10405 | /// The index into `frames` of each coded frame, in CODING order — what a |
| 10406 | /// per-coded-frame census (`take_predicted_bits`) must be zipped against. |
| 10407 | /// `0..frames.len()` on the flat path. |
| 10408 | pub coding_order: Vec<usize>, |
| 10409 | } |
| 10410 | |
| 10411 | /// Encodes a sequence of pictures as a key frame followed by one inter frame |
| 10412 | /// per remaining picture, each predicting from the previous frame's own |
| 10413 | /// decoded reconstruction — never from the source, which is what a decoder |
| 10414 | /// cannot see. Every picture must be the same even size (any even width and |
| 10415 | /// height — each is padded to a whole number of 64x64 superblocks |
| 10416 | /// internally, which is what lets an inter frame's reference always match |
| 10417 | /// the frame being coded against it), and `pictures` must be non-empty. |
| 10418 | /// |
| 10419 | /// # Errors |
| 10420 | /// Returns an error when `pictures` is empty, when any picture besides the |
| 10421 | /// first is not the same size as the first, or under the same conditions |
| 10422 | /// [`encode_key_frame`] and the inter frame path do. |
| 10423 | pub(crate) fn encode_sequence_with_ctx( |
| 10424 | pictures: &[Picture], |
| 10425 | base_q_idx: u8, |
| 10426 | deadzone: f64, fctx: &crate::decode::FrameCtx, |
| 10427 | ) -> Result<EncodedSequence> { |
| 10428 | let Some((first, rest)) = pictures.split_first() else { |
| 10429 | return Err(Error::unsupported( |
| 10430 | "AV1 encode", |
| 10431 | "a sequence needs at least one picture", |
| 10432 | )); |
| 10433 | }; |
| 10434 | first.check_even()?; |
| 10435 | let render = (first.width, first.height); |
| 10436 | // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is |
| 10437 | // coded as mini-GOPs -- a hidden ALTREF ahead of its display position, |
| 10438 | // the leaves that predict backward off it, and a `show_existing_frame` |
| 10439 | // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for |
| 10440 | // an A/B. Screen content stays flat (the content gate in |
| 10441 | // `Av1Encoder::encode_frames`, whose detector this asks first so the |
| 10442 | // whole sequence path is decided in one place), and so does a run that |
| 10443 | // asks for a quantizer rounding offset the facade does not carry: the |
| 10444 | // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone -- |
| 10445 | // the ablations' -- must keep the flat path rather than be silently |
| 10446 | // ignored. |
| 10447 | // |
| 10448 | // The reordering itself is NOT reimplemented here: it is the facade's |
| 10449 | // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]), |
| 10450 | // called with this sequence's shape, so the two paths cannot drift. |
| 10451 | let pyramid = crate::encoder::Pyramid::from_env() |
| 10452 | .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON) |
| 10453 | .filter(|_| !picture_is_screen(first)); |
| 10454 | LAST_SEQ_PYRAMID.with(|c| c.set(pyramid)); |
| 10455 | if let Some(pyramid) = pyramid { |
| 10456 | for picture in rest { |
| 10457 | picture.check_even()?; |
| 10458 | if (picture.width, picture.height) != render { |
| 10459 | return Err(Error::unsupported( |
| 10460 | "AV1 encode", |
| 10461 | "every picture in a sequence must be the same size as the first", |
| 10462 | )); |
| 10463 | } |
| 10464 | } |
| 10465 | return crate::encoder::Av1Encoder::encode_sequence_pyramid( |
| 10466 | pictures, |
| 10467 | base_q_idx, |
| 10468 | pyramid, |
| 10469 | armed_tiles(), |
| 10470 | ); |
| 10471 | } |
| 10472 | // The key frame and every inter frame after it are coded at the same |
| 10473 | // padded size, so the reference each inter frame predicts from -- the |
| 10474 | // previous frame's own uncropped reconstruction, at the size a decoder's |
| 10475 | // reference buffer actually holds -- always matches the frame being |
| 10476 | // coded against it. |
| 10477 | let key = encode_key_frame_inner( |
| 10478 | &first.padded_to(SUPERBLOCK), |
| 10479 | base_q_idx, |
| 10480 | deadzone, |
| 10481 | &KEY_FRAME_MODES, |
| 10482 | split_blocks(), |
| 10483 | render, |
| 10484 | unspecified_color_config(), fctx, |
| 10485 | )?; |
| 10486 | let mut stream = key.stream.clone(); |
| 10487 | // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the |
| 10488 | // key frame refreshes every slot, each inter frame only slot 0), which is |
| 10489 | // what `GOLDEN_FRAME` names. |
| 10490 | let golden = key.reconstruction.clone(); |
| 10491 | // The frame two back, once there is one that is not the key frame |
| 10492 | // itself (which `GOLDEN_FRAME` already names). |
| 10493 | let mut prev2: Option<Picture> = None; |
| 10494 | let mut carried = key.next_cdfs.clone(); |
| 10495 | let mut reference = key.reconstruction.clone(); |
| 10496 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 10497 | for (i, picture) in rest.iter().enumerate() { |
| 10498 | picture.check_even()?; |
| 10499 | // lane-av1tpl2: the lookahead window the per-block lambda weighting |
| 10500 | // propagates back through -- the next [`tpl_depth`] - 1 pictures' |
| 10501 | // sources at this frame's coded (padded) size. The tail of the |
| 10502 | // sequence gets a shorter window, and the last frame none at all. |
| 10503 | let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..] |
| 10504 | .iter() |
| 10505 | .take(tpl_depth() - 1) |
| 10506 | .map(|n| n.padded_to(SUPERBLOCK)) |
| 10507 | .collect(); |
| 10508 | if (picture.width, picture.height) != render { |
| 10509 | return Err(Error::unsupported( |
| 10510 | "AV1 encode", |
| 10511 | "every picture in a sequence must be the same size as the first", |
| 10512 | )); |
| 10513 | } |
| 10514 | let order_hint = (i + 1) as u32; |
| 10515 | let inter = encode_inter_frame( |
| 10516 | &picture.padded_to(SUPERBLOCK), |
| 10517 | &reference, |
| 10518 | base_q_idx, |
| 10519 | deadzone, |
| 10520 | order_hint, |
| 10521 | flat_order_hints(order_hint, 0, prev2.is_some()), |
| 10522 | render, |
| 10523 | Some(&carried.0), |
| 10524 | Some(&golden), |
| 10525 | prev2.as_ref(), fctx, |
| 10526 | None, |
| 10527 | &lookahead, |
| 10528 | )?; |
| 10529 | stream.extend_from_slice(&inter.stream); |
| 10530 | carried = inter.next_cdfs.clone(); |
| 10531 | prev2 = Some(std::mem::replace( |
| 10532 | &mut reference, |
| 10533 | inter.reconstruction.clone(), |
| 10534 | )); |
| 10535 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 10536 | } |
| 10537 | Ok(EncodedSequence { |
| 10538 | stream, |
| 10539 | coding_order: (0..frames.len()).collect(), |
| 10540 | frames, |
| 10541 | }) |
| 10542 | } |
| 10543 | |
| 10544 | #[cfg(test)] |
| 10545 | mod tests { |
| 10546 | |
| 10547 | /// lane-av1tpl2's propagated map, on the two properties every decision |
| 10548 | /// under it rests on: a frame the whole lookahead window repeats exactly |
| 10549 | /// (uniform texture) leans on every cell alike, so every factor is 1 and |
| 10550 | /// the weighting is a no-op; and where the window really does save bits |
| 10551 | /// by predicting -- the textured half of a frame whose other half is |
| 10552 | /// flat -- the factor FALLS below 1, i.e. that half is coded more |
| 10553 | /// distortion-averse than the half nothing gains from. |
| 10554 | /// The distortion metric itself (lane-sse): a block the true frame edge |
| 10555 | /// cuts through is scored over its INSIDE part only, so a difference that |
| 10556 | /// lives entirely in the padding costs nothing and a block wholly past |
| 10557 | /// the edge scores zero. Before this, the search ranked modes, |
| 10558 | /// transforms and partition trees on samples the display crop throws |
| 10559 | /// away -- which lane-b64b had fixed for the 64x64 root alone. |
| 10560 | #[test] |
| 10561 | fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() { |
| 10562 | // A 40x40 true frame on a 64x64 padded coding surface. |
| 10563 | let source = vec![10u8; 64 * 64]; |
| 10564 | let plane = fresh_plane(&source, 64, 64, 40, 40); |
| 10565 | let mut reconstruction = vec![10u8; 64 * 64]; |
| 10566 | // Off by 190 at (50, 50) -- past the true edge in both axes. |
| 10567 | reconstruction[50 * 64 + 50] = 200; |
| 10568 | assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored"); |
| 10569 | // Off by 10 at (39, 39) -- the last sample the decoder shows. |
| 10570 | reconstruction[39 * 64 + 39] = 20; |
| 10571 | assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored"); |
| 10572 | // A 16x16 block whose every sample is padding. |
| 10573 | let block = vec![200u8; 16 * 16]; |
| 10574 | assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored"); |
| 10575 | // A 16x16 block the edge cuts: 8 of its columns are inside. |
| 10576 | assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0); |
| 10577 | } |
| 10578 | |
| 10579 | #[test] |
| 10580 | fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { |
| 10581 | // Four 64x64 superblocks across: the shipped map forms its ratio per |
| 10582 | // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could |
| 10583 | // only ever produce one ratio -- and one ratio, mean-normalised, is |
| 10584 | // the flat map, whatever the content underneath it. |
| 10585 | let (w, h) = (256usize, 64usize); |
| 10586 | let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); |
| 10587 | let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; |
| 10588 | let f = super::tpl_lambda_factors(&frames, w, h, 1.0); |
| 10589 | assert_eq!(f.len(), 64, "16x4 cells of 16x16"); |
| 10590 | for (i, &v) in f.iter().enumerate() { |
| 10591 | assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda"); |
| 10592 | } |
| 10593 | |
| 10594 | // Left half textured, right half constant: the window saves bits |
| 10595 | // predicting the left half and nothing at all on the right. |
| 10596 | let split: Vec<u8> = (0..w * h) |
| 10597 | .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 }) |
| 10598 | .collect(); |
| 10599 | let frames: Vec<&[u8]> = vec![&split, &split, &split]; |
| 10600 | let cells_x = w / 16; |
| 10601 | for k in [0.25f64, 0.5, 1.0, 2.0] { |
| 10602 | let f = super::tpl_lambda_factors(&frames, w, h, k); |
| 10603 | for r in 0..h / 16 { |
| 10604 | let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); |
| 10605 | assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1"); |
| 10606 | assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1"); |
| 10607 | } |
| 10608 | } |
| 10609 | } |
| 10610 | |
| 10611 | /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a |
| 10612 | /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a |
| 10613 | /// row holds `32 >> bw_in_mi_log2` bits and the table holds |
| 10614 | /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that |
| 10615 | /// superblock must therefore hit every bit of the table EXACTLY ONCE. |
| 10616 | /// r4's `4 - bw_log2` index halved the row stride: the walk then covered |
| 10617 | /// only a quarter of the 16x8 table and read the wrong byte for every |
| 10618 | /// block row but the first (silently wrong above-right/below-left |
| 10619 | /// availability -- wrong pixels, no error). |
| 10620 | #[test] |
| 10621 | fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { |
| 10622 | for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 10623 | let (bw_log2, bh_log2) = |
| 10624 | ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); |
| 10625 | let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); |
| 10626 | for (name, table) in |
| 10627 | [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] |
| 10628 | { |
| 10629 | assert_eq!( |
| 10630 | table.len() * 8, |
| 10631 | rows * cols, |
| 10632 | "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" |
| 10633 | ); |
| 10634 | let mut seen = vec![0u32; table.len() * 8]; |
| 10635 | for blk_row in 0..rows { |
| 10636 | for blk_col in 0..cols { |
| 10637 | let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); |
| 10638 | assert!( |
| 10639 | idx < seen.len(), |
| 10640 | "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" |
| 10641 | ); |
| 10642 | seen[idx] += 1; |
| 10643 | } |
| 10644 | } |
| 10645 | assert!( |
| 10646 | seen.iter().all(|&n| n == 1), |
| 10647 | "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ |
| 10648 | (row stride is not {cols})" |
| 10649 | ); |
| 10650 | } |
| 10651 | } |
| 10652 | } |
| 10653 | use super::*; |
| 10654 | use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; |
| 10655 | use std::io::Write; |
| 10656 | use std::process::{Command, Stdio}; |
| 10657 | |
| 10658 | /// Every rectangular shape this decoder codes, at every position a block |
| 10659 | /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`] |
| 10660 | /// must answer exactly what libaom's `has_top_right`/`has_bottom_left` |
| 10661 | /// (`reconintra.c`) answer, whose bodies are ported below. |
| 10662 | /// |
| 10663 | /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): |
| 10664 | /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the |
| 10665 | /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right) |
| 10666 | /// and 7 (below-left) of the 21 reachable positions with no gate seeing |
| 10667 | /// it. The per-shape `(len, byte sum)` fingerprints below come from the |
| 10668 | /// oracle's own arrays, so a re-routed or truncated table fails here even |
| 10669 | /// where the two rows happen to agree. |
| 10670 | /// |
| 10671 | /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/ |
| 10672 | /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the |
| 10673 | /// callers handle by predicting each transform unit as its own block. |
| 10674 | /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's |
| 10675 | /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is |
| 10676 | /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL |
| 10677 | /// (the horizontal shapes, which those partitions never produce). |
| 10678 | #[test] |
| 10679 | fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { |
| 10680 | let fctx = &crate::decode::FrameCtx::new(); |
| 10681 | // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum). |
| 10682 | const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ |
| 10683 | (4, 8, 64, 9280, 64, 550), |
| 10684 | (8, 4, 64, 3712, 64, 9630), |
| 10685 | (8, 16, 16, 2352, 16, 134), |
| 10686 | (16, 8, 16, 960, 16, 2400), |
| 10687 | (16, 32, 4, 620, 4, 32), |
| 10688 | (32, 16, 4, 32, 4, 184), |
| 10689 | (32, 64, 1, 127, 1, 0), |
| 10690 | (64, 32, 1, 19, 1, 34), |
| 10691 | (4, 16, 32, 5472, 32, 14), |
| 10692 | (16, 4, 32, 960, 32, 6464), |
| 10693 | (8, 32, 8, 1400, 8, 2), |
| 10694 | (32, 8, 8, 32, 8, 1136), |
| 10695 | (16, 64, 2, 382, 2, 0), |
| 10696 | (64, 16, 2, 4, 2, 84), |
| 10697 | ]; |
| 10698 | /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for |
| 10699 | /// a block whose transform covers it whole (`row_off == col_off == 0`, |
| 10700 | /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel |
| 10701 | /// superblock (`sb_mi_size == 16`). |
| 10702 | fn libaom_reach( |
| 10703 | bw: usize, |
| 10704 | bh: usize, |
| 10705 | x: usize, |
| 10706 | y: usize, |
| 10707 | width: usize, |
| 10708 | height: usize, _fctx: &crate::decode::FrameCtx, |
| 10709 | ) -> (bool, bool) { |
| 10710 | let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); |
| 10711 | let (_bw_unit, bh_unit) = (bw / 4, bh / 4); |
| 10712 | let sb_mi_size = 16usize; |
| 10713 | let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; |
| 10714 | let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; |
| 10715 | let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; |
| 10716 | let (tr_table, bl_table) = rect_reach_tables(bw, bh); |
| 10717 | let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; |
| 10718 | // has_top_right: top_available && right_available, then row_off == 0. |
| 10719 | let top_right = if y == 0 || x + bw >= width { |
| 10720 | false |
| 10721 | } else if blk_row_in_sb == 0 { |
| 10722 | // (`col_off + tx_wide_unit < plane_bw_unit` above this is |
| 10723 | // `bw_unit < bw_unit`, false for a whole-block transform.) |
| 10724 | true |
| 10725 | } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { |
| 10726 | false |
| 10727 | } else { |
| 10728 | bit(tr_table) |
| 10729 | }; |
| 10730 | // has_bottom_left: bottom_available && left_available, col_off == 0. |
| 10731 | let bottom_left = if x == 0 || y + bh >= height { |
| 10732 | false |
| 10733 | } else if blk_col_in_sb == 0 { |
| 10734 | // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.) |
| 10735 | (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size |
| 10736 | } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { |
| 10737 | false |
| 10738 | } else { |
| 10739 | bit(bl_table) |
| 10740 | }; |
| 10741 | (top_right, bottom_left) |
| 10742 | } |
| 10743 | for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { |
| 10744 | let (tr, bl) = rect_reach_tables(bw, bh); |
| 10745 | let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>(); |
| 10746 | assert_eq!( |
| 10747 | (tr.len(), sum(tr), bl.len(), sum(bl)), |
| 10748 | (tr_len, tr_sum, bl_len, bl_sum), |
| 10749 | "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" |
| 10750 | ); |
| 10751 | // Two superblocks across and down, so the superblock-relative |
| 10752 | // position (and not the frame position) is what decides. |
| 10753 | for sb_y in [0usize, 64] { |
| 10754 | for sb_x in [0usize, 64] { |
| 10755 | for y in (sb_y..sb_y + 64).step_by(bh) { |
| 10756 | for x in (sb_x..sb_x + 64).step_by(bw) { |
| 10757 | let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); |
| 10758 | let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); |
| 10759 | assert_eq!( |
| 10760 | (got.above_right, got.below_left), |
| 10761 | want, |
| 10762 | "{bw}x{bh} at ({x}, {y})" |
| 10763 | ); |
| 10764 | } |
| 10765 | } |
| 10766 | } |
| 10767 | } |
| 10768 | } |
| 10769 | } |
| 10770 | |
| 10771 | /// Whether ffmpeg is on PATH. Absence normally SKIPs, but |
| 10772 | /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every |
| 10773 | /// aomenc gate decodes its stream through ffmpeg and is meaningless |
| 10774 | /// without it -- turns it into a hard failure. Without this the require |
| 10775 | /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first |
| 10776 | /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg |
| 10777 | /// printed SKIP and reported green (class gate-skips-on-its-own-failure). |
| 10778 | fn have_ffmpeg() -> bool { |
| 10779 | let present = Command::new("ffmpeg") |
| 10780 | .arg("-version") |
| 10781 | .stdout(Stdio::null()) |
| 10782 | .stderr(Stdio::null()) |
| 10783 | .status() |
| 10784 | .is_ok_and(|s| s.success()); |
| 10785 | assert!( |
| 10786 | present |
| 10787 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 10788 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 10789 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 10790 | ); |
| 10791 | present |
| 10792 | } |
| 10793 | |
| 10794 | /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes. |
| 10795 | fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { |
| 10796 | let mut child = Command::new("ffmpeg") |
| 10797 | .args([ |
| 10798 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 10799 | ]) |
| 10800 | .stdin(Stdio::piped()) |
| 10801 | .stdout(Stdio::piped()) |
| 10802 | .stderr(Stdio::piped()) |
| 10803 | .spawn() |
| 10804 | .expect("ffmpeg failed to start"); |
| 10805 | // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing |
| 10806 | // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB) |
| 10807 | // fills before the last input byte is written -- which is exactly what |
| 10808 | // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does |
| 10809 | // (measured: 45 min, both processes at 0% CPU). A write error here is |
| 10810 | // swallowed on purpose: ffmpeg's own exit status and stderr, asserted |
| 10811 | // below, are the real diagnosis. |
| 10812 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 10813 | let payload = stream.to_vec(); |
| 10814 | let writer = std::thread::spawn(move || { |
| 10815 | let _ = stdin.write_all(&payload); |
| 10816 | }); |
| 10817 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 10818 | writer.join().expect("ffmpeg stdin writer thread"); |
| 10819 | assert!( |
| 10820 | out.status.success(), |
| 10821 | "ffmpeg refused the stream: {}", |
| 10822 | String::from_utf8_lossy(&out.stderr) |
| 10823 | ); |
| 10824 | let (luma, chroma) = (width * height, width * height / 4); |
| 10825 | assert_eq!( |
| 10826 | out.stdout.len(), |
| 10827 | luma + 2 * chroma, |
| 10828 | "expected one 4:2:0 frame" |
| 10829 | ); |
| 10830 | Picture { |
| 10831 | width, |
| 10832 | height, |
| 10833 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 10834 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 10835 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 10836 | } |
| 10837 | } |
| 10838 | |
| 10839 | /// A picture with something of everything in it: a gradient, an edge, a |
| 10840 | /// ripple and a block of flat colour, none of them aligned to the block |
| 10841 | /// grid. |
| 10842 | /// The in-loop filters actually FIRE and the stream still decodes to |
| 10843 | /// exactly what the encoder kept as its reconstruction |
| 10844 | /// (gate-blind-to-feature: a filter search that always answered "off" |
| 10845 | /// would leave every other test just as green, and the BD gate that |
| 10846 | /// would notice is `#[ignore]`d). |
| 10847 | /// |
| 10848 | /// Run: |
| 10849 | /// cargo test -p ec-av1 --release --lib -- \ |
| 10850 | /// encode::tests::the_filter_search_picks_real_filters |
| 10851 | #[test] |
| 10852 | fn the_filter_search_picks_real_filters() { |
| 10853 | let _knobs = crate::speed::knob_read(); |
| 10854 | let fctx = &crate::decode::FrameCtx::new(); |
| 10855 | let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); |
| 10856 | let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); |
| 10857 | let fired = encoded |
| 10858 | .frames |
| 10859 | .iter() |
| 10860 | .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) |
| 10861 | .count(); |
| 10862 | assert!( |
| 10863 | fired > 0, |
| 10864 | "no frame of this sequence chose any in-loop filtering: {:?}", |
| 10865 | encoded |
| 10866 | .frames |
| 10867 | .iter() |
| 10868 | .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) |
| 10869 | .collect::<Vec<_>>() |
| 10870 | ); |
| 10871 | // The reconstruction the encoder predicts from is the FILTERED one, |
| 10872 | // and it is what a decoder of the stream produces -- byte for byte, |
| 10873 | // frame for frame. |
| 10874 | let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 10875 | assert_eq!(decoded.len(), encoded.frames.len()); |
| 10876 | for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 10877 | assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); |
| 10878 | assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); |
| 10879 | assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); |
| 10880 | } |
| 10881 | } |
| 10882 | |
| 10883 | fn test_card(width: usize, height: usize) -> Picture { |
| 10884 | let mut picture = Picture::grey(width, height); |
| 10885 | for y in 0..height { |
| 10886 | for x in 0..width { |
| 10887 | let gradient = x as f64 * 200.0 / width as f64; |
| 10888 | let ripple = 30.0 |
| 10889 | * (x as f64 * std::f64::consts::PI / 23.0).sin() |
| 10890 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 10891 | let edge = if x > width * 3 / 7 && y > height / 3 { |
| 10892 | 40.0 |
| 10893 | } else { |
| 10894 | 0.0 |
| 10895 | }; |
| 10896 | picture.y[y * width + x] = |
| 10897 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 10898 | } |
| 10899 | } |
| 10900 | for y in 0..height / 2 { |
| 10901 | for x in 0..width / 2 { |
| 10902 | let i = y * width / 2 + x; |
| 10903 | picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; |
| 10904 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 10905 | } |
| 10906 | } |
| 10907 | picture |
| 10908 | } |
| 10909 | |
| 10910 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 10911 | let squared: f64 = a |
| 10912 | .iter() |
| 10913 | .zip(b) |
| 10914 | .map(|(&x, &y)| { |
| 10915 | let d = f64::from(x) - f64::from(y); |
| 10916 | d * d |
| 10917 | }) |
| 10918 | .sum(); |
| 10919 | if squared == 0.0 { |
| 10920 | return f64::INFINITY; |
| 10921 | } |
| 10922 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 10923 | } |
| 10924 | |
| 10925 | /// The claim the whole encoder rests on: what a decoder produces is what |
| 10926 | /// the encoder said it would, sample for sample, on every plane. |
| 10927 | /// |
| 10928 | /// Prediction reads the reconstruction, so a single sample of drift |
| 10929 | /// anywhere would spread into every block below and to the right of it — |
| 10930 | /// which is why this is an equality and not a tolerance. |
| 10931 | #[test] |
| 10932 | fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { |
| 10933 | let _knobs = crate::speed::knob_read(); |
| 10934 | let fctx = &crate::decode::FrameCtx::new(); |
| 10935 | if !have_ffmpeg() { |
| 10936 | eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); |
| 10937 | return; |
| 10938 | } |
| 10939 | for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] { |
| 10940 | let picture = test_card(width, height); |
| 10941 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 10942 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 10943 | assert_eq!( |
| 10944 | decoded.y, encoded.reconstruction.y, |
| 10945 | "{width}x{height}: luma" |
| 10946 | ); |
| 10947 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 10948 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 10949 | } |
| 10950 | // One q index from each of the four coefficient-CDF contexts |
| 10951 | // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size. |
| 10952 | let (width, height) = (64usize, 64usize); |
| 10953 | let picture = test_card(width, height); |
| 10954 | let _ = take_tx_depth_hits(); |
| 10955 | for &q in &[15u8, 45, 100, 200] { |
| 10956 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 10957 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 10958 | assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); |
| 10959 | assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); |
| 10960 | assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); |
| 10961 | } |
| 10962 | // lane-av1tx: the exactness above is only a claim about SPLIT |
| 10963 | // transforms if some block actually split one (`gate-blind-to-feature` |
| 10964 | // -- with `tx_depth` stuck at 0 every assert here passes on the |
| 10965 | // pre-lane stream). The test card's edges split at these four |
| 10966 | // quantizers; the counter is per-process (another test encoding in |
| 10967 | // parallel can only ADD to it, so this can be masked, never falsely |
| 10968 | // failed), so it is read once for the whole q ladder. |
| 10969 | let depths = take_tx_depth_hits(); |
| 10970 | assert!( |
| 10971 | depths[1] + depths[2] > 0, |
| 10972 | "no block split its transform: depths {depths:?}" |
| 10973 | ); |
| 10974 | } |
| 10975 | |
| 10976 | /// A synthetic screen-content picture -- a few flat colours in a grid of |
| 10977 | /// boxes with hard edges and text-like bars, the shape a desktop capture |
| 10978 | /// has -- so the palette path is exercised on content it is for. |
| 10979 | #[cfg(test)] |
| 10980 | fn screen_card(width: usize, height: usize) -> Picture { |
| 10981 | const INK: [u16; 4] = [16, 90, 180, 235]; |
| 10982 | let mut picture = Picture::grey(width, height); |
| 10983 | for y in 0..height { |
| 10984 | for x in 0..width { |
| 10985 | let cell = (x / 24 + y / 24) % 2; |
| 10986 | let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); |
| 10987 | picture.y[y * width + x] = INK[cell * 2 + bar]; |
| 10988 | } |
| 10989 | } |
| 10990 | // Four chroma colours, not two: a two-colour chroma block only ever |
| 10991 | // codes a `PaletteSizeUV` of 2, which leaves |
| 10992 | // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking |
| 10993 | // deltas and the neighbour cache flags, exercised only when |
| 10994 | // neighbouring blocks share colours) unproven by the ffmpeg oracle. |
| 10995 | const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; |
| 10996 | const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; |
| 10997 | for y in 0..height / 2 { |
| 10998 | for x in 0..width / 2 { |
| 10999 | let cell = (x / 12 + 2 * (y / 12)) % 4; |
| 11000 | picture.u[y * (width / 2) + x] = CHROMA_U[cell]; |
| 11001 | picture.v[y * (width / 2) + x] = CHROMA_V[cell]; |
| 11002 | } |
| 11003 | } |
| 11004 | picture |
| 11005 | } |
| 11006 | |
| 11007 | /// The lane's own end-to-end check: on screen content the detector fires, |
| 11008 | /// blocks really take a palette (fire count, class |
| 11009 | /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every |
| 11010 | /// symbol this lane writes -- reconstructs exactly what the encoder did. |
| 11011 | /// The film-shaped `test_card` must NOT trip the detector, which is what |
| 11012 | /// keeps every non-screen stream byte-identical. |
| 11013 | #[test] |
| 11014 | fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { |
| 11015 | let _knobs = crate::speed::knob_read(); |
| 11016 | let fctx = &crate::decode::FrameCtx::new(); |
| 11017 | let (width, height) = (192usize, 96usize); |
| 11018 | let _ = crate::tile::take_palette_hits(); |
| 11019 | let picture = screen_card(width, height); |
| 11020 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11021 | assert!( |
| 11022 | encoded.screen, |
| 11023 | "the detector did not fire on screen content -- no palette syntax was coded at all" |
| 11024 | ); |
| 11025 | let hits = crate::tile::take_palette_hits(); |
| 11026 | assert!(hits[0] > 0, "no block took a palette: {hits:?}"); |
| 11027 | eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); |
| 11028 | // The chroma half is a claim about the plane-1 syntax only if some |
| 11029 | // block really took a chroma palette (`gate-blind-to-feature`): every |
| 11030 | // exactness assert below passes on a stream that codes |
| 11031 | // `palette_uv_mode == 0` everywhere. |
| 11032 | let uv_hits = crate::tile::take_palette_uv_hits(); |
| 11033 | assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}"); |
| 11034 | let uv_cached = crate::tile::take_palette_uv_cache_hits(); |
| 11035 | eprintln!( |
| 11036 | "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", |
| 11037 | uv_hits[0], |
| 11038 | &uv_hits[2..] |
| 11039 | ); |
| 11040 | assert!( |
| 11041 | uv_cached > 0, |
| 11042 | "no chroma base colour came out of the neighbour cache -- \ |
| 11043 | `write_palette_colors_uv`'s cache half is unproven by the oracle below" |
| 11044 | ); |
| 11045 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 11046 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 11047 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 11048 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 11049 | if !have_ffmpeg() { |
| 11050 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 11051 | return; |
| 11052 | } |
| 11053 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 11054 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 11055 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 11056 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 11057 | // A whole GOP: the inter frames' own intra blocks carry the palette |
| 11058 | // syntax too (the three intra arms of the inter writers), which only |
| 11059 | // ffmpeg reading the frames back can prove. |
| 11060 | let moved: Vec<Picture> = (0..4) |
| 11061 | .map(|f| { |
| 11062 | let base = screen_card(width, height); |
| 11063 | let mut out = Picture::grey(width, height); |
| 11064 | for y in 0..height { |
| 11065 | for x in 0..width { |
| 11066 | let sx = (x + f * 7) % width; |
| 11067 | out.y[y * width + x] = base.y[y * width + sx]; |
| 11068 | } |
| 11069 | } |
| 11070 | for y in 0..height / 2 { |
| 11071 | for x in 0..width / 2 { |
| 11072 | let sx = (x + f * 3) % (width / 2); |
| 11073 | out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; |
| 11074 | out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; |
| 11075 | } |
| 11076 | } |
| 11077 | out |
| 11078 | }) |
| 11079 | .collect(); |
| 11080 | let _ = crate::tile::take_palette_hits(); |
| 11081 | let _ = crate::tile::take_palette_uv_hits(); |
| 11082 | let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); |
| 11083 | let gop_hits = crate::tile::take_palette_hits(); |
| 11084 | let gop_uv_hits = crate::tile::take_palette_uv_hits(); |
| 11085 | let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); |
| 11086 | eprintln!( |
| 11087 | "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ |
| 11088 | {} chroma palette blocks", |
| 11089 | inter_screen, gop_hits[0], gop_uv_hits[0] |
| 11090 | ); |
| 11091 | assert!( |
| 11092 | gop_uv_hits[0] > 0, |
| 11093 | "no block of the GOP took a chroma palette: {gop_uv_hits:?}" |
| 11094 | ); |
| 11095 | assert!( |
| 11096 | inter_screen > 0, |
| 11097 | "no inter frame set allow_screen_content_tools" |
| 11098 | ); |
| 11099 | let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); |
| 11100 | for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { |
| 11101 | assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma"); |
| 11102 | } |
| 11103 | if have_ffmpeg() { |
| 11104 | let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); |
| 11105 | for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { |
| 11106 | assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma"); |
| 11107 | assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); |
| 11108 | assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); |
| 11109 | } |
| 11110 | } |
| 11111 | |
| 11112 | // The other half of the keep rule: film-shaped content leaves the |
| 11113 | // detector (and so the whole sequence header) alone. |
| 11114 | let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); |
| 11115 | assert!(!film.screen, "the detector fired on the film-shaped test card"); |
| 11116 | } |
| 11117 | |
| 11118 | /// The lane's keep-rule measurement: the gate's own screen capture, one |
| 11119 | /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers. |
| 11120 | /// Setting the bit forces deblocking, CDEF and loop restoration off for |
| 11121 | /// that frame, so the table is exactly the filter loss against the bytes |
| 11122 | /// the copied blocks save. |
| 11123 | #[test] |
| 11124 | #[ignore = "needs the real-library manifest and ffmpeg"] |
| 11125 | fn probe_intrabc_key_frame() { |
| 11126 | let _knobs = crate::speed::knob_write(); |
| 11127 | let fctx = &crate::decode::FrameCtx::new(); |
| 11128 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 11129 | .join("../../fixtures"); |
| 11130 | let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else { |
| 11131 | eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest"); |
| 11132 | return; |
| 11133 | }; |
| 11134 | let Some(clip) = manifest |
| 11135 | .lines() |
| 11136 | .skip(1) |
| 11137 | .filter_map(|l| l.split('\t').next()) |
| 11138 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 11139 | else { |
| 11140 | eprintln!("SKIP probe_intrabc_key_frame: no OBS recording"); |
| 11141 | return; |
| 11142 | }; |
| 11143 | let (width, height) = (640usize, 384usize); |
| 11144 | let picture = clip_frame(clip, "0", width, height); |
| 11145 | eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |"); |
| 11146 | for q in [5u8, 20, 35, 45] { |
| 11147 | for on in [false, true] { |
| 11148 | force_intrabc(Some(on)); |
| 11149 | let _ = crate::tile::take_intrabc_hits(); |
| 11150 | let _ = take_intrabc_search(); |
| 11151 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 11152 | let hits = crate::tile::take_intrabc_hits(); |
| 11153 | let search = take_intrabc_search(); |
| 11154 | eprintln!( |
| 11155 | "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |", |
| 11156 | if encoded.allow_intrabc { "on" } else { "off" }, |
| 11157 | encoded.stream.len(), |
| 11158 | psnr_all(&encoded.reconstruction, &picture), |
| 11159 | hits[0], |
| 11160 | &hits[1..], |
| 11161 | search[0], search[1], search[2], |
| 11162 | ); |
| 11163 | } |
| 11164 | } |
| 11165 | force_intrabc(None); |
| 11166 | } |
| 11167 | |
| 11168 | /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card |
| 11169 | /// sets `allow_intrabc` (so every in-loop filter is off), blocks really |
| 11170 | /// take a block vector (fire count + DV histogram, class |
| 11171 | /// `gate-blind-to-feature`), and both our own decoder and ffmpeg -- |
| 11172 | /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct |
| 11173 | /// exactly what the encoder did. |
| 11174 | #[test] |
| 11175 | fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() { |
| 11176 | let _knobs = crate::speed::knob_write(); |
| 11177 | let fctx = &crate::decode::FrameCtx::new(); |
| 11178 | // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4 |
| 11179 | // superblocks of 64) and tall enough for a source superblock row |
| 11180 | // above the blocks that copy from it. |
| 11181 | let (width, height) = (512usize, 256usize); |
| 11182 | let picture = screen_card(width, height); |
| 11183 | let _ = crate::tile::take_intrabc_hits(); |
| 11184 | // The default is OFF (it measured worse on the real screen capture -- |
| 11185 | // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns |
| 11186 | // the arm on for its own encode and puts it back straight after. |
| 11187 | force_intrabc(Some(true)); |
| 11188 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11189 | force_intrabc(None); |
| 11190 | assert!( |
| 11191 | encoded.allow_intrabc, |
| 11192 | "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)", |
| 11193 | intrabc_source_share() * 100.0 |
| 11194 | ); |
| 11195 | let hits = crate::tile::take_intrabc_hits(); |
| 11196 | eprintln!( |
| 11197 | "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%", |
| 11198 | hits[0], |
| 11199 | &hits[1..], |
| 11200 | intrabc_source_share() * 100.0 |
| 11201 | ); |
| 11202 | let search = take_intrabc_search(); |
| 11203 | eprintln!( |
| 11204 | "intrabc searches {} found-valid {} won-RD {}", |
| 11205 | search[0], search[1], search[2] |
| 11206 | ); |
| 11207 | assert!( |
| 11208 | hits[0] > 0, |
| 11209 | "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}" |
| 11210 | ); |
| 11211 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 11212 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 11213 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 11214 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 11215 | if !have_ffmpeg() { |
| 11216 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 11217 | return; |
| 11218 | } |
| 11219 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 11220 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 11221 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 11222 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 11223 | } |
| 11224 | |
| 11225 | /// The minimal repro that isolated the inter-residual desync: a key frame |
| 11226 | /// followed by one inter frame whose single superblock carries one |
| 11227 | /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma |
| 11228 | /// coefficient, its three sibling blocks all `skip: true`. Before the |
| 11229 | /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data |
| 11230 | /// found when processing input") even though every symbol either block |
| 11231 | /// codes is otherwise proven (all-skip inter blocks decode clean, and the |
| 11232 | /// same coefficient syntax decodes clean on every intra key-frame gate). |
| 11233 | #[test] |
| 11234 | fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { |
| 11235 | let _knobs = crate::speed::knob_write(); |
| 11236 | let fctx = &crate::decode::FrameCtx::new(); |
| 11237 | if !have_ffmpeg() { |
| 11238 | eprintln!( |
| 11239 | "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg" |
| 11240 | ); |
| 11241 | return; |
| 11242 | } |
| 11243 | let (width, height) = (64usize, 64usize); |
| 11244 | let picture = Picture::grey(width, height); |
| 11245 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11246 | |
| 11247 | let (seq, _) = key_frame_headers(width, height, 100).unwrap(); |
| 11248 | let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); |
| 11249 | |
| 11250 | let residual_block = BlockCoeffs { |
| 11251 | angle_delta_y: 0, |
| 11252 | cfl_alphas: None, |
| 11253 | filter_intra: None, |
| 11254 | luma: vec![Coeff { |
| 11255 | row: 0, |
| 11256 | col: 0, |
| 11257 | level: 4, |
| 11258 | }], |
| 11259 | u: Vec::new(), |
| 11260 | v: Vec::new(), |
| 11261 | mode: 0, |
| 11262 | uv_mode: 0, |
| 11263 | skip: false, |
| 11264 | eight: None, |
| 11265 | dv: None, |
| 11266 | palette: None, |
| 11267 | palette_uv: None, |
| 11268 | tx_depth: 0, |
| 11269 | inter: Some(InterInfo { |
| 11270 | ref1: None, |
| 11271 | mv1: (0, 0), |
| 11272 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11273 | mode: InterMode::NearestMv, |
| 11274 | mv: (0, 0), |
| 11275 | ref_mv_idx: 0, |
| 11276 | }), |
| 11277 | motion_mode: 0, |
| 11278 | }; |
| 11279 | let skipped_block = BlockCoeffs { |
| 11280 | skip: true, |
| 11281 | inter: Some(InterInfo { |
| 11282 | ref1: None, |
| 11283 | mv1: (0, 0), |
| 11284 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11285 | mode: InterMode::NearestMv, |
| 11286 | mv: (0, 0), |
| 11287 | ref_mv_idx: 0, |
| 11288 | }), |
| 11289 | ..BlockCoeffs::default() |
| 11290 | }; |
| 11291 | let blocks = vec![ |
| 11292 | Quadrant::Whole(residual_block), |
| 11293 | Quadrant::Whole(skipped_block.clone()), |
| 11294 | Quadrant::Whole(skipped_block.clone()), |
| 11295 | Quadrant::Whole(skipped_block), |
| 11296 | ]; |
| 11297 | // lane-av1obmc: the header this tile is decoded under carries |
| 11298 | // `is_motion_mode_switchable`, so the writer must be armed with it |
| 11299 | // too or the decoder reads a `motion_mode` symbol nobody wrote. |
| 11300 | crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable); |
| 11301 | crate::tile::arm_warped_motion(inter_header.allow_warped_motion); |
| 11302 | let tile = |
| 11303 | crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) |
| 11304 | .unwrap(); |
| 11305 | |
| 11306 | // `key.stream` is already a temporal delimiter, the sequence header |
| 11307 | // and the key frame's own OBU (`encode_key_frame` built it from the |
| 11308 | // same `key_frame_headers(width, height, 100)` this test calls), so |
| 11309 | // the inter frame's OBU is appended straight onto it rather than |
| 11310 | // re-deriving the key frame's tile bytes. |
| 11311 | let mut stream = key.stream.clone(); |
| 11312 | stream.extend_from_slice(&temporal_delimiter()); |
| 11313 | stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); |
| 11314 | |
| 11315 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 11316 | } |
| 11317 | |
| 11318 | /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded |
| 11319 | /// frame size an AV1 decoder allocates, not necessarily the render size |
| 11320 | /// (see [`a_frame_round_trips_at_its_own_size`]). |
| 11321 | fn ffprobe_size(stream: &[u8]) -> (u32, u32) { |
| 11322 | // Distinct per call, not per process: the test binary runs callers on |
| 11323 | // parallel threads, and a shared name lets one test's cleanup delete |
| 11324 | // the stream another test's ffprobe is still reading. |
| 11325 | static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 11326 | let path = std::env::temp_dir().join(format!( |
| 11327 | "ec-av1-probe-{}-{}.obu", |
| 11328 | std::process::id(), |
| 11329 | PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 11330 | )); |
| 11331 | let _ = std::fs::remove_file(&path); |
| 11332 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 11333 | let out = Command::new("ffprobe") |
| 11334 | .args([ |
| 11335 | "-v", |
| 11336 | "error", |
| 11337 | "-f", |
| 11338 | "obu", |
| 11339 | "-select_streams", |
| 11340 | "v:0", |
| 11341 | "-show_entries", |
| 11342 | "stream=width,height", |
| 11343 | "-of", |
| 11344 | "csv=p=0", |
| 11345 | ]) |
| 11346 | .arg(&path) |
| 11347 | .output() |
| 11348 | .expect("ffprobe failed to run"); |
| 11349 | let _ = std::fs::remove_file(&path); |
| 11350 | assert!( |
| 11351 | out.status.success(), |
| 11352 | "ffprobe refused the stream: {}", |
| 11353 | String::from_utf8_lossy(&out.stderr) |
| 11354 | ); |
| 11355 | let text = String::from_utf8_lossy(&out.stdout); |
| 11356 | let mut fields = text.trim().split(','); |
| 11357 | let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); |
| 11358 | let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); |
| 11359 | (width, height) |
| 11360 | } |
| 11361 | |
| 11362 | /// lane-av1cap: the final filter replay against the capture decode it |
| 11363 | /// replaced, at the block-padded and straddling sizes the whole-frame |
| 11364 | /// tests cover -- `set_verify_final_replay` makes |
| 11365 | /// [`pick_and_apply_filters`] run both on every frame and assert, per |
| 11366 | /// frame, that the spliced picture and the two filter stages the |
| 11367 | /// restoration search reads are bit-identical over the frame's own crop. |
| 11368 | #[test] |
| 11369 | fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() { |
| 11370 | let _knobs = crate::speed::knob_write(); |
| 11371 | let fctx = &crate::decode::FrameCtx::new(); |
| 11372 | crate::decode::set_verify_final_replay(true); |
| 11373 | for &(width, height) in |
| 11374 | &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)] |
| 11375 | { |
| 11376 | eprintln!("--- {width}x{height}"); |
| 11377 | let picture = test_card(width, height); |
| 11378 | let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11379 | } |
| 11380 | crate::decode::set_verify_final_replay(false); |
| 11381 | } |
| 11382 | |
| 11383 | /// A key frame at an arbitrary even size round-trips through ffmpeg over |
| 11384 | /// its own render rectangle: [`Encoded::reconstruction`] is exactly the |
| 11385 | /// picture's own size, and what ffmpeg decodes over that same top-left |
| 11386 | /// region equals it sample for sample. |
| 11387 | /// |
| 11388 | /// This does not check that `ffprobe` reports the picture's own size, |
| 11389 | /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded |
| 11390 | /// (block-padded) frame size, the same one libaom itself would code for |
| 11391 | /// a non-block-aligned picture. `render_width`/`render_height` (which |
| 11392 | /// this crate sets correctly, spec 5.9.6) is a display hint no AV1 |
| 11393 | /// decoder is required to crop pixels by, and ffmpeg's does not -- |
| 11394 | /// checked empirically against ffprobe here and against a real libaom |
| 11395 | /// encode separately. So the coded size, not the render size, is what |
| 11396 | /// `ffprobe` is asserted to report below. |
| 11397 | #[test] |
| 11398 | fn a_frame_round_trips_at_its_own_size() { |
| 11399 | let _knobs = crate::speed::knob_read(); |
| 11400 | let fctx = &crate::decode::FrameCtx::new(); |
| 11401 | if !have_ffmpeg() { |
| 11402 | eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); |
| 11403 | return; |
| 11404 | } |
| 11405 | // 854x480 is covered separately by |
| 11406 | // `an_854x480_picture_round_trips_through_its_padding`, which its own |
| 11407 | // doc comment explains was worth keeping as its own test. |
| 11408 | for &(width, height) in &[ |
| 11409 | (1920usize, 1080usize), |
| 11410 | (640, 352), |
| 11411 | (1280, 720), |
| 11412 | (64, 56), |
| 11413 | (854, 480), |
| 11414 | (216, 96), |
| 11415 | (192, 120), |
| 11416 | ] { |
| 11417 | let picture = test_card(width, height); |
| 11418 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11419 | assert_eq!( |
| 11420 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 11421 | (width, height), |
| 11422 | "{width}x{height}: reconstruction is cropped to the picture's own size" |
| 11423 | ); |
| 11424 | assert_eq!( |
| 11425 | ffprobe_size(&encoded.stream), |
| 11426 | (width as u32, height as u32), |
| 11427 | "{width}x{height}: ffprobe reports the true (display) size, not the padded one" |
| 11428 | ); |
| 11429 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 11430 | assert_eq!( |
| 11431 | decoded.y, encoded.reconstruction.y, |
| 11432 | "{width}x{height}: luma" |
| 11433 | ); |
| 11434 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 11435 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 11436 | } |
| 11437 | } |
| 11438 | |
| 11439 | /// 854x480 (padded to 864x480, an edge-replication padded key frame) used |
| 11440 | /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug |
| 11441 | /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact |
| 11442 | /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned |
| 11443 | /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while |
| 11444 | /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 + |
| 11445 | /// col`) -- different bits of an 8-byte table, one true, one false. The |
| 11446 | /// stride libaom indexes by is fixed at its compile-time maximum |
| 11447 | /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock |
| 11448 | /// size a stream uses, so the right stride for a 16x16 or 32x32 block is |
| 11449 | /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s |
| 11450 | /// row/col position within the (correctly 64-relative) superblock stayed |
| 11451 | /// right, only the table's own row stride was wrong. Fixed in |
| 11452 | /// `Reach::table_stride`; not an arithmetic-coder desync (an |
| 11453 | /// EC_RNG-per-symbol trace against the same debug decoder found the |
| 11454 | /// bitstream byte-for-byte identical to libaom's across all 51188 |
| 11455 | /// symbols of this frame before this bug was found). |
| 11456 | /// |
| 11457 | /// Since the frame header started writing the true (unpadded) display |
| 11458 | /// size into `frame_width`/`frame_height` rather than the padded coded |
| 11459 | /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded |
| 11460 | /// 864x480 and cropping ourselves now reads past what ffmpeg actually |
| 11461 | /// emits (`av1_common_int.h`'s render/upscale path, mirrored by |
| 11462 | /// `av1_frame_size` on the decode side, crops the loop-filtered picture to |
| 11463 | /// the header's own size before output). |
| 11464 | #[test] |
| 11465 | fn an_854x480_picture_round_trips_through_its_padding() { |
| 11466 | let _knobs = crate::speed::knob_read(); |
| 11467 | let fctx = &crate::decode::FrameCtx::new(); |
| 11468 | if !have_ffmpeg() { |
| 11469 | return; |
| 11470 | } |
| 11471 | let (width, height) = (854usize, 480usize); |
| 11472 | let picture = test_card(width, height); |
| 11473 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11474 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 11475 | assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); |
| 11476 | assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); |
| 11477 | assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); |
| 11478 | } |
| 11479 | |
| 11480 | /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left` |
| 11481 | /// transform-unit path, for every 4x4 unit of every 8x8 block of a |
| 11482 | /// superblock, both partition tables: |
| 11483 | /// |
| 11484 | /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the |
| 11485 | /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so |
| 11486 | /// wiring the TU sites onto it changes no existing stream; |
| 11487 | /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is |
| 11488 | /// NULL in libaom because that lookup never happens, and reading a |
| 11489 | /// 4x4 row out of the three-row vert tables is what crashed a real |
| 11490 | /// `--enable-tx-size-search=1` stream (r2); |
| 11491 | /// 3. and it must be the BLOCK's vert answer where the two tables |
| 11492 | /// disagree: the top-right 4x4 unit of the 8x8 block at superblock |
| 11493 | /// row 1, column 0 reads its above-right samples from the 8x8 to its |
| 11494 | /// upper right, which a vertical AB partition codes AFTER it |
| 11495 | /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1). |
| 11496 | #[test] |
| 11497 | fn of_tu_follows_the_block_row_including_under_vert_ab() { |
| 11498 | let fctx = &crate::decode::FrameCtx::new(); |
| 11499 | // The 8x8 square at superblock row 1, column 0, and the TX4 unit in |
| 11500 | // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's |
| 11501 | // above-right answer is the BLOCK's, which is the whole reason a unit |
| 11502 | // asks the block instead of looking itself up (the |
| 11503 | // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2). |
| 11504 | let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 11505 | assert_eq!( |
| 11506 | Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, |
| 11507 | plain.above_right, |
| 11508 | "ordinary table: the top-right TX4 unit takes the block's row" |
| 11509 | ); |
| 11510 | let guard = Reach::vert_ab_partition(); |
| 11511 | let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 11512 | assert_eq!( |
| 11513 | Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, |
| 11514 | vert.above_right, |
| 11515 | "vert AB: the unit follows the vert row the block just picked" |
| 11516 | ); |
| 11517 | assert_ne!( |
| 11518 | plain.above_right, vert.above_right, |
| 11519 | "this position is the cell where the vert tables disagree; pick another if libaom's tables change" |
| 11520 | ); |
| 11521 | drop(guard); |
| 11522 | } |
| 11523 | |
| 11524 | /// `Reach::top_right`/`bottom_left` against a from-scratch transcription |
| 11525 | /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/ |
| 11526 | /// reconintra.c`), for every 16x16 and 32x32 block position across three |
| 11527 | /// superblocks square -- interior and every superblock edge (top row, |
| 11528 | /// left column, right column, bottom row) both sizes reach. Written to |
| 11529 | /// catch the class the `table_stride` bug was: an index stride silently |
| 11530 | /// wrong for one block size while looking plausible for the other. |
| 11531 | #[test] |
| 11532 | fn reach_matches_libaom_has_top_right_and_has_bottom_left() { |
| 11533 | let fctx = &crate::decode::FrameCtx::new(); |
| 11534 | // Transcribed from has_top_right/has_bottom_left's row_off==0, |
| 11535 | // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a |
| 11536 | // 128px reference grid) pinned as libaom pins it, independent of the |
| 11537 | // 64px superblock this crate actually codes. |
| 11538 | fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { |
| 11539 | if y == 0 || x + side >= width { |
| 11540 | return false; |
| 11541 | } |
| 11542 | let (row, col, per_side) = ( |
| 11543 | (y % SUPERBLOCK) / side, |
| 11544 | (x % SUPERBLOCK) / side, |
| 11545 | SUPERBLOCK / side, |
| 11546 | ); |
| 11547 | if row == 0 { |
| 11548 | return true; |
| 11549 | } |
| 11550 | if col + 1 == per_side { |
| 11551 | return false; |
| 11552 | } |
| 11553 | let stride = 128 / side; |
| 11554 | let index = row * stride + col; |
| 11555 | let table = if side == BLOCK { |
| 11556 | [95u8, 87].to_vec() |
| 11557 | } else { |
| 11558 | vec![255, 85, 119, 85, 127, 85, 119, 85] |
| 11559 | }; |
| 11560 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 11561 | } |
| 11562 | |
| 11563 | fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool { |
| 11564 | if x == 0 || y + side >= height { |
| 11565 | return false; |
| 11566 | } |
| 11567 | let (row, col, per_side) = ( |
| 11568 | (y % SUPERBLOCK) / side, |
| 11569 | (x % SUPERBLOCK) / side, |
| 11570 | SUPERBLOCK / side, |
| 11571 | ); |
| 11572 | if col == 0 { |
| 11573 | return row * side + side < SUPERBLOCK; |
| 11574 | } |
| 11575 | if row + 1 == per_side { |
| 11576 | return false; |
| 11577 | } |
| 11578 | let stride = 128 / side; |
| 11579 | let index = row * stride + col; |
| 11580 | let table = if side == BLOCK { |
| 11581 | [4u8, 4].to_vec() |
| 11582 | } else { |
| 11583 | vec![84, 16, 84, 0, 84, 16, 84, 0] |
| 11584 | }; |
| 11585 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 11586 | } |
| 11587 | |
| 11588 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 11589 | for side in [16usize, BLOCK] { |
| 11590 | for y in (0..height).step_by(side) { |
| 11591 | for x in (0..width).step_by(side) { |
| 11592 | let reach = Reach::of(side, x, y, width, height, fctx); |
| 11593 | assert_eq!( |
| 11594 | reach.above_right, |
| 11595 | libaom_top_right(side, x, y, width, height), |
| 11596 | "side={side} x={x} y={y}: above_right" |
| 11597 | ); |
| 11598 | assert_eq!( |
| 11599 | reach.below_left, |
| 11600 | libaom_bottom_left(side, x, y, height, fctx), |
| 11601 | "side={side} x={x} y={y}: below_left" |
| 11602 | ); |
| 11603 | } |
| 11604 | } |
| 11605 | } |
| 11606 | } |
| 11607 | |
| 11608 | /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are |
| 11609 | /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8 |
| 11610 | /// column inside the superblock) may read the below-left samples the |
| 11611 | /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots |
| 11612 | /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe |
| 11613 | /// swept in r6 produced a decodable 16x16-level VERT_B stream (every |
| 11614 | /// stream that partitions that small first hits the still-refused |
| 11615 | /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms). |
| 11616 | /// [`Reach::of_tu`] against a from-scratch transcription of libaom's |
| 11617 | /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma, |
| 11618 | /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in |
| 11619 | /// pixels -- lane-palette2 r12: the square multi-TU path used the |
| 11620 | /// standalone-block tables instead of this rule and granted a 16x16 |
| 11621 | /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses. |
| 11622 | #[test] |
| 11623 | fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { |
| 11624 | // libaom, in MI units: bw_unit/bh_unit = block size / 4, |
| 11625 | // *_count_unit = tx size / 4. |
| 11626 | fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 11627 | let (plane_bw_unit, count) = (bw / 4, tx / 4); |
| 11628 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 11629 | let _ = bh; |
| 11630 | if row_off_u > 0 { |
| 11631 | col_off_u + count < plane_bw_unit |
| 11632 | } else if col_off_u + count < plane_bw_unit { |
| 11633 | true |
| 11634 | } else { |
| 11635 | blk |
| 11636 | } |
| 11637 | } |
| 11638 | fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 11639 | let (plane_bh_unit, count) = (bh / 4, tx / 4); |
| 11640 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 11641 | let _ = bw; |
| 11642 | if col_off_u > 0 { |
| 11643 | false |
| 11644 | } else if row_off_u + count < plane_bh_unit { |
| 11645 | true |
| 11646 | } else { |
| 11647 | blk |
| 11648 | } |
| 11649 | } |
| 11650 | for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 11651 | for &tx in &[4usize, 8, 16, 32] { |
| 11652 | if tx > bw.min(bh) { |
| 11653 | continue; |
| 11654 | } |
| 11655 | for row_off in (0..bh).step_by(tx) { |
| 11656 | for col_off in (0..bw).step_by(tx) { |
| 11657 | for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { |
| 11658 | let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); |
| 11659 | assert_eq!( |
| 11660 | got.above_right, |
| 11661 | libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), |
| 11662 | "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 11663 | ); |
| 11664 | assert_eq!( |
| 11665 | got.below_left, |
| 11666 | libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), |
| 11667 | "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 11668 | ); |
| 11669 | } |
| 11670 | } |
| 11671 | } |
| 11672 | } |
| 11673 | } |
| 11674 | } |
| 11675 | |
| 11676 | #[test] |
| 11677 | fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { |
| 11678 | let fctx = &crate::decode::FrameCtx::new(); |
| 11679 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 11680 | // Interior superblock, so neither the frame edge nor the col == 0 / |
| 11681 | // last-row early returns answer instead of the table. |
| 11682 | let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); |
| 11683 | let mut flipped = 0; |
| 11684 | for row in 0..8 { |
| 11685 | for col in 1..8 { |
| 11686 | let (x, y) = (sb_x + col * 8, sb_y + row * 8); |
| 11687 | let raster = Reach::of(8, x, y, width, height, fctx).below_left; |
| 11688 | let vert = { |
| 11689 | let _guard = Reach::vert_ab_partition(); |
| 11690 | Reach::of(8, x, y, width, height, fctx).below_left |
| 11691 | }; |
| 11692 | // The TR square of a VERT_A/_B sits at an even row, odd |
| 11693 | // column; every other slot must be untouched by the guard. |
| 11694 | if row % 2 == 0 && col % 2 == 1 { |
| 11695 | assert!(!raster, "raster below_left at row={row} col={col}"); |
| 11696 | assert!(vert, "vert below_left at row={row} col={col}"); |
| 11697 | flipped += 1; |
| 11698 | } else { |
| 11699 | assert_eq!(raster, vert, "guard moved row={row} col={col}"); |
| 11700 | } |
| 11701 | } |
| 11702 | } |
| 11703 | assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); |
| 11704 | // The guard is scoped: it must not leak past its own block. |
| 11705 | assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); |
| 11706 | } |
| 11707 | |
| 11708 | /// An odd width or height is refused by name, not by however the padder |
| 11709 | /// or the block coder would happen to fail on it. |
| 11710 | #[test] |
| 11711 | fn odd_dimensions_are_refused() { |
| 11712 | let _knobs = crate::speed::knob_read(); |
| 11713 | let fctx = &crate::decode::FrameCtx::new(); |
| 11714 | for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { |
| 11715 | let picture = Picture::grey(width, height); |
| 11716 | let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) |
| 11717 | .expect_err(&format!("{width}x{height} is odd and must be refused")); |
| 11718 | assert!( |
| 11719 | err.to_string().contains("even"), |
| 11720 | "{width}x{height}: error was {err}" |
| 11721 | ); |
| 11722 | } |
| 11723 | } |
| 11724 | |
| 11725 | /// A sequence at a size that is not a multiple of the block grid decodes |
| 11726 | /// to the right frame count and the right size for every frame, |
| 11727 | /// including the inter frames whose reference is the previous frame's |
| 11728 | /// own (padded) reconstruction. |
| 11729 | #[test] |
| 11730 | fn sequence_round_trips_at_a_non_multiple_size() { |
| 11731 | let _knobs = crate::speed::knob_read(); |
| 11732 | let fctx = &crate::decode::FrameCtx::new(); |
| 11733 | if !have_ffmpeg() { |
| 11734 | eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); |
| 11735 | return; |
| 11736 | } |
| 11737 | let (width, height) = (160usize, 96usize); |
| 11738 | let pictures: Vec<Picture> = (0..3) |
| 11739 | .map(|i| panned_test_card(width, height, i * 3)) |
| 11740 | .collect(); |
| 11741 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 11742 | assert_eq!(encoded.frames.len(), 3); |
| 11743 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 11744 | assert_eq!( |
| 11745 | (frame.reconstruction.width, frame.reconstruction.height), |
| 11746 | (width, height), |
| 11747 | "frame {i}: reconstruction size" |
| 11748 | ); |
| 11749 | } |
| 11750 | // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the |
| 11751 | // true (display) size a sequence's frames share, not the padded one. |
| 11752 | assert_eq!( |
| 11753 | ffprobe_size(&encoded.stream), |
| 11754 | (width as u32, height as u32), |
| 11755 | "sequence: ffprobe reports the true (display) size" |
| 11756 | ); |
| 11757 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 11758 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 11759 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 11760 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 11761 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 11762 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 11763 | } |
| 11764 | } |
| 11765 | |
| 11766 | /// 1280x720 -- the export size a real edith timeline hits -- is exactly |
| 11767 | /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge |
| 11768 | /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s |
| 11769 | /// `pos + side_mi / 2 < bound` boundary), which is the case |
| 11770 | /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than |
| 11771 | /// refusing. A key frame alone already covered this size; this proves the |
| 11772 | /// inter tile writer's parity with it across a real multi-frame export. |
| 11773 | #[test] |
| 11774 | fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { |
| 11775 | let _knobs = crate::speed::knob_read(); |
| 11776 | let fctx = &crate::decode::FrameCtx::new(); |
| 11777 | if !have_ffmpeg() { |
| 11778 | eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg"); |
| 11779 | return; |
| 11780 | } |
| 11781 | let (width, height) = (1280usize, 720usize); |
| 11782 | let pictures: Vec<Picture> = (0..3) |
| 11783 | .map(|i| panned_test_card(width, height, i * 3)) |
| 11784 | .collect(); |
| 11785 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 11786 | assert_eq!(encoded.frames.len(), 3); |
| 11787 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 11788 | assert_eq!( |
| 11789 | (frame.reconstruction.width, frame.reconstruction.height), |
| 11790 | (width, height), |
| 11791 | "frame {i}: reconstruction size" |
| 11792 | ); |
| 11793 | } |
| 11794 | assert_eq!( |
| 11795 | ffprobe_size(&encoded.stream), |
| 11796 | (width as u32, height as u32), |
| 11797 | "ffprobe reports the true (display) 1280x720 size" |
| 11798 | ); |
| 11799 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 11800 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 11801 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 11802 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 11803 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 11804 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 11805 | } |
| 11806 | } |
| 11807 | |
| 11808 | /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16 |
| 11809 | /// leaf's own half (`has_half` at the SUB level) itself straddles the |
| 11810 | /// true edge on one axis only. lane-av1-rect r7 wired the key frame |
| 11811 | /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly |
| 11812 | /// this case; lane-av1inter8 extends the same leaf-8 path to inter |
| 11813 | /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s |
| 11814 | /// straddling-16x16 branch), so an inter frame no longer refuses this |
| 11815 | /// size either. This only proves the encoder does not error out -- see |
| 11816 | /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the |
| 11817 | /// decoder-clean proof (a 3-frame sequence, so the inter path is |
| 11818 | /// actually exercised). |
| 11819 | #[test] |
| 11820 | fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { |
| 11821 | let _knobs = crate::speed::knob_read(); |
| 11822 | let fctx = &crate::decode::FrameCtx::new(); |
| 11823 | let (width, height) = (640usize, 360usize); |
| 11824 | let picture = Picture::grey(width, height); |
| 11825 | encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle"); |
| 11826 | |
| 11827 | // `encode_sequence`'s second frame is the inter path: same size, now |
| 11828 | // wired the same way. |
| 11829 | let pictures = vec![picture.clone(), picture]; |
| 11830 | encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) |
| 11831 | .expect("inter frame now codes the mod-32==8 straddle too"); |
| 11832 | } |
| 11833 | |
| 11834 | /// The r15 fix at production size: three 640x360 key frames (inter is |
| 11835 | /// still refused at this size, per the test above, so this stands in for |
| 11836 | /// the charter's "3-frame sequence" using three independent key frames of |
| 11837 | /// shifted content), each proven decoder-clean through ffmpeg rather than |
| 11838 | /// only encoder-clean. |
| 11839 | #[test] |
| 11840 | fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { |
| 11841 | let _knobs = crate::speed::knob_read(); |
| 11842 | let fctx = &crate::decode::FrameCtx::new(); |
| 11843 | if !have_ffmpeg() { |
| 11844 | eprintln!( |
| 11845 | "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \ |
| 11846 | no ffmpeg" |
| 11847 | ); |
| 11848 | return; |
| 11849 | } |
| 11850 | let (width, height) = (640usize, 360usize); |
| 11851 | for shift in [0i64, 7, 19] { |
| 11852 | let picture = panned_test_card(width, height, shift); |
| 11853 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 11854 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 11855 | assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); |
| 11856 | assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); |
| 11857 | assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); |
| 11858 | } |
| 11859 | } |
| 11860 | |
| 11861 | /// The 640x360 straddle class, but through the inter path an actual |
| 11862 | /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)): |
| 11863 | /// proves the leaf-8 inter stream this round wires up is not just |
| 11864 | /// encoder-clean (the test above) but decoder-clean against ffmpeg too. |
| 11865 | #[test] |
| 11866 | fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { |
| 11867 | let _knobs = crate::speed::knob_read(); |
| 11868 | let fctx = &crate::decode::FrameCtx::new(); |
| 11869 | if !have_ffmpeg() { |
| 11870 | eprintln!( |
| 11871 | "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" |
| 11872 | ); |
| 11873 | return; |
| 11874 | } |
| 11875 | let (width, height) = (640usize, 360usize); |
| 11876 | let pictures: Vec<Picture> = (0..4) |
| 11877 | .map(|i| panned_test_card(width, height, i * 3)) |
| 11878 | .collect(); |
| 11879 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 11880 | assert_eq!(encoded.frames.len(), 4); |
| 11881 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 11882 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 11883 | } |
| 11884 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); |
| 11885 | assert_eq!(decoded.len(), 4, "decoded frame count"); |
| 11886 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 11887 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 11888 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 11889 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 11890 | } |
| 11891 | } |
| 11892 | |
| 11893 | /// One frame of a real clip, scaled to a whole number of 32x32 blocks. |
| 11894 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 11895 | let out = Command::new("ffmpeg") |
| 11896 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) |
| 11897 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 11898 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 11899 | .output() |
| 11900 | .expect("ffmpeg failed to run"); |
| 11901 | assert!( |
| 11902 | out.status.success(), |
| 11903 | "ffmpeg: {}", |
| 11904 | String::from_utf8_lossy(&out.stderr) |
| 11905 | ); |
| 11906 | let (luma, chroma) = (width * height, width * height / 4); |
| 11907 | assert_eq!( |
| 11908 | out.stdout.len(), |
| 11909 | luma + 2 * chroma, |
| 11910 | "expected one 4:2:0 frame" |
| 11911 | ); |
| 11912 | Picture { |
| 11913 | width, |
| 11914 | height, |
| 11915 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 11916 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 11917 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 11918 | } |
| 11919 | } |
| 11920 | |
| 11921 | /// Prints what the mode search saves over DC prediction alone, for the |
| 11922 | /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the |
| 11923 | /// weight the search puts on rate can be swept. |
| 11924 | #[test] |
| 11925 | #[ignore = "a sweep, not a gate"] |
| 11926 | fn probe_lambda() { |
| 11927 | let _knobs = crate::speed::knob_read(); |
| 11928 | let fctx = &crate::decode::FrameCtx::new(); |
| 11929 | let mut pictures = vec![ |
| 11930 | ("test card".to_string(), test_card(160, 96)), |
| 11931 | ("stripes".to_string(), stripes(160, 96, true)), |
| 11932 | ]; |
| 11933 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 11934 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 11935 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 11936 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 11937 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 11938 | } |
| 11939 | } |
| 11940 | for (name, picture) in pictures { |
| 11941 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 11942 | let searched = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 11943 | println!( |
| 11944 | "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", |
| 11945 | bd_rate(&dc, &searched) * 100.0, |
| 11946 | 10f64.powf(searched[1].1), |
| 11947 | searched[1].0, |
| 11948 | 10f64.powf(dc[1].1), |
| 11949 | dc[1].0, |
| 11950 | ); |
| 11951 | } |
| 11952 | } |
| 11953 | |
| 11954 | /// Prints the whole mode-search ladder, so two builds of the search can be |
| 11955 | /// compared against each other rather than each against its own baseline. |
| 11956 | #[test] |
| 11957 | #[ignore = "a sweep, not a gate"] |
| 11958 | fn probe_ladder() { |
| 11959 | let _knobs = crate::speed::knob_read(); |
| 11960 | let fctx = &crate::decode::FrameCtx::new(); |
| 11961 | for (name, picture) in sweep_pictures() { |
| 11962 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 11963 | let points = all |
| 11964 | .iter() |
| 11965 | .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) |
| 11966 | .collect::<Vec<_>>() |
| 11967 | .join(" "); |
| 11968 | println!("ladder {name}: {points}"); |
| 11969 | } |
| 11970 | } |
| 11971 | |
| 11972 | /// Splitting a 32x32 block into four 16x16 ones, measured both ways over |
| 11973 | /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what |
| 11974 | /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report. |
| 11975 | #[test] |
| 11976 | #[ignore = "a sweep, not a gate"] |
| 11977 | fn probe_split() { |
| 11978 | let _knobs = crate::speed::knob_read(); |
| 11979 | let fctx = &crate::decode::FrameCtx::new(); |
| 11980 | for (name, picture) in sweep_pictures() { |
| 11981 | let ladder = |split: bool| { |
| 11982 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 11983 | .iter() |
| 11984 | .map(|&q| { |
| 11985 | let encoded = encode_key_frame_inner( |
| 11986 | &picture, |
| 11987 | q, |
| 11988 | 0.5, |
| 11989 | &KEY_FRAME_MODES, |
| 11990 | split, |
| 11991 | (picture.width, picture.height), |
| 11992 | unspecified_color_config(), fctx, |
| 11993 | ) |
| 11994 | .unwrap(); |
| 11995 | ( |
| 11996 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 11997 | (encoded.stream.len() as f64).log10(), |
| 11998 | ) |
| 11999 | }) |
| 12000 | .collect(); |
| 12001 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 12002 | points |
| 12003 | }; |
| 12004 | let (whole, split) = (ladder(false), ladder(true)); |
| 12005 | let blocks = encode_key_frame_inner( |
| 12006 | &picture, |
| 12007 | 90, |
| 12008 | 0.5, |
| 12009 | &KEY_FRAME_MODES, |
| 12010 | true, |
| 12011 | (picture.width, picture.height), |
| 12012 | unspecified_color_config(), fctx, |
| 12013 | ) |
| 12014 | .unwrap() |
| 12015 | .modes |
| 12016 | .len(); |
| 12017 | let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); |
| 12018 | println!( |
| 12019 | "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", |
| 12020 | bd_rate(&whole, &split) * 100.0 |
| 12021 | ); |
| 12022 | } |
| 12023 | } |
| 12024 | |
| 12025 | /// A striped picture, running one way or the other. The stripes are what |
| 12026 | /// separates a vertical predictor from a horizontal one: a mode search |
| 12027 | /// reading a transposed edge would pick the wrong one of the pair, which no |
| 12028 | /// symmetric picture would show. |
| 12029 | fn stripes(width: usize, height: usize, vertical: bool) -> Picture { |
| 12030 | let mut picture = Picture::grey(width, height); |
| 12031 | for y in 0..height { |
| 12032 | for x in 0..width { |
| 12033 | let along = if vertical { x } else { y }; |
| 12034 | picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; |
| 12035 | } |
| 12036 | } |
| 12037 | picture |
| 12038 | } |
| 12039 | |
| 12040 | /// Where two planes first disagree, and by how much: a mismatch reported as |
| 12041 | /// a position says which block and which sample of it went wrong, which a |
| 12042 | /// pair of thousand-sample arrays does not. |
| 12043 | fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> { |
| 12044 | let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?; |
| 12045 | let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); |
| 12046 | Some(format!( |
| 12047 | "{differ} samples differ, first at ({}, {}): ours {} theirs {}", |
| 12048 | i % width, |
| 12049 | i / width, |
| 12050 | ours[i], |
| 12051 | theirs[i] |
| 12052 | )) |
| 12053 | } |
| 12054 | |
| 12055 | /// Every mode the encoder offers has to predict what the decoder predicts, |
| 12056 | /// not just the ones a particular picture happens to choose: each is forced |
| 12057 | /// over a whole picture and the reconstruction gated against ffmpeg. |
| 12058 | #[test] |
| 12059 | fn every_mode_decodes_to_what_the_encoder_predicted() { |
| 12060 | let _knobs = crate::speed::knob_write(); |
| 12061 | let fctx = &crate::decode::FrameCtx::new(); |
| 12062 | if !have_ffmpeg() { |
| 12063 | eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); |
| 12064 | return; |
| 12065 | } |
| 12066 | // A mode ablation measures the MODE search: a filter-intra block is |
| 12067 | // coded `DC_PRED` whatever mode the arm forces, so it would fail the |
| 12068 | // "the encoder coded something else" check for a reason that is not |
| 12069 | // about the mode search at all. |
| 12070 | force_filter_intra(Some(false)); |
| 12071 | // 128 wide is a whole number of superblocks and 160 is not: the last |
| 12072 | // superblock of a 160-wide row is half a one, whose blocks have no |
| 12073 | // above-right samples inside the frame at all. |
| 12074 | for (width, height) in [(128, 96), (160, 96)] { |
| 12075 | let picture = test_card(width, height); |
| 12076 | for mode in KEY_FRAME_MODES { |
| 12077 | let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap(); |
| 12078 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 12079 | for (plane, ours, theirs, stride) in [ |
| 12080 | ("luma", &encoded.reconstruction.y, &decoded.y, width), |
| 12081 | ("U", &encoded.reconstruction.u, &decoded.u, width / 2), |
| 12082 | ("V", &encoded.reconstruction.v, &decoded.v, width / 2), |
| 12083 | ] { |
| 12084 | assert!( |
| 12085 | first_difference(ours, theirs, stride).is_none(), |
| 12086 | "{width}x{height} mode {mode}, {plane}: {}", |
| 12087 | first_difference(ours, theirs, stride).unwrap() |
| 12088 | ); |
| 12089 | } |
| 12090 | assert!( |
| 12091 | encoded.modes.iter().all(|&m| m == mode), |
| 12092 | "mode {mode}: the encoder coded something else" |
| 12093 | ); |
| 12094 | } |
| 12095 | } |
| 12096 | } |
| 12097 | |
| 12098 | /// The search has to follow the picture: vertical stripes are cheapest |
| 12099 | /// predicted from the row above, horizontal ones from the column to the |
| 12100 | /// left. Reading the edges the other way round would swap the two answers |
| 12101 | /// while leaving every fidelity gate intact. |
| 12102 | #[test] |
| 12103 | fn the_search_picks_the_direction_the_picture_runs() { |
| 12104 | let _knobs = crate::speed::knob_write(); |
| 12105 | let fctx = &crate::decode::FrameCtx::new(); |
| 12106 | // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]: |
| 12107 | // a filter-intra block is coded `DC_PRED` whatever mode the arm |
| 12108 | // offers, and these stripes are SCREEN content, where the filter arm |
| 12109 | // now searches its own transform depth (lane-fitu) and wins outright |
| 12110 | // -- which says nothing about the mode search this gate measures. |
| 12111 | force_filter_intra(Some(false)); |
| 12112 | for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { |
| 12113 | let picture = stripes(128, 96, vertical); |
| 12114 | // Only the pair, because on stripes a third mode predicts exactly |
| 12115 | // what the right one of the pair does -- PAETH reads the corner and |
| 12116 | // the left column, which a striped picture makes equal -- and the |
| 12117 | // tie then goes to whichever is cheaper to name, which is not what |
| 12118 | // this gate is about. |
| 12119 | let encoded = |
| 12120 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap(); |
| 12121 | // The first block of the picture has neither neighbour, so it |
| 12122 | // cannot tell the modes apart; every other one can. |
| 12123 | let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); |
| 12124 | assert!( |
| 12125 | picked * 2 > encoded.modes.len() - 1, |
| 12126 | "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", |
| 12127 | encoded.modes.len() - 1, |
| 12128 | encoded.modes |
| 12129 | ); |
| 12130 | } |
| 12131 | } |
| 12132 | |
| 12133 | /// What the search is for: the same picture, at the same quantizer, coded |
| 12134 | /// smaller and more faithfully than DC alone can manage. |
| 12135 | /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid |
| 12136 | /// between the two rate-distortion curves in log-rate against PSNR, as a |
| 12137 | /// fraction of the reference's rate. Negative means the second curve costs |
| 12138 | /// less for the same picture. |
| 12139 | fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { |
| 12140 | let low = reference[0].0.max(other[0].0); |
| 12141 | let high = reference[reference.len() - 1] |
| 12142 | .0 |
| 12143 | .min(other[other.len() - 1].0); |
| 12144 | // lane-av1tx: `TxMode::Select` moved the directional ladder clear of |
| 12145 | // the non-directional one on the synthetic diagonals -- every point |
| 12146 | // both higher in PSNR *and* lower in rate -- so there is no PSNR band |
| 12147 | // to integrate over any more. A curve that dominates that way has |
| 12148 | // saved everything the measure can express (the |
| 12149 | // `instrument-at-bound` class: the answer is at the instrument's own |
| 12150 | // edge, not undefined), so name it rather than panicking; anything |
| 12151 | // less clean than strict dominance still is. |
| 12152 | if high <= low { |
| 12153 | let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); |
| 12154 | let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); |
| 12155 | let dominates = other[0].0 > reference[reference.len() - 1].0 |
| 12156 | && other_hi_rate <= ref_lo_rate; |
| 12157 | assert!( |
| 12158 | dominates, |
| 12159 | "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" |
| 12160 | ); |
| 12161 | return -1.0; |
| 12162 | } |
| 12163 | let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { |
| 12164 | let i = curve |
| 12165 | .windows(2) |
| 12166 | .position(|w| psnr >= w[0].0 && psnr <= w[1].0) |
| 12167 | .unwrap_or(0); |
| 12168 | let (x0, y0) = curve[i]; |
| 12169 | let (x1, y1) = curve[i + 1]; |
| 12170 | y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) |
| 12171 | }; |
| 12172 | let steps = 64; |
| 12173 | let mut area = 0.0; |
| 12174 | for step in 0..steps { |
| 12175 | let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); |
| 12176 | area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); |
| 12177 | } |
| 12178 | 10f64.powf(area / f64::from(steps)) - 1.0 |
| 12179 | } |
| 12180 | |
| 12181 | /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by |
| 12182 | /// fidelity. |
| 12183 | fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { |
| 12184 | // A mode ablation measures the MODE search: the palette would code |
| 12185 | // these synthetic two-colour pictures losslessly under every arm and |
| 12186 | // leave nothing to compare (see [`force_screen`]). |
| 12187 | force_screen(Some(false)); |
| 12188 | // Same reason, for the filter-intra candidate: it wins blocks under |
| 12189 | // BOTH arms of a mode ablation and so cancels the difference the |
| 12190 | // ablation measures (class `gate-recipe-confound`). |
| 12191 | force_filter_intra(Some(false)); |
| 12192 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 12193 | .iter() |
| 12194 | .map(|&q| { |
| 12195 | let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap(); |
| 12196 | ( |
| 12197 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 12198 | (encoded.stream.len() as f64).log10(), |
| 12199 | ) |
| 12200 | }) |
| 12201 | .collect(); |
| 12202 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 12203 | points |
| 12204 | } |
| 12205 | |
| 12206 | /// What the search is for: the same pictures cost less to code at the same |
| 12207 | /// fidelity than DC prediction alone can manage. A picture that runs one |
| 12208 | /// way saves far more than a busy one, which is the shape a working |
| 12209 | /// directional pair has. |
| 12210 | #[test] |
| 12211 | fn the_search_beats_dc_alone() { |
| 12212 | let _knobs = crate::speed::knob_read(); |
| 12213 | let fctx = &crate::decode::FrameCtx::new(); |
| 12214 | for (name, picture, want) in [ |
| 12215 | ("test card", test_card(160, 96), -0.05), |
| 12216 | ("stripes", stripes(160, 96, true), -0.40), |
| 12217 | ] { |
| 12218 | let saved = bd_rate( |
| 12219 | &ladder(&picture, &[DC_PRED], fctx), |
| 12220 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 12221 | ); |
| 12222 | assert!( |
| 12223 | saved < want, |
| 12224 | "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", |
| 12225 | saved * 100.0, |
| 12226 | -want * 100.0 |
| 12227 | ); |
| 12228 | } |
| 12229 | } |
| 12230 | |
| 12231 | /// The pictures a sweep is measured over: two synthetic ones, plus a frame |
| 12232 | /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated. |
| 12233 | fn sweep_pictures() -> Vec<(String, Picture)> { |
| 12234 | let mut pictures = vec![ |
| 12235 | ("test card".to_string(), test_card(160, 96)), |
| 12236 | ("stripes".to_string(), stripes(160, 96, true)), |
| 12237 | ("diagonal".to_string(), diagonal(160, 96, true)), |
| 12238 | ]; |
| 12239 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 12240 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 12241 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 12242 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 12243 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 12244 | } |
| 12245 | } |
| 12246 | pictures |
| 12247 | } |
| 12248 | |
| 12249 | /// What the six directional modes are worth, per picture, at whatever |
| 12250 | /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read |
| 12251 | /// no further, and how often the search picks one. |
| 12252 | #[test] |
| 12253 | #[ignore = "a sweep, not a gate"] |
| 12254 | fn probe_directional() { |
| 12255 | let _knobs = crate::speed::knob_write(); |
| 12256 | let fctx = &crate::decode::FrameCtx::new(); |
| 12257 | for (name, picture) in sweep_pictures() { |
| 12258 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 12259 | let flat = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 12260 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 12261 | let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap(); |
| 12262 | let directional = encoded |
| 12263 | .modes |
| 12264 | .iter() |
| 12265 | .filter(|&&m| (3..=8).contains(&m)) |
| 12266 | .count(); |
| 12267 | // A picture whose ladders sit at different fidelities altogether |
| 12268 | // has no BD-rate to report -- see the flat-sample-window class. |
| 12269 | let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 12270 | a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) |
| 12271 | }; |
| 12272 | let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 12273 | if overlap(a, b) { |
| 12274 | format!("{:+.2}%", bd_rate(a, b) * 100.0) |
| 12275 | } else { |
| 12276 | "no overlap".to_string() |
| 12277 | } |
| 12278 | }; |
| 12279 | println!( |
| 12280 | "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", |
| 12281 | against(&flat, &all), |
| 12282 | against(&dc, &all), |
| 12283 | encoded.modes.len(), |
| 12284 | ); |
| 12285 | } |
| 12286 | } |
| 12287 | |
| 12288 | /// A picture whose stripes run along a diagonal, one way or the other. |
| 12289 | /// This is to the directional modes what [`stripes`] is to the vertical and |
| 12290 | /// horizontal pair: a predictor that walked the edge in the wrong direction |
| 12291 | /// would answer the two pictures the same way round. |
| 12292 | fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { |
| 12293 | let mut picture = Picture::grey(width, height); |
| 12294 | for y in 0..height { |
| 12295 | for x in 0..width { |
| 12296 | let along = if down_right { x + height - y } else { x + y }; |
| 12297 | picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; |
| 12298 | } |
| 12299 | } |
| 12300 | picture |
| 12301 | } |
| 12302 | |
| 12303 | /// The mode picked by the most blocks of a picture, ignoring the first |
| 12304 | /// block, which has no neighbours to tell the modes apart with. |
| 12305 | fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { |
| 12306 | // A mode ablation measures the MODE search: the palette would code |
| 12307 | // these synthetic two-colour pictures losslessly under every arm and |
| 12308 | // leave nothing to compare (see [`force_screen`]). |
| 12309 | force_screen(Some(false)); |
| 12310 | let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); |
| 12311 | let blocks = &encoded.modes[1..]; |
| 12312 | let mut counts = [0usize; 13]; |
| 12313 | for &mode in blocks { |
| 12314 | counts[usize::from(mode)] += 1; |
| 12315 | } |
| 12316 | let (mode, count) = counts |
| 12317 | .iter() |
| 12318 | .enumerate() |
| 12319 | .max_by_key(|&(_, count)| *count) |
| 12320 | .expect("thirteen modes"); |
| 12321 | (mode as u8, *count, blocks.len()) |
| 12322 | } |
| 12323 | |
| 12324 | /// The search has to follow a diagonal the way it runs: stripes down and to |
| 12325 | /// the right are cheapest predicted at 135 degrees, stripes down and to the |
| 12326 | /// left at 45. A walk that stepped the wrong way along the edge, or read |
| 12327 | /// the above row where it should read the left column, would swap these. |
| 12328 | #[test] |
| 12329 | fn the_search_picks_the_diagonal_the_picture_runs() { |
| 12330 | let _knobs = crate::speed::knob_write(); |
| 12331 | let fctx = &crate::decode::FrameCtx::new(); |
| 12332 | for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { |
| 12333 | let picture = diagonal(160, 96, down_right); |
| 12334 | let (mode, count, blocks) = favourite_mode(&picture, fctx); |
| 12335 | assert_eq!( |
| 12336 | mode, want, |
| 12337 | "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" |
| 12338 | ); |
| 12339 | } |
| 12340 | } |
| 12341 | |
| 12342 | /// What the directional modes are for: a picture that runs along a diagonal |
| 12343 | /// costs far less to code with them than the seven that read only their own |
| 12344 | /// edges can manage, and a picture that runs no particular way costs no |
| 12345 | /// more. The second half is the one that bites: a mode set the search |
| 12346 | /// cannot price is a mode set that loses rate on content that does not want |
| 12347 | /// it, which is what costing the mode symbol is for. |
| 12348 | #[test] |
| 12349 | fn the_diagonals_beat_the_modes_that_read_no_further() { |
| 12350 | let _knobs = crate::speed::knob_read(); |
| 12351 | let fctx = &crate::decode::FrameCtx::new(); |
| 12352 | for (name, picture, want) in [ |
| 12353 | ("down-right", diagonal(160, 96, true), -0.20), |
| 12354 | ("down-left", diagonal(160, 96, false), -0.20), |
| 12355 | ("test card", test_card(160, 96), 0.01), |
| 12356 | ] { |
| 12357 | let saved = bd_rate( |
| 12358 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 12359 | &ladder(&picture, &KEY_FRAME_MODES, fctx), |
| 12360 | ); |
| 12361 | assert!( |
| 12362 | saved < want, |
| 12363 | "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", |
| 12364 | saved * 100.0, |
| 12365 | -want * 100.0 |
| 12366 | ); |
| 12367 | } |
| 12368 | } |
| 12369 | |
| 12370 | /// A mode the encoder cannot predict must be refused rather than coded as |
| 12371 | /// something else, and a search with nothing to choose from likewise. |
| 12372 | #[test] |
| 12373 | fn a_mode_the_encoder_cannot_predict_is_refused() { |
| 12374 | let _knobs = crate::speed::knob_read(); |
| 12375 | let fctx = &crate::decode::FrameCtx::new(); |
| 12376 | let picture = test_card(64, 64); |
| 12377 | let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) |
| 12378 | .unwrap_err() |
| 12379 | .to_string(); |
| 12380 | assert!( |
| 12381 | message.contains("intra mode 13"), |
| 12382 | "the refusal must name the mode, got {message}" |
| 12383 | ); |
| 12384 | assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); |
| 12385 | } |
| 12386 | |
| 12387 | /// The picture that comes back is the picture that went in, to within the |
| 12388 | /// quantizer. A prediction that read the wrong neighbours, or a block |
| 12389 | /// written into the wrong place, would still decode to what the encoder |
| 12390 | /// reconstructed — it is this gate that says the reconstruction is of the |
| 12391 | /// right picture. |
| 12392 | #[test] |
| 12393 | fn the_encoded_picture_is_the_one_that_went_in() { |
| 12394 | let _knobs = crate::speed::knob_read(); |
| 12395 | let fctx = &crate::decode::FrameCtx::new(); |
| 12396 | let picture = test_card(160, 96); |
| 12397 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 12398 | let luma = psnr(&encoded.reconstruction.y, &picture.y); |
| 12399 | assert!(luma > 36.0, "luma PSNR {luma} at q 100"); |
| 12400 | for (plane, (got, want)) in [ |
| 12401 | (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), |
| 12402 | (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), |
| 12403 | ] |
| 12404 | .iter() |
| 12405 | .enumerate() |
| 12406 | { |
| 12407 | let chroma = psnr(got, want); |
| 12408 | assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); |
| 12409 | } |
| 12410 | } |
| 12411 | |
| 12412 | /// A finer quantizer costs bits and buys fidelity, and a wider deadzone |
| 12413 | /// does the opposite. Both are monotone, which is what a rate-distortion |
| 12414 | /// loop above this will assume. |
| 12415 | #[test] |
| 12416 | fn fidelity_and_rate_move_with_the_quantizer() { |
| 12417 | let _knobs = crate::speed::knob_read(); |
| 12418 | let fctx = &crate::decode::FrameCtx::new(); |
| 12419 | let picture = test_card(128, 128); |
| 12420 | let mut previous: Option<(usize, f64)> = None; |
| 12421 | for &q in &[70u8, 90, 110] { |
| 12422 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 12423 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 12424 | if let Some((bytes, better)) = previous { |
| 12425 | assert!( |
| 12426 | encoded.stream.len() < bytes, |
| 12427 | "q {q}: {} bytes", |
| 12428 | encoded.stream.len() |
| 12429 | ); |
| 12430 | assert!(quality < better, "q {q}: PSNR {quality}"); |
| 12431 | } |
| 12432 | previous = Some((encoded.stream.len(), quality)); |
| 12433 | } |
| 12434 | |
| 12435 | let mut previous = None; |
| 12436 | for &deadzone in &[0.5f64, 0.3, 0.15] { |
| 12437 | let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap(); |
| 12438 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 12439 | if let Some((bytes, better)) = previous { |
| 12440 | assert!( |
| 12441 | encoded.stream.len() < bytes, |
| 12442 | "deadzone {deadzone}: {} bytes", |
| 12443 | encoded.stream.len() |
| 12444 | ); |
| 12445 | assert!(quality < better, "deadzone {deadzone}: PSNR {quality}"); |
| 12446 | } |
| 12447 | previous = Some((encoded.stream.len(), quality)); |
| 12448 | } |
| 12449 | |
| 12450 | // Bytes must not jump up across a q-context boundary: a wrong CDF |
| 12451 | // table for the far side would show up as a rate discontinuity here, |
| 12452 | // even though a coarser quantizer always codes no more than a finer |
| 12453 | // one on the same picture. |
| 12454 | // |
| 12455 | // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since |
| 12456 | // chroma searches its own mode, a coarser quantizer can pick a |
| 12457 | // *different* uv_mode on a block whose modes now cost nearly the |
| 12458 | // same, and the search prices that symbol against the static default |
| 12459 | // CDF while the writer codes it against an adapted one -- 311 -> 319 |
| 12460 | // bytes at q 120->121 on this picture. The table this gate is really |
| 12461 | // watching would move the rate by far more than the mode churn does. |
| 12462 | // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the |
| 12463 | // same block can also change transform DEPTH between two neighbouring |
| 12464 | // quantizers (297 -> 315 bytes at q 120->121 here), and the depth |
| 12465 | // symbol is priced off the static CDF row 0 for the same reason the |
| 12466 | // uv_mode one is. |
| 12467 | // Ceiling: a q-context table wrong by under 10% would pass. Upgrade |
| 12468 | // path is pricing through the adapting CDF state (what |
| 12469 | // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the |
| 12470 | // drift of), after which the exact bound comes back. |
| 12471 | for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { |
| 12472 | let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len(); |
| 12473 | let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len(); |
| 12474 | assert!( |
| 12475 | hi_bytes as f64 <= lo_bytes as f64 * 1.10, |
| 12476 | "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" |
| 12477 | ); |
| 12478 | } |
| 12479 | } |
| 12480 | |
| 12481 | /// A flat picture is a flat stream: every block predicts its neighbours' |
| 12482 | /// average, which is the picture's own value, and codes nothing. |
| 12483 | #[test] |
| 12484 | fn a_flat_picture_costs_almost_nothing() { |
| 12485 | let _knobs = crate::speed::knob_read(); |
| 12486 | let fctx = &crate::decode::FrameCtx::new(); |
| 12487 | let mut picture = Picture::grey(128, 128); |
| 12488 | picture.y.fill(97); |
| 12489 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 12490 | // The first block has no neighbour and predicts 128, so it carries a |
| 12491 | // DC; every block after it predicts 97 and carries nothing. |
| 12492 | assert!( |
| 12493 | encoded.stream.len() < 100, |
| 12494 | "{} bytes for a flat picture", |
| 12495 | encoded.stream.len() |
| 12496 | ); |
| 12497 | for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { |
| 12498 | assert_eq!(s, 97, "sample {i} of a flat picture"); |
| 12499 | } |
| 12500 | } |
| 12501 | |
| 12502 | /// The sizes the encoder refuses, refused for a reason rather than by |
| 12503 | /// panicking somewhere below. Sizes off the 32x32 block grid encode fine |
| 12504 | /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge |
| 12505 | /// lands past the halfway point of whichever block it falls in, so |
| 12506 | /// `PARTITION_NONE` or a single gathered split flag still says everything |
| 12507 | /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16 |
| 12508 | /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the |
| 12509 | /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4 |
| 12510 | /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred, |
| 12511 | /// down to the in-frame 8x8s, no rectangular transform anywhere (the old |
| 12512 | /// refusal here claimed otherwise and was wrong; see |
| 12513 | /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_ |
| 12514 | /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never |
| 12515 | /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec |
| 12516 | /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the |
| 12517 | /// true edge always lands on an 8-luma-sample boundary in mi terms and a |
| 12518 | /// 4x4 leaf -- which neither writer has -- is never asked for. What is |
| 12519 | /// still refused is a malformed picture. |
| 12520 | #[test] |
| 12521 | fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() { |
| 12522 | let _knobs = crate::speed::knob_read(); |
| 12523 | let fctx = &crate::decode::FrameCtx::new(); |
| 12524 | encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) |
| 12525 | .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split"); |
| 12526 | encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx) |
| 12527 | .expect("36 luma columns still round up to an even MiCols"); |
| 12528 | |
| 12529 | let mut short = Picture::grey(64, 64); |
| 12530 | short.u.truncate(10); |
| 12531 | assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); |
| 12532 | } |
| 12533 | |
| 12534 | /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own |
| 12535 | /// column half only (`has_half` false on cols, true on rows) -- exactly |
| 12536 | /// the single-axis straddle lane-av1-rect r7 wires through |
| 12537 | /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean: |
| 12538 | /// dav1d rejects the stream ("Invalid data found"). r7's falsification |
| 12539 | /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is |
| 12540 | /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own |
| 12541 | /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every |
| 12542 | /// `partition_context_lookup` entry this writer ever produces (no 4x4 |
| 12543 | /// splits exist) has bit 0 clear, so the ctx is provably 0 for every |
| 12544 | /// leaf regardless of neighbour state -- our writer already agreed with |
| 12545 | /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise |
| 12546 | /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a |
| 12547 | /// spec-accurate fix in its own right (it matters once 4x4 exists), and |
| 12548 | /// it does not regress the gate. r11 tell-for-tell traced two further, |
| 12549 | /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read |
| 12550 | /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both |
| 12551 | /// leaves, when the second leaf's true above (or left) neighbour is the |
| 12552 | /// first leaf itself -- fixed by threading the first leaf's mode into the |
| 12553 | /// second leaf's context, mi-precise, like `record_mi` already does for |
| 12554 | /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was |
| 12555 | /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when |
| 12556 | /// `reduced_tx_set` is false), but this crate's key frames set |
| 12557 | /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts |
| 12558 | /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2` |
| 12559 | /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE` |
| 12560 | /// symbol bits to desync everything after it. Fixed with a new |
| 12561 | /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact |
| 12562 | /// eset/size slot). Both fixes are provably correct against libaom |
| 12563 | /// source and each closed part of the gap (leaf0's `eob` went from a |
| 12564 | /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual |
| 12565 | /// divergence remained in the `EOB_PT` symbol's decoded value despite an |
| 12566 | /// aligned bit cost. r12 traced that residual with a fresh dual-trace |
| 12567 | /// (do not reuse r11's committed logs, which predate its own fixes) and |
| 12568 | /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded |
| 12569 | /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but |
| 12570 | /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` -- |
| 12571 | /// every other `write_block` caller at 16x16 and up already passes |
| 12572 | /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of |
| 12573 | /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a |
| 12574 | /// different amount of arithmetic range and derailed everything after |
| 12575 | /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an |
| 12576 | /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and |
| 12577 | /// `write_leaf8` called only `record_mi` (the coefficient-context half), |
| 12578 | /// never updating those coarse arrays itself -- so a *second* straddling |
| 12579 | /// 16x16 quadrant stacked above or left of the first (never covered by |
| 12580 | /// r11's same-call `prev_leaf` override, which only threads state |
| 12581 | /// between the two leaves of one shared quadrant) read whatever stale |
| 12582 | /// mode sat in that slot before either leaf ran. Fixed by writing the |
| 12583 | /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing |
| 12584 | /// (3) alone shrank the tell drift after leaf(0,8) from a decoder |
| 12585 | /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell` |
| 12586 | /// offset of a single unit; fixing (3)+(4) together still leaves a |
| 12587 | /// residual divergence one leaf further in -- the decoder now reads |
| 12588 | /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample |
| 12589 | /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning |
| 12590 | /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still |
| 12591 | /// desyncs the stream by exactly the width of one earlier symbol -- not |
| 12592 | /// yet isolated to a single named symbol. r15 found the last bug: the |
| 12593 | /// header fix from r14 explained the rng skew fully, and the remaining |
| 12594 | /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself -- |
| 12595 | /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf |
| 12596 | /// loop, once per leaf, so the first leaf's write clobbered the true |
| 12597 | /// external neighbour mode the second leaf of the *same* straddling |
| 12598 | /// quadrant still needed for its non-adjacency axis (a column-straddle |
| 12599 | /// case: two leaves share one `outer_at` column index, so leaf 1's |
| 12600 | /// write to `left_mode[r]` overwrote the real western neighbour before |
| 12601 | /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and |
| 12602 | /// doing it once, after the whole leaf loop, from the last (bottom/ |
| 12603 | /// right-most) leaf's mode. The stream now round-trips through ffmpeg. |
| 12604 | #[test] |
| 12605 | fn a_single_axis_straddle_round_trips_through_ffmpeg() { |
| 12606 | let _knobs = crate::speed::knob_read(); |
| 12607 | let fctx = &crate::decode::FrameCtx::new(); |
| 12608 | if !have_ffmpeg() { |
| 12609 | eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg"); |
| 12610 | return; |
| 12611 | } |
| 12612 | let (width, height) = (40usize, 32usize); |
| 12613 | let picture = test_card(width, height); |
| 12614 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 12615 | assert_eq!( |
| 12616 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 12617 | (width, height) |
| 12618 | ); |
| 12619 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 12620 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 12621 | } |
| 12622 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 12623 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 12624 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 12625 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 12626 | } |
| 12627 | |
| 12628 | /// A frame of real video, rather than a picture built to be easy. |
| 12629 | /// |
| 12630 | /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to |
| 12631 | /// seek; ffmpeg decodes one frame, crops it to the block grid, and the |
| 12632 | /// encoder's reconstruction has to survive the same equality gate as the |
| 12633 | /// synthetic pictures — real video reaches contexts a test card does not. |
| 12634 | #[test] |
| 12635 | fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() { |
| 12636 | let _knobs = crate::speed::knob_read(); |
| 12637 | let fctx = &crate::decode::FrameCtx::new(); |
| 12638 | let Ok(clip) = std::env::var("EC_AV1_CLIP") else { |
| 12639 | eprintln!( |
| 12640 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \ |
| 12641 | set EC_AV1_CLIP to a clip" |
| 12642 | ); |
| 12643 | return; |
| 12644 | }; |
| 12645 | if !have_ffmpeg() { |
| 12646 | eprintln!( |
| 12647 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 12648 | ); |
| 12649 | return; |
| 12650 | } |
| 12651 | let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into()); |
| 12652 | // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the |
| 12653 | // test quick while still spanning many superblocks. |
| 12654 | let (width, height) = (640usize, 352usize); |
| 12655 | let picture = clip_frame(&clip, &skip, width, height); |
| 12656 | |
| 12657 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 12658 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 12659 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 12660 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 12661 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 12662 | eprintln!( |
| 12663 | "{} bytes, luma PSNR {:.2} dB", |
| 12664 | encoded.stream.len(), |
| 12665 | psnr(&decoded.y, &picture.y) |
| 12666 | ); |
| 12667 | } |
| 12668 | |
| 12669 | /// [`test_card`], panned `shift` samples to the right (wrapping), so a |
| 12670 | /// sequence of these is a translation a motion search can actually find |
| 12671 | /// — the content [`test_card`] itself draws, not a fresh pattern, so an |
| 12672 | /// inter frame's rate against the key frame's is measuring the same |
| 12673 | /// picture moving, not two different pictures. |
| 12674 | fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { |
| 12675 | let mut picture = Picture::grey(width, height); |
| 12676 | for y in 0..height { |
| 12677 | for x in 0..width { |
| 12678 | let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; |
| 12679 | let gradient = sx * 200.0 / width as f64; |
| 12680 | let ripple = 30.0 |
| 12681 | * (sx * std::f64::consts::PI / 23.0).sin() |
| 12682 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 12683 | let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { |
| 12684 | 40.0 |
| 12685 | } else { |
| 12686 | 0.0 |
| 12687 | }; |
| 12688 | picture.y[y * width + x] = |
| 12689 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 12690 | } |
| 12691 | } |
| 12692 | for y in 0..height / 2 { |
| 12693 | for x in 0..width / 2 { |
| 12694 | let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; |
| 12695 | let i = y * width / 2 + x; |
| 12696 | picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; |
| 12697 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 12698 | } |
| 12699 | } |
| 12700 | picture |
| 12701 | } |
| 12702 | |
| 12703 | /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. |
| 12704 | fn ffmpeg_decode_sequence( |
| 12705 | stream: &[u8], |
| 12706 | width: usize, |
| 12707 | height: usize, |
| 12708 | frames: usize, |
| 12709 | ) -> Vec<Picture> { |
| 12710 | let mut child = Command::new("ffmpeg") |
| 12711 | .args([ |
| 12712 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 12713 | ]) |
| 12714 | .stdin(Stdio::piped()) |
| 12715 | .stdout(Stdio::piped()) |
| 12716 | .stderr(Stdio::piped()) |
| 12717 | .spawn() |
| 12718 | .expect("ffmpeg failed to start"); |
| 12719 | // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing |
| 12720 | // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB) |
| 12721 | // fills before the last input byte is written -- which is exactly what |
| 12722 | // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does |
| 12723 | // (measured: 45 min, both processes at 0% CPU). A write error here is |
| 12724 | // swallowed on purpose: ffmpeg's own exit status and stderr, asserted |
| 12725 | // below, are the real diagnosis. |
| 12726 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 12727 | let payload = stream.to_vec(); |
| 12728 | let writer = std::thread::spawn(move || { |
| 12729 | let _ = stdin.write_all(&payload); |
| 12730 | }); |
| 12731 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 12732 | writer.join().expect("ffmpeg stdin writer thread"); |
| 12733 | assert!( |
| 12734 | out.status.success(), |
| 12735 | "ffmpeg refused the stream: {}", |
| 12736 | String::from_utf8_lossy(&out.stderr) |
| 12737 | ); |
| 12738 | let (luma, chroma) = (width * height, width * height / 4); |
| 12739 | let frame_bytes = luma + 2 * chroma; |
| 12740 | assert_eq!( |
| 12741 | out.stdout.len(), |
| 12742 | frame_bytes * frames, |
| 12743 | "expected {frames} 4:2:0 frames, ffmpeg said: {}", |
| 12744 | String::from_utf8_lossy(&out.stderr) |
| 12745 | ); |
| 12746 | (0..frames) |
| 12747 | .map(|i| { |
| 12748 | let base = i * frame_bytes; |
| 12749 | Picture { |
| 12750 | width, |
| 12751 | height, |
| 12752 | y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), |
| 12753 | u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 12754 | v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), |
| 12755 | } |
| 12756 | }) |
| 12757 | .collect() |
| 12758 | } |
| 12759 | |
| 12760 | /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`] |
| 12761 | /// makes for a key frame, extended down the reference chain: each inter |
| 12762 | /// frame's reconstruction predicts from the previous frame's own decoded |
| 12763 | /// reconstruction, so a single sample of drift anywhere would propagate |
| 12764 | /// into every frame after it -- which is why every frame is checked, not |
| 12765 | /// just the last one, and why this is an equality and not a tolerance. |
| 12766 | #[test] |
| 12767 | fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { |
| 12768 | let _knobs = crate::speed::knob_read(); |
| 12769 | let fctx = &crate::decode::FrameCtx::new(); |
| 12770 | if !have_ffmpeg() { |
| 12771 | eprintln!( |
| 12772 | "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 12773 | ); |
| 12774 | return; |
| 12775 | } |
| 12776 | let (width, height) = (128usize, 64usize); |
| 12777 | let pictures: Vec<Picture> = (0..5) |
| 12778 | .map(|i| panned_test_card(width, height, i * 3)) |
| 12779 | .collect(); |
| 12780 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 12781 | assert_eq!(encoded.frames.len(), 5); |
| 12782 | |
| 12783 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); |
| 12784 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 12785 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); |
| 12786 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); |
| 12787 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); |
| 12788 | } |
| 12789 | |
| 12790 | eprintln!("frame bytes luma PSNR (dB) inter share"); |
| 12791 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 12792 | eprintln!( |
| 12793 | "{i:5} {:5} {:14.2} {:11.2}", |
| 12794 | frame.stream.len(), |
| 12795 | psnr(&frame.reconstruction.y, &pictures[i].y), |
| 12796 | frame.inter_block_share |
| 12797 | ); |
| 12798 | } |
| 12799 | } |
| 12800 | |
| 12801 | /// The same sequence through OUR OWN decoder, sample-exact against the |
| 12802 | /// encoder's reconstruction. ffmpeg stays the bitstream oracle |
| 12803 | /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no |
| 12804 | /// divergence point at all, while our decoder can be traced symbol by |
| 12805 | /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is |
| 12806 | /// the instrument the inter `TxMode::Select` hunt lacked; on failure it |
| 12807 | /// names the first differing frame, plane and position. |
| 12808 | #[test] |
| 12809 | fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { |
| 12810 | let _knobs = crate::speed::knob_read(); |
| 12811 | let fctx = &crate::decode::FrameCtx::new(); |
| 12812 | // 256x128, not the 128x64 this started at: once a leaf could search |
| 12813 | // its second reference (lane-av1comp4) the small card's every |
| 12814 | // eligible block went to a compound winner, which commits its flat |
| 12815 | // transform, and the split below stopped firing on content that |
| 12816 | // still splits at every larger size ([[gate-blind-to-feature]] -- |
| 12817 | // the guard is right, the fixture had shrunk under it). |
| 12818 | let (width, height) = (256usize, 128usize); |
| 12819 | let pictures: Vec<Picture> = |
| 12820 | (0..5).map(|i| panned_test_card(width, height, i * 3)).collect(); |
| 12821 | let _ = take_inter_tx_split_hits(); |
| 12822 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 12823 | let raw = take_inter_tx_split_hits(); |
| 12824 | // Summed over the four block classes the census keys on (leaf/32x32 x |
| 12825 | // single/compound): this assert is about the split firing at all. |
| 12826 | let split = [ |
| 12827 | raw.iter().step_by(2).sum::<usize>(), |
| 12828 | raw.iter().skip(1).step_by(2).sum::<usize>(), |
| 12829 | ]; |
| 12830 | eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); |
| 12831 | // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this |
| 12832 | // content splits -- a green round trip in which the split never fires |
| 12833 | // would prove only the flat path. |
| 12834 | if tx_select() && tx_select_inter() { |
| 12835 | assert!(split[1] > 0, "the inter var-tx split never fired"); |
| 12836 | } |
| 12837 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 12838 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 12839 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 12840 | let recon = &frame.reconstruction; |
| 12841 | for (plane, got, want, stride) in [ |
| 12842 | ("luma", &dec.y, &recon.y, width), |
| 12843 | ("U", &dec.u, &recon.u, width / 2), |
| 12844 | ("V", &dec.v, &recon.v, width / 2), |
| 12845 | ] { |
| 12846 | assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); |
| 12847 | if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { |
| 12848 | panic!( |
| 12849 | "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ |
| 12850 | reconstruction {} ({} of {} samples differ)", |
| 12851 | at % stride, |
| 12852 | at / stride, |
| 12853 | got[at], |
| 12854 | want[at], |
| 12855 | got.iter().zip(want).filter(|(a, b)| a != b).count(), |
| 12856 | got.len(), |
| 12857 | ); |
| 12858 | } |
| 12859 | } |
| 12860 | } |
| 12861 | } |
| 12862 | |
| 12863 | /// The rate term the mode search ranks every decision by has to be the |
| 12864 | /// rate the writer then spends. The search prices a block's coefficients |
| 12865 | /// through `tile::coeff_bits` -- the writer's own symbol chain, but |
| 12866 | /// against the default CDFs a tile starts from and the contexts of a |
| 12867 | /// block whose neighbours coded nothing -- while the tile writer codes |
| 12868 | /// them against a state that has been adapting all frame (the |
| 12869 | /// price-the-narrowing class). This measures that drift: the sum of what |
| 12870 | /// the search paid for the coefficients it kept, against the bytes the |
| 12871 | /// writer actually emitted for the whole tile (which also carries the |
| 12872 | /// partition/mode/skip/mv syntax the sum leaves out, so the writer is |
| 12873 | /// expected to be the larger of the two). |
| 12874 | #[test] |
| 12875 | fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { |
| 12876 | let _knobs = crate::speed::knob_read(); |
| 12877 | let fctx = &crate::decode::FrameCtx::new(); |
| 12878 | let (width, height) = (256usize, 128usize); |
| 12879 | let pictures: Vec<Picture> = (0..5) |
| 12880 | .map(|i| panned_test_card(width, height, i * 2)) |
| 12881 | .collect(); |
| 12882 | let _ = take_predicted_bits(); |
| 12883 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 12884 | let predicted = take_predicted_bits(); |
| 12885 | assert_eq!(predicted.len(), encoded.frames.len()); |
| 12886 | |
| 12887 | eprintln!("frame predicted bits written bits drift"); |
| 12888 | // Split by sign: a NEGATIVE drift is the search OVER-pricing (the |
| 12889 | // defect this gate exists to catch), a positive one is the written |
| 12890 | // side carrying syntax the coefficient sum leaves out -- and since |
| 12891 | // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual |
| 12892 | // on that side, so the two directions no longer share a bound. |
| 12893 | let mut worst_over: f64 = 0.0; |
| 12894 | let mut worst_under: f64 = 0.0; |
| 12895 | // The census is per CODED frame, so it is zipped in coding order -- |
| 12896 | // which is not display order under a pyramid. |
| 12897 | let coded: Vec<&Encoded> = |
| 12898 | encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect(); |
| 12899 | for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() { |
| 12900 | let written = frame.tile.len() as f64 * 8.0; |
| 12901 | let drift = (written - bits) / written; |
| 12902 | worst_over = worst_over.max(-drift); |
| 12903 | // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at |
| 12904 | // all (150-250 bits of tile, nearly all of it partition/mode/mv |
| 12905 | // syntax the coefficient sum never counts), so its ratio measures |
| 12906 | // that floor rather than any drift. Frames under 512 written bits |
| 12907 | // are left out of the under-price bound for that reason; the |
| 12908 | // over-price bound -- the defect direction, where the search pays |
| 12909 | // MORE than the writer -- still covers every frame. |
| 12910 | if written >= 512.0 { |
| 12911 | worst_under = worst_under.max(drift); |
| 12912 | } |
| 12913 | eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); |
| 12914 | } |
| 12915 | // Measured 2026-09-06 on this sequence: -13.5% at the key frame, |
| 12916 | // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search |
| 12917 | // over-prices every frame but the last (its sum EXCLUDES the |
| 12918 | // partition/mode/skip/mv syntax the written side carries, so the true |
| 12919 | // coefficient over-price is larger still): the writer's CDFs adapt to |
| 12920 | // the content while the search's stay at the defaults. The bound is |
| 12921 | // set just above the worst measured point -- a widening drift is the |
| 12922 | // thing this gate exists to catch. |
| 12923 | assert!( |
| 12924 | worst_over <= 0.16, |
| 12925 | "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", |
| 12926 | worst_over * 100.0 |
| 12927 | ); |
| 12928 | // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at |
| 12929 | // the worst inter frame, where nearly every block now codes an MV |
| 12930 | // residual and a reference the coefficient sum never counts. Re-measured |
| 12931 | // at +29.6% once the encoder's grid published compound blocks properly |
| 12932 | // (compound share 8.8% -> 11.5%): a compound block carries a second |
| 12933 | // reference tree, a compound mode symbol and -- for the half-new modes |
| 12934 | // -- an MV residual, none of which the coefficient sum counts. |
| 12935 | // lane-av1txbits: pricing against the tables the frame's writer really |
| 12936 | // starts from collapses the over-price above to nothing, so the whole |
| 12937 | // remaining gap is the syntax the coefficient sum leaves out. That is |
| 12938 | // the default on a non-screen frame since lane-av1price2 (this |
| 12939 | // fixture is one), and it reads +32.6% here. |
| 12940 | // lane-av1obmc: every eligible single-reference inter block now also |
| 12941 | // carries a `motion_mode` symbol the coefficient sum never counts, |
| 12942 | // and an OBMC block carries the more expensive of the two values -- |
| 12943 | // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like |
| 12944 | // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder |
| 12945 | // decisions, so this bound and the byte pins above FAIL BY DESIGN |
| 12946 | // under it; the default path (no motion_mode syntax at all) is the |
| 12947 | // one they are measured on. |
| 12948 | // lane-av1pyrdef: `encode_sequence` codes this fixture under the |
| 12949 | // coding pyramid now, so the five frames are a key frame, a hidden |
| 12950 | // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two |
| 12951 | // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the |
| 12952 | // near-empty leaves below it. Both bounds stand where they were. |
| 12953 | // lane-av1rejudge: local warp is ON by default now, so every eligible |
| 12954 | // single-reference block carries that same `motion_mode` symbol (a |
| 12955 | // 3-value alphabet where a warp sample exists) on the DEFAULT path -- |
| 12956 | // +34.9% here, one point past the OBMC reading above. The bound moves |
| 12957 | // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number. |
| 12958 | // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs` |
| 12959 | // symbol and one or two magnitude symbols, none of which the |
| 12960 | // coefficient sum counts either -- +36.9% here against the same |
| 12961 | // fixture's +34.9% with `EC_AV1_CFL=0`. |
| 12962 | // ... and a directional block whose `angle_delta_y` is no longer |
| 12963 | // always ZERO codes a costlier symbol off the same CDF -- +39.1%. |
| 12964 | assert!( |
| 12965 | worst_under <= 0.40, |
| 12966 | "the writer spent {:.2}% more than the search priced -- more than \ |
| 12967 | the mode/mv syntax outside the coefficient sum explains", |
| 12968 | worst_under * 100.0 |
| 12969 | ); |
| 12970 | } |
| 12971 | |
| 12972 | /// The census behind step (1) of the pricer lane: for every transform |
| 12973 | /// block the writer really codes, what the search priced those levels at |
| 12974 | /// against what the writer spent on them, split by table set and non-zero |
| 12975 | /// count. One average hides the interesting part -- the classes the |
| 12976 | /// estimate is systematically wrong about (all-zero blocks, the |
| 12977 | /// one-coefficient blocks the inter search lives on) -- so the split is |
| 12978 | /// printed and only the total is asserted on. |
| 12979 | #[test] |
| 12980 | fn pricer_error_census_by_block_class() { |
| 12981 | let _knobs = crate::speed::knob_read(); |
| 12982 | let fctx = &crate::decode::FrameCtx::new(); |
| 12983 | let (width, height) = (256usize, 128usize); |
| 12984 | let pictures: Vec<Picture> = (0..5) |
| 12985 | .map(|i| panned_test_card(width, height, i * 2)) |
| 12986 | .collect(); |
| 12987 | crate::tile::pricer_census_on(); |
| 12988 | let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 12989 | let rows = crate::tile::take_pricer_census(); |
| 12990 | assert!(!rows.is_empty(), "the census saw no transform block"); |
| 12991 | |
| 12992 | println!("| set | nz | blocks | priced bits | written bits | error |"); |
| 12993 | println!("|---|---|---|---|---|---|"); |
| 12994 | let (mut priced_all, mut written_all) = (0.0, 0.0); |
| 12995 | for ((set, bucket), (blocks, priced, written)) in &rows { |
| 12996 | priced_all += priced; |
| 12997 | written_all += written; |
| 12998 | println!( |
| 12999 | "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", |
| 13000 | crate::tile::census_bucket_label(*bucket), |
| 13001 | if *written > 0.0 { |
| 13002 | (priced - written) / written * 100.0 |
| 13003 | } else { |
| 13004 | 0.0 |
| 13005 | } |
| 13006 | ); |
| 13007 | } |
| 13008 | println!( |
| 13009 | "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", |
| 13010 | rows.values().map(|r| r.0).sum::<u64>(), |
| 13011 | (priced_all - written_all) / written_all * 100.0 |
| 13012 | ); |
| 13013 | assert!(written_all > 0.0); |
| 13014 | } |
| 13015 | |
| 13016 | /// Step (2) of the pricer lane: the same census, but on the REAL clips |
| 13017 | /// the BD gate scores -- one film clip and the screen capture -- so the |
| 13018 | /// question the film/screen split raises can be answered from data. Real |
| 13019 | /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and |
| 13020 | /// the screen capture larger, and the census says why: on a screen |
| 13021 | /// capture the frame's own starting tables are the tables of a frame that |
| 13022 | /// coded PALETTE and long runs of zero blocks, so they are far from the |
| 13023 | /// tables the writer ends the frame with; the pricer error does not fall |
| 13024 | /// the way it does on film. |
| 13025 | /// |
| 13026 | /// Not a gate -- it prints. Run it once per mode: |
| 13027 | /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \ |
| 13028 | /// --ignored pricer_error_census_on_clips --nocapture |
| 13029 | #[test] |
| 13030 | #[ignore = "reads the real library, needs ffmpeg"] |
| 13031 | fn pricer_error_census_on_clips() { |
| 13032 | let _knobs = crate::speed::knob_write(); |
| 13033 | if !have_ffmpeg() { |
| 13034 | eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg"); |
| 13035 | return; |
| 13036 | } |
| 13037 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 13038 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 13039 | let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4"); |
| 13040 | if film.exists() { |
| 13041 | clips.push(("film 1080p".to_string(), film)); |
| 13042 | } |
| 13043 | if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) |
| 13044 | && let Some(p) = manifest |
| 13045 | .lines() |
| 13046 | .skip(1) |
| 13047 | .filter_map(|l| l.split('\t').next()) |
| 13048 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 13049 | { |
| 13050 | clips.push(("screen".to_string(), std::path::PathBuf::from(p))); |
| 13051 | } |
| 13052 | assert!(!clips.is_empty(), "no source clip available"); |
| 13053 | let (width, height, frames) = (640usize, 384usize, 6usize); |
| 13054 | for (name, path) in &clips { |
| 13055 | let fctx = &crate::decode::FrameCtx::new(); |
| 13056 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 13057 | SCREEN_FRAMES.iter().for_each(|c| { |
| 13058 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 13059 | }); |
| 13060 | let _ = crate::tile::take_pricing_hits(); |
| 13061 | crate::tile::pricer_census_on(); |
| 13062 | let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 13063 | let rows = crate::tile::take_pricer_census(); |
| 13064 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 13065 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 13066 | println!( |
| 13067 | "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \ |
| 13068 | {screen_on}, pricer armings default={price_default} real={price_real}" |
| 13069 | ); |
| 13070 | println!("| set | nz | blocks | priced bits | written bits | error |"); |
| 13071 | println!("|---|---|---|---|---|---|"); |
| 13072 | let (mut priced_all, mut written_all) = (0.0, 0.0); |
| 13073 | for ((set, bucket), (blocks, priced, written)) in &rows { |
| 13074 | priced_all += priced; |
| 13075 | written_all += written; |
| 13076 | println!( |
| 13077 | "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", |
| 13078 | crate::tile::census_bucket_label(*bucket), |
| 13079 | if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 } |
| 13080 | ); |
| 13081 | } |
| 13082 | println!( |
| 13083 | "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", |
| 13084 | rows.values().map(|r| r.0).sum::<u64>(), |
| 13085 | (priced_all - written_all) / written_all * 100.0 |
| 13086 | ); |
| 13087 | assert!(written_all > 0.0, "{name}: the census saw no transform block"); |
| 13088 | } |
| 13089 | } |
| 13090 | |
| 13091 | /// Low motion has to actually buy something: at least one inter frame of |
| 13092 | /// a panning sequence has to cost fewer bytes than the key frame that |
| 13093 | /// starts it, and the inter-block share it prints has to be non-zero -- |
| 13094 | /// a search that never picks an inter mode would still pass a rate gate |
| 13095 | /// on a picture with no motion in it (the class this repo calls |
| 13096 | /// gate-blind-to-feature), so the share is printed even though it is not |
| 13097 | /// asserted on beyond being reachable at all. |
| 13098 | #[test] |
| 13099 | fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { |
| 13100 | let _knobs = crate::speed::knob_read(); |
| 13101 | let fctx = &crate::decode::FrameCtx::new(); |
| 13102 | let (width, height) = (256usize, 128usize); |
| 13103 | let pictures: Vec<Picture> = (0..5) |
| 13104 | .map(|i| panned_test_card(width, height, i * 2)) |
| 13105 | .collect(); |
| 13106 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 13107 | |
| 13108 | let key_bytes = encoded.frames[0].stream.len(); |
| 13109 | eprintln!("frame bytes inter share"); |
| 13110 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 13111 | eprintln!( |
| 13112 | "{i:5} {:5} {:11.2}", |
| 13113 | frame.stream.len(), |
| 13114 | frame.inter_block_share |
| 13115 | ); |
| 13116 | } |
| 13117 | assert!( |
| 13118 | encoded.frames[1..] |
| 13119 | .iter() |
| 13120 | .any(|f| f.stream.len() < key_bytes), |
| 13121 | "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" |
| 13122 | ); |
| 13123 | assert!( |
| 13124 | encoded.frames[1..] |
| 13125 | .iter() |
| 13126 | .any(|f| f.inter_block_share > 0.0), |
| 13127 | "no inter frame coded a single inter block -- the search never fired" |
| 13128 | ); |
| 13129 | } |
| 13130 | |
| 13131 | /// A manual perf probe, not a gate: prints where a key frame's and an |
| 13132 | /// inter frame's time goes, coarse stage by coarse stage, so a perf lane |
| 13133 | /// measures before it optimizes rather than guessing. Run with |
| 13134 | /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`. |
| 13135 | #[test] |
| 13136 | #[ignore = "a perf probe, not a gate"] |
| 13137 | fn stage_timing_breakdown() { |
| 13138 | let _knobs = crate::speed::knob_read(); |
| 13139 | let fctx = &crate::decode::FrameCtx::new(); |
| 13140 | use std::time::Instant; |
| 13141 | |
| 13142 | for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { |
| 13143 | let picture = test_card(width, height); |
| 13144 | |
| 13145 | let t = Instant::now(); |
| 13146 | let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap(); |
| 13147 | let dc_only_t = t.elapsed(); |
| 13148 | |
| 13149 | let t = Instant::now(); |
| 13150 | let non_directional = |
| 13151 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap(); |
| 13152 | let non_directional_t = t.elapsed(); |
| 13153 | |
| 13154 | let t = Instant::now(); |
| 13155 | let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 13156 | let all_modes_t = t.elapsed(); |
| 13157 | |
| 13158 | eprintln!( |
| 13159 | "\n=== key frame {width}x{height} ===\n\ |
| 13160 | 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ |
| 13161 | 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ |
| 13162 | 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", |
| 13163 | dc_only.stream.len(), |
| 13164 | non_directional.stream.len(), |
| 13165 | all_modes.stream.len(), |
| 13166 | ); |
| 13167 | |
| 13168 | // One inter frame predicting off the key frame's own |
| 13169 | // reconstruction, the (256, 256)-padded surface encode_sequence |
| 13170 | // itself would hand encode_inter_frame. |
| 13171 | let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); |
| 13172 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 13173 | let t = Instant::now(); |
| 13174 | let inter = |
| 13175 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap(); |
| 13176 | let inter_t = t.elapsed(); |
| 13177 | eprintln!( |
| 13178 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| 13179 | {:.2})", |
| 13180 | inter.stream.len(), |
| 13181 | inter.inter_block_share |
| 13182 | ); |
| 13183 | } |
| 13184 | |
| 13185 | // Isolated per-call cost of the trial pipeline's own stages, at both |
| 13186 | // transform sizes the search runs, averaged over enough calls to |
| 13187 | // rise above `Instant::now`'s own noise. |
| 13188 | for side in [16usize, 32] { |
| 13189 | const N: u32 = 20_000; |
| 13190 | let residual: Vec<i32> = (0..side * side) |
| 13191 | .map(|i| ((i * 37 % 61) as i32) - 30) |
| 13192 | .collect(); |
| 13193 | |
| 13194 | let t = Instant::now(); |
| 13195 | let mut levels = Vec::new(); |
| 13196 | for _ in 0..N { |
| 13197 | levels = forward_and_quantize(&residual, side, 8, 100, 0.5); |
| 13198 | } |
| 13199 | let forward_t = t.elapsed() / N; |
| 13200 | |
| 13201 | let t = Instant::now(); |
| 13202 | for _ in 0..N { |
| 13203 | std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100)); |
| 13204 | } |
| 13205 | let inverse_t = t.elapsed() / N; |
| 13206 | |
| 13207 | let set = if side == 32 { |
| 13208 | crate::cdf_state::TxbSet::Luma32 |
| 13209 | } else { |
| 13210 | crate::cdf_state::TxbSet::Luma16 |
| 13211 | }; |
| 13212 | let t = Instant::now(); |
| 13213 | for _ in 0..N { |
| 13214 | std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0)); |
| 13215 | } |
| 13216 | let entropy_t = t.elapsed() / N; |
| 13217 | |
| 13218 | let above = vec![128u8; side * 2]; |
| 13219 | let left = vec![128u8; side * 2]; |
| 13220 | let mut prediction = vec![0u8; side * side]; |
| 13221 | let t = Instant::now(); |
| 13222 | for _ in 0..N { |
| 13223 | intra_predict_u8( |
| 13224 | D45_PRED, |
| 13225 | 0, |
| 13226 | Some(&above), |
| 13227 | Some(&left), |
| 13228 | Some(128), |
| 13229 | side, |
| 13230 | side, |
| 13231 | false, |
| 13232 | false, |
| 13233 | &mut prediction, fctx, |
| 13234 | ); |
| 13235 | } |
| 13236 | let predict_t = t.elapsed() / N; |
| 13237 | |
| 13238 | eprintln!( |
| 13239 | "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ |
| 13240 | predict (1 directional mode): {predict_t:>9.2?}\n\ |
| 13241 | forward_and_quantize: {forward_t:>9.2?}\n\ |
| 13242 | dequant_and_inverse: {inverse_t:>9.2?}\n\ |
| 13243 | coeff_bits: {entropy_t:>9.2?}" |
| 13244 | ); |
| 13245 | } |
| 13246 | } |
| 13247 | |
| 13248 | /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets |
| 13249 | /// (motion search, [`crate::mc::predict`], transform+quantize, |
| 13250 | /// `coeff_bits`), plus what is left over once those are subtracted -- |
| 13251 | /// the thirteen-mode intra-candidate loop `search_inter_block` still |
| 13252 | /// runs on every inter block (its own transform/quant/entropy calls are |
| 13253 | /// already inside buckets 2/3, so "left over" here is everything NOT |
| 13254 | /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping, |
| 13255 | /// symbol-cost lookups outside `coeff_bits`). |
| 13256 | /// |
| 13257 | /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`. |
| 13258 | #[test] |
| 13259 | #[ignore = "a perf probe, not a gate"] |
| 13260 | fn stage_timing_breakdown_inter() { |
| 13261 | let _knobs = crate::speed::knob_read(); |
| 13262 | let fctx = &crate::decode::FrameCtx::new(); |
| 13263 | use std::time::Instant; |
| 13264 | |
| 13265 | let (width, height) = (1280usize, 720); |
| 13266 | let picture = test_card(width, height); |
| 13267 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 13268 | let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); |
| 13269 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 13270 | |
| 13271 | stage_reset(); |
| 13272 | let t = Instant::now(); |
| 13273 | let inter = |
| 13274 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap(); |
| 13275 | let total_t = t.elapsed(); |
| 13276 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 13277 | let accounted = motion_search + transform_quant + entropy; |
| 13278 | // motion_search already contains interpolation's own time (every |
| 13279 | // candidate the search costs calls crate::mc::predict), so it is not |
| 13280 | // added again here -- interpolation is reported alongside as "of |
| 13281 | // which interpolation", not as a fifth additive bucket. |
| 13282 | let other = total_t.saturating_sub(accounted); |
| 13283 | |
| 13284 | eprintln!( |
| 13285 | "\n=== inter frame {width}x{height}, one frame ===\n\ |
| 13286 | total: {total_t:>9.2?} ({} bytes)\n\ |
| 13287 | motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \ |
| 13288 | {interpolation:>9.2?})\n\ |
| 13289 | transform + quantize: {transform_quant:>9.2?}\n\ |
| 13290 | coeff_bits (entropy pricing): {entropy:>9.2?}\n\ |
| 13291 | everything else (13-mode intra {other:>9.2?}\n\ |
| 13292 | candidate loop's own predict/bookkeeping, NEARESTMV's own \ |
| 13293 | predict, RD glue):", |
| 13294 | inter.stream.len(), |
| 13295 | ); |
| 13296 | } |
| 13297 | |
| 13298 | /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real |
| 13299 | /// frames (a dark/flat one, a detailed one, a normal film one) at two |
| 13300 | /// `base_q_idx` values, encoded with the mode search unpruned (`top_k = |
| 13301 | /// None`, the baseline this same build produces without |
| 13302 | /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes |
| 13303 | /// and luma PSNR compared side by side. Not a gate itself -- the numbers |
| 13304 | /// go in the lane report, which is where "ship as default" is decided -- |
| 13305 | /// so it stays `#[ignore]`, run by hand with real clips on this machine. |
| 13306 | /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`. |
| 13307 | #[test] |
| 13308 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 13309 | fn prune_k_quality_sweep() { |
| 13310 | let _knobs = crate::speed::knob_read(); |
| 13311 | let fctx = &crate::decode::FrameCtx::new(); |
| 13312 | if !have_ffmpeg() { |
| 13313 | eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); |
| 13314 | return; |
| 13315 | } |
| 13316 | let (width, height) = (640usize, 352usize); |
| 13317 | let frames: &[(&str, &str, &str)] = &[ |
| 13318 | // (label, clip, seek) -- a near-black scene, a busy one, and an |
| 13319 | // ordinary film frame, each from a different real file. |
| 13320 | ( |
| 13321 | "dark/flat", |
| 13322 | "/home/user/Videos/reela.mp4", |
| 13323 | "3", |
| 13324 | ), |
| 13325 | ( |
| 13326 | "detailed", |
| 13327 | "/home/user/Downloads/reelb.mkv", |
| 13328 | "1200", |
| 13329 | ), |
| 13330 | ( |
| 13331 | "film", |
| 13332 | "/home/user/Videos/Films/reelc.mkv", |
| 13333 | "600", |
| 13334 | ), |
| 13335 | ]; |
| 13336 | for &(label, clip, skip) in frames { |
| 13337 | if !std::path::Path::new(clip).exists() { |
| 13338 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 13339 | continue; |
| 13340 | } |
| 13341 | let picture = clip_frame(clip, skip, width, height); |
| 13342 | for &q in &[60u8, 150] { |
| 13343 | // SAFETY (not literally unsafe, just process-global): this is |
| 13344 | // a single-threaded #[ignore] probe, run by hand, never |
| 13345 | // alongside other tests that read Search::top_k. |
| 13346 | set_test_top_k_override(None); |
| 13347 | let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 13348 | let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); |
| 13349 | eprint!( |
| 13350 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 13351 | baseline.stream.len(), |
| 13352 | baseline_psnr |
| 13353 | ); |
| 13354 | for &k in &[3usize, 4, 6] { |
| 13355 | set_test_top_k_override(Some(k)); |
| 13356 | let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 13357 | let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); |
| 13358 | eprint!( |
| 13359 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 13360 | pruned.stream.len(), |
| 13361 | pruned_psnr, |
| 13362 | pruned_psnr - baseline_psnr |
| 13363 | ); |
| 13364 | } |
| 13365 | eprintln!(); |
| 13366 | } |
| 13367 | } |
| 13368 | set_test_top_k_override(None); |
| 13369 | } |
| 13370 | |
| 13371 | /// Two consecutive decoded frames from one clip, for an inter-frame |
| 13372 | /// sweep -- [`clip_frame`] alone only ever gives one. |
| 13373 | fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { |
| 13374 | let out = Command::new("ffmpeg") |
| 13375 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) |
| 13376 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 13377 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 13378 | .output() |
| 13379 | .expect("ffmpeg failed to run"); |
| 13380 | assert!( |
| 13381 | out.status.success(), |
| 13382 | "ffmpeg: {}", |
| 13383 | String::from_utf8_lossy(&out.stderr) |
| 13384 | ); |
| 13385 | let (luma, chroma) = (width * height, width * height / 4); |
| 13386 | let frame_len = luma + 2 * chroma; |
| 13387 | assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); |
| 13388 | std::array::from_fn(|i| { |
| 13389 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 13390 | Picture { |
| 13391 | width, |
| 13392 | height, |
| 13393 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 13394 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 13395 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 13396 | } |
| 13397 | }) |
| 13398 | } |
| 13399 | |
| 13400 | /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same |
| 13401 | /// three real clips as [`prune_k_quality_sweep`], but coding a key frame |
| 13402 | /// then one inter frame off it (`search_inter_block`'s own intra |
| 13403 | /// candidates are what [`prune_by_sad`] prunes here, not the key-frame |
| 13404 | /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no |
| 13405 | /// padding step complicates the comparison. Prints bytes and luma PSNR |
| 13406 | /// for the inter frame alone, unpruned vs each `K`. |
| 13407 | /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`. |
| 13408 | #[test] |
| 13409 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 13410 | fn prune_k_quality_sweep_inter() { |
| 13411 | let _knobs = crate::speed::knob_read(); |
| 13412 | let fctx = &crate::decode::FrameCtx::new(); |
| 13413 | if !have_ffmpeg() { |
| 13414 | eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); |
| 13415 | return; |
| 13416 | } |
| 13417 | let (width, height) = (1280usize, 704usize); |
| 13418 | let frames: &[(&str, &str, &str)] = &[ |
| 13419 | ( |
| 13420 | "dark/flat", |
| 13421 | "/home/user/Videos/reela.mp4", |
| 13422 | "3", |
| 13423 | ), |
| 13424 | ( |
| 13425 | "detailed", |
| 13426 | "/home/user/Downloads/reelb.mkv", |
| 13427 | "1200", |
| 13428 | ), |
| 13429 | ( |
| 13430 | "film", |
| 13431 | "/home/user/Videos/Films/reelc.mkv", |
| 13432 | "600", |
| 13433 | ), |
| 13434 | ]; |
| 13435 | for &(label, clip, skip) in frames { |
| 13436 | if !std::path::Path::new(clip).exists() { |
| 13437 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 13438 | continue; |
| 13439 | } |
| 13440 | let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); |
| 13441 | for &q in &[60u8, 150] { |
| 13442 | // SAFETY (not literally unsafe, just process-global): a |
| 13443 | // single-threaded #[ignore] probe, run by hand, never |
| 13444 | // alongside other tests that read Search::top_k. |
| 13445 | set_test_top_k_override_inter(None); |
| 13446 | let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap(); |
| 13447 | let baseline = encode_inter_frame( |
| 13448 | &inter_source, |
| 13449 | &key.reconstruction, |
| 13450 | q, |
| 13451 | 0.5, |
| 13452 | 1, |
| 13453 | flat_order_hints(1, 0, false), |
| 13454 | (width, height), None, None, None, fctx, None, &[], |
| 13455 | ) |
| 13456 | .unwrap(); |
| 13457 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| 13458 | eprint!( |
| 13459 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 13460 | baseline.stream.len(), |
| 13461 | baseline_psnr |
| 13462 | ); |
| 13463 | for &k in &[3usize, 4, 6] { |
| 13464 | set_test_top_k_override_inter(Some(k)); |
| 13465 | let pruned = encode_inter_frame( |
| 13466 | &inter_source, |
| 13467 | &key.reconstruction, |
| 13468 | q, |
| 13469 | 0.5, |
| 13470 | 1, |
| 13471 | flat_order_hints(1, 0, false), |
| 13472 | (width, height), None, None, None, fctx, None, &[], |
| 13473 | ) |
| 13474 | .unwrap(); |
| 13475 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| 13476 | eprint!( |
| 13477 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 13478 | pruned.stream.len(), |
| 13479 | pruned_psnr, |
| 13480 | pruned_psnr - baseline_psnr |
| 13481 | ); |
| 13482 | } |
| 13483 | eprintln!(); |
| 13484 | } |
| 13485 | } |
| 13486 | set_test_top_k_override_inter(None); |
| 13487 | } |
| 13488 | |
| 13489 | /// `frames` consecutive pictures out of a real clip, scaled to a whole |
| 13490 | /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`] |
| 13491 | /// to an arbitrary count for the fixture regression gate below. |
| 13492 | fn clip_frames( |
| 13493 | clip: &str, |
| 13494 | skip: &str, |
| 13495 | width: usize, |
| 13496 | height: usize, |
| 13497 | frames: usize, |
| 13498 | ) -> Vec<Picture> { |
| 13499 | clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames) |
| 13500 | } |
| 13501 | |
| 13502 | /// [`clip_frames`] with the filter chain spelled out, so a caller can ask |
| 13503 | /// for a native-resolution CROP instead of a downscale (the downscale is |
| 13504 | /// what destroys a screen capture's exact repeats -- class |
| 13505 | /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces. |
| 13506 | fn clip_frames_vf( |
| 13507 | clip: &str, |
| 13508 | skip: &str, |
| 13509 | vf: &str, |
| 13510 | width: usize, |
| 13511 | height: usize, |
| 13512 | frames: usize, |
| 13513 | ) -> Vec<Picture> { |
| 13514 | // ONE definition of the gate's loader recipe, shared with |
| 13515 | // `examples/enc_probe` so the instrument cannot arm a different source |
| 13516 | // than the gate it reports on (class `instrument disagrees with the |
| 13517 | // gate`; lane-probe). |
| 13518 | crate::probe::source(clip, skip, vf, width, height, frames) |
| 13519 | } |
| 13520 | |
| 13521 | /// The standing regression gate on real content: 12 frames of a real |
| 13522 | /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to |
| 13523 | /// this crate's own input regardless of its own source codec), encoded |
| 13524 | /// as an AV1 GOP and checked against three numeric floors so a |
| 13525 | /// compatibility or quality regression fails the suite instead of |
| 13526 | /// waiting for a downstream repo's gate to catch it (as happened for a |
| 13527 | /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export |
| 13528 | /// refusal, both caught only that way). |
| 13529 | /// |
| 13530 | /// 640x384 is a whole number of 32x32 blocks (no straddle edge case; |
| 13531 | /// that geometry is already covered elsewhere), chosen only so encode |
| 13532 | /// time and gate numbers are not muddied by an edge-block class this |
| 13533 | /// test is not about. |
| 13534 | /// |
| 13535 | /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR |
| 13536 | /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling |
| 13537 | /// below carry a margin off those measured numbers (PSNR floor = |
| 13538 | /// measured - 0.5 dB; byte ceiling = measured * 1.15). |
| 13539 | #[test] |
| 13540 | fn real_clip_encodes_within_its_quality_and_size_budget() { |
| 13541 | let _knobs = crate::speed::knob_read(); |
| 13542 | let fctx = &crate::decode::FrameCtx::new(); |
| 13543 | if !have_ffmpeg() { |
| 13544 | eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg"); |
| 13545 | return; |
| 13546 | } |
| 13547 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 13548 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 13549 | if !clip.exists() { |
| 13550 | eprintln!( |
| 13551 | "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing", |
| 13552 | clip.display() |
| 13553 | ); |
| 13554 | return; |
| 13555 | } |
| 13556 | let (width, height, frame_count) = (640usize, 384usize, 12usize); |
| 13557 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 13558 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 13559 | assert_eq!(encoded.frames.len(), frame_count); |
| 13560 | |
| 13561 | // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole |
| 13562 | // stream and hands back every frame -- a stream a downstream |
| 13563 | // decoder refuses is the exact class of regression this gate |
| 13564 | // exists for. |
| 13565 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 13566 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 13567 | |
| 13568 | // Gate 2: quality vs the source did not silently collapse. |
| 13569 | let mean_psnr: f64 = decoded |
| 13570 | .iter() |
| 13571 | .zip(&source) |
| 13572 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 13573 | .sum::<f64>() |
| 13574 | / frame_count as f64; |
| 13575 | assert!( |
| 13576 | mean_psnr >= 44.91, |
| 13577 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor" |
| 13578 | ); |
| 13579 | |
| 13580 | // Gate 3: the stream did not silently bloat. |
| 13581 | assert!( |
| 13582 | encoded.stream.len() <= 80_340, |
| 13583 | "stream grew to {} bytes, over the 80340-byte ceiling", |
| 13584 | encoded.stream.len() |
| 13585 | ); |
| 13586 | } |
| 13587 | |
| 13588 | /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a |
| 13589 | /// straddle size: 640x384 is exact on both axes (32-aligned), so |
| 13590 | /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf |
| 13591 | /// path landed in e19bb47 goes unexercised by real, mixed intra/inter |
| 13592 | /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half |
| 13593 | /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_ |
| 13594 | /// straddle_size`'s 1280x720, but that test is a synthetic panned test |
| 13595 | /// card; this one is the real-clip gate, same three floors. |
| 13596 | /// |
| 13597 | /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average |
| 13598 | /// luma PSNR 45.48 dB across the 8 decoded frames vs the source. |
| 13599 | /// Floor/ceiling below carry the same margin as the sibling test (PSNR |
| 13600 | /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15). |
| 13601 | #[test] |
| 13602 | fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() { |
| 13603 | let _knobs = crate::speed::knob_read(); |
| 13604 | let fctx = &crate::decode::FrameCtx::new(); |
| 13605 | if !have_ffmpeg() { |
| 13606 | eprintln!( |
| 13607 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 13608 | no ffmpeg" |
| 13609 | ); |
| 13610 | return; |
| 13611 | } |
| 13612 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 13613 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 13614 | if !clip.exists() { |
| 13615 | eprintln!( |
| 13616 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 13617 | {} missing", |
| 13618 | clip.display() |
| 13619 | ); |
| 13620 | return; |
| 13621 | } |
| 13622 | let (width, height, frame_count) = (704usize, 400usize, 8usize); |
| 13623 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 13624 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 13625 | assert_eq!(encoded.frames.len(), frame_count); |
| 13626 | |
| 13627 | // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole |
| 13628 | // stream and hands back every frame. |
| 13629 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 13630 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 13631 | |
| 13632 | // Gate 2: quality vs the source did not silently collapse. |
| 13633 | let mean_psnr: f64 = decoded |
| 13634 | .iter() |
| 13635 | .zip(&source) |
| 13636 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 13637 | .sum::<f64>() |
| 13638 | / frame_count as f64; |
| 13639 | assert!( |
| 13640 | mean_psnr >= 44.98, |
| 13641 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor" |
| 13642 | ); |
| 13643 | |
| 13644 | // Gate 3: the stream did not silently bloat. |
| 13645 | assert!( |
| 13646 | encoded.stream.len() <= 62_703, |
| 13647 | "stream grew to {} bytes, over the 62703-byte ceiling", |
| 13648 | encoded.stream.len() |
| 13649 | ); |
| 13650 | } |
| 13651 | |
| 13652 | /// The replica-shaped path: 24 frames, 1280x720, one key frame followed |
| 13653 | /// by inter frames -- the same GOP shape [`encode_sequence`] gives the |
| 13654 | /// facade -- timed end to end, so the edith export-time projection is a |
| 13655 | /// real number rather than a guess from the isolated key/inter numbers |
| 13656 | /// above. Run with and without `EC_AV1_PRUNE_K` set to compare. |
| 13657 | /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`. |
| 13658 | #[test] |
| 13659 | #[ignore = "a perf probe, not a gate"] |
| 13660 | fn sequence_bench_sanity() { |
| 13661 | let _knobs = crate::speed::knob_read(); |
| 13662 | let fctx = &crate::decode::FrameCtx::new(); |
| 13663 | use std::time::Instant; |
| 13664 | let (width, height) = (1280usize, 720usize); |
| 13665 | let pictures: Vec<Picture> = (0..24) |
| 13666 | .map(|i| panned_test_card(width, height, i * 3)) |
| 13667 | .collect(); |
| 13668 | let t = Instant::now(); |
| 13669 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 13670 | let elapsed = t.elapsed(); |
| 13671 | let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); |
| 13672 | eprintln!( |
| 13673 | "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", |
| 13674 | elapsed / 24 |
| 13675 | ); |
| 13676 | } |
| 13677 | |
| 13678 | /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the |
| 13679 | /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a |
| 13680 | /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx |
| 13681 | /// -- --ignored --nocapture`. |
| 13682 | #[test] |
| 13683 | #[ignore = "a calibration probe, not a gate"] |
| 13684 | fn calibration_sweep_base_q_idx() { |
| 13685 | let _knobs = crate::speed::knob_read(); |
| 13686 | let fctx = &crate::decode::FrameCtx::new(); |
| 13687 | if !have_ffmpeg() { |
| 13688 | eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg"); |
| 13689 | return; |
| 13690 | } |
| 13691 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 13692 | for clip in [ |
| 13693 | "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps |
| 13694 | "h264-1080p-60-8bit.mp4", // higher motion, 60fps |
| 13695 | ] { |
| 13696 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 13697 | .join("../../fixtures/video") |
| 13698 | .join(clip); |
| 13699 | if !path.exists() { |
| 13700 | eprintln!("SKIP {clip}: fixture missing"); |
| 13701 | continue; |
| 13702 | } |
| 13703 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 13704 | eprintln!("--- {clip} ---"); |
| 13705 | for q in [40u8, 70, 100, 130, 160, 190, 220, 240] { |
| 13706 | let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); |
| 13707 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames); |
| 13708 | let mean_psnr: f64 = decoded |
| 13709 | .iter() |
| 13710 | .zip(&source) |
| 13711 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 13712 | .sum::<f64>() |
| 13713 | / frames as f64; |
| 13714 | let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64; |
| 13715 | eprintln!( |
| 13716 | "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB", |
| 13717 | encoded.stream.len() |
| 13718 | ); |
| 13719 | } |
| 13720 | } |
| 13721 | } |
| 13722 | |
| 13723 | // ----------------------------------------------------------------------- |
| 13724 | // The encoder's standing BD-rate baseline against libaom and rav1e. |
| 13725 | // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an |
| 13726 | // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder |
| 13727 | // agreeing with our encoder proves nothing about the bitstream. |
| 13728 | // ----------------------------------------------------------------------- |
| 13729 | |
| 13730 | /// All-plane PSNR of a decoded picture against its source, on the same |
| 13731 | /// 8-bit scale [`psnr`] uses. |
| 13732 | fn psnr_all(decoded: &Picture, source: &Picture) -> f64 { |
| 13733 | let cat = |p: &Picture| { |
| 13734 | let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len()); |
| 13735 | v.extend_from_slice(&p.y); |
| 13736 | v.extend_from_slice(&p.u); |
| 13737 | v.extend_from_slice(&p.v); |
| 13738 | v |
| 13739 | }; |
| 13740 | psnr(&cat(decoded), &cat(source)) |
| 13741 | } |
| 13742 | |
| 13743 | /// The pictures back as the planar 8-bit bytes an encoder reads. |
| 13744 | fn raw_yuv420p(source: &[Picture]) -> Vec<u8> { |
| 13745 | let mut raw = Vec::new(); |
| 13746 | for p in source { |
| 13747 | for plane in [&p.y, &p.u, &p.v] { |
| 13748 | raw.extend(plane.iter().map(|&s| s as u8)); |
| 13749 | } |
| 13750 | } |
| 13751 | raw |
| 13752 | } |
| 13753 | |
| 13754 | /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven |
| 13755 | /// through ffmpeg: one point per entry of `points`, each a quality flag |
| 13756 | /// set. Returns the ladder ordered by fidelity and the total encode wall |
| 13757 | /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`], |
| 13758 | /// so both curves are measured by the same decoder. |
| 13759 | fn external_ladder( |
| 13760 | source: &[Picture], |
| 13761 | width: usize, |
| 13762 | height: usize, |
| 13763 | encoder: &str, |
| 13764 | points: &[Vec<String>], |
| 13765 | ) -> (Vec<(f64, f64)>, f64) { |
| 13766 | // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. |
| 13767 | let dir = std::env::temp_dir(); |
| 13768 | let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id())); |
| 13769 | std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source"); |
| 13770 | let mut ladder = Vec::new(); |
| 13771 | let mut wall = 0.0; |
| 13772 | for (i, params) in points.iter().enumerate() { |
| 13773 | let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id())); |
| 13774 | let start = std::time::Instant::now(); |
| 13775 | let out = Command::new("ffmpeg") |
| 13776 | .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 13777 | .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) |
| 13778 | .arg(&raw_path) |
| 13779 | .args(["-an", "-threads", "1"]) |
| 13780 | .args(["-g", &source.len().to_string(), "-c:v", encoder]) |
| 13781 | .args(params) |
| 13782 | .args(["-f", "obu"]) |
| 13783 | .arg(&obu) |
| 13784 | .output() |
| 13785 | .expect("ffmpeg failed to run"); |
| 13786 | wall += start.elapsed().as_secs_f64(); |
| 13787 | assert!( |
| 13788 | out.status.success(), |
| 13789 | "{encoder} {params:?}: {}", |
| 13790 | String::from_utf8_lossy(&out.stderr) |
| 13791 | ); |
| 13792 | let stream = std::fs::read(&obu).expect("reference stream"); |
| 13793 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 13794 | // lane-dkey: every reference point must also decode through OUR |
| 13795 | // decoder, sample-exact against ffmpeg's decode of the same bytes. |
| 13796 | // A BD table computed off streams we cannot read is a table about |
| 13797 | // an encoder we cannot check; this is the assertion that would |
| 13798 | // have caught the `force_integer_mv` defect (its stream decoded to |
| 13799 | // 25 dB garbage while this gate stayed green) and the crf-5 key |
| 13800 | // frame desync. A failure names the encoder, the point's flags and |
| 13801 | // the first differing frame/plane/sample. |
| 13802 | // lane-dpm1: a failing reference point is COLLECTED, not panicked |
| 13803 | // on, so one run still prints the whole BD table and names every |
| 13804 | // bad point instead of stopping at the first. The collection is |
| 13805 | // asserted empty by [`assert_ladder_decodes`] at the end of each |
| 13806 | // gate. |
| 13807 | match crate::stream::decode_stream(&stream) { |
| 13808 | Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!( |
| 13809 | "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}", |
| 13810 | ours.len(), |
| 13811 | decoded.len(), |
| 13812 | )), |
| 13813 | Ok(ours) => { |
| 13814 | for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() { |
| 13815 | if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) { |
| 13816 | note_ladder_failure(format!( |
| 13817 | "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \ |
| 13818 | decoder decoded {got}, ffmpeg {want}" |
| 13819 | )); |
| 13820 | break; |
| 13821 | } |
| 13822 | } |
| 13823 | } |
| 13824 | Err(e) => note_ladder_failure(format!( |
| 13825 | "{encoder} {params:?}: our decoder refused the stream ({e})" |
| 13826 | )), |
| 13827 | } |
| 13828 | let mean: f64 = decoded |
| 13829 | .iter() |
| 13830 | .zip(source) |
| 13831 | .map(|(d, s)| psnr_all(d, s)) |
| 13832 | .sum::<f64>() |
| 13833 | / source.len() as f64; |
| 13834 | ladder.push((mean, (stream.len() as f64).log10())); |
| 13835 | let _ = std::fs::remove_file(&obu); |
| 13836 | } |
| 13837 | let _ = std::fs::remove_file(&raw_path); |
| 13838 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 13839 | (ladder, wall) |
| 13840 | } |
| 13841 | |
| 13842 | /// Every reference ladder point that did not decode sample-exactly |
| 13843 | /// through our own decoder, collected across a whole gate run so the BD |
| 13844 | /// table still prints and EVERY bad point is named |
| 13845 | /// (`encoder params frame plane sample`) instead of only the first. |
| 13846 | static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); |
| 13847 | |
| 13848 | fn note_ladder_failure(msg: String) { |
| 13849 | eprintln!("LADDER DECODE FAILURE: {msg}"); |
| 13850 | LADDER_FAILURES.lock().expect("ladder failures").push(msg); |
| 13851 | } |
| 13852 | |
| 13853 | /// Fail the gate at its END on everything [`external_ladder`] collected. |
| 13854 | fn assert_ladder_decodes() { |
| 13855 | let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures")); |
| 13856 | assert!( |
| 13857 | failures.is_empty(), |
| 13858 | "{} reference ladder point(s) did not decode exactly through our decoder:\n{}", |
| 13859 | failures.len(), |
| 13860 | failures.join("\n"), |
| 13861 | ); |
| 13862 | } |
| 13863 | |
| 13864 | /// First differing sample between two pictures, as |
| 13865 | /// `(plane, index, left, right)` -- so a gate failure names the plane and |
| 13866 | /// the sample instead of just "differs". A length difference counts as a |
| 13867 | /// mismatch of that plane at the first index past the shorter one. |
| 13868 | fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> { |
| 13869 | for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { |
| 13870 | if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { |
| 13871 | return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); |
| 13872 | } |
| 13873 | if l.len() != r.len() { |
| 13874 | return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); |
| 13875 | } |
| 13876 | } |
| 13877 | None |
| 13878 | } |
| 13879 | |
| 13880 | /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR |
| 13881 | /// comes from ffmpeg's decode of our own stream, and at EVERY point the |
| 13882 | /// stream is decoded twice -- by ffmpeg and by our own |
| 13883 | /// [`crate::stream::decode_stream`] -- and all three pictures (encoder |
| 13884 | /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact |
| 13885 | /// in Y, U and V over every shown frame in display order. That is itself |
| 13886 | /// a gate: it proves the bitstream says what the encoder thinks, in the |
| 13887 | /// only two decoders that read it. |
| 13888 | fn our_ladder( |
| 13889 | name: &str, |
| 13890 | source: &[Picture], |
| 13891 | width: usize, |
| 13892 | height: usize, |
| 13893 | fctx: &crate::decode::FrameCtx, |
| 13894 | ) -> (Vec<(f64, f64)>, f64) { |
| 13895 | let mut ladder = Vec::new(); |
| 13896 | let mut wall = 0.0; |
| 13897 | for &q in &[150u8, 120, 90, 60] { |
| 13898 | let start = std::time::Instant::now(); |
| 13899 | let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap(); |
| 13900 | wall += start.elapsed().as_secs_f64(); |
| 13901 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len()); |
| 13902 | let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 13903 | assert_eq!( |
| 13904 | ours.len(), |
| 13905 | source.len(), |
| 13906 | "{name} q={q}: our decoder's display-order frame count" |
| 13907 | ); |
| 13908 | for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 13909 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { |
| 13910 | panic!( |
| 13911 | "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ |
| 13912 | {got}, the encoder reconstructed {want}" |
| 13913 | ); |
| 13914 | } |
| 13915 | } |
| 13916 | for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() { |
| 13917 | if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) { |
| 13918 | panic!( |
| 13919 | "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \ |
| 13920 | {got}, the encoder reconstructed {want}" |
| 13921 | ); |
| 13922 | } |
| 13923 | } |
| 13924 | let mean: f64 = decoded |
| 13925 | .iter() |
| 13926 | .zip(source) |
| 13927 | .map(|(d, s)| psnr_all(d, s)) |
| 13928 | .sum::<f64>() |
| 13929 | / source.len() as f64; |
| 13930 | ladder.push((mean, (encoded.stream.len() as f64).log10())); |
| 13931 | } |
| 13932 | // What this clip asked for and what the content gate left it coding |
| 13933 | // under: a screen clip requests a pyramid and codes flat, and that |
| 13934 | // difference is what keeps its row identical to the flat baseline |
| 13935 | // (class `gate-blind-to-feature`). |
| 13936 | eprintln!( |
| 13937 | "{name}: sequence, pyramid requested {:?} effective {:?}", |
| 13938 | crate::encoder::Pyramid::from_env(), |
| 13939 | last_sequence_pyramid(), |
| 13940 | ); |
| 13941 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 13942 | (ladder, wall) |
| 13943 | } |
| 13944 | |
| 13945 | /// [`our_ladder`] through the streaming facade — the surface the editor's |
| 13946 | /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`] |
| 13947 | /// each stream is also reordered (hidden `ALTREF` first, |
| 13948 | /// `show_existing_frame` last per group) and each level is coded at its |
| 13949 | /// own quantizer offset; without one it is the flat ladder, which |
| 13950 | /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` |
| 13951 | /// pins byte-identical to [`our_ladder`]'s, so this arm must print the |
| 13952 | /// same BD numbers. Returns the ladder, the wall, per pyramid level over |
| 13953 | /// the whole ladder how many frames and how many bytes it spent, and the |
| 13954 | /// pyramid the streams were EFFECTIVELY coded under — the content gate in |
| 13955 | /// `Av1Encoder::encode_frames` drops a screen-content clip back to the |
| 13956 | /// flat path, so a requested pyramid can come back `None` here. |
| 13957 | fn our_ladder_facade( |
| 13958 | name: &str, |
| 13959 | source: &[Picture], |
| 13960 | width: usize, |
| 13961 | height: usize, |
| 13962 | pyramid: Option<crate::encoder::Pyramid>, |
| 13963 | ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) { |
| 13964 | use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; |
| 13965 | let slot = |l: Level| match l { |
| 13966 | Level::Key => 0, |
| 13967 | Level::Arf => 1, |
| 13968 | Level::Leaf => 2, |
| 13969 | Level::ShowExisting => 3, |
| 13970 | }; |
| 13971 | let mut ladder = Vec::new(); |
| 13972 | let mut wall = 0.0; |
| 13973 | let mut effective = None; |
| 13974 | let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); |
| 13975 | for &q in &[150u8, 120, 90, 60] { |
| 13976 | let config = EncoderConfig { |
| 13977 | width, |
| 13978 | height, |
| 13979 | base_q_idx: q, |
| 13980 | gop: source.len(), |
| 13981 | colour: Colour::Unspecified, |
| 13982 | tile_cols_log2: 0, |
| 13983 | tile_rows_log2: 0, |
| 13984 | }; |
| 13985 | let start = std::time::Instant::now(); |
| 13986 | let mut enc = match pyramid { |
| 13987 | None => Av1Encoder::new(config).unwrap(), |
| 13988 | Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(), |
| 13989 | }; |
| 13990 | let mut packets = Vec::new(); |
| 13991 | for picture in source { |
| 13992 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 13993 | } |
| 13994 | packets.extend(enc.flush().unwrap()); |
| 13995 | wall += start.elapsed().as_secs_f64(); |
| 13996 | effective = enc.pyramid(); |
| 13997 | let mut stream = Vec::new(); |
| 13998 | for p in &packets { |
| 13999 | counts[slot(p.level)] += 1; |
| 14000 | bytes[slot(p.level)] += p.data.len(); |
| 14001 | stream.extend_from_slice(&p.data); |
| 14002 | } |
| 14003 | // [[gate-blind-to-hidden-frames]]: a reordered stream is only |
| 14004 | // correct if the DISPLAY-order output still has one frame per |
| 14005 | // source picture, in the right order -- checked against our own |
| 14006 | // decoder as well as ffmpeg's, both below. |
| 14007 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 14008 | assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count"); |
| 14009 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 14010 | for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { |
| 14011 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) { |
| 14012 | panic!( |
| 14013 | "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \ |
| 14014 | decoded {got}, our decoder decoded {want}" |
| 14015 | ); |
| 14016 | } |
| 14017 | } |
| 14018 | let mean: f64 = decoded |
| 14019 | .iter() |
| 14020 | .zip(source) |
| 14021 | .map(|(d, s)| psnr_all(d, s)) |
| 14022 | .sum::<f64>() |
| 14023 | / source.len() as f64; |
| 14024 | ladder.push((mean, (stream.len() as f64).log10())); |
| 14025 | } |
| 14026 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 14027 | (ladder, wall, counts, bytes, effective) |
| 14028 | } |
| 14029 | |
| 14030 | /// Byte-exactness gate for encoder work that is meant to change only |
| 14031 | /// how long the encoder takes. |
| 14032 | /// |
| 14033 | /// The BD gate above measures quality, which a speed lane can move by a |
| 14034 | /// hair without failing anything; this pins the streams themselves. |
| 14035 | /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 |
| 14036 | /// `cdef_idx` literals and per-unit loop restoration syntax are new bits |
| 14037 | /// in the tile) and again on lane-av1mv's merge of it: an extra |
| 14038 | /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate |
| 14039 | /// above, not by this pin. Re-pinned on lane-av1price2: the search now |
| 14040 | /// prices coefficients against the tables the frame's writer really |
| 14041 | /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a |
| 14042 | /// decision change the BD gate judges. Re-pinned again on |
| 14043 | /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the |
| 14044 | /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which |
| 14045 | /// is the same kind of decision change. Re-pinned on lane-av1lambda: |
| 14046 | /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the |
| 14047 | /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on |
| 14048 | /// by default ([`warp_on`], a sequence/frame header bit and a new |
| 14049 | /// motion_mode symbol on eligible blocks) and |
| 14050 | /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl: |
| 14051 | /// every inter frame's superblocks now code at their own lambda |
| 14052 | /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved. |
| 14053 | /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 |
| 14054 | /// and the two var-tx depth searches ([`tx32_depth_search`], |
| 14055 | /// [`compound_var_tx`]) are on by default, all three re-judged on the |
| 14056 | /// native gate's real film rows. |
| 14057 | /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so |
| 14058 | /// every block whose chroma takes it codes a different mode symbol, two |
| 14059 | /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0` |
| 14060 | /// restores the previous streams. Re-pinned again in the same lane once |
| 14061 | /// directional luma winners searched their `angle_delta_y` |
| 14062 | /// (`EC_AV1_ANGLE=0` restores that half). |
| 14063 | #[test] |
| 14064 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { |
| 14065 | let _knobs = crate::speed::knob_read(); |
| 14066 | if !have_ffmpeg() { |
| 14067 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); |
| 14068 | return; |
| 14069 | } |
| 14070 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 14071 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 14072 | if !clip.exists() { |
| 14073 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip"); |
| 14074 | return; |
| 14075 | } |
| 14076 | let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4); |
| 14077 | // FNV-1a over the stream: a witness that every coded bit is where it |
| 14078 | // was, which a byte count alone is not. |
| 14079 | let fnv = |b: &[u8]| { |
| 14080 | b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { |
| 14081 | (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) |
| 14082 | }) |
| 14083 | }; |
| 14084 | // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen) |
| 14085 | // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP |
| 14086 | // of 4, its leaves at q+8 and a `show_existing_frame` header per |
| 14087 | // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over |
| 14088 | // four frames; four pictures is one short mini-GOP, which is the |
| 14089 | // shape that pays least (the ARF's own quality has no later group to |
| 14090 | // carry it), so this is not the BD gate's number. |
| 14091 | // Re-taken again on lane-av1cfl: the chroma search offers |
| 14092 | // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`, |
| 14093 | // so every block taking either codes different syntax and different |
| 14094 | // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60. |
| 14095 | // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half. |
| 14096 | // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16 |
| 14097 | // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]), |
| 14098 | // so these four pictures code as one truncated group -- a hidden |
| 14099 | // ALTREF at `q-24` and three leaves at `q+16` -- instead of one |
| 14100 | // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and |
| 14101 | // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these. |
| 14102 | // Re-taken on lane-fintra: the sequence header sets |
| 14103 | // `enable_filter_intra`, so every DC_PRED intra block of at most |
| 14104 | // 32x32 without a luma palette carries a `use_filter_intra` flag and |
| 14105 | // the blocks that take one code a filter-intra mode, a different |
| 14106 | // prediction and different coefficients -- 7321 -> 7373 at q=150 and |
| 14107 | // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these. |
| 14108 | // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge |
| 14109 | // (default pyramid `8:-32:16`, one truncated group of 8 with its |
| 14110 | // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64 |
| 14111 | // root can code a REAL residual now (one TX_64X64 luma transform and |
| 14112 | // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548; |
| 14113 | // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid. |
| 14114 | // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at |
| 14115 | // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and |
| 14116 | // one of these four pictures is the key -- 8590 -> 9778 at q=150 and |
| 14117 | // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these. |
| 14118 | // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above |
| 14119 | // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778 |
| 14120 | // -> 9835 at q=150 and 35450 -> 35798 at q=60. |
| 14121 | // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these. |
| 14122 | // Re-taken at the lane-b64b merge: the 64x64 root prices compound |
| 14123 | // references and depth-1 var-tx, on top of the tpl window and the |
| 14124 | // ARF's second reference from lane-arfcen. `EC_AV1_B64COMP=0 |
| 14125 | // EC_AV1_B64VARTX=0` restores 9853 / 35866. |
| 14126 | let pins: [(u8, usize, u64); 2] = |
| 14127 | [(150, 9808, 0xb71a_2a4c_0aff_713c), (60, 35791, 0x57a3_93fa_5324_255b)]; |
| 14128 | for (q, bytes, hash) in pins { |
| 14129 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 14130 | assert_eq!( |
| 14131 | (encoded.stream.len(), fnv(&encoded.stream)), |
| 14132 | (bytes, hash), |
| 14133 | "q={q}: the encoder's stream moved" |
| 14134 | ); |
| 14135 | } |
| 14136 | } |
| 14137 | |
| 14138 | /// A ladder is only a ladder if both axes rise together. |
| 14139 | fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { |
| 14140 | assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); |
| 14141 | for w in ladder.windows(2) { |
| 14142 | assert!( |
| 14143 | w[1].0 > w[0].0 && w[1].1 > w[0].1, |
| 14144 | "{name}: not monotone, {ladder:?}" |
| 14145 | ); |
| 14146 | } |
| 14147 | } |
| 14148 | |
| 14149 | /// The sweep behind [`screen_content`]'s constants |
| 14150 | /// (`unswept-decision-constants`), on the SAME five clips |
| 14151 | /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the |
| 14152 | /// same native crop: for each colour bound N the share of 16x16 luma |
| 14153 | /// blocks with 2..=N distinct colours, and the share of those whose |
| 14154 | /// per-pixel variance also clears a floor V -- libaom's |
| 14155 | /// `av1_set_screen_content_options` counts the variance-cleared blocks |
| 14156 | /// too (its `counts_2`, which gates intrabc), and without that term a |
| 14157 | /// smooth dark film frame reads as screen content. |
| 14158 | /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture` |
| 14159 | #[test] |
| 14160 | #[ignore = "reads the real library"] |
| 14161 | fn probe_screen_detect() { |
| 14162 | let _knobs = crate::speed::knob_read(); |
| 14163 | if !have_ffmpeg() { |
| 14164 | eprintln!("SKIP probe_screen_detect: no ffmpeg"); |
| 14165 | return; |
| 14166 | } |
| 14167 | let limits = [4usize, 8, 16, 32, 64, 128]; |
| 14168 | let floors = [0u64, 4, 16, 64, 256]; |
| 14169 | // The census of one clip at one size: mean share, over the frames, of |
| 14170 | // 16x16 blocks with 2..=N colours whose per-pixel variance is > V. |
| 14171 | let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| { |
| 14172 | let mut acc = [[0f64; 5]; 6]; |
| 14173 | for picture in frames { |
| 14174 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 14175 | let mut hit = [[0usize; 5]; 6]; |
| 14176 | let mut blocks = 0usize; |
| 14177 | for by in (0..ch).step_by(16) { |
| 14178 | for bx in (0..cw).step_by(16) { |
| 14179 | let mut seen = [false; 256]; |
| 14180 | let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64); |
| 14181 | for row in 0..16 { |
| 14182 | for col in 0..16 { |
| 14183 | let v = y[(by + row) * cw + bx + col]; |
| 14184 | sum += u64::from(v); |
| 14185 | sq += u64::from(v) * u64::from(v); |
| 14186 | if !seen[usize::from(v)] { |
| 14187 | seen[usize::from(v)] = true; |
| 14188 | colors += 1; |
| 14189 | } |
| 14190 | } |
| 14191 | } |
| 14192 | let var = (sq - sum * sum / 256) / 256; |
| 14193 | blocks += 1; |
| 14194 | for (li, &limit) in limits.iter().enumerate() { |
| 14195 | if colors > 1 && colors <= limit { |
| 14196 | for (fi, &floor) in floors.iter().enumerate() { |
| 14197 | hit[li][fi] += usize::from(var > floor); |
| 14198 | } |
| 14199 | } |
| 14200 | } |
| 14201 | } |
| 14202 | } |
| 14203 | for li in 0..6 { |
| 14204 | for fi in 0..5 { |
| 14205 | acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64; |
| 14206 | } |
| 14207 | } |
| 14208 | } |
| 14209 | let n = frames.len().max(1) as f64; |
| 14210 | eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len()); |
| 14211 | eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>()); |
| 14212 | for (li, &limit) in limits.iter().enumerate() { |
| 14213 | eprintln!( |
| 14214 | " {limit:>5} |{}", |
| 14215 | (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>() |
| 14216 | ); |
| 14217 | } |
| 14218 | }; |
| 14219 | for (name, path, seek) in native_gate_clips() { |
| 14220 | let Some((nw, nh)) = probe_dims(&path) else { |
| 14221 | eprintln!("SKIP {name}: ffprobe gave no size"); |
| 14222 | continue; |
| 14223 | }; |
| 14224 | let cw = nw.min(1920) / 128 * 128; |
| 14225 | let ch = nh.min(1024) / 128 * 128; |
| 14226 | let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 14227 | let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12); |
| 14228 | census(&name, &frames, cw, ch); |
| 14229 | // The 640x384 gate scales instead of cropping, and the scaling |
| 14230 | // changes the census (bars smooth out): the constants have to |
| 14231 | // separate at BOTH sizes. |
| 14232 | let small = clip_frames(&path, &seek, 640, 384, 12); |
| 14233 | census(&name, &small, 640, 384); |
| 14234 | } |
| 14235 | } |
| 14236 | |
| 14237 | /// The detector against the WHOLE real library (class |
| 14238 | /// `unswept-decision-constants`, user rule "his data is the gate"): |
| 14239 | /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the |
| 14240 | /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its |
| 14241 | /// duration, four frames each, 8-bit 4:2:0, at native size or a |
| 14242 | /// 1920x1080 centred crop when larger (the crop keeps a capture's exact |
| 14243 | /// repeats, which a downscale destroys -- class `gate-recipe-confound`). |
| 14244 | /// Prints per file and offset the share of qualifying 16x16 blocks, the |
| 14245 | /// [`screen_content`] verdict and a content hint (mean luma, luma |
| 14246 | /// standard deviation, inter MAD), then sweeps the colour bound against |
| 14247 | /// the variance floor over the whole library: for each (N, V) the worst |
| 14248 | /// (highest) share among the camera/film rows against the best (lowest) |
| 14249 | /// among the screen-recording rows, so the rule with the widest gap can |
| 14250 | /// be read off. Rows carry the manifest index, codec and size only -- |
| 14251 | /// no titles, no home paths. |
| 14252 | /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture` |
| 14253 | #[test] |
| 14254 | #[ignore = "reads the real library"] |
| 14255 | fn probe_screen_library() { |
| 14256 | let _knobs = crate::speed::knob_read(); |
| 14257 | if !have_ffmpeg() { |
| 14258 | eprintln!("SKIP probe_screen_library: no ffmpeg"); |
| 14259 | return; |
| 14260 | } |
| 14261 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 14262 | let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else { |
| 14263 | eprintln!("SKIP probe_screen_library: no real-library manifest"); |
| 14264 | return; |
| 14265 | }; |
| 14266 | let limits = [4usize, 8, 16, 32, 64]; |
| 14267 | let floors = [0u64, 4, 8, 16, 32, 64, 128]; |
| 14268 | // Whatever ffmpeg gave us, without the exact-count assertion the |
| 14269 | // gate loaders make: a seek near the end of a clip returns fewer |
| 14270 | // frames, and that is a row to print, not a panic. |
| 14271 | let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> { |
| 14272 | let out = Command::new("ffmpeg") |
| 14273 | .args(["-v", "error", "-ss", seek, "-i", clip]) |
| 14274 | .args(["-frames:v", &n.to_string()]) |
| 14275 | .args(["-vf", vf]) |
| 14276 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 14277 | .output(); |
| 14278 | let Ok(out) = out else { return Vec::new() }; |
| 14279 | if !out.status.success() { |
| 14280 | return Vec::new(); |
| 14281 | } |
| 14282 | let (luma, chroma) = (w * h, w * h / 4); |
| 14283 | let frame_len = luma + 2 * chroma; |
| 14284 | (0..out.stdout.len() / frame_len) |
| 14285 | .map(|i| { |
| 14286 | let b = &out.stdout[i * frame_len..][..frame_len]; |
| 14287 | Picture { |
| 14288 | width: w, |
| 14289 | height: h, |
| 14290 | y: b[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 14291 | u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 14292 | v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 14293 | } |
| 14294 | }) |
| 14295 | .collect() |
| 14296 | }; |
| 14297 | // Share (%) of 16x16 blocks with 2..=N colours and per-pixel |
| 14298 | // variance > V, for every (N, V) of the sweep grid, over one frame. |
| 14299 | let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] { |
| 14300 | let mut hit = [[0usize; 7]; 5]; |
| 14301 | let mut blocks = 0usize; |
| 14302 | for by in (0..h).step_by(16) { |
| 14303 | for bx in (0..w).step_by(16) { |
| 14304 | let (bh, bw) = ((h - by).min(16), (w - bx).min(16)); |
| 14305 | let mut seen = [false; 256]; |
| 14306 | let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64); |
| 14307 | for row in 0..bh { |
| 14308 | for col in 0..bw { |
| 14309 | let v = y[(by + row) * w + bx + col]; |
| 14310 | sum += u64::from(v); |
| 14311 | sq += u64::from(v) * u64::from(v); |
| 14312 | if !seen[usize::from(v)] { |
| 14313 | seen[usize::from(v)] = true; |
| 14314 | colors += 1; |
| 14315 | } |
| 14316 | } |
| 14317 | } |
| 14318 | let n = (bh * bw) as u64; |
| 14319 | let var = (sq - sum * sum / n) / n; |
| 14320 | blocks += 1; |
| 14321 | for (li, &limit) in limits.iter().enumerate() { |
| 14322 | if colors > 1 && colors <= limit { |
| 14323 | for (fi, &floor) in floors.iter().enumerate() { |
| 14324 | hit[li][fi] += usize::from(var > floor); |
| 14325 | } |
| 14326 | } |
| 14327 | } |
| 14328 | } |
| 14329 | } |
| 14330 | let mut out = [[0f64; 7]; 5]; |
| 14331 | for li in 0..5 { |
| 14332 | for fi in 0..7 { |
| 14333 | out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64; |
| 14334 | } |
| 14335 | } |
| 14336 | out |
| 14337 | }; |
| 14338 | // (index, label, path, duration, screen-by-its-own-content). The |
| 14339 | // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS") |
| 14340 | // are desktop recordings; everything else in this library is camera |
| 14341 | // or film material. |
| 14342 | let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new(); |
| 14343 | for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] { |
| 14344 | let path = fixtures.join("video").join(file); |
| 14345 | if path.exists() { |
| 14346 | rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false)); |
| 14347 | } |
| 14348 | } |
| 14349 | for (i, line) in manifest.lines().skip(1).enumerate() { |
| 14350 | let f: Vec<&str> = line.split('\t').collect(); |
| 14351 | if f.len() < 10 { |
| 14352 | continue; |
| 14353 | } |
| 14354 | let (path, codec) = (f[0], f[2]); |
| 14355 | if codec == "-" || codec.is_empty() { |
| 14356 | continue; |
| 14357 | } |
| 14358 | let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else { |
| 14359 | eprintln!("SKIP {}: manifest carries no coded size", i + 1); |
| 14360 | continue; |
| 14361 | }; |
| 14362 | if !std::path::Path::new(path).exists() { |
| 14363 | eprintln!("SKIP {}: file is gone", i + 1); |
| 14364 | continue; |
| 14365 | } |
| 14366 | let name = path.rsplit('/').next().unwrap_or(path); |
| 14367 | let is_capture = path.contains("/OBS/") |
| 14368 | || (name.len() > 19 |
| 14369 | && name.as_bytes()[4] == b'-' |
| 14370 | && name.as_bytes()[7] == b'-' |
| 14371 | && name.as_bytes()[10] == b' ' |
| 14372 | && name.as_bytes()[13] == b'-'); |
| 14373 | rows.push(( |
| 14374 | format!("{}", i + 1), |
| 14375 | format!("{codec} {w}x{h}"), |
| 14376 | path.to_string(), |
| 14377 | f[8].parse::<f64>().unwrap_or(0.0), |
| 14378 | is_capture, |
| 14379 | )); |
| 14380 | } |
| 14381 | // Per (N, V): the worst camera/film row and the best screen row, so |
| 14382 | // the separation of the whole library is one subtraction. |
| 14383 | let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]); |
| 14384 | eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"); |
| 14385 | for (idx, label, path, dur, is_capture) in &rows { |
| 14386 | let Some((nw, nh)) = probe_dims(path) else { |
| 14387 | eprintln!("SKIP {idx}: ffprobe gave no size"); |
| 14388 | continue; |
| 14389 | }; |
| 14390 | let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1); |
| 14391 | let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 14392 | let vf = format!("crop={cw}:{ch}:{x}:{y0}"); |
| 14393 | let mut file_grid = [[0f64; 7]; 5]; |
| 14394 | let mut file_frames = 0usize; |
| 14395 | for pct in [10u32, 50, 90] { |
| 14396 | let seek = format!("{:.3}", dur * f64::from(pct) / 100.0); |
| 14397 | let frames = decode(path, &seek, &vf, cw, ch, 4); |
| 14398 | if frames.is_empty() { |
| 14399 | eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" }); |
| 14400 | continue; |
| 14401 | } |
| 14402 | let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64); |
| 14403 | let mut prev: Option<Vec<u8>> = None; |
| 14404 | for picture in &frames { |
| 14405 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 14406 | let grid = census(&y, cw, ch); |
| 14407 | for li in 0..5 { |
| 14408 | for fi in 0..7 { |
| 14409 | file_grid[li][fi] += grid[li][fi]; |
| 14410 | } |
| 14411 | } |
| 14412 | file_frames += 1; |
| 14413 | // The shipped rule is (16 colours, var > 16): grid row 2, |
| 14414 | // floor 16 is column 3. |
| 14415 | share += grid[2][3]; |
| 14416 | yes += usize::from(screen_content(&y, cw, cw, ch)); |
| 14417 | let n = y.len() as f64; |
| 14418 | let sum: f64 = y.iter().map(|&v| f64::from(v)).sum(); |
| 14419 | let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum(); |
| 14420 | mean += sum / n; |
| 14421 | sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt(); |
| 14422 | if let Some(p) = &prev { |
| 14423 | mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n; |
| 14424 | } |
| 14425 | prev = Some(y); |
| 14426 | } |
| 14427 | let f = frames.len() as f64; |
| 14428 | eprintln!( |
| 14429 | "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |", |
| 14430 | if *is_capture { "screen" } else { "camera" }, |
| 14431 | share / f, |
| 14432 | if yes * 2 > frames.len() { "SCREEN" } else { "camera" }, |
| 14433 | frames.len(), |
| 14434 | mean / f, |
| 14435 | sd / f, |
| 14436 | mad / (f - 1.0).max(1.0), |
| 14437 | ); |
| 14438 | } |
| 14439 | if file_frames == 0 { |
| 14440 | continue; |
| 14441 | } |
| 14442 | for li in 0..5 { |
| 14443 | for fi in 0..7 { |
| 14444 | let s = file_grid[li][fi] / file_frames as f64; |
| 14445 | match is_capture { |
| 14446 | true => scr_min[li][fi] = scr_min[li][fi].min(s), |
| 14447 | false => cam_max[li][fi] = cam_max[li][fi].max(s), |
| 14448 | } |
| 14449 | } |
| 14450 | } |
| 14451 | } |
| 14452 | eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"); |
| 14453 | eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>()); |
| 14454 | let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64)); |
| 14455 | for (li, &limit) in limits.iter().enumerate() { |
| 14456 | let mut row = String::new(); |
| 14457 | for fi in 0..7 { |
| 14458 | let (c, s) = (cam_max[li][fi], scr_min[li][fi]); |
| 14459 | row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c))); |
| 14460 | if s - c > best { |
| 14461 | best = s - c; |
| 14462 | best_rule = (limit, floors[fi]); |
| 14463 | } |
| 14464 | } |
| 14465 | eprintln!(" {limit:>5} |{row}"); |
| 14466 | } |
| 14467 | // The threshold sits at the midpoint of the widest gap; the shipped |
| 14468 | // constant is its reciprocal in whole parts of the frame. |
| 14469 | let (li, fi) = ( |
| 14470 | limits.iter().position(|&l| l == best_rule.0).unwrap(), |
| 14471 | floors.iter().position(|&f| f == best_rule.1).unwrap(), |
| 14472 | ); |
| 14473 | let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0; |
| 14474 | eprintln!( |
| 14475 | "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}", |
| 14476 | best_rule.0, |
| 14477 | best_rule.1, |
| 14478 | best, |
| 14479 | cam_max[li][fi], |
| 14480 | scr_min[li][fi], |
| 14481 | mid, |
| 14482 | (100.0 / mid.max(0.1)).round() as usize, |
| 14483 | ); |
| 14484 | } |
| 14485 | |
| 14486 | /// The missing instrument: what this encoder costs against libaom and |
| 14487 | /// rav1e at matched fidelity, and how long it takes to get there. |
| 14488 | /// |
| 14489 | /// Recipe, identical on all three sides: 12 consecutive frames of each |
| 14490 | /// clip scaled to 640x384 (a whole number of superblocks), one key frame |
| 14491 | /// then 11 inter frames (`-g 12`, matching our own sequence shape), one |
| 14492 | /// tile, `-threads 1`, no film grain synthesis (neither reference enables |
| 14493 | /// it by default), 4:2:0 8-bit in and out. Reference points: |
| 14494 | /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}` |
| 14495 | /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}: |
| 14496 | /// tile_cols=1:tile_rows=1:threads=1` |
| 14497 | /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on |
| 14498 | /// ffmpeg-decoded frames of each encoder's own stream. |
| 14499 | /// |
| 14500 | /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame |
| 14501 | /// deblocking levels and CDEF strengths, both chosen by re-decoding the |
| 14502 | /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the |
| 14503 | /// four encodes of that ladder together): |
| 14504 | /// |
| 14505 | /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e | |
| 14506 | /// |---|---|---|---|---| |
| 14507 | /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s | |
| 14508 | /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | |
| 14509 | /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | |
| 14510 | /// |
| 14511 | /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long |
| 14512 | /// the encoder takes -- every stream it writes is byte-identical, so the |
| 14513 | /// BD columns are this box's own re-run of the same recipe rather than a |
| 14514 | /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs |
| 14515 | /// rav1e). What moved is the wall of the four encodes: |
| 14516 | /// |
| 14517 | /// | clip | wall ours before | after | instructions:u before -> after | |
| 14518 | /// |---|---|---|---| |
| 14519 | /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) | |
| 14520 | /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) | |
| 14521 | /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) | |
| 14522 | /// |
| 14523 | /// Three exact steps, none of which touches a coded bit: the coefficient |
| 14524 | /// rate pricer stopped rebuilding every CDF table per candidate |
| 14525 | /// (`tile::coeff_bits`), the filter search stopped re-decoding its own |
| 14526 | /// tile once per candidate (`decode::FilterReplay`), and the forward |
| 14527 | /// transform stopped transforming the all-zero residual that 70% of its |
| 14528 | /// calls carry. |
| 14529 | /// |
| 14530 | /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): |
| 14531 | /// |
| 14532 | /// | step | 1080p | 2160p | screen | |
| 14533 | /// |---|---|---|---| |
| 14534 | /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 | |
| 14535 | /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 | |
| 14536 | /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 | |
| 14537 | /// |
| 14538 | /// Re-measured for the record 2026-09-07 (lane-av1resweep), after |
| 14539 | /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth |
| 14540 | /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults |
| 14541 | /// -- all three decided on the REAL film rows of |
| 14542 | /// [`bd_rate_screen_native`], which this downscaled recipe does not |
| 14543 | /// carry: |
| 14544 | /// |
| 14545 | /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e | |
| 14546 | /// |---|---|---|---| |
| 14547 | /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s | |
| 14548 | /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s | |
| 14549 | /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s | |
| 14550 | /// |
| 14551 | /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the |
| 14552 | /// DEFAULT of the sequence path this gate codes through -- the bars are |
| 14553 | /// non-screen so they take it, the capture is gated flat: |
| 14554 | /// |
| 14555 | /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall | |
| 14556 | /// |---|---|---|---|---| |
| 14557 | /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s | |
| 14558 | /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s | |
| 14559 | /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s | |
| 14560 | /// |
| 14561 | /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the |
| 14562 | /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the |
| 14563 | /// facade arm -- which is what "one mini-GOP driver, two entry points" |
| 14564 | /// means here. This downscaled recipe HATES the pyramid (as it hates |
| 14565 | /// every knob the real film rows of `bd_rate_screen_native` keep, which |
| 14566 | /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows |
| 14567 | /// above. The capture's row is the flat row to the byte in both runs -- |
| 14568 | /// that equality IS the content gate. |
| 14569 | /// |
| 14570 | /// Loop restoration is NOT in yet: it is the one filter whose parameters |
| 14571 | /// are per restoration UNIT inside the tile payload, so it needs both |
| 14572 | /// tile writers to code `lr` syntax and an encoder-visible post-CDEF |
| 14573 | /// buffer to solve against -- neither of which this frame-header-level |
| 14574 | /// search reaches. |
| 14575 | /// |
| 14576 | /// The baseline it replaced, before an inter frame's blocks chose their |
| 14577 | /// own partition, was +501.4/+504.4/+440.9 against libaom and |
| 14578 | /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s. |
| 14579 | /// |
| 14580 | /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched |
| 14581 | /// fidelity, while spending far more time than either (the partition |
| 14582 | /// search's own cost, uncut: see the two intra-pruning variants measured |
| 14583 | /// and rejected in the lane report). No |
| 14584 | /// threshold is asserted yet -- this run sets the baseline; the gate |
| 14585 | /// asserts four monotone points per ladder, and at EVERY ladder point of |
| 14586 | /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own |
| 14587 | /// `crate::stream::decode_stream` -- and asserts the encoder's |
| 14588 | /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U |
| 14589 | /// and V over every shown frame in display order. A failure names the |
| 14590 | /// clip, the q, the frame, the plane and the first differing sample. |
| 14591 | /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade, |
| 14592 | /// which exposes no per-packet reconstruction, so that path asserts the |
| 14593 | /// two decoders against each other on all three planes.) |
| 14594 | /// |
| 14595 | /// Run: |
| 14596 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 14597 | /// bd_rate_vs_libaom_and_rav1e --nocapture |
| 14598 | #[test] |
| 14599 | #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"] |
| 14600 | fn bd_rate_vs_libaom_and_rav1e() { |
| 14601 | let _knobs = crate::speed::knob_write(); |
| 14602 | if !have_ffmpeg() { |
| 14603 | eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg"); |
| 14604 | return; |
| 14605 | } |
| 14606 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 14607 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 14608 | // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these |
| 14609 | // rows for real content (the real rows live in the native gate). |
| 14610 | for (label, name) in [ |
| 14611 | ("bars 1080p", "h264-1080p-23.976-8bit.mp4"), |
| 14612 | ("bars 2160p", "h264-2160p-23.976-8bit.mp4"), |
| 14613 | ] { |
| 14614 | let path = fixtures.join("video").join(name); |
| 14615 | if path.exists() { |
| 14616 | clips.push((label.to_string(), path)); |
| 14617 | } else { |
| 14618 | eprintln!("SKIP clip {name}: missing"); |
| 14619 | } |
| 14620 | } |
| 14621 | // Screen capture: the repo carries no screen-capture fixture, so take |
| 14622 | // the first OBS recording the real-library manifest names. |
| 14623 | match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) { |
| 14624 | Ok(manifest) => { |
| 14625 | let screen = manifest |
| 14626 | .lines() |
| 14627 | .skip(1) |
| 14628 | .filter_map(|l| l.split('\t').next()) |
| 14629 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()); |
| 14630 | match screen { |
| 14631 | Some(p) => clips.push(( |
| 14632 | format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), |
| 14633 | std::path::PathBuf::from(p), |
| 14634 | )), |
| 14635 | None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), |
| 14636 | } |
| 14637 | } |
| 14638 | Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"), |
| 14639 | } |
| 14640 | assert!(!clips.is_empty(), "no source clip available"); |
| 14641 | |
| 14642 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 14643 | let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] |
| 14644 | .iter() |
| 14645 | .map(|q| { |
| 14646 | ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] |
| 14647 | .map(String::from) |
| 14648 | .to_vec() |
| 14649 | }) |
| 14650 | .collect(); |
| 14651 | let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] |
| 14652 | .iter() |
| 14653 | .map(|q| { |
| 14654 | vec![ |
| 14655 | "-rav1e-params".to_string(), |
| 14656 | format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), |
| 14657 | ] |
| 14658 | }) |
| 14659 | .collect(); |
| 14660 | println!( |
| 14661 | "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread" |
| 14662 | ); |
| 14663 | println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"); |
| 14664 | println!("|---|---|---|---|---|"); |
| 14665 | for (name, path) in &clips { |
| 14666 | let fctx = &crate::decode::FrameCtx::new(); |
| 14667 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 14668 | let _ = take_partition_hits(); |
| 14669 | let _ = crate::tile::take_palette_hits(); |
| 14670 | SCREEN_FRAMES.iter().for_each(|c| { |
| 14671 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 14672 | }); |
| 14673 | let _ = take_uv_mode_hits(); |
| 14674 | let _ = crate::tile::take_inter_mode_hits(); |
| 14675 | let _ = crate::tile::take_drl_hits(); |
| 14676 | let _ = crate::tile::take_ref_hits(); |
| 14677 | let _ = crate::tile::take_compound_mode_hits(); |
| 14678 | let _ = crate::tile::take_compound_pair_hits(); |
| 14679 | let _ = crate::tile::take_compound_size_hits(); |
| 14680 | let _ = crate::tile::take_compound_leaf_mode_hits(); |
| 14681 | let _ = take_b64_root_hits(); |
| 14682 | let _ = take_b64_residual_hits(); |
| 14683 | let _ = take_b64_compound_hits(); |
| 14684 | let _ = crate::motion::take_census(); |
| 14685 | // The entry-surface arm: run the SAME ladder through the |
| 14686 | // streaming facade the editor's export calls, which must print |
| 14687 | // the same BD numbers as the sequence path -- byte for byte the |
| 14688 | // same stream now that both drive one mini-GOP driver |
| 14689 | // (lane-av1pyrdef). |
| 14690 | let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some(); |
| 14691 | let (ours, ours_wall) = match facade { |
| 14692 | false => our_ladder(name, &source, width, height, fctx), |
| 14693 | true => { |
| 14694 | let pyramid = crate::encoder::Pyramid::from_env(); |
| 14695 | let (ladder, wall, counts, bytes, effective) = |
| 14696 | our_ladder_facade(name, &source, width, height, pyramid); |
| 14697 | eprintln!( |
| 14698 | "{name}: facade, pyramid requested {pyramid:?} effective \ |
| 14699 | {effective:?} -- frames key {} arf {} leaf {} \ |
| 14700 | show_existing {}; bytes key {} arf {} leaf {} show_existing {}", |
| 14701 | counts[0], counts[1], counts[2], counts[3], |
| 14702 | bytes[0], bytes[1], bytes[2], bytes[3], |
| 14703 | ); |
| 14704 | (ladder, wall) |
| 14705 | } |
| 14706 | }; |
| 14707 | // How often the inter split actually fired over this clip's four |
| 14708 | // encodes, against the whole 32x32 that was the only outcome |
| 14709 | // before (gate-blind-to-feature). |
| 14710 | let [whole32, split32, whole16, split16] = take_partition_hits(); |
| 14711 | // Which inter modes actually fired over this clip's four encodes, |
| 14712 | // and at which DRL index -- a mode nobody picks is a mode the BD |
| 14713 | // number cannot be crediting (gate-blind-to-feature). |
| 14714 | let [nearest, near, global, new] = crate::tile::take_inter_mode_hits(); |
| 14715 | let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits(); |
| 14716 | let refs = crate::tile::take_ref_hits(); |
| 14717 | let modes_total = (nearest + near + global + new).max(1); |
| 14718 | eprintln!( |
| 14719 | "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \ |
| 14720 | GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \ |
| 14721 | {drl0}/{drl1}/{drl2}/{drl3}", |
| 14722 | 100.0 * nearest as f64 / modes_total as f64, |
| 14723 | 100.0 * near as f64 / modes_total as f64, |
| 14724 | 100.0 * global as f64 / modes_total as f64, |
| 14725 | 100.0 * new as f64 / modes_total as f64, |
| 14726 | ); |
| 14727 | // The compound census: what share of the coded inter blocks took |
| 14728 | // a compound reference at all, which compound mode they took, and |
| 14729 | // which pair (gate-blind-to-feature -- a compound mode nobody |
| 14730 | // picks cannot be what a BD number credits). |
| 14731 | // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many |
| 14732 | // superblocks were left whole at all, and how many of those coded |
| 14733 | // a residual or took a compound reference. |
| 14734 | let (roots, root_res, root_comp) = ( |
| 14735 | take_b64_root_hits(), |
| 14736 | take_b64_residual_hits(), |
| 14737 | take_b64_compound_hits(), |
| 14738 | ); |
| 14739 | eprintln!( |
| 14740 | "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})" |
| 14741 | ); |
| 14742 | let comp_modes = crate::tile::take_compound_mode_hits(); |
| 14743 | let comp_pairs = crate::tile::take_compound_pair_hits(); |
| 14744 | let comp_sizes = crate::tile::take_compound_size_hits(); |
| 14745 | let comp_leaf = crate::tile::take_compound_leaf_mode_hits(); |
| 14746 | let comp_total: usize = comp_modes.iter().sum(); |
| 14747 | eprintln!( |
| 14748 | "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \ |
| 14749 | NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \ |
| 14750 | GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}", |
| 14751 | modes_total + comp_total, |
| 14752 | 100.0 * comp_total as f64 / (modes_total + comp_total) as f64, |
| 14753 | comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3], |
| 14754 | comp_modes[6], comp_modes[7], |
| 14755 | comp_pairs[3], comp_pairs[6], |
| 14756 | ); |
| 14757 | eprintln!( |
| 14758 | "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \ |
| 14759 | NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}", |
| 14760 | comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], |
| 14761 | comp_leaf[7], |
| 14762 | ); |
| 14763 | eprintln!( |
| 14764 | "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}", |
| 14765 | comp_sizes[1], comp_sizes[2], comp_sizes[3], |
| 14766 | ); |
| 14767 | // Where the wall-owning stage actually goes: how many candidate |
| 14768 | // evaluations (one `mc::predict` + SAD each) a search spends, how |
| 14769 | // many of them are subpel, and how often the winner is the seed |
| 14770 | // it started from -- the census the seeded search is judged by. |
| 14771 | let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census(); |
| 14772 | let per = |n: u64| n as f64 / calls.max(1) as f64; |
| 14773 | eprintln!( |
| 14774 | "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \ |
| 14775 | {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \ |
| 14776 | +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%", |
| 14777 | per(evals), |
| 14778 | 100.0 * subpel as f64 / evals.max(1) as f64, |
| 14779 | per(rounds), |
| 14780 | 100.0 * near_pred as f64 / calls.max(1) as f64, |
| 14781 | 100.0 * unmoved as f64 / calls.max(1) as f64, |
| 14782 | ); |
| 14783 | eprintln!( |
| 14784 | "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", |
| 14785 | refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] |
| 14786 | ); |
| 14787 | eprintln!( |
| 14788 | "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ |
| 14789 | 16x16 leaves split into 8s {split16} of {} ({:.1}%)", |
| 14790 | whole32 + split32, |
| 14791 | 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64, |
| 14792 | whole16 + split16, |
| 14793 | 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 |
| 14794 | ); |
| 14795 | // The deblocking level each of this clip's frames chose |
| 14796 | // (lane-av1filt): 0 everywhere would mean the filter never fires. |
| 14797 | let levels = crate::filter_search::take_chosen_levels(); |
| 14798 | type Chosen = ((u8, u8), (u8, u8), (u8, u8)); |
| 14799 | let mean = |f: fn(&Chosen) -> u8| { |
| 14800 | levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64 |
| 14801 | }; |
| 14802 | eprintln!( |
| 14803 | "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \ |
| 14804 | cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}", |
| 14805 | levels.len(), |
| 14806 | mean(|l| l.0.0), |
| 14807 | mean(|l| l.0.1), |
| 14808 | mean(|l| l.1.0), |
| 14809 | mean(|l| l.1.1), |
| 14810 | mean(|l| l.2.0), |
| 14811 | mean(|l| l.2.1), |
| 14812 | ); |
| 14813 | // How many strength presets each frame's CDEF list carried and |
| 14814 | // how the 64x64 units spread over them (lane-av1lr): `bits 0` |
| 14815 | // everywhere would mean the per-unit choice never fires. |
| 14816 | let presets = crate::filter_search::take_cdef_presets(); |
| 14817 | let mut by_bits = [0usize; 4]; |
| 14818 | for (b, _) in &presets { |
| 14819 | by_bits[usize::from(*b)] += 1; |
| 14820 | } |
| 14821 | let units: usize = presets.iter().flat_map(|(_, c)| c).sum(); |
| 14822 | let on_extra: usize = presets |
| 14823 | .iter() |
| 14824 | .flat_map(|(_, c)| c.iter().skip(1)) |
| 14825 | .sum(); |
| 14826 | eprintln!( |
| 14827 | "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \ |
| 14828 | on a non-default preset ({:.1}%)", |
| 14829 | by_bits[0], |
| 14830 | by_bits[1], |
| 14831 | by_bits[2], |
| 14832 | by_bits[3], |
| 14833 | on_extra, |
| 14834 | units, |
| 14835 | 100.0 * on_extra as f64 / units.max(1) as f64 |
| 14836 | ); |
| 14837 | // How the 64x64 luma restoration units split between |
| 14838 | // RESTORE_NONE and Wiener (lane-av1lr). |
| 14839 | let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram(); |
| 14840 | eprintln!( |
| 14841 | "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)", |
| 14842 | 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64 |
| 14843 | ); |
| 14844 | // Which chroma modes the search actually wins with, against the |
| 14845 | // unconditional DC_PRED that was the only outcome before |
| 14846 | // (gate-blind-to-feature). |
| 14847 | // Screen-content detection and the palette it turns on |
| 14848 | // (gate-blind-to-feature): how many frames set |
| 14849 | // `allow_screen_content_tools`, how many blocks took a palette, |
| 14850 | // and of what size. A film clip must print `screen frames on=0`. |
| 14851 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 14852 | let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); |
| 14853 | // Which tables the SEARCH priced against, per frame arming |
| 14854 | // (`tile::arm_pricing_cdfs`): the default tables or the frame's |
| 14855 | // real starting ones. A film clip must show every inter arming on |
| 14856 | // the real side, a screen clip none of them. |
| 14857 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 14858 | eprintln!("{name}: pricer armings default={price_default} real={price_real}"); |
| 14859 | let palette = crate::tile::take_palette_hits(); |
| 14860 | eprintln!( |
| 14861 | "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", |
| 14862 | palette[0], |
| 14863 | (2..=8) |
| 14864 | .filter(|&n| palette[n] > 0) |
| 14865 | .map(|n| format!("{n}={}", palette[n])) |
| 14866 | .collect::<Vec<_>>() |
| 14867 | .join(" ") |
| 14868 | ); |
| 14869 | // The CfL alpha histogram (lane-av1cfl): one entry per chroma |
| 14870 | // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that |
| 14871 | // only ever fires at one magnitude is a search that never left |
| 14872 | // its first candidate (gate-blind-to-feature). |
| 14873 | // The luma angle-delta histogram (lane-av1cfl): how many |
| 14874 | // directional blocks won at each delta. All-zero would mean the |
| 14875 | // refinement never beat the base angle. |
| 14876 | let deltas = take_angle_delta_hits(); |
| 14877 | if deltas.iter().sum::<usize>() > 0 { |
| 14878 | eprintln!( |
| 14879 | "{name}: angle_delta_y {}", |
| 14880 | deltas |
| 14881 | .iter() |
| 14882 | .enumerate() |
| 14883 | .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3)) |
| 14884 | .collect::<Vec<_>>() |
| 14885 | .join(" ") |
| 14886 | ); |
| 14887 | } |
| 14888 | let alphas = take_cfl_alpha_hits(); |
| 14889 | if alphas.iter().sum::<usize>() > 0 { |
| 14890 | eprintln!( |
| 14891 | "{name}: cfl |alpha| {}", |
| 14892 | alphas |
| 14893 | .iter() |
| 14894 | .enumerate() |
| 14895 | .filter(|&(_, &n)| n > 0) |
| 14896 | .map(|(a, &n)| format!("{a}={n}")) |
| 14897 | .collect::<Vec<_>>() |
| 14898 | .join(" ") |
| 14899 | ); |
| 14900 | } |
| 14901 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 14902 | eprintln!( |
| 14903 | "{name}: chroma palette blocks {} sizes {}", |
| 14904 | palette_uv[0], |
| 14905 | (2..=8) |
| 14906 | .filter(|&n| palette_uv[n] > 0) |
| 14907 | .map(|n| format!("{n}={}", palette_uv[n])) |
| 14908 | .collect::<Vec<_>>() |
| 14909 | .join(" ") |
| 14910 | ); |
| 14911 | let uv = take_uv_mode_hits(); |
| 14912 | let uv_total: usize = uv.iter().sum(); |
| 14913 | eprintln!( |
| 14914 | "{name}: uv modes {}", |
| 14915 | uv.iter() |
| 14916 | .enumerate() |
| 14917 | .filter(|&(_, &n)| n > 0) |
| 14918 | .map(|(m, &n)| format!( |
| 14919 | "{}={n} ({:.1}%)", |
| 14920 | UV_MODE_NAMES[m], |
| 14921 | 100.0 * n as f64 / uv_total.max(1) as f64 |
| 14922 | )) |
| 14923 | .collect::<Vec<_>>() |
| 14924 | .join(" ") |
| 14925 | ); |
| 14926 | // Which transform depth the intra blocks of this clip's key |
| 14927 | // frames resolved to (lane-av1tx): depth 0 is one transform over |
| 14928 | // the whole block, 1 and 2 its halvings. |
| 14929 | let depths = take_tx_depth_hits(); |
| 14930 | let depth_total: usize = depths.iter().sum(); |
| 14931 | eprintln!( |
| 14932 | "{name}: intra tx depths {}", |
| 14933 | depths |
| 14934 | .iter() |
| 14935 | .enumerate() |
| 14936 | .map(|(d, &n)| format!( |
| 14937 | "{d}={n} ({:.1}%)", |
| 14938 | 100.0 * n as f64 / depth_total.max(1) as f64 |
| 14939 | )) |
| 14940 | .collect::<Vec<_>>() |
| 14941 | .join(" ") |
| 14942 | ); |
| 14943 | print_inter_tx_census(name); |
| 14944 | // lane-av1obmc: how many blocks actually CODED a motion_mode |
| 14945 | // symbol and which value they took, by footprint -- "OBMC is on" |
| 14946 | // as a measurement rather than a claim (class |
| 14947 | // `gate-blind-to-feature`). |
| 14948 | let mm = crate::tile::take_motion_mode_hits(); |
| 14949 | eprintln!( |
| 14950 | "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \ |
| 14951 | WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \ |
| 14952 | eligible)", |
| 14953 | mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8], |
| 14954 | 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 14955 | 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 14956 | mm.iter().sum::<usize>(), |
| 14957 | ); |
| 14958 | let (aom, aom_wall) = |
| 14959 | external_ladder(&source, width, height, "libaom-av1", &aom_points); |
| 14960 | let (rav1e, rav1e_wall) = |
| 14961 | external_ladder(&source, width, height, "librav1e", &rav1e_points); |
| 14962 | assert_monotone(&format!("{name}: ours"), &ours); |
| 14963 | assert_monotone(&format!("{name}: libaom"), &aom); |
| 14964 | assert_monotone(&format!("{name}: rav1e"), &rav1e); |
| 14965 | let points = ours |
| 14966 | .iter() |
| 14967 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 14968 | .collect::<Vec<_>>() |
| 14969 | .join(", "); |
| 14970 | println!( |
| 14971 | "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", |
| 14972 | bd_rate(&aom, &ours) * 100.0, |
| 14973 | bd_rate(&rav1e, &ours) * 100.0, |
| 14974 | ); |
| 14975 | println!( |
| 14976 | "| references | libaom {} | rav1e {} | | |", |
| 14977 | aom.iter() |
| 14978 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 14979 | .collect::<Vec<_>>() |
| 14980 | .join(", "), |
| 14981 | rav1e |
| 14982 | .iter() |
| 14983 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 14984 | .collect::<Vec<_>>() |
| 14985 | .join(", "), |
| 14986 | ); |
| 14987 | } |
| 14988 | assert_ladder_decodes(); |
| 14989 | } |
| 14990 | /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2, |
| 14991 | /// split by block class in lane-av1txdepth): depth 0 is one transform over |
| 14992 | /// the whole block, 1 its four halves; the classes are the 16x16/8x8 |
| 14993 | /// leaves and the 32x32 root, each single-reference or compound. A class |
| 14994 | /// with no counts at all never reached `commit_inter_luma` -- which is |
| 14995 | /// what its knob being off looks like (class `gate-blind-to-feature`). |
| 14996 | fn print_inter_tx_census(name: &str) { |
| 14997 | let splits = take_inter_tx_split_hits(); |
| 14998 | let total: usize = splits.iter().sum(); |
| 14999 | let row = |label: &str, base: usize| { |
| 15000 | let (n0, n1) = (splits[base], splits[base + 1]); |
| 15001 | format!( |
| 15002 | "{label} 0={n0} 1={n1} ({:.1}% split)", |
| 15003 | 100.0 * n1 as f64 / (n0 + n1).max(1) as f64 |
| 15004 | ) |
| 15005 | }; |
| 15006 | eprintln!( |
| 15007 | "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}", |
| 15008 | row("leaf single", 0), |
| 15009 | row("leaf compound", 2), |
| 15010 | row("32x32 single", 4), |
| 15011 | row("32x32 compound", 6), |
| 15012 | ); |
| 15013 | } |
| 15014 | |
| 15015 | /// The video stream's coded size, from ffprobe. |
| 15016 | fn probe_dims(clip: &str) -> Option<(usize, usize)> { |
| 15017 | crate::probe::dims(clip) |
| 15018 | } |
| 15019 | |
| 15020 | /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a |
| 15021 | /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s |
| 15022 | /// superblock-aligned one, still centred and still even for 4:2:0. |
| 15023 | /// |
| 15024 | /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide |
| 15025 | /// superblocks by design, so no default gate row has a block the frame |
| 15026 | /// edge cuts through -- while every arbitrary export size does (3840x1608 |
| 15027 | /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP= |
| 15028 | /// 1920x1080` is the straddling arm the edge-clipped distortion score is |
| 15029 | /// read on. |
| 15030 | fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> { |
| 15031 | let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?; |
| 15032 | let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>"); |
| 15033 | let (cw, ch): (usize, usize) = |
| 15034 | (w.parse().expect("crop width"), h.parse().expect("crop height")); |
| 15035 | let (nw, nh) = crate::probe::dims(clip)?; |
| 15036 | assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}"); |
| 15037 | let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 15038 | Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch)) |
| 15039 | } |
| 15040 | |
| 15041 | /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared |
| 15042 | /// with `probe_screen_detect` so the detector sweep measures exactly the |
| 15043 | /// clips the keep table is read off. Selector env vars as documented on |
| 15044 | /// the gate; a missing clip prints a SKIP and drops its row. |
| 15045 | fn native_gate_clips() -> Vec<(String, String, String)> { |
| 15046 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 15047 | let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1"); |
| 15048 | let (film, film4k, screen) = ( |
| 15049 | on("EC_AV1_NATIVE_FILM"), |
| 15050 | on("EC_AV1_NATIVE_FILM4K"), |
| 15051 | on("EC_AV1_NATIVE_SCREEN"), |
| 15052 | ); |
| 15053 | // No selector at all means every clip; any selector means that subset. |
| 15054 | let all = !(film || film4k || screen); |
| 15055 | // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS, |
| 15056 | // not film -- they print as "bars" so no reader takes them for real |
| 15057 | // content -- and the two rows below them are the real AV1 films. |
| 15058 | let mut clips: Vec<(String, String, String)> = Vec::new(); |
| 15059 | for (want, label, file) in [ |
| 15060 | (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"), |
| 15061 | (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"), |
| 15062 | ] { |
| 15063 | if !want { |
| 15064 | continue; |
| 15065 | } |
| 15066 | let path = fixtures.join("video").join(file); |
| 15067 | match path.exists() { |
| 15068 | true => { |
| 15069 | clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into())) |
| 15070 | } |
| 15071 | false => eprintln!("SKIP {label}: {file} missing"), |
| 15072 | } |
| 15073 | } |
| 15074 | let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")); |
| 15075 | // The real films, taken out of the real-library manifest by codec and |
| 15076 | // coded width so no title and no home path lives in this file. Each |
| 15077 | // seek is PINNED (class `seeded fixture not reproducible`) at a |
| 15078 | // moving, non-black window -- a black leader would make every arm |
| 15079 | // read +0.000 (class `flat sample window`). Both sources are 10-bit |
| 15080 | // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is |
| 15081 | // what all three encoders see, so the comparison stays |
| 15082 | // encoder-vs-encoder. |
| 15083 | let pick = |width: &str| -> Option<String> { |
| 15084 | let m = manifest.as_ref().ok()?; |
| 15085 | m.lines() |
| 15086 | .skip(1) |
| 15087 | .map(|l| l.split('\t').collect::<Vec<_>>()) |
| 15088 | .find(|f| { |
| 15089 | f.len() > 4 |
| 15090 | && f[2] == "av1" |
| 15091 | && f[3] == width |
| 15092 | && std::path::Path::new(f[0]).exists() |
| 15093 | }) |
| 15094 | .map(|f| f[0].to_string()) |
| 15095 | }; |
| 15096 | for (want, label, width, seek) in [ |
| 15097 | (all || film, "film A (1080p source)", "1920", "00:35:00"), |
| 15098 | (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"), |
| 15099 | ] { |
| 15100 | if !want { |
| 15101 | continue; |
| 15102 | } |
| 15103 | match pick(width) { |
| 15104 | Some(path) => clips.push((label.to_string(), path, seek.to_string())), |
| 15105 | None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"), |
| 15106 | } |
| 15107 | } |
| 15108 | if all || screen { |
| 15109 | match &manifest { |
| 15110 | Ok(manifest) => match manifest |
| 15111 | .lines() |
| 15112 | .skip(1) |
| 15113 | .filter_map(|l| l.split('\t').next()) |
| 15114 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 15115 | { |
| 15116 | Some(p) => clips.push(( |
| 15117 | format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), |
| 15118 | p.to_string(), |
| 15119 | "0".into(), |
| 15120 | )), |
| 15121 | None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), |
| 15122 | }, |
| 15123 | Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"), |
| 15124 | } |
| 15125 | } |
| 15126 | clips |
| 15127 | } |
| 15128 | |
| 15129 | /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate |
| 15130 | /// downscales the OBS capture to 640x384, which destroys exactly the |
| 15131 | /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist |
| 15132 | /// for (class `gate-recipe-confound`), so every screen-tool decision taken |
| 15133 | /// on that recipe is taken on content the tool cannot serve. This arm |
| 15134 | /// crops -- never scales -- a superblock-aligned window out of the middle |
| 15135 | /// of the capture at its own resolution (at most 1920x1024, so the wall |
| 15136 | /// stays in the minutes) and runs the same 12-frame, four-quantizer |
| 15137 | /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one |
| 15138 | /// thread, with the same three-way (encoder / ffmpeg / our decoder) |
| 15139 | /// sample-exactness assertion `our_ladder` makes. |
| 15140 | /// |
| 15141 | /// It is its own `--ignored` test so the default gate's wall does not |
| 15142 | /// grow. Every variant is an environment knob, and each of those is a |
| 15143 | /// `OnceLock` read once per process, so a variant is a separate run: |
| 15144 | /// |
| 15145 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 15146 | /// bd_rate_screen_native --nocapture # baseline |
| 15147 | /// EC_AV1_INTRABC=1 ... same command # intra block copy |
| 15148 | /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound |
| 15149 | /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles |
| 15150 | /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid |
| 15151 | /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing |
| 15152 | /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm |
| 15153 | /// |
| 15154 | /// The coding pyramid is the DEFAULT of the sequence path this arm codes |
| 15155 | /// through (lane-av1pyrdef); the run prints the requested and the |
| 15156 | /// effective pyramid per clip, and a screen clip's effective one is |
| 15157 | /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the |
| 15158 | /// streaming facade instead, which prints the per-level frame and byte |
| 15159 | /// census and asserts ffmpeg's decode against our own decoder on all |
| 15160 | /// three planes in display order; both arms code the same bytes |
| 15161 | /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`). |
| 15162 | /// |
| 15163 | /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are |
| 15164 | /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg |
| 15165 | /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra |
| 15166 | /// cost -- so every "film" column in the historical tables of this file |
| 15167 | /// is that generator, not film. The real content is `film A`, `film B` |
| 15168 | /// (native crops out of the two AV1 films the real-library manifest |
| 15169 | /// names, at a pinned seek; added 2026-09-07) and the screen capture. A |
| 15170 | /// decision only the bars rows support is not supported. |
| 15171 | /// |
| 15172 | /// Measured 2026-09-07, the five rows before and after the screen |
| 15173 | /// detector grew libaom's variance term ([`screen_var`]) -- before it, |
| 15174 | /// BOTH real films were classified as screen content on 48/48 frames, so |
| 15175 | /// their coefficients were priced against the DEFAULT CDFs and the |
| 15176 | /// palette search ran over film; after, both are non-screen (0/48) and |
| 15177 | /// the capture is unchanged at 48/48: |
| 15178 | /// |
| 15179 | /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours | |
| 15180 | /// |---|---|---|---| |
| 15181 | /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s | |
| 15182 | /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s | |
| 15183 | /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s | |
| 15184 | /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s | |
| 15185 | /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s | |
| 15186 | /// |
| 15187 | /// Both bars rows and the capture are byte-identical across that change |
| 15188 | /// (their classification never moved); the palette search over film was |
| 15189 | /// costing roughly a tenth of the film rows' wall. |
| 15190 | /// |
| 15191 | /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the |
| 15192 | /// sequence path's default -- the four non-screen rows take `4:-16:8`, |
| 15193 | /// the capture is gated flat and does not move a byte: |
| 15194 | /// |
| 15195 | /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e | |
| 15196 | /// |---|---|---|---|---| |
| 15197 | /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s | |
| 15198 | /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s | |
| 15199 | /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s | |
| 15200 | /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s | |
| 15201 | /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s | |
| 15202 | /// |
| 15203 | /// Every row lands on lane-av1pyrgate's facade-arm number to the digit, |
| 15204 | /// which is the point of the shared driver: the two entry points code one |
| 15205 | /// stream. The bars rows are fixtures (recorded, never a decision); the |
| 15206 | /// two real films are what the pyramid ships for. |
| 15207 | /// |
| 15208 | /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`, |
| 15209 | /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset: |
| 15210 | /// setting any one of them keeps only the selected rows (the two 1080p |
| 15211 | /// rows, the two 2160p rows, the capture row respectively). A missing |
| 15212 | /// real film SKIPs its row; it never fails the gate. |
| 15213 | #[test] |
| 15214 | #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"] |
| 15215 | fn bd_rate_screen_native() { |
| 15216 | let _knobs = crate::speed::knob_read(); |
| 15217 | native_bd_arm("bd_rate_screen_native", 12, false); |
| 15218 | } |
| 15219 | |
| 15220 | /// The LONG-GOP arm of the native BD gate: the same recipe as |
| 15221 | /// [`bd_rate_screen_native`] over the two real film rows only, but 48 |
| 15222 | /// pictures with `gop = 48` (`encode_sequence` sets `gop = |
| 15223 | /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which |
| 15224 | /// reaches libaom as `--kf-max-dist=48` and rav1e as |
| 15225 | /// `key_frame_interval=48`), so every encoder sees one key frame and 47 |
| 15226 | /// inter pictures. |
| 15227 | /// |
| 15228 | /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop = |
| 15229 | /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key |
| 15230 | /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`] |
| 15231 | /// above 12 codes the same stream there -- the shipped `16` was measured |
| 15232 | /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture |
| 15233 | /// group (class `instrument at bound` / `gate blind to feature`). The |
| 15234 | /// user's exports are long GOPs, so the pyramid shape is decided here. |
| 15235 | /// |
| 15236 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 15237 | /// bd_rate_film_long_gop --nocapture |
| 15238 | /// |
| 15239 | /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1` |
| 15240 | /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape. |
| 15241 | /// Read every row off the log's own "pyramid requested/effective" print, |
| 15242 | /// never off the argument order of the runs (lane-pyr3 misattributed |
| 15243 | /// three rows that way). |
| 15244 | /// |
| 15245 | /// Table: `lanes/pyr4.sweep.txt`. |
| 15246 | #[test] |
| 15247 | #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"] |
| 15248 | fn bd_rate_film_long_gop() { |
| 15249 | let _knobs = crate::speed::knob_write(); |
| 15250 | native_bd_arm("bd_rate_film_long_gop", 48, true); |
| 15251 | } |
| 15252 | |
| 15253 | /// The shared driver of the two native BD arms above: `frames` pictures |
| 15254 | /// per row (the sequence's `gop` is the same number, so one key frame), |
| 15255 | /// four quantizers, `films_only` dropping every row but the two real |
| 15256 | /// films. |
| 15257 | fn native_bd_arm(label: &str, frames: usize, films_only: bool) { |
| 15258 | if !have_ffmpeg() { |
| 15259 | eprintln!("SKIP {label}: no ffmpeg"); |
| 15260 | return; |
| 15261 | } |
| 15262 | let mut clips = native_gate_clips(); |
| 15263 | if films_only { |
| 15264 | clips.retain(|(name, _, _)| name.starts_with("film ")); |
| 15265 | } |
| 15266 | if clips.is_empty() { |
| 15267 | eprintln!("SKIP {label}: no clip"); |
| 15268 | return; |
| 15269 | } |
| 15270 | |
| 15271 | let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] |
| 15272 | .iter() |
| 15273 | .map(|q| { |
| 15274 | ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] |
| 15275 | .map(String::from) |
| 15276 | .to_vec() |
| 15277 | }) |
| 15278 | .collect(); |
| 15279 | let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] |
| 15280 | .iter() |
| 15281 | .map(|q| { |
| 15282 | vec![ |
| 15283 | "-rav1e-params".to_string(), |
| 15284 | format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), |
| 15285 | ] |
| 15286 | }) |
| 15287 | .collect(); |
| 15288 | println!( |
| 15289 | "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \ |
| 15290 | intrabc {}, palette maxcolors {}", |
| 15291 | armed_tiles(), |
| 15292 | crate::par::tile_threads(), |
| 15293 | intrabc_enabled(), |
| 15294 | palette_max_colors(), |
| 15295 | ); |
| 15296 | println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |"); |
| 15297 | println!("|---|---|---|---|---|"); |
| 15298 | for (name, path, seek) in &clips { |
| 15299 | let fctx = &crate::decode::FrameCtx::new(); |
| 15300 | if probe_dims(path).is_none() { |
| 15301 | eprintln!("SKIP {name}: ffprobe gave no size"); |
| 15302 | continue; |
| 15303 | } |
| 15304 | // A whole number of 128-wide superblocks, at most 1920x1024, out |
| 15305 | // of the middle of the frame; the offsets stay even for 4:2:0. |
| 15306 | // ONE definition, shared with `examples/enc_probe` so the probe |
| 15307 | // cannot measure a different window than this gate (lane-probe). |
| 15308 | let (vf, cw, ch) = match native_crop_override(path) { |
| 15309 | Some(over) => over, |
| 15310 | None => crate::probe::gate_crop(path), |
| 15311 | }; |
| 15312 | let source = clip_frames_vf(path, seek, &vf, cw, ch, frames); |
| 15313 | SCREEN_FRAMES.iter().for_each(|c| { |
| 15314 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 15315 | }); |
| 15316 | let _ = crate::tile::take_palette_hits(); |
| 15317 | let _ = crate::tile::take_palette_uv_hits(); |
| 15318 | let _ = crate::tile::take_intrabc_hits(); |
| 15319 | let _ = take_intrabc_search(); |
| 15320 | let _ = crate::tile::take_filter_intra_hits(); |
| 15321 | let _ = take_edge_census(); |
| 15322 | // The sequence path itself codes the pyramid now |
| 15323 | // (lane-av1pyrdef), and prints what it requested and what the |
| 15324 | // content gate left effective. |
| 15325 | let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx); |
| 15326 | // lane-sse: the blocks the true frame edge cuts through, and how |
| 15327 | // much of their RAW squared error sat in the padding the encoder |
| 15328 | // invented past it -- what the inside-only score stopped ranking |
| 15329 | // on. Empty on a superblock-aligned crop, which is every default |
| 15330 | // gate row (class `gate-blind-to-feature`). |
| 15331 | if edge_census() { |
| 15332 | for (side, n, inside, padding) in take_edge_census() { |
| 15333 | eprintln!( |
| 15334 | "{name}: edge {side}x{side} scores={n} inside_sse={inside} \ |
| 15335 | padding_sse={padding} ({:.1}% of raw)", |
| 15336 | 100.0 * padding as f64 / (inside + padding).max(1) as f64, |
| 15337 | ); |
| 15338 | } |
| 15339 | } |
| 15340 | // gate-blind-to-feature: what the screen tools actually did at |
| 15341 | // native resolution, over this clip's four encodes. |
| 15342 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 15343 | let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); |
| 15344 | // Which tables the SEARCH priced against, per frame arming |
| 15345 | // (`tile::arm_pricing_cdfs`): the default tables or the frame's |
| 15346 | // real starting ones. A film clip must show every inter arming on |
| 15347 | // the real side, a screen clip none of them. |
| 15348 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 15349 | eprintln!("{name}: pricer armings default={price_default} real={price_real}"); |
| 15350 | // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many |
| 15351 | // superblocks stayed whole, and how many of those coded a |
| 15352 | // residual, split that residual's luma, or took a compound |
| 15353 | // reference (class `gate-blind-to-feature`). |
| 15354 | eprintln!( |
| 15355 | "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})", |
| 15356 | take_b64_root_hits(), |
| 15357 | take_b64_residual_hits(), |
| 15358 | take_b64_var_tx_hits(), |
| 15359 | take_b64_compound_hits(), |
| 15360 | ); |
| 15361 | // lane-av1obmc2: the same motion_mode census the 640x384 gate |
| 15362 | // prints (class `gate-blind-to-feature`) -- how many blocks coded |
| 15363 | // the symbol at each footprint and how many took OBMC. Without it |
| 15364 | // the native table, which is the standing keep table, could not |
| 15365 | // say whether the tool fired at all. |
| 15366 | let mm = crate::tile::take_motion_mode_hits(); |
| 15367 | eprintln!( |
| 15368 | "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \ |
| 15369 | WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \ |
| 15370 | eligible)", |
| 15371 | mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8], |
| 15372 | 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 15373 | 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 15374 | mm.iter().sum::<usize>(), |
| 15375 | ); |
| 15376 | print_inter_tx_census(name); |
| 15377 | let palette = crate::tile::take_palette_hits(); |
| 15378 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 15379 | let ibc = crate::tile::take_intrabc_hits(); |
| 15380 | let search = take_intrabc_search(); |
| 15381 | eprintln!( |
| 15382 | "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \ |
| 15383 | palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \ |
| 15384 | won {})", |
| 15385 | 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64, |
| 15386 | palette[0], |
| 15387 | palette_uv[0], |
| 15388 | ibc[0], |
| 15389 | search[0], |
| 15390 | search[1], |
| 15391 | search[2], |
| 15392 | ); |
| 15393 | // gate-blind-to-feature: how often the five recursive filter-intra |
| 15394 | // modes actually won a block over this clip's four encodes -- a |
| 15395 | // tool that never fires is not measured by the row above it. |
| 15396 | let fi = crate::tile::take_filter_intra_hits(); |
| 15397 | eprintln!( |
| 15398 | "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})", |
| 15399 | filter_intra_on(), |
| 15400 | fi[0], |
| 15401 | fi[1], |
| 15402 | fi[2], |
| 15403 | fi[3], |
| 15404 | fi[4], |
| 15405 | fi[5], |
| 15406 | ); |
| 15407 | let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points); |
| 15408 | let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points); |
| 15409 | assert_monotone(&format!("{name}: ours"), &ours); |
| 15410 | assert_monotone(&format!("{name}: libaom"), &aom); |
| 15411 | assert_monotone(&format!("{name}: rav1e"), &rav1e); |
| 15412 | let points = ours |
| 15413 | .iter() |
| 15414 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 15415 | .collect::<Vec<_>>() |
| 15416 | .join(", "); |
| 15417 | println!( |
| 15418 | "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", |
| 15419 | bd_rate(&aom, &ours) * 100.0, |
| 15420 | bd_rate(&rav1e, &ours) * 100.0, |
| 15421 | ); |
| 15422 | } |
| 15423 | assert_ladder_decodes(); |
| 15424 | } |
| 15425 | |
| 15426 | /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator |
| 15427 | /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC) |
| 15428 | /// on the two film clips at their native gate crop. The 2160p clip loses |
| 15429 | /// at every arm of the propagating map and the named suspect was that its |
| 15430 | /// heavily filtered flat cells give a tiny denominator, so the dependence |
| 15431 | /// ratio explodes exactly where coding is cheap; this prints the numbers |
| 15432 | /// that confirm or refute it. |
| 15433 | #[test] |
| 15434 | #[ignore = "needs ffmpeg and the film fixtures"] |
| 15435 | fn tpl_intra_denominator_histogram() { |
| 15436 | let _knobs = crate::speed::knob_read(); |
| 15437 | if !have_ffmpeg() { |
| 15438 | eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg"); |
| 15439 | return; |
| 15440 | } |
| 15441 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 15442 | for (label, file) in [ |
| 15443 | ("bars 1080p", "h264-1080p-23.976-8bit.mp4"), |
| 15444 | ("bars 2160p", "h264-2160p-23.976-8bit.mp4"), |
| 15445 | ] { |
| 15446 | let path = fixtures.join("video").join(file); |
| 15447 | if !path.exists() { |
| 15448 | eprintln!("SKIP {label}: {file} missing"); |
| 15449 | continue; |
| 15450 | } |
| 15451 | let path = path.to_str().unwrap(); |
| 15452 | let Some((nw, nh)) = probe_dims(path) else { |
| 15453 | eprintln!("SKIP {label}: ffprobe gave no size"); |
| 15454 | continue; |
| 15455 | }; |
| 15456 | let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); |
| 15457 | let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 15458 | let source = |
| 15459 | clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8); |
| 15460 | let mut costs: Vec<f64> = Vec::new(); |
| 15461 | for pic in &source { |
| 15462 | let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect(); |
| 15463 | costs.extend( |
| 15464 | super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)), |
| 15465 | ); |
| 15466 | } |
| 15467 | let mean = costs.iter().sum::<f64>() / costs.len() as f64; |
| 15468 | let mut sorted = costs.clone(); |
| 15469 | sorted.sort_by(f64::total_cmp); |
| 15470 | let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean; |
| 15471 | let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count(); |
| 15472 | eprintln!( |
| 15473 | "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \ |
| 15474 | as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \ |
| 15475 | p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \ |
| 15476 | below 1.0x {} ({:.1}%)", |
| 15477 | costs.len(), |
| 15478 | q(0.0), |
| 15479 | q(0.01), |
| 15480 | q(0.05), |
| 15481 | q(0.25), |
| 15482 | q(0.50), |
| 15483 | q(0.75), |
| 15484 | q(0.99), |
| 15485 | q(1.0), |
| 15486 | below(0.25), |
| 15487 | 100.0 * below(0.25) as f64 / costs.len() as f64, |
| 15488 | below(0.5), |
| 15489 | 100.0 * below(0.5) as f64 / costs.len() as f64, |
| 15490 | below(1.0), |
| 15491 | 100.0 * below(1.0) as f64 / costs.len() as f64, |
| 15492 | ); |
| 15493 | } |
| 15494 | } |
| 15495 | |
| 15496 | /// The probe arms the gate's source (lane-probe, class `instrument |
| 15497 | /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg |
| 15498 | /// command line and had no `-ss`, so it read film B from frame 0 -- a |
| 15499 | /// black leader -- and coded 59 kB where the gate's own ladder point |
| 15500 | /// coded 89 kB of the same title; every census taken through it was |
| 15501 | /// probe-relative. Both now call [`crate::probe::source`]; this pins that |
| 15502 | /// the shared loader honours the seek (arming the probe's way and the |
| 15503 | /// gate's way gives byte-identical streams, and dropping the seek does |
| 15504 | /// not), on a synthetic clip whose content moves over time. |
| 15505 | #[test] |
| 15506 | fn the_probe_arms_the_gates_source() { |
| 15507 | let _knobs = crate::speed::knob_write(); |
| 15508 | if !have_ffmpeg() { |
| 15509 | eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg"); |
| 15510 | return; |
| 15511 | } |
| 15512 | let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id())); |
| 15513 | std::fs::create_dir_all(&dir).unwrap(); |
| 15514 | let clip = dir.join("testsrc2.y4m"); |
| 15515 | // 384x202: neither side is a multiple of 128, so the gate's centre |
| 15516 | // window is a real derivation and not the frame itself -- exactly the |
| 15517 | // shape film B has (3840x1608, never 3840x2160). |
| 15518 | let ok = Command::new("ffmpeg") |
| 15519 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"]) |
| 15520 | .args(["-frames:v", "20", "-pix_fmt", "yuv420p"]) |
| 15521 | .arg(&clip) |
| 15522 | .status() |
| 15523 | .expect("ffmpeg failed to run") |
| 15524 | .success(); |
| 15525 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 15526 | let path = clip.to_str().unwrap(); |
| 15527 | |
| 15528 | // The window: superblock-aligned, centred, even offsets. |
| 15529 | let (vf, w, h) = crate::probe::gate_crop(path); |
| 15530 | assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128)); |
| 15531 | |
| 15532 | let (seek, q) = ("00:00:01", 150u8); |
| 15533 | let gate = clip_frames_vf(path, seek, &vf, w, h, 6); |
| 15534 | let probe = crate::probe::source(path, seek, &vf, w, h, 6); |
| 15535 | assert!( |
| 15536 | gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v), |
| 15537 | "the probe's source differs from the gate's at the same window" |
| 15538 | ); |
| 15539 | let bytes = |src: &[Picture]| { |
| 15540 | encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::new()) |
| 15541 | .unwrap() |
| 15542 | .stream |
| 15543 | }; |
| 15544 | assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes"); |
| 15545 | // The two witnesses that both halves of the arming reach ffmpeg: the |
| 15546 | // seek, and the crop's own offset (the film-B defect in miniature -- |
| 15547 | // the probe was reading `crop=..:568` of a 1608-high frame). |
| 15548 | let unseeked = crate::probe::source(path, "0", &vf, w, h, 6); |
| 15549 | assert_ne!( |
| 15550 | bytes(&gate), |
| 15551 | bytes(&unseeked), |
| 15552 | "seeked and unseeked arming coded the same bytes -- the seek is inert" |
| 15553 | ); |
| 15554 | let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6); |
| 15555 | assert_ne!( |
| 15556 | bytes(&gate), |
| 15557 | bytes(&offset), |
| 15558 | "centred and top-aligned windows coded the same bytes -- the crop is inert" |
| 15559 | ); |
| 15560 | std::fs::remove_dir_all(&dir).ok(); |
| 15561 | } |
| 15562 | |
| 15563 | /// lane-probe diagnostic: the gate's own loader + ladder call for ONE |
| 15564 | /// point inside the test binary, to compare against `examples/enc_probe`. |
| 15565 | #[test] |
| 15566 | #[ignore = "diagnostic: needs ffmpeg and a clip"] |
| 15567 | fn probe_parity_point() { |
| 15568 | let _knobs = crate::speed::knob_write(); |
| 15569 | let g = |k: &str| std::env::var(k).unwrap(); |
| 15570 | let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap(); |
| 15571 | let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap(); |
| 15572 | let q: u8 = g("EC_PARITY_Q").parse().unwrap(); |
| 15573 | let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames); |
| 15574 | let fctx = &crate::decode::FrameCtx::new(); |
| 15575 | let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); |
| 15576 | let mut hash: u64 = 0xcbf2_9ce4_8422_2325; |
| 15577 | for &b in &e.stream { |
| 15578 | hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); |
| 15579 | } |
| 15580 | eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}", |
| 15581 | e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid()); |
| 15582 | } |
| 15583 | } |