edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 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_typed, |
| 45 | forward_and_quantize_typed_scaled, |
| 46 | }; |
| 47 | #[cfg(test)] |
| 48 | use crate::transform::forward_and_quantize; |
| 49 | |
| 50 | /// The side of the larger of the two luma blocks this encoder codes, in |
| 51 | /// samples. |
| 52 | const BLOCK: usize = 32; |
| 53 | |
| 54 | /// The side of the smaller one, which a 32x32 block may be split into four of. |
| 55 | const SUB: usize = 16; |
| 56 | |
| 57 | /// The side of a superblock, which is what the partition tree starts from. |
| 58 | pub(crate) const SUPERBLOCK: usize = 64; |
| 59 | |
| 60 | // lane-sb128 r1: the superblock size in samples the intra-reach rules |
| 61 | // (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the |
| 62 | // block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and |
| 63 | // tests the "top row"/"rightmost column" of THAT superblock, so a 128x128 |
| 64 | // superblock changes every answer inside it (the tables themselves are |
| 65 | // already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`] |
| 66 | // stays the encoder's own fixed 64. |
| 67 | |
| 68 | /// Sets the superblock size [`Reach`] answers against (64 or 128). |
| 69 | pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) { |
| 70 | fctx.reach_sb_px.with(|c| c.set(px)); |
| 71 | } |
| 72 | |
| 73 | fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize { |
| 74 | fctx.reach_sb_px.with(|c| c.get()) |
| 75 | } |
| 76 | |
| 77 | /// How heavily the mode search weighs rate against squared error, in units of |
| 78 | /// the quantizer's reconstruction step squared per bit. |
| 79 | /// |
| 80 | /// Swept three times over his clips and three synthetic pictures |
| 81 | /// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in |
| 82 | /// the three lane reports). The first sweep, before the mode symbol was |
| 83 | /// costed, put the best point at 0.05; costing it moved the point to 0.1. The |
| 84 | /// third sweep, after the levels were costed through the writer's own CDFs |
| 85 | /// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98% |
| 86 | /// on film and -0.20% against -0.14% on screen capture. |
| 87 | /// |
| 88 | /// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than |
| 89 | /// those ladders, and 0.1 was far off the point: the rate term was carrying |
| 90 | /// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom / |
| 91 | /// vs rav1e for 1080p film, 2160p film, screen capture: |
| 92 | /// |
| 93 | /// | lambda | 1080p | 2160p | screen | |
| 94 | /// |--------|-------|-------|--------| |
| 95 | /// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 | |
| 96 | /// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 | |
| 97 | /// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 | |
| 98 | /// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 | |
| 99 | /// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 | |
| 100 | /// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 | |
| 101 | /// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 | |
| 102 | /// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 | |
| 103 | /// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 | |
| 104 | /// |
| 105 | /// and on the native 1920x1024 crops, which is the table that decides: |
| 106 | /// |
| 107 | /// | lambda | film 1080p | film 2160p | screen | |
| 108 | /// |--------|------------|------------|--------| |
| 109 | /// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 | |
| 110 | /// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 | |
| 111 | /// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 | |
| 112 | /// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 | |
| 113 | /// |
| 114 | /// 0.0375 was the best point on two clips of three there and cost the "2160p |
| 115 | /// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept |
| 116 | /// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the |
| 117 | /// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of |
| 118 | /// whose cells have no intra cost -- no real film supported the point. |
| 119 | /// |
| 120 | /// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL |
| 121 | /// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs |
| 122 | /// libaom / vs rav1e, everything else at the shipped defaults: |
| 123 | /// |
| 124 | /// | lambda | bars 1080p | bars 2160p | film A | film B | screen | |
| 125 | /// |--------|------------|------------|--------|--------|--------| |
| 126 | /// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 | |
| 127 | /// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 | |
| 128 | /// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 | |
| 129 | /// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 | |
| 130 | /// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 | |
| 131 | /// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 | |
| 132 | /// |
| 133 | /// Real film wants roughly HALF the rate weight the bars asked for: the bowl |
| 134 | /// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep |
| 135 | /// against the shipped 0.05, while the bars rows walk the other way (they are |
| 136 | /// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so |
| 137 | /// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture |
| 138 | /// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx |
| 139 | /// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall. |
| 140 | const LAMBDA_SCALE: f64 = 0.0275; |
| 141 | |
| 142 | /// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes |
| 143 | /// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen). |
| 144 | /// |
| 145 | /// The ARF-vs-ARF census says our top ARF codes residual over HALF its area |
| 146 | /// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x |
| 147 | /// its bytes at the same PSNR, while every leaf that predicts from it is |
| 148 | /// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at |
| 149 | /// a rate weight fitted on shown frames and does not propagate. This is the |
| 150 | /// one knob that prices a hidden frame's rate differently from its q, which |
| 151 | /// the pyramid's q offsets cannot do (they move lambda and step together). |
| 152 | const HIDDEN_LAMBDA_FACTOR: f64 = 1.0; |
| 153 | |
| 154 | /// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build. |
| 155 | fn hidden_lambda_factor() -> f64 { |
| 156 | match std::env::var("EC_AV1_LAMBDA_HIDDEN").ok().and_then(|v| v.parse().ok()) { |
| 157 | Some(f) => f, |
| 158 | None => HIDDEN_LAMBDA_FACTOR, |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that |
| 163 | /// picks it is the thing running. A release build has no such knob. |
| 164 | fn lambda_scale() -> f64 { |
| 165 | let swept = std::env::var("EC_AV1_LAMBDA") |
| 166 | .ok() |
| 167 | .and_then(|v| v.parse::<f64>().ok()); |
| 168 | match swept { |
| 169 | Some(scale) if cfg!(test) => scale, |
| 170 | _ => LAMBDA_SCALE, |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// How a key frame's lambda differs from an inter frame's: libaom weighs the |
| 175 | /// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out |
| 176 | /// of 128), because every later frame predicts from the key frame, so an error |
| 177 | /// left in it is paid for over the whole group. This encoder has no temporal |
| 178 | /// propagation model at all, and this factor is the cheapest stand-in for one. |
| 179 | /// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`]. |
| 180 | /// |
| 181 | /// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs |
| 182 | /// libaom / vs rav1e: |
| 183 | /// |
| 184 | /// | k_key | 1080p | 2160p | screen | |
| 185 | /// |---|---|---|---| |
| 186 | /// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 | |
| 187 | /// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 | |
| 188 | /// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 | |
| 189 | /// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 | |
| 190 | /// |
| 191 | /// The two films want the key frame coded finer and the screen capture wants |
| 192 | /// the opposite, by about the same amount, and at native the whole lever is |
| 193 | /// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3, |
| 194 | /// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2, |
| 195 | /// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a |
| 196 | /// per-frame-type weight; the real lever here is temporal propagation |
| 197 | /// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames |
| 198 | /// predict from, not each frame. |
| 199 | const KEY_LAMBDA_FACTOR: f64 = 1.0; |
| 200 | |
| 201 | /// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build. |
| 202 | fn key_lambda_factor() -> f64 { |
| 203 | match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) { |
| 204 | Some(k) if cfg!(test) => k, |
| 205 | _ => KEY_LAMBDA_FACTOR, |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // Every frame's predicted coefficient bits since the last |
| 210 | // `take_predicted_bits`, in coding order -- the encoder half of |
| 211 | // `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement. |
| 212 | #[cfg(test)] |
| 213 | thread_local! { |
| 214 | static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) }; |
| 215 | } |
| 216 | |
| 217 | /// Records one frame's predicted coefficient bits. |
| 218 | #[cfg(test)] |
| 219 | fn record_predicted_bits(bits: f64) { |
| 220 | PREDICTED_BITS.with(|p| p.borrow_mut().push(bits)); |
| 221 | } |
| 222 | |
| 223 | /// Takes (and clears) what the frames encoded on this thread were predicted to |
| 224 | /// spend on coefficients. |
| 225 | #[cfg(test)] |
| 226 | pub(crate) fn take_predicted_bits() -> Vec<f64> { |
| 227 | PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut())) |
| 228 | } |
| 229 | |
| 230 | /// Whether a 16x16 inter leaf may split into four 8x8 ones of its own. |
| 231 | pub(crate) const SPLIT_INTER_8: bool = true; |
| 232 | |
| 233 | /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build. |
| 234 | /// Whether a key frame codes `tx_mode == TxMode::Select` and searches each |
| 235 | /// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0` |
| 236 | /// turns it off for an A/B on one build. |
| 237 | /// Whether an INTER frame also carries `TxMode::Select`: an inter block's |
| 238 | /// residual as one transform over the whole block or as the four transforms |
| 239 | /// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every |
| 240 | /// intra block inside the inter frame. ON since lane-av1tx2, which found why |
| 241 | /// the streams desynced -- the writer counted the [`crate::decode:: |
| 242 | /// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the |
| 243 | /// reader drops the term -- and measured the split search: BD-rate vs libaom |
| 244 | /// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the |
| 245 | /// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an |
| 246 | /// A/B on one build. |
| 247 | fn tx_select_inter() -> bool { |
| 248 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 249 | crate::envflags::var("EC_AV1_TX_SELECT_INTER") |
| 250 | .ok() |
| 251 | .map(|v| !matches!(v.as_str(), "0" | "off")) |
| 252 | }); |
| 253 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER)) |
| 254 | } |
| 255 | |
| 256 | /// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control |
| 257 | /// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points |
| 258 | /// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 -> |
| 259 | /// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1. |
| 260 | /// The keep rule wants both films down, so this takes the same content gate |
| 261 | /// palette, intrabc and the angle-delta refinement already stand behind: a |
| 262 | /// non-screen frame is byte-identical to the encoder before the lane. |
| 263 | /// |
| 264 | /// The transform types an intra luma transform unit of `set` may be coded |
| 265 | /// with -- exactly the alphabet the writer's `tx_type` symbol names for that |
| 266 | /// set, so a searched type is always one the tile can express (lane-txset). |
| 267 | /// `DCT_DCT` first: it is the incumbent every other candidate has to beat. |
| 268 | /// |
| 269 | /// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16 |
| 270 | /// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types |
| 271 | /// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all, |
| 272 | /// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT` |
| 273 | /// here. |
| 274 | pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] { |
| 275 | const DCT: [TxType; 1] = [TxType::DctDct]; |
| 276 | const INTRA1: [TxType; 7] = [ |
| 277 | TxType::DctDct, |
| 278 | TxType::AdstAdst, |
| 279 | TxType::AdstDct, |
| 280 | TxType::DctAdst, |
| 281 | TxType::Idtx, |
| 282 | TxType::VDct, |
| 283 | TxType::HDct, |
| 284 | ]; |
| 285 | const INTRA2: [TxType; 5] = [ |
| 286 | TxType::DctDct, |
| 287 | TxType::AdstAdst, |
| 288 | TxType::AdstDct, |
| 289 | TxType::DctAdst, |
| 290 | TxType::Idtx, |
| 291 | ]; |
| 292 | match set { |
| 293 | TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 |
| 294 | if intra_tx_search_on(screen) => |
| 295 | { |
| 296 | &INTRA2 |
| 297 | } |
| 298 | // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the |
| 299 | // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`; |
| 300 | // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two |
| 301 | // extra members are the 1-D DCTs, and the order is the reader's own |
| 302 | // map (`decode::tx_type_from_symbol`, 8-wide CDF). |
| 303 | TxbSet::Luma8Set1 | TxbSet::Luma4Set1 |
| 304 | if intra_tx_search_on(screen) => |
| 305 | { |
| 306 | &INTRA1 |
| 307 | } |
| 308 | _ => &DCT, |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /// The transform types an INTER luma transform unit of `set` may be coded |
| 313 | /// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every |
| 314 | /// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3` |
| 315 | /// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two |
| 316 | /// types, a symbol the writer already codes and never varied. 64x64 codes no |
| 317 | /// `tx_type` symbol at all, so it is not offered one. |
| 318 | /// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the |
| 319 | /// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars |
| 320 | /// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 -> |
| 321 | /// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its |
| 322 | /// loudest, and restricting the offer to 16x16 and below does not soften it |
| 323 | /// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the |
| 324 | /// intra search, palette and intrabc stand behind: a non-screen frame is |
| 325 | /// byte-identical to the encoder before the lane. |
| 326 | /// |
| 327 | /// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16` |
| 328 | /// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT` |
| 329 | /// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else |
| 330 | /// on for every frame at every size. |
| 331 | pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] { |
| 332 | const DCT: [TxType; 1] = [TxType::DctDct]; |
| 333 | const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx]; |
| 334 | const INTER_WIDE: [TxType; 7] = [ |
| 335 | TxType::DctDct, |
| 336 | TxType::AdstAdst, |
| 337 | TxType::AdstDct, |
| 338 | TxType::DctAdst, |
| 339 | TxType::Idtx, |
| 340 | TxType::VDct, |
| 341 | TxType::HDct, |
| 342 | ]; |
| 343 | let mode = inter_tx_type_search(); |
| 344 | let on = match mode { |
| 345 | InterTxSearch::Off => false, |
| 346 | InterTxSearch::Screen => screen, |
| 347 | InterTxSearch::All | InterTxSearch::Le16 => true, |
| 348 | }; |
| 349 | match set { |
| 350 | TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3, |
| 351 | TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3, |
| 352 | // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the |
| 353 | // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32 |
| 354 | // stays the two-type `DCT_IDTX`). The seven offered here are the |
| 355 | // members those two alphabets SHARE with the intra set -- the four |
| 356 | // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the |
| 357 | // candidate list rav1e's speed 6 prunes to; the FLIPADST family and |
| 358 | // the 1-D ADSTs are codable and left unoffered (deferred). |
| 359 | TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => { |
| 360 | &INTER_WIDE |
| 361 | } |
| 362 | _ => &DCT, |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | /// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e. |
| 367 | /// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below? |
| 368 | /// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything |
| 369 | /// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated |
| 370 | /// like both halves of the type search itself. |
| 371 | pub(crate) fn wide_tx_set(screen: bool) -> bool { |
| 372 | match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 373 | 0 => return false, |
| 374 | 1 => return true, |
| 375 | _ => {} |
| 376 | } |
| 377 | static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| { |
| 378 | crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() { |
| 379 | "0" | "off" => InterTxSearch::Off, |
| 380 | "screen" => InterTxSearch::Screen, |
| 381 | _ => InterTxSearch::All, |
| 382 | }) |
| 383 | }); |
| 384 | match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) { |
| 385 | InterTxSearch::Screen |
| 386 | } else { |
| 387 | InterTxSearch::Off |
| 388 | }) { |
| 389 | InterTxSearch::Off => false, |
| 390 | InterTxSearch::Screen => screen, |
| 391 | _ => true, |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | /// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the |
| 396 | /// environment and the preset (`u8::MAX` = unset), the shape |
| 397 | /// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the |
| 398 | /// witness that has to see the wider alphabets turns it on through this while |
| 399 | /// holding [`crate::speed::knob_write`]. |
| 400 | static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 401 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 402 | |
| 403 | /// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it. |
| 404 | #[allow(dead_code)] // set only from the `#[cfg(test)]` gates |
| 405 | pub(crate) fn set_wide_tx_set(on: Option<bool>) { |
| 406 | WIDE_TX_OVERRIDE.store( |
| 407 | on.map_or(u8::MAX, u8::from), |
| 408 | std::sync::atomic::Ordering::Relaxed, |
| 409 | ); |
| 410 | } |
| 411 | |
| 412 | /// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes |
| 413 | /// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own |
| 414 | /// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read |
| 415 | /// the same alphabet or the two disagree on what a `tx_type` symbol costs. |
| 416 | pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet { |
| 417 | if wide_tx_set(screen) { |
| 418 | set.wide() |
| 419 | } else { |
| 420 | set |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | #[derive(Clone, Copy, PartialEq)] |
| 425 | pub(crate) enum InterTxSearch { |
| 426 | Off, |
| 427 | Screen, |
| 428 | /// 16x16 and below only. |
| 429 | Le16, |
| 430 | All, |
| 431 | } |
| 432 | |
| 433 | /// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the |
| 434 | /// environment and the preset (`u8::MAX` = unset), the shape |
| 435 | /// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness |
| 436 | /// that has to see a non-`DCT_DCT` inter unit turns it on through this while |
| 437 | /// holding [`crate::speed::knob_write`]. |
| 438 | static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 439 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 440 | |
| 441 | /// Sets [`INTER_TX_OVERRIDE`]; `None` clears it. |
| 442 | #[allow(dead_code)] // set only from the `#[cfg(test)]` gates |
| 443 | pub(crate) fn set_inter_tx_search(on: Option<bool>) { |
| 444 | INTER_TX_OVERRIDE.store( |
| 445 | on.map_or(u8::MAX, u8::from), |
| 446 | std::sync::atomic::Ordering::Relaxed, |
| 447 | ); |
| 448 | } |
| 449 | |
| 450 | fn inter_tx_type_search() -> InterTxSearch { |
| 451 | match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 452 | 0 => return InterTxSearch::Off, |
| 453 | 1 => return InterTxSearch::All, |
| 454 | _ => {} |
| 455 | } |
| 456 | static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| { |
| 457 | crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() { |
| 458 | "0" | "off" => InterTxSearch::Off, |
| 459 | "screen" => InterTxSearch::Screen, |
| 460 | "le16" => InterTxSearch::Le16, |
| 461 | _ => InterTxSearch::All, |
| 462 | }) |
| 463 | }); |
| 464 | ENV.unwrap_or_else(|| { |
| 465 | if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) { |
| 466 | InterTxSearch::Screen |
| 467 | } else { |
| 468 | InterTxSearch::Off |
| 469 | } |
| 470 | }) |
| 471 | } |
| 472 | |
| 473 | /// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the |
| 474 | /// 64-point one (it codes no `tx_type` symbol). |
| 475 | /// lane-txw history, resolved by lane-intertx: the INTER half of the |
| 476 | /// widening was blocked by `refusal-from-own-desync` twice over. Half of it |
| 477 | /// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D` |
| 478 | /// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra |
| 479 | /// half). The other half was the CHROMA inheritance: an inter block's |
| 480 | /// chroma transform type is the luma type reduced to the chroma size's set |
| 481 | /// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never |
| 482 | /// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced |
| 483 | /// against a STALE allowance, and (b) `tile::write_block_planes` coded |
| 484 | /// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the |
| 485 | /// chroma exactly as luma did. lane-intertx fixed both -- the frame sets |
| 486 | /// its own bit on the context (`encode_inter_frame`), the writer derives |
| 487 | /// the chroma type from this frame's own header bit |
| 488 | /// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH |
| 489 | /// names these sets through [`luma_set_for`] at its call sites, so the |
| 490 | /// wider candidates are reachable and honestly priced. The intra half |
| 491 | /// never needed either (an intra block's chroma type comes off its own UV |
| 492 | /// mode, never off luma). |
| 493 | fn inter_luma_set(tx: usize) -> Option<TxbSet> { |
| 494 | Some(match tx { |
| 495 | 4 => TxbSet::Luma4Inter, |
| 496 | 8 => TxbSet::Luma8Inter, |
| 497 | 16 => TxbSet::Luma16Inter, |
| 498 | 32 => TxbSet::Luma32Inter, |
| 499 | _ => return None, |
| 500 | }) |
| 501 | } |
| 502 | |
| 503 | fn tx_type_search() -> bool { |
| 504 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 505 | crate::envflags::var("EC_AV1_TXSET") |
| 506 | .ok() |
| 507 | .map(|v| !matches!(v.as_str(), "0" | "off")) |
| 508 | }); |
| 509 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH)) |
| 510 | } |
| 511 | |
| 512 | /// Whether an intra luma unit of this frame searches its own type at all: |
| 513 | /// the preset lever ([`tx_type_search`]) under the screen content gate, which |
| 514 | /// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global |
| 515 | /// [`set_intra_tx_search`] override wins over (the witness needs the search |
| 516 | /// on a frame the detector called non-screen). |
| 517 | fn intra_tx_search_on(screen: bool) -> bool { |
| 518 | match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 519 | 0 => return false, |
| 520 | 1 => return true, |
| 521 | _ => {} |
| 522 | } |
| 523 | (screen || intra_tx_all_frames()) && tx_type_search() |
| 524 | } |
| 525 | |
| 526 | /// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the |
| 527 | /// shape [`set_inter_tx_search`] has. |
| 528 | static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 529 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 530 | |
| 531 | /// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it. |
| 532 | #[allow(dead_code)] // set only from the `#[cfg(test)]` gates |
| 533 | pub(crate) fn set_intra_tx_search(on: Option<bool>) { |
| 534 | INTRA_TX_OVERRIDE.store( |
| 535 | on.map_or(u8::MAX, u8::from), |
| 536 | std::sync::atomic::Ordering::Relaxed, |
| 537 | ); |
| 538 | } |
| 539 | |
| 540 | /// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY |
| 541 | /// frame -- the unconditional arm the gate measures -- instead of the screen |
| 542 | /// content gate [`tx_type_candidates`] ships behind. Any other value keeps |
| 543 | /// the gate (`0`/`off` still switches the search off entirely). |
| 544 | fn intra_tx_all_frames() -> bool { |
| 545 | static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| { |
| 546 | crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all") |
| 547 | }); |
| 548 | *ENV |
| 549 | } |
| 550 | |
| 551 | fn tx_select() -> bool { |
| 552 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 553 | crate::envflags::var("EC_AV1_TX_SELECT") |
| 554 | .ok() |
| 555 | .map(|v| !matches!(v.as_str(), "0" | "off")) |
| 556 | }); |
| 557 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY)) |
| 558 | } |
| 559 | |
| 560 | fn split_inter_8() -> bool { |
| 561 | match std::env::var("EC_AV1_SPLIT_INTER8").ok() { |
| 562 | Some(v) if cfg!(test) => v != "0", |
| 563 | _ => crate::speed::at(&crate::speed::SPLIT_8), |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | /// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the |
| 568 | /// NEARESTMV candidate it always had. |
| 569 | pub(crate) const LEAF_NEW_MV: bool = true; |
| 570 | |
| 571 | /// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the |
| 572 | /// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0 |
| 573 | /// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion |
| 574 | /// searches (the census `bd_rate_vs_libaom_and_rav1e` prints). |
| 575 | pub(crate) const EXTRA_REF_NEW_MV: bool = true; |
| 576 | |
| 577 | /// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's |
| 578 | /// own best vector before that reference's `NEWMV` search is skipped: a |
| 579 | /// factor on the search cost scale, `1.0` meaning "as good or better". |
| 580 | /// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`, |
| 581 | /// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9 |
| 582 | /// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the |
| 583 | /// extra searches drop from +27% to +4% of the base count -- and on screen |
| 584 | /// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of |
| 585 | /// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7). |
| 586 | /// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25 |
| 587 | /// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7, |
| 588 | /// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1, |
| 589 | /// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's |
| 590 | /// own noise. 0.35 stays; the lever that did move at the new rate weight is |
| 591 | /// [`LEAF_SECOND_NEW_MARGIN`], not this one. |
| 592 | const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35; |
| 593 | |
| 594 | /// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`. |
| 595 | fn extra_new_skip_margin() -> f64 { |
| 596 | match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() { |
| 597 | Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN), |
| 598 | _ => EXTRA_NEW_SKIP_MARGIN, |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | /// The margin on a LEAF's SECOND-reference motion search, the same early-out |
| 603 | /// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference |
| 604 | /// `NEWMV`: the search is skipped when that reference's own |
| 605 | /// `NEAREST_NEARESTMV` vector already prices this many times better than the |
| 606 | /// leaf's `LAST` search found. `0.0` never skips. |
| 607 | /// |
| 608 | /// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs |
| 609 | /// libaom (1080p/2160p/screen) against the extra `motion::search` calls at |
| 610 | /// 2160p (38195 with no second-reference search at all): |
| 611 | /// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093, |
| 612 | /// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at |
| 613 | /// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the |
| 614 | /// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter |
| 615 | /// of its extra searches; past it the calls double for another -0.3/-0.5. |
| 616 | /// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is |
| 617 | /// all `NEAREST_NEARESTMV` and no searched second vector ever wins there -- |
| 618 | /// so the margin is pure wall on that content (+10% searches at 0.8). |
| 619 | /// |
| 620 | /// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on |
| 621 | /// the native gate with local warp on, BD vs libaom / vs rav1e: |
| 622 | /// |
| 623 | /// | margin | film 1080p | film 2160p | screen | |
| 624 | /// |---|---|---|---| |
| 625 | /// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 | |
| 626 | /// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 | |
| 627 | /// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 | |
| 628 | /// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 | |
| 629 | /// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 | |
| 630 | /// |
| 631 | /// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns |
| 632 | /// with screen flat -- and it beats never-skipping, i.e. the early-out is |
| 633 | /// still worth having, just at a looser margin than the old rate weight |
| 634 | /// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs |
| 635 | /// 32.6s at 2160p), which is the price of the extra second-reference |
| 636 | /// searches. |
| 637 | const LEAF_SECOND_NEW_MARGIN: f64 = 1.2; |
| 638 | |
| 639 | /// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the |
| 640 | /// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`. |
| 641 | fn leaf_second_new_margin() -> f64 { |
| 642 | match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() { |
| 643 | Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN), |
| 644 | None => LEAF_SECOND_NEW_MARGIN, |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | /// Whether a leaf searches its SECOND reference at all (lane-av1comp4). |
| 649 | fn leaf_second_new_mv() -> bool { |
| 650 | match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() { |
| 651 | Some(v) => v != "0", |
| 652 | None => crate::speed::at(&crate::speed::LEAF_SECOND), |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | /// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the |
| 657 | /// whole 32x32 block is (lane-av1comp3). The writer already codes a compound |
| 658 | /// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both |
| 659 | /// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what |
| 660 | /// was missing was the encoder ever forming one below 32x32. |
| 661 | pub(crate) const LEAF_COMPOUND: bool = true; |
| 662 | |
| 663 | /// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build. |
| 664 | fn leaf_compound() -> bool { |
| 665 | match std::env::var("EC_AV1_LEAF_COMPOUND").ok() { |
| 666 | Some(v) => v != "0", |
| 667 | None => crate::speed::at(&crate::speed::LEAF_COMPOUND), |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build. |
| 672 | fn leaf_new_mv() -> bool { |
| 673 | match std::env::var("EC_AV1_LEAF_NEWMV").ok() { |
| 674 | Some(v) if cfg!(test) => v != "0", |
| 675 | _ => LEAF_NEW_MV, |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | /// Whether an INTER frame's 32x32 block may be split into four 16x16 ones |
| 680 | /// when the trial says four cost less. Before lane-av1rd2 only a quadrant |
| 681 | /// the true frame edge cut through was ever split there; inside the frame |
| 682 | /// every block was coded whole, which left the partition decision the key |
| 683 | /// frame already makes unmade for eleven frames out of twelve. |
| 684 | pub(crate) const SPLIT_INTER_BLOCKS: bool = true; |
| 685 | |
| 686 | /// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the |
| 687 | /// measurement that keeps it is running (test builds only, like |
| 688 | /// [`lambda_scale`]). |
| 689 | fn split_inter_blocks() -> bool { |
| 690 | match std::env::var("EC_AV1_SPLIT_INTER").ok() { |
| 691 | Some(v) if cfg!(test) => v != "0", |
| 692 | _ => crate::speed::at(&crate::speed::SPLIT_INTER), |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | /// Whether the inter search offers the whole superblock as ONE 64x64 block |
| 697 | /// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32 |
| 698 | /// quadrants it would otherwise always split into. |
| 699 | /// |
| 700 | /// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6 |
| 701 | /// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of |
| 702 | /// them skip at 328 bytes a frame -- while every block this encoder wrote was |
| 703 | /// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669 |
| 704 | /// bits against rav1e's 61,988, about 46% of the film B gap. |
| 705 | /// |
| 706 | /// lane-tx64: no longer skip-only. The root also prices a REAL residual -- |
| 707 | /// one TX_64X64 luma transform (`transform.rs`'s forward network has always |
| 708 | /// reached 64 points; what was missing was the block coder and the writer |
| 709 | /// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`], |
| 710 | /// which carries that arm's own gate table. Still refused at the 64 root: |
| 711 | /// compound references, a depth-1 4x32x32 var-tx tree, intra, and a |
| 712 | /// superblock the true frame edge cuts through. |
| 713 | /// |
| 714 | /// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the |
| 715 | /// root and restores the skip-only shape lane-b64 shipped. |
| 716 | pub(crate) const B64_ROOT: bool = true; |
| 717 | |
| 718 | /// How many superblocks took the 64x64 root since the last |
| 719 | /// [`take_b64_root_hits`], so a gate reports how often it fires rather than |
| 720 | /// assuming it does (class `gate-blind-to-feature`). |
| 721 | static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 722 | |
| 723 | /// The 64x64-root count since the last call, and zero it. |
| 724 | pub fn take_b64_root_hits() -> usize { |
| 725 | B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 726 | } |
| 727 | |
| 728 | /// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at |
| 729 | /// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off, |
| 730 | /// which is the attribution arm for a 128-superblock stream: it separates |
| 731 | /// what the SIZE costs from what the 128x128 BLOCK buys. |
| 732 | fn b128_root() -> bool { |
| 733 | static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| { |
| 734 | crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0") |
| 735 | }); |
| 736 | *ENV |
| 737 | } |
| 738 | |
| 739 | /// lane-b128r: whether the 128 root prices a REAL residual as well as the |
| 740 | /// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma |
| 741 | /// pair per 64x64 mu chunk, var-tx depth 0 (the shape |
| 742 | /// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block` |
| 743 | /// reads). Written, witnessed and byte-exact through both decoders, and |
| 744 | /// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT |
| 745 | /// on content: the RD takes it 0.7-1.9 times per frame against thousands of |
| 746 | /// whole 128 roots (lane-b128res census, native 12-frame gate, every clip), |
| 747 | /// and the BD effect is inside the noise on both gates -- long-GOP films |
| 748 | /// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default. |
| 749 | /// |
| 750 | /// The historical reason for the parking is CLOSED: the bars 2160p q=90 |
| 751 | /// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a |
| 752 | /// 128-superblock horizontal edge) was the CDEF search pricing a preset per |
| 753 | /// 64x64 unit under a root that codes ONE literal for all four -- lane- |
| 754 | /// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one |
| 755 | /// the decoder derives, and on this HEAD the same row re-measures three-way |
| 756 | /// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame, |
| 757 | /// every plane, both gates). The knob stays as the arm's gate, not as a |
| 758 | /// defect flag. |
| 759 | fn b128_residual() -> bool { |
| 760 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 761 | crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0") |
| 762 | }); |
| 763 | (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed)) |
| 764 | && b128_root() |
| 765 | } |
| 766 | /// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two |
| 767 | /// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares |
| 768 | /// plus one half) -- price a REAL residual in the RD as well as the skip arm |
| 769 | /// ([`search_root_128_rect`] / [`search_root_128_ab`], written through |
| 770 | /// [`crate::tile::write_inter_block_128_rect`]). **Off by default** |
| 771 | /// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit -- |
| 772 | /// no rect/AB piece can come out non-skip, so the writer's refusal is never |
| 773 | /// reached. The residual shape is the whole 128 block's, halved or quartered |
| 774 | /// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64 |
| 775 | /// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads |
| 776 | /// for any inter partition shape). |
| 777 | fn rectres() -> bool { |
| 778 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 779 | crate::envflags::var("EC_AV1_RECTRES") |
| 780 | .ok() |
| 781 | .map(|v| v != "0") |
| 782 | }); |
| 783 | ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) |
| 784 | } |
| 785 | |
| 786 | /// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a |
| 787 | /// witness clip codes the shape rather than waiting for content on which the |
| 788 | /// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE |
| 789 | /// root). Never read outside `#[cfg(test)]` builds. |
| 790 | static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool = |
| 791 | std::sync::atomic::AtomicBool::new(false); |
| 792 | |
| 793 | /// Arms [`FORCE_B128_RECTRES`] for the rest of the process. |
| 794 | #[cfg(test)] |
| 795 | pub(crate) fn force_b128_rectres(on: bool) { |
| 796 | FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed); |
| 797 | } |
| 798 | |
| 799 | /// How many rect/AB pieces the search left WITH a residual rather than |
| 800 | /// skipped, since the last [`take_b128_rectres_hits`] (class |
| 801 | /// `gate-blind-to-feature`). |
| 802 | static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize = |
| 803 | std::sync::atomic::AtomicUsize::new(0); |
| 804 | |
| 805 | /// The rect/AB-piece-residual count since the last call, and zero it. |
| 806 | pub fn take_b128_rectres_hits() -> usize { |
| 807 | B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 808 | } |
| 809 | |
| 810 | /// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64 |
| 811 | /// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, |
| 812 | /// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's |
| 813 | /// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this |
| 814 | /// arm's attribution control; the writer has always had the path |
| 815 | /// (`write_inter_block_128` calls `write_compound_block` for a block that |
| 816 | /// names a second reference). |
| 817 | fn b128_compound() -> bool { |
| 818 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 819 | crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0") |
| 820 | }); |
| 821 | ENV.unwrap_or(true) && b128_root() |
| 822 | } |
| 823 | |
| 824 | /// How many 128 roots came out COMPOUND since the last |
| 825 | /// [`take_b128_compound_hits`] (class `gate-blind-to-feature`). |
| 826 | static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = |
| 827 | std::sync::atomic::AtomicUsize::new(0); |
| 828 | |
| 829 | /// The compound-128 count since the last call, and zero it. |
| 830 | pub fn take_b128_compound_hits() -> usize { |
| 831 | B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 832 | } |
| 833 | |
| 834 | /// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ` |
| 835 | /// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the |
| 836 | /// same skip-only single-reference/compound machinery the NONE arm ships, |
| 837 | /// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`). |
| 838 | /// `EC_AV1_B128HV=0` is this arm's attribution control. |
| 839 | fn b128_rect() -> bool { |
| 840 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 841 | crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0") |
| 842 | }); |
| 843 | ENV.unwrap_or(true) && b128_root() |
| 844 | } |
| 845 | |
| 846 | /// lane-rectdq: whether the delta_q symbol group is priced on the root |
| 847 | /// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's |
| 848 | /// attribution control (the pre-lane pricing, where a 128 rect root and the |
| 849 | /// four-superblock arm were both priced as if the group were free). |
| 850 | fn rectdq() -> bool { |
| 851 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 852 | crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0") |
| 853 | }); |
| 854 | ENV.unwrap_or(true) |
| 855 | } |
| 856 | |
| 857 | /// lane-rectdq: what `crate::tile::write_delta_q` spends to move |
| 858 | /// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of |
| 859 | /// `res` -- the same three pieces that writer codes, in its order: the |
| 860 | /// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the |
| 861 | /// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from |
| 862 | /// exactly this row), the escape literal pair when `abs >= 3`, and the sign |
| 863 | /// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`). |
| 864 | pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 { |
| 865 | if res <= 0 { |
| 866 | return 0.0; |
| 867 | } |
| 868 | /// spec `DELTA_Q_SMALL`, as in the writer. |
| 869 | const DELTA_Q_SMALL: usize = 3; |
| 870 | let reduced = (target - cur) / res; |
| 871 | let abs = reduced.unsigned_abs() as usize; |
| 872 | // A pricing coder, not a sum of table entries: the escape's literal bits |
| 873 | // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB` |
| 874 | // floor, so each really costs a little over one bit (class |
| 875 | // `price-the-narrowing-not-the-table`). Read off the same |
| 876 | // `SymbolEncoder::bits` account the writer's own coder keeps. |
| 877 | let mut enc = crate::msac::SymbolEncoder::pricer(); |
| 878 | enc.reset_bits(); |
| 879 | enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q); |
| 880 | if abs >= DELTA_Q_SMALL { |
| 881 | let rem_bits = 31 - ((abs as u32) - 1).leading_zeros(); |
| 882 | enc.literal(rem_bits - 1, 3); |
| 883 | enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits); |
| 884 | } |
| 885 | if abs != 0 { |
| 886 | enc.literal(u32::from(reduced < 0), 1); |
| 887 | } |
| 888 | enc.bits() |
| 889 | } |
| 890 | |
| 891 | /// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64 |
| 892 | /// superblock units): the group every root shape but a SKIPPED |
| 893 | /// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for |
| 894 | /// `side == write_w == write_h == sb_px` and neither a rect half nor a 64 |
| 895 | /// superblock under a 128 grid is that. |
| 896 | /// |
| 897 | /// The target is the root's own cell of the `sb_q` grid, exactly the entry |
| 898 | /// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search -- |
| 899 | /// the writer's `plan.cur` only advances at the roots that really code a |
| 900 | /// group, and which those are is decided by this very comparison -- so the |
| 901 | /// PREVIOUS 128 root's target in raster order stands in for it (the frame's |
| 902 | /// `base_q_idx` at the first root of the frame, which is also the writer's |
| 903 | /// own per-tile reset). Wrong only where a neighbouring root came out a |
| 904 | /// skipped NONE block, and then only by the difference of two adjacent tpl |
| 905 | /// cells. |
| 906 | fn delta_q_bits_at_root( |
| 907 | sb_q: Option<&Vec<u8>>, |
| 908 | sb_cols: usize, |
| 909 | base_q_idx: u8, |
| 910 | res: i32, |
| 911 | (root_r, root_c): (usize, usize), |
| 912 | ) -> f64 { |
| 913 | if !rectdq() || res <= 0 { |
| 914 | return 0.0; |
| 915 | } |
| 916 | let Some(q) = sb_q.filter(|q| !q.is_empty()) else { |
| 917 | return 0.0; |
| 918 | }; |
| 919 | let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]); |
| 920 | let target = at(root_r, root_c); |
| 921 | let cur = if root_c >= 2 { |
| 922 | at(root_r, root_c - 2) |
| 923 | } else if root_r >= 2 { |
| 924 | // The last 128 root of the row above, i.e. the previous one in the |
| 925 | // writer's raster walk. |
| 926 | at(root_r - 2, (sb_cols.saturating_sub(1)) & !1) |
| 927 | } else { |
| 928 | i32::from(base_q_idx) |
| 929 | }; |
| 930 | delta_q_bits(target, cur, res) |
| 931 | } |
| 932 | |
| 933 | /// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT) |
| 934 | /// halves since the last take (class `gate-blind-to-feature`). |
| 935 | static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 936 | /// The VERT twin of [`B128_HORZ_HITS`]. |
| 937 | static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 938 | |
| 939 | /// The HORZ-128-root count since the last call, and zero it. |
| 940 | pub fn take_b128_horz_hits() -> usize { |
| 941 | B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 942 | } |
| 943 | |
| 944 | /// The VERT-128-root count since the last call, and zero it. |
| 945 | pub fn take_b128_vert_hits() -> usize { |
| 946 | B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 947 | } |
| 948 | |
| 949 | /// Test-only: force the 128 root's rect partition whatever it costs -- 0 off, |
| 950 | /// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because |
| 951 | /// synthetic content is where the shape is cheapest to decode-check and the |
| 952 | /// RD there prefers one whole block; the gate census is the unforced count. |
| 953 | static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); |
| 954 | |
| 955 | /// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT). |
| 956 | #[cfg(test)] |
| 957 | pub(crate) fn force_b128_rect(which: u8) { |
| 958 | FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed); |
| 959 | } |
| 960 | |
| 961 | /// lane-ab128: whether the 128 superblock root offers its four AB shapes -- |
| 962 | /// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one |
| 963 | /// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128 |
| 964 | /// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is |
| 965 | /// the same skip-only single-reference/compound block the NONE and HORZ/VERT |
| 966 | /// arms ship, at its own footprint ([`search_root_128_ab`], |
| 967 | /// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this |
| 968 | /// arm's attribution control. |
| 969 | /// |
| 970 | /// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates |
| 971 | /// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded |
| 972 | /// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse -- |
| 973 | /// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8 |
| 974 | /// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B |
| 975 | /// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The |
| 976 | /// machinery is written, witnessed sample-exact through both decoders on all |
| 977 | /// four shapes, and kept for the arm that makes it pay: a non-skip piece (the |
| 978 | /// 64x64 pieces could carry the 64 root's residual, which is where libaom's |
| 979 | /// AB shapes earn their keep) or a cheaper partition price. |
| 980 | fn b128_ab() -> bool { |
| 981 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 982 | crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0") |
| 983 | }); |
| 984 | ENV.unwrap_or(false) && b128_root() |
| 985 | } |
| 986 | |
| 987 | /// How many 128 roots the search left as each AB shape since the last take, |
| 988 | /// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class |
| 989 | /// `gate-blind-to-feature`). |
| 990 | static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] = |
| 991 | [const { std::sync::atomic::AtomicUsize::new(0) }; 4]; |
| 992 | |
| 993 | /// The four per-shape AB-root counts since the last call, and zero them. |
| 994 | pub fn take_b128_ab_hits() -> [usize; 4] { |
| 995 | std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 996 | } |
| 997 | |
| 998 | /// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then |
| 999 | /// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic |
| 1000 | /// content is where the shapes are cheapest to decode-check and the RD there |
| 1001 | /// prefers one whole block). |
| 1002 | static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); |
| 1003 | |
| 1004 | /// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7). |
| 1005 | #[cfg(test)] |
| 1006 | pub(crate) fn force_b128_ab(which: u8) { |
| 1007 | FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed); |
| 1008 | } |
| 1009 | |
| 1010 | /// lane-ab128: the three pieces of an AB shape at a 128 root, in the order |
| 1011 | /// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm |
| 1012 | /// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B = |
| 1013 | /// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR. |
| 1014 | /// Each entry is the piece's own top-left in mode-info units and its |
| 1015 | /// footprint in samples. |
| 1016 | pub(crate) fn ab128_pieces( |
| 1017 | symbol: usize, |
| 1018 | (mi_row, mi_col): (usize, usize), |
| 1019 | ) -> [((usize, usize), (usize, usize)); 3] { |
| 1020 | const S: usize = SUPERBLOCK; |
| 1021 | let (r, c) = (mi_row, mi_col); |
| 1022 | let (r1, c1) = (mi_row + 16, mi_col + 16); |
| 1023 | match symbol { |
| 1024 | // PARTITION_HORZ_A |
| 1025 | 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))], |
| 1026 | // PARTITION_HORZ_B |
| 1027 | 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))], |
| 1028 | // PARTITION_VERT_A |
| 1029 | 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))], |
| 1030 | // PARTITION_VERT_B |
| 1031 | _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))], |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | /// Test-only: take the 128 root's residual arm whatever it costs, so a |
| 1036 | /// witness clip codes the shape rather than waiting for content on which the |
| 1037 | /// RD picks it (the same role [`force_sb128`] plays for the superblock size). |
| 1038 | /// Never read outside `#[cfg(test)]` builds. |
| 1039 | static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool = |
| 1040 | std::sync::atomic::AtomicBool::new(false); |
| 1041 | |
| 1042 | /// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take |
| 1043 | /// the 128 root whenever it produced a candidate at all, whatever its four |
| 1044 | /// cells cost, so a witness codes the block it is about rather than waiting |
| 1045 | /// for content on which the root also wins its own comparison. |
| 1046 | static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = |
| 1047 | std::sync::atomic::AtomicBool::new(false); |
| 1048 | |
| 1049 | /// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a |
| 1050 | /// forced residual block only reaches the writer if its root is taken. |
| 1051 | #[cfg(test)] |
| 1052 | pub(crate) fn force_b128_residual(on: bool) { |
| 1053 | FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed); |
| 1054 | force_b128_root(on); |
| 1055 | } |
| 1056 | |
| 1057 | /// Arms [`FORCE_B128_ROOT`] for the rest of the process. |
| 1058 | #[cfg(test)] |
| 1059 | pub(crate) fn force_b128_root(on: bool) { |
| 1060 | FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed); |
| 1061 | } |
| 1062 | |
| 1063 | /// How many 128 roots came out cheaper WITH a residual than skipped, since |
| 1064 | /// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`). |
| 1065 | static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = |
| 1066 | std::sync::atomic::AtomicUsize::new(0); |
| 1067 | |
| 1068 | /// The 128-residual count since the last call, and zero it. |
| 1069 | pub fn take_b128_residual_hits() -> usize { |
| 1070 | B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 1071 | } |
| 1072 | |
| 1073 | /// How many 128x128 `PARTITION_NONE` roots the search took since the last |
| 1074 | /// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result |
| 1075 | /// is only attributable once the fire count is known. |
| 1076 | static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 1077 | |
| 1078 | /// The 128x128-root count since the last call, and zero it. |
| 1079 | pub fn take_b128_none_hits() -> usize { |
| 1080 | B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 1081 | } |
| 1082 | |
| 1083 | /// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq). |
| 1084 | /// Preset-gated: it re-prices the block once per candidate level, so it buys |
| 1085 | /// bits with wall (see `crate::speed::RDOQ` for the per-preset table). |
| 1086 | /// |
| 1087 | /// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser -- |
| 1088 | /// which is what the byte pins are taken under when they name it. |
| 1089 | fn rdoq_on() -> bool { |
| 1090 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1091 | crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0") |
| 1092 | }); |
| 1093 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ)) |
| 1094 | } |
| 1095 | |
| 1096 | /// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in |
| 1097 | /// units of one squared AC quantiser step -- the search's own |
| 1098 | /// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency. |
| 1099 | /// |
| 1100 | /// The per-frame factors the search multiplies onto it ([`key_lambda_factor`], |
| 1101 | /// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock |
| 1102 | /// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here: |
| 1103 | /// corner-cut, ceiling = a superblock the temporal map weighs away from the |
| 1104 | /// frame average has its coefficients optimised at the frame's weight. The |
| 1105 | /// upgrade is one `lambda` field on the trial call sites, which is the whole |
| 1106 | /// mode-search argument list. |
| 1107 | /// |
| 1108 | /// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom |
| 1109 | /// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above |
| 1110 | /// the mode search's own weight, and it is the same multiplier on all three |
| 1111 | /// rows: |
| 1112 | /// |
| 1113 | /// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen | |
| 1114 | /// |---|---|---|---| |
| 1115 | /// | 0.7 | +27.6 | +39.5 | +29.6 | |
| 1116 | /// | 1.0 | +26.3 | +37.5 | +29.1 | |
| 1117 | /// | 1.3 | +25.6 | +37.0 | +28.8 | |
| 1118 | /// | 1.6 | +24.6 | +35.9 | +28.7 | |
| 1119 | /// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 | |
| 1120 | /// | 3.2 | +24.7 | +36.1 | +29.4 | |
| 1121 | /// |
| 1122 | /// A coefficient's rate is worth twice here what the mode search prices it |
| 1123 | /// at, and the likeliest reason is that the price is taken against tables |
| 1124 | /// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded |
| 1125 | /// late in a frame whose `txb_skip`/`base` tables have narrowed really costs |
| 1126 | /// less than the pricer says, and this pass is the one decision taken per |
| 1127 | /// COEFFICIENT, so it feels that error most. The honest fix is an adapted |
| 1128 | /// price, not a fitted multiplier; this is the fitted multiplier, and its |
| 1129 | /// bowl is measured rather than assumed. |
| 1130 | const RDOQ_LAMBDA_MULT: f64 = 2.2; |
| 1131 | |
| 1132 | /// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term |
| 1133 | /// calibration sweep). |
| 1134 | fn rdoq_lambda() -> f64 { |
| 1135 | static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| { |
| 1136 | crate::envflags::var("EC_AV1_RDOQ_LAMBDA") |
| 1137 | .ok() |
| 1138 | .and_then(|v| v.parse().ok()) |
| 1139 | .unwrap_or(RDOQ_LAMBDA_MULT) |
| 1140 | }); |
| 1141 | lambda_scale() * *MULT |
| 1142 | } |
| 1143 | |
| 1144 | /// [`B64_ROOT`], or what `EC_AV1_B64` names. |
| 1145 | fn b64_root() -> bool { |
| 1146 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1147 | crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0") |
| 1148 | }); |
| 1149 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT)) |
| 1150 | } |
| 1151 | |
| 1152 | /// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched |
| 1153 | /// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64 |
| 1154 | /// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner) |
| 1155 | /// and one TX_32X32 per chroma plane -- and compared against the four 32x32 |
| 1156 | /// quadrants at the same lambda, exactly the shape the inter root |
| 1157 | /// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to |
| 1158 | /// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`); |
| 1159 | /// nothing produced one, so the key frame -- 21.6% of a real film stream -- |
| 1160 | /// coded every superblock split while libaom and rav1e leave 45-54% of theirs |
| 1161 | /// whole. |
| 1162 | /// |
| 1163 | /// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on |
| 1164 | /// it), no filter intra (`filter_intra_size_class` has no 64 row) and no |
| 1165 | /// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32 |
| 1166 | /// level grid, so only depth 0 is representable) -- the root is refused |
| 1167 | /// outright on an `allow_intrabc` frame, whose quadrant searches carry DV |
| 1168 | /// state a discarded trial would desync. |
| 1169 | /// |
| 1170 | /// Switched off by `EC_AV1_I64=0` in any build. |
| 1171 | pub(crate) const I64_ROOT: bool = true; |
| 1172 | |
| 1173 | /// How many key-frame superblocks were coded as one 64x64 intra block since |
| 1174 | /// the last [`take_i64_root_hits`], so a gate reports the fire rate rather |
| 1175 | /// than assuming it (class `gate-blind-to-feature`). |
| 1176 | /// Index 1 is how many were OFFERED the trial at all, so a gate reads a |
| 1177 | /// SHARE and not a bare count, and index 2 how many of the whole ones sat on |
| 1178 | /// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the |
| 1179 | /// `gate-blind-to-feature` guard for the edge path, which no |
| 1180 | /// superblock-aligned clip fires at all. |
| 1181 | static I64_HITS: [std::sync::atomic::AtomicUsize; 3] = |
| 1182 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 1183 | |
| 1184 | /// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the |
| 1185 | /// last call, and zero them. |
| 1186 | pub fn take_i64_root_hits() -> [usize; 3] { |
| 1187 | std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 1188 | } |
| 1189 | |
| 1190 | /// [`I64_ROOT`], or what `EC_AV1_I64` names. |
| 1191 | fn i64_root() -> bool { |
| 1192 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1193 | crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0") |
| 1194 | }); |
| 1195 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT)) |
| 1196 | } |
| 1197 | |
| 1198 | /// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the |
| 1199 | /// winner's prediction through one TX_64X64 luma transform and two TX_32X32 |
| 1200 | /// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root |
| 1201 | /// lane-b64 shipped, so the two can be measured against each other on the |
| 1202 | /// same build. |
| 1203 | /// |
| 1204 | /// MEASURED on the native gate (two arms of one build, baseline reproduced to |
| 1205 | /// the tenth): both film rows improve on both columns -- film A |
| 1206 | /// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and |
| 1207 | /// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's |
| 1208 | /// +-0.3 screen clause. So the caller gates this off on a screen frame |
| 1209 | /// (`allow_screen_content_tools`), the same content gate the coding pyramid |
| 1210 | /// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm |
| 1211 | /// already codes them for nothing, and a residual there only spends bits the |
| 1212 | /// intra/palette tools would have spent better. |
| 1213 | /// |
| 1214 | /// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` + |
| 1215 | /// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on: |
| 1216 | /// |
| 1217 | /// | | skip-only | + residual | |
| 1218 | /// |---|---|---| |
| 1219 | /// | 64x64 share, all frames | 36.4% | 38.3% | |
| 1220 | /// | 64x64 share, leaf frames | 53.3% | 56.0% | |
| 1221 | /// | skip area, all frames | 80.4% | 78.8% | |
| 1222 | /// | skip area, leaf frames | 90.2% | 88.5% | |
| 1223 | /// | stream bytes | 34,366 | 34,295 | |
| 1224 | /// | encoder wall | 13.4s | 9.6s | |
| 1225 | /// |
| 1226 | /// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the |
| 1227 | /// TX_64X64 coefficients are really being coded. The root wins MORE often |
| 1228 | /// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is |
| 1229 | /// 45.2%), which is also why the arm is 28% FASTER despite costing three more |
| 1230 | /// transforms per superblock: a root that wins is four quadrant searches that |
| 1231 | /// never run. |
| 1232 | fn b64_residual() -> bool { |
| 1233 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1234 | crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0") |
| 1235 | }); |
| 1236 | ENV.unwrap_or(true) && b64_root() |
| 1237 | } |
| 1238 | |
| 1239 | /// How many 64x64 roots came out cheaper with a residual than skipped, since |
| 1240 | /// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate |
| 1241 | /// rather than assuming one (class `gate-blind-to-feature`). |
| 1242 | static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 1243 | |
| 1244 | /// The non-skip 64x64-root count since the last call, and zero it. |
| 1245 | pub fn take_b64_residual_hits() -> usize { |
| 1246 | B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 1247 | } |
| 1248 | |
| 1249 | /// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the |
| 1250 | /// `LAST` + extra-reference pairs the 32x32 level already offers, at the |
| 1251 | /// three modes a root can form without a second 64x64 motion search -- |
| 1252 | /// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half |
| 1253 | /// is the vector `search_skip_64`'s own single-reference search already |
| 1254 | /// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own |
| 1255 | /// `NEWMV` vector, which only a second search per superblock produces -- the |
| 1256 | /// wall this root exists to save -- so they are not offered here. |
| 1257 | /// |
| 1258 | /// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build. |
| 1259 | fn b64_compound() -> bool { |
| 1260 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1261 | crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0") |
| 1262 | }); |
| 1263 | ENV.unwrap_or(true) && b64_root() |
| 1264 | } |
| 1265 | |
| 1266 | /// How many 64x64 roots took a COMPOUND candidate since the last |
| 1267 | /// [`take_b64_compound_hits`] (class `gate-blind-to-feature`). |
| 1268 | static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 1269 | |
| 1270 | /// The compound 64x64-root count since the last call, and zero it. |
| 1271 | pub fn take_b64_compound_hits() -> usize { |
| 1272 | B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 1273 | } |
| 1274 | |
| 1275 | /// Whether a 64x64 root that codes a residual may SPLIT its luma transform |
| 1276 | /// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by |
| 1277 | /// [`commit_inter_luma`] like every other inter block's var-tx, and coded by |
| 1278 | /// the writer's `Whole64` arm as `txfm_split = 1`. It exists because |
| 1279 | /// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose |
| 1280 | /// residual has detail in the other three quadrants cannot code it at all. |
| 1281 | /// |
| 1282 | /// Off by `EC_AV1_B64VARTX=0`. |
| 1283 | fn b64_var_tx() -> bool { |
| 1284 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1285 | crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0") |
| 1286 | }); |
| 1287 | ENV.unwrap_or(true) && b64_root() |
| 1288 | } |
| 1289 | |
| 1290 | /// How many 64x64 roots split their luma transform since the last |
| 1291 | /// [`take_b64_var_tx_hits`]. |
| 1292 | static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 1293 | |
| 1294 | /// The split-luma 64x64-root count since the last call, and zero it. |
| 1295 | pub fn take_b64_var_tx_hits() -> usize { |
| 1296 | B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 1297 | } |
| 1298 | |
| 1299 | /// Whether a superblock the true frame edge CUTS THROUGH may be left whole |
| 1300 | /// (lane-b64b). AV1 asks only that the block's own half is inside |
| 1301 | /// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already |
| 1302 | /// codes that case; what was missing was a trial whose SSE is scored over the |
| 1303 | /// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse) |
| 1304 | /// instead of over the padding the encoder |
| 1305 | /// invented past the edge. Both gate films are superblock-aligned, so this |
| 1306 | /// only reaches the user's own arbitrary export sizes. |
| 1307 | /// |
| 1308 | /// Off by `EC_AV1_B64EDGE=0`. |
| 1309 | fn b64_edge() -> bool { |
| 1310 | edge_root_enabled() && b64_root() |
| 1311 | } |
| 1312 | |
| 1313 | /// What `EC_AV1_B64EDGE` names on its own, without the inter root's own |
| 1314 | /// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag |
| 1315 | /// but is gated by [`i64_root`]. |
| 1316 | fn edge_root_enabled() -> bool { |
| 1317 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 1318 | crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0") |
| 1319 | }); |
| 1320 | ENV.unwrap_or(true) |
| 1321 | } |
| 1322 | |
| 1323 | /// How many 64x64 roots the frame edge cut through since the last |
| 1324 | /// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are |
| 1325 | /// superblock-aligned, so nothing but a synthetic size fires this). |
| 1326 | static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 1327 | |
| 1328 | /// The edge 64x64-root count since the last call, and zero it. |
| 1329 | pub fn take_b64_edge_hits() -> usize { |
| 1330 | B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 1331 | } |
| 1332 | |
| 1333 | /// Whether the encoder searches loop restoration at all (spec 7.17): one |
| 1334 | /// Wiener filter per 64x64 luma restoration unit, picked from |
| 1335 | /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a |
| 1336 | /// test build, like [`lambda_scale`]. |
| 1337 | pub(crate) const RESTORATION: bool = true; |
| 1338 | |
| 1339 | /// [`RESTORATION`], or what `EC_AV1_LR` names in a test build. |
| 1340 | fn restoration_enabled() -> bool { |
| 1341 | match std::env::var("EC_AV1_LR").ok() { |
| 1342 | Some(v) if cfg!(test) => v != "0", |
| 1343 | _ => crate::speed::at(&crate::speed::RESTORATION), |
| 1344 | } |
| 1345 | } |
| 1346 | |
| 1347 | /// libaom's `partition_search_breakout` shape: how many non-zero luma |
| 1348 | /// coefficients per 256 luma samples a block may code and still be judged |
| 1349 | /// well enough predicted that the split below it is not worth trying. `0` |
| 1350 | /// disables the breakout (only the existing all-skip prune applies), which |
| 1351 | /// is the default until the sweep below justifies otherwise. |
| 1352 | /// |
| 1353 | /// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which |
| 1354 | /// is where this lane's wall would have gone: 1 cuts the three clips' |
| 1355 | /// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9 |
| 1356 | /// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs |
| 1357 | /// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this |
| 1358 | /// encoder's inter quality lives, so `0` ships and the knob stays for a |
| 1359 | /// future explicit speed preset. |
| 1360 | pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0; |
| 1361 | |
| 1362 | /// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own |
| 1363 | /// currency: a 32x32 inter block whose whole-block RD cost per pixel comes |
| 1364 | /// out under `threshold * lambda` is not offered the split at all, and a |
| 1365 | /// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both |
| 1366 | /// always, as before this lever. |
| 1367 | /// |
| 1368 | /// The census is what points here: the split trial runs on nearly every |
| 1369 | /// non-skip block (15132 leaf searches per ladder point on the 1080p clip) |
| 1370 | /// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient |
| 1371 | /// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD |
| 1372 | /// points, so the gate has to read the block's own RD cost, not its levels. |
| 1373 | /// |
| 1374 | /// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of |
| 1375 | /// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for |
| 1376 | /// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and |
| 1377 | /// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs |
| 1378 | /// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships -- |
| 1379 | /// the largest threshold whose BD stays inside the +0.3 keep rule on every |
| 1380 | /// clip. |
| 1381 | /// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base |
| 1382 | /// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1, |
| 1383 | /// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is |
| 1384 | /// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off |
| 1385 | /// the screen wall). Neither clears the keep rule; 0.125 stays. |
| 1386 | pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125; |
| 1387 | |
| 1388 | /// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build. |
| 1389 | fn split_rd_threshold() -> f64 { |
| 1390 | static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| { |
| 1391 | crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok()) |
| 1392 | }); |
| 1393 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD)) |
| 1394 | } |
| 1395 | |
| 1396 | /// Whether `cost` over a `side` x `side` block is cheap enough per pixel that |
| 1397 | /// [`split_rd_threshold`] withholds the split trial. |
| 1398 | fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool { |
| 1399 | split_rd_breakout_at(split_rd_threshold(), cost, side, lambda) |
| 1400 | } |
| 1401 | |
| 1402 | /// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own |
| 1403 | /// early-out reads. |
| 1404 | fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool { |
| 1405 | t > 0.0 && cost < t * lambda * (side * side) as f64 |
| 1406 | } |
| 1407 | |
| 1408 | /// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`] |
| 1409 | /// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64). |
| 1410 | /// |
| 1411 | /// The 32x32 level is allowed to loosen its breakout with the speed preset |
| 1412 | /// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured |
| 1413 | /// what that does one size up: at 0.5 a whole superblock is taken at 64x64 |
| 1414 | /// without its four quadrants ever being searched, and film B goes |
| 1415 | /// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the |
| 1416 | /// same per-pixel threshold withholds four times as much search -- the |
| 1417 | /// preset's step is priced for the 32 level and does not carry up here. |
| 1418 | fn b64_breakout_threshold() -> f64 { |
| 1419 | split_rd_threshold().min(SPLIT_RD_THRESHOLD) |
| 1420 | } |
| 1421 | |
| 1422 | /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test |
| 1423 | /// build. |
| 1424 | fn split_breakout_coeffs() -> usize { |
| 1425 | match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() { |
| 1426 | Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS), |
| 1427 | _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT), |
| 1428 | } |
| 1429 | } |
| 1430 | |
| 1431 | /// How often each partition decision was taken since the last |
| 1432 | /// [`take_partition_hits`], so a gate can report how often a new partition |
| 1433 | /// fires rather than assume it does (gate-blind-to-feature). Index 0 is an |
| 1434 | /// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is |
| 1435 | /// such a leaf left whole, 3 one split into four 8x8 leaves of its own. |
| 1436 | static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [ |
| 1437 | std::sync::atomic::AtomicUsize::new(0), |
| 1438 | std::sync::atomic::AtomicUsize::new(0), |
| 1439 | std::sync::atomic::AtomicUsize::new(0), |
| 1440 | std::sync::atomic::AtomicUsize::new(0), |
| 1441 | ]; |
| 1442 | |
| 1443 | /// Records one such decision. |
| 1444 | fn partition_hit(which: usize) { |
| 1445 | PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1446 | } |
| 1447 | |
| 1448 | /// Takes (and clears) the counts. |
| 1449 | #[cfg(test)] |
| 1450 | pub(crate) fn take_partition_hits() -> [usize; 4] { |
| 1451 | [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 1452 | } |
| 1453 | |
| 1454 | /// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full |
| 1455 | /// rate-distortion trials the block search actually runs, by kind, and where |
| 1456 | /// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by |
| 1457 | /// default, and a measurement build rather than a speed one -- the census |
| 1458 | /// runs the SAD pre-pass the unpruned search otherwise skips. |
| 1459 | pub fn census_on() -> bool { |
| 1460 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 1461 | *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1"))) |
| 1462 | } |
| 1463 | |
| 1464 | /// What each [`CENSUS`] counter counts. |
| 1465 | pub const CENSUS_KINDS: [&str; 11] = [ |
| 1466 | "intra blocks searched (key frame + inter leaves)", |
| 1467 | "intra luma mode trials", |
| 1468 | "chroma searches", |
| 1469 | "chroma mode trials (each = 2 plane trials)", |
| 1470 | "tx-depth trials (transform units, depth >= 1)", |
| 1471 | "inter 32x32 blocks searched", |
| 1472 | "inter block intra-mode trials", |
| 1473 | "inter mv candidates (each = 3 mc trials)", |
| 1474 | "inter leaves searched (intra vs NEARESTMV/NEWMV)", |
| 1475 | " of those, intra won", |
| 1476 | " of those, the NEARESTMV trial coded no residual", |
| 1477 | ]; |
| 1478 | |
| 1479 | /// The census counters themselves, indexed by [`CENSUS_KINDS`]. |
| 1480 | static CENSUS: [std::sync::atomic::AtomicUsize; 11] = |
| 1481 | [const { std::sync::atomic::AtomicUsize::new(0) }; 11]; |
| 1482 | |
| 1483 | /// Where the RD winner sat in the SAD ranking, for the luma intra search and |
| 1484 | /// the chroma mode search -- what says whether a top-N prune would have kept |
| 1485 | /// the block the search actually chose. |
| 1486 | static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] = |
| 1487 | [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; |
| 1488 | static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] = |
| 1489 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 1490 | |
| 1491 | fn census_add(kind: usize, n: usize) { |
| 1492 | if census_on() { |
| 1493 | CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 1494 | } |
| 1495 | } |
| 1496 | |
| 1497 | /// Reads (and clears) the census, so a driver can attribute it to its own encode. |
| 1498 | pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) { |
| 1499 | let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed); |
| 1500 | ( |
| 1501 | std::array::from_fn(|i| take(&CENSUS[i])), |
| 1502 | std::array::from_fn(|i| take(&LUMA_RANK[i])), |
| 1503 | std::array::from_fn(|i| take(&CHROMA_RANK[i])), |
| 1504 | ) |
| 1505 | } |
| 1506 | |
| 1507 | /// The rank of `winner` in `scored` ordered by its cheap score, cheapest |
| 1508 | /// first -- the census's one shared rule, so the luma and chroma histograms |
| 1509 | /// mean the same thing. |
| 1510 | fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize { |
| 1511 | scored |
| 1512 | .iter() |
| 1513 | .filter(|&&(score, mode)| { |
| 1514 | mode != winner |
| 1515 | && score |
| 1516 | < scored |
| 1517 | .iter() |
| 1518 | .find(|&&(_, m)| m == winner) |
| 1519 | .map_or(f64::INFINITY, |&(s, _)| s) |
| 1520 | }) |
| 1521 | .count() |
| 1522 | } |
| 1523 | |
| 1524 | /// Whether a 32x32 block may be split into four 16x16 ones when the trial says |
| 1525 | /// four cost less. Set from the measurement in the lane report. |
| 1526 | const SPLIT_BLOCKS: bool = true; |
| 1527 | |
| 1528 | /// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides |
| 1529 | /// by calling [`encode_key_frame_inner`] both ways. |
| 1530 | pub(crate) fn split_blocks() -> bool { |
| 1531 | SPLIT_BLOCKS |
| 1532 | } |
| 1533 | |
| 1534 | /// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as |
| 1535 | /// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used |
| 1536 | /// `u16` throughout since the round-hbd-r1/r2 widen; this is the last |
| 1537 | /// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit |
| 1538 | /// stream's decode output actually carries 10-bit precision instead of |
| 1539 | /// silently losing its low 2 bits). The encoder only ever produces values in |
| 1540 | /// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2 |
| 1541 | /// decision); `Plane::source` narrows right back to `u8` at its two |
| 1542 | /// construction sites, a lossless round trip for that range. |
| 1543 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 1544 | pub struct Picture { |
| 1545 | /// The picture's width in luma samples. |
| 1546 | pub width: usize, |
| 1547 | /// Its height in luma samples. |
| 1548 | pub height: usize, |
| 1549 | /// The luma plane, `width * height` samples in raster order. |
| 1550 | pub y: Vec<u16>, |
| 1551 | /// The U plane: half the width, and the frame's own chroma height -- a |
| 1552 | /// quarter of the luma samples at 4:2:0, half at 4:2:2, all of them at |
| 1553 | /// 4:4:4. A consumer that only knows the luma size reads the chroma |
| 1554 | /// format off this sample count (see `decode::ref_chroma_shape`). |
| 1555 | pub u: Vec<u16>, |
| 1556 | /// The V plane, the same shape as U. |
| 1557 | pub v: Vec<u16>, |
| 1558 | } |
| 1559 | |
| 1560 | impl Picture { |
| 1561 | /// A mid-grey picture of the given size. |
| 1562 | #[must_use] |
| 1563 | pub fn grey(width: usize, height: usize) -> Self { |
| 1564 | Self { |
| 1565 | width, |
| 1566 | height, |
| 1567 | y: vec![128; width * height], |
| 1568 | u: vec![128; width * height / 4], |
| 1569 | v: vec![128; width * height / 4], |
| 1570 | } |
| 1571 | } |
| 1572 | |
| 1573 | pub(crate) fn check(&self) -> Result<()> { |
| 1574 | if self.width == 0 |
| 1575 | || !self.width.is_multiple_of(BLOCK) |
| 1576 | || !self.height.is_multiple_of(BLOCK) |
| 1577 | || !self.height.is_multiple_of(BLOCK) |
| 1578 | { |
| 1579 | return Err(Error::unsupported( |
| 1580 | "AV1 encode", |
| 1581 | "the picture must be a whole number of 32x32 blocks in each direction", |
| 1582 | )); |
| 1583 | } |
| 1584 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 1585 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 1586 | return Err(Error::unsupported( |
| 1587 | "AV1 encode", |
| 1588 | "each plane must carry one sample per position at 4:2:0", |
| 1589 | )); |
| 1590 | } |
| 1591 | Ok(()) |
| 1592 | } |
| 1593 | |
| 1594 | /// What the public entry points require of the picture they are handed, |
| 1595 | /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 |
| 1596 | /// needs a whole chroma sample per two luma ones) and one sample per |
| 1597 | /// position on each plane. |
| 1598 | pub(crate) fn check_even(&self) -> Result<()> { |
| 1599 | if self.width == 0 |
| 1600 | || self.height == 0 |
| 1601 | || !self.width.is_multiple_of(2) |
| 1602 | || !self.height.is_multiple_of(2) |
| 1603 | { |
| 1604 | return Err(Error::unsupported( |
| 1605 | "AV1 encode", |
| 1606 | "the picture's width and height must each be even and nonzero", |
| 1607 | )); |
| 1608 | } |
| 1609 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 1610 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 1611 | return Err(Error::unsupported( |
| 1612 | "AV1 encode", |
| 1613 | "each plane must carry one sample per position at 4:2:0", |
| 1614 | )); |
| 1615 | } |
| 1616 | Ok(()) |
| 1617 | } |
| 1618 | |
| 1619 | /// This picture, padded by edge replication to the next whole number of |
| 1620 | /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key |
| 1621 | /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a |
| 1622 | /// sequence (what the inter tile writer's partition needs on top of |
| 1623 | /// that). Identity (a plain clone, not a copy through the replication |
| 1624 | /// loop) when the picture is already that size — the multiple-of-32 (or |
| 1625 | /// -64) fast path is unchanged. |
| 1626 | pub(crate) fn padded_to(&self, align: usize) -> Picture { |
| 1627 | let padded_width = self.width.next_multiple_of(align); |
| 1628 | let padded_height = self.height.next_multiple_of(align); |
| 1629 | if padded_width == self.width && padded_height == self.height { |
| 1630 | return self.clone(); |
| 1631 | } |
| 1632 | Picture { |
| 1633 | width: padded_width, |
| 1634 | height: padded_height, |
| 1635 | y: pad_plane( |
| 1636 | &self.y, |
| 1637 | self.width, |
| 1638 | self.height, |
| 1639 | padded_width, |
| 1640 | padded_height, |
| 1641 | ), |
| 1642 | u: pad_plane( |
| 1643 | &self.u, |
| 1644 | self.width / 2, |
| 1645 | self.height / 2, |
| 1646 | padded_width / 2, |
| 1647 | padded_height / 2, |
| 1648 | ), |
| 1649 | v: pad_plane( |
| 1650 | &self.v, |
| 1651 | self.width / 2, |
| 1652 | self.height / 2, |
| 1653 | padded_width / 2, |
| 1654 | padded_height / 2, |
| 1655 | ), |
| 1656 | } |
| 1657 | } |
| 1658 | } |
| 1659 | |
| 1660 | /// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8` |
| 1661 | /// (8-bit only, unchanged this round -- widening the encoder is out of this |
| 1662 | /// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that |
| 1663 | /// lets it keep calling [`crate::intra::predict`] now that shape is `u16` |
| 1664 | /// in and out. A block-sized round-trip through `u16` is exact for 8-bit |
| 1665 | /// content (every value fits both ways), so this changes no encoder output. |
| 1666 | #[allow(clippy::too_many_arguments)] |
| 1667 | fn intra_predict_u8( |
| 1668 | mode: u8, |
| 1669 | angle_delta: i32, |
| 1670 | above: Option<&[u8]>, |
| 1671 | left: Option<&[u8]>, |
| 1672 | corner: Option<u8>, |
| 1673 | bw: usize, |
| 1674 | bh: usize, |
| 1675 | enable_edge_filter: bool, |
| 1676 | smooth_neighbor: bool, |
| 1677 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 1678 | ) { |
| 1679 | // Three heap allocations per call became three stack buffers: this runs |
| 1680 | // once per mode per trial, and an edge is at most `bw + bh` samples while |
| 1681 | // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's |
| 1682 | // 64x64 intra root predicts through here too, and reads up to `2 * bw` |
| 1683 | // samples above). |
| 1684 | let mut above_buf = [0u16; 2 * SUPERBLOCK]; |
| 1685 | let mut left_buf = [0u16; 2 * SUPERBLOCK]; |
| 1686 | // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode |
| 1687 | // trial of every block, and a 4x4 block writes 32 bytes of it. The |
| 1688 | // predictor fills every sample it is handed, so the zeros are dead |
| 1689 | // either way -- size the scratch to the block instead of to the largest |
| 1690 | // block there is. |
| 1691 | |
| 1692 | let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| { |
| 1693 | for (d, &v) in buf[..src.len()].iter_mut().zip(src) { |
| 1694 | *d = u16::from(v); |
| 1695 | } |
| 1696 | }; |
| 1697 | if let Some(s) = above { |
| 1698 | widen(s, &mut above_buf); |
| 1699 | } |
| 1700 | if let Some(s) = left { |
| 1701 | widen(s, &mut left_buf); |
| 1702 | } |
| 1703 | let above16 = above.map(|s| &above_buf[..s.len()]); |
| 1704 | let left16 = left.map(|s| &left_buf[..s.len()]); |
| 1705 | let mut run = |dst16: &mut [u16]| { |
| 1706 | crate::intra::predict( |
| 1707 | mode, |
| 1708 | angle_delta, |
| 1709 | above16, |
| 1710 | left16, |
| 1711 | corner.map(u16::from), |
| 1712 | bw, |
| 1713 | bh, |
| 1714 | enable_edge_filter, |
| 1715 | smooth_neighbor, |
| 1716 | dst16, fctx, |
| 1717 | ); |
| 1718 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { |
| 1719 | *d = s as u8; |
| 1720 | } |
| 1721 | }; |
| 1722 | let n = bw * bh; |
| 1723 | if n <= 64 { |
| 1724 | run(&mut [0u16; 64][..n]); |
| 1725 | } else if n <= 256 { |
| 1726 | run(&mut [0u16; 256][..n]); |
| 1727 | } else if n <= BLOCK * BLOCK { |
| 1728 | run(&mut [0u16; BLOCK * BLOCK][..n]); |
| 1729 | } else { |
| 1730 | run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]); |
| 1731 | } |
| 1732 | } |
| 1733 | |
| 1734 | /// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same |
| 1735 | /// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one |
| 1736 | /// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode. |
| 1737 | fn filter_intra_predict_u8( |
| 1738 | mode: usize, |
| 1739 | above: Option<&[u8]>, |
| 1740 | left: Option<&[u8]>, |
| 1741 | corner: Option<u8>, |
| 1742 | side: usize, |
| 1743 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 1744 | ) { |
| 1745 | let mut above_buf = [0u16; 2 * BLOCK]; |
| 1746 | let mut left_buf = [0u16; 2 * BLOCK]; |
| 1747 | let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| { |
| 1748 | for (d, &v) in buf[..src.len()].iter_mut().zip(src) { |
| 1749 | *d = u16::from(v); |
| 1750 | } |
| 1751 | }; |
| 1752 | if let Some(a) = above { |
| 1753 | widen(a, &mut above_buf); |
| 1754 | } |
| 1755 | if let Some(l) = left { |
| 1756 | widen(l, &mut left_buf); |
| 1757 | } |
| 1758 | let mut dst16 = [0u16; BLOCK * BLOCK]; |
| 1759 | let n = side * side; |
| 1760 | crate::intra::predict_filter_intra( |
| 1761 | mode, |
| 1762 | above.map(|a| &above_buf[..a.len()]), |
| 1763 | left.map(|l| &left_buf[..l.len()]), |
| 1764 | corner.map(u16::from), |
| 1765 | side, |
| 1766 | side, |
| 1767 | &mut dst16[..n], fctx, |
| 1768 | ); |
| 1769 | for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) { |
| 1770 | *d = v as u8; |
| 1771 | } |
| 1772 | } |
| 1773 | |
| 1774 | /// Pads one plane to `(padded_width, padded_height)` by repeating its last |
| 1775 | /// row and column, so the block coder always sees a whole number of blocks. |
| 1776 | /// [`crop_plane`] undoes this on the way back out. |
| 1777 | fn pad_plane<T: Copy + Default>( |
| 1778 | source: &[T], |
| 1779 | width: usize, |
| 1780 | height: usize, |
| 1781 | padded_width: usize, |
| 1782 | padded_height: usize, |
| 1783 | ) -> Vec<T> { |
| 1784 | let mut out = vec![T::default(); padded_width * padded_height]; |
| 1785 | for row in 0..padded_height { |
| 1786 | let src = source[row.min(height - 1) * width..][..width].as_ref(); |
| 1787 | let dst = &mut out[row * padded_width..][..padded_width]; |
| 1788 | dst[..width].copy_from_slice(src); |
| 1789 | dst[width..].fill(src[width - 1]); |
| 1790 | } |
| 1791 | out |
| 1792 | } |
| 1793 | |
| 1794 | /// The top-left `width` x `height` region of a plane that is `padded_width` |
| 1795 | /// wide, which is the render-size crop [`Picture::padded`]'s replication |
| 1796 | /// exists to let a decoder undo. |
| 1797 | fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> { |
| 1798 | let mut out = Vec::with_capacity(width * height); |
| 1799 | for row in 0..height { |
| 1800 | out.extend_from_slice(&source[row * padded_width..][..width]); |
| 1801 | } |
| 1802 | out |
| 1803 | } |
| 1804 | |
| 1805 | /// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size |
| 1806 | /// region a decoder produces, which is the public contract for what a caller |
| 1807 | /// sees back — the padded planes the encoder coded against never leave this |
| 1808 | /// module. Identity when the reconstruction is already that size. |
| 1809 | pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { |
| 1810 | let reconstruction = &encoded.reconstruction; |
| 1811 | let cropped = if reconstruction.width == width && reconstruction.height == height { |
| 1812 | reconstruction.clone() |
| 1813 | } else { |
| 1814 | Picture { |
| 1815 | width, |
| 1816 | height, |
| 1817 | y: crop_plane(&reconstruction.y, reconstruction.width, width, height), |
| 1818 | u: crop_plane( |
| 1819 | &reconstruction.u, |
| 1820 | reconstruction.width / 2, |
| 1821 | width / 2, |
| 1822 | height / 2, |
| 1823 | ), |
| 1824 | v: crop_plane( |
| 1825 | &reconstruction.v, |
| 1826 | reconstruction.width / 2, |
| 1827 | width / 2, |
| 1828 | height / 2, |
| 1829 | ), |
| 1830 | } |
| 1831 | }; |
| 1832 | Encoded { |
| 1833 | stream: encoded.stream.clone(), |
| 1834 | modes: encoded.modes.clone(), |
| 1835 | inter_block_share: encoded.inter_block_share, |
| 1836 | reconstruction: cropped, |
| 1837 | tile: encoded.tile.clone(), |
| 1838 | mi_cols: encoded.mi_cols, |
| 1839 | mi_rows: encoded.mi_rows, |
| 1840 | base_q_idx: encoded.base_q_idx, |
| 1841 | tx_select: encoded.tx_select, |
| 1842 | switchable_motion_mode: encoded.switchable_motion_mode, |
| 1843 | screen: encoded.screen, |
| 1844 | reduced_tx_set: encoded.reduced_tx_set, |
| 1845 | start_cdfs: encoded.start_cdfs.clone(), |
| 1846 | next_cdfs: encoded.next_cdfs.clone(), |
| 1847 | loop_filter: encoded.loop_filter, |
| 1848 | loop_restoration: encoded.loop_restoration, |
| 1849 | allow_intrabc: encoded.allow_intrabc, |
| 1850 | delta: encoded.delta.clone(), |
| 1851 | cdef: encoded.cdef, |
| 1852 | } |
| 1853 | } |
| 1854 | |
| 1855 | /// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of |
| 1856 | /// numbers nobody wants printed, and [`Encoded`] derives `Debug`. |
| 1857 | #[derive(Clone)] |
| 1858 | pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs); |
| 1859 | |
| 1860 | impl std::fmt::Debug for CdfSnapshot { |
| 1861 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1862 | f.write_str("CdfSnapshot") |
| 1863 | } |
| 1864 | } |
| 1865 | |
| 1866 | /// What one call to [`encode_key_frame`] produced. |
| 1867 | #[derive(Clone, Debug)] |
| 1868 | pub struct Encoded { |
| 1869 | /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame |
| 1870 | /// OBU carrying one tile. |
| 1871 | pub stream: Vec<u8>, |
| 1872 | /// What a decoder will produce from `stream` — the encoder's own |
| 1873 | /// reconstruction, which its prediction was built on. |
| 1874 | pub reconstruction: Picture, |
| 1875 | /// The luma intra mode each block was coded under, in the order the blocks |
| 1876 | /// are coded — raster order among the quadrants of each superblock, and |
| 1877 | /// among the four 16x16 blocks of a quadrant that was split. |
| 1878 | pub modes: Vec<u8>, |
| 1879 | /// The fraction of this frame's 32x32 blocks that were coded inter (any |
| 1880 | /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0` |
| 1881 | /// for a key frame, which has no such choice — so a caller can tell a |
| 1882 | /// frame with no motion worth coding from one that never got the chance. |
| 1883 | pub inter_block_share: f64, |
| 1884 | /// The tile payload alone, undecorated by any OBU framing, and the frame |
| 1885 | /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`. |
| 1886 | /// `crate::decode`'s tests are the only reader; a real decoder gets these |
| 1887 | /// off the wire by parsing `stream`'s OBUs instead. |
| 1888 | pub(crate) tile: Vec<u8>, |
| 1889 | pub(crate) mi_cols: u32, |
| 1890 | pub(crate) mi_rows: u32, |
| 1891 | pub(crate) base_q_idx: u8, |
| 1892 | /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and |
| 1893 | /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it, |
| 1894 | /// and reading it off `stream`'s header is what `decode_stream` does. A |
| 1895 | /// test that decodes `tile` directly must pass this one along, or it reads |
| 1896 | /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first |
| 1897 | /// block. |
| 1898 | pub(crate) tx_select: bool, |
| 1899 | /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the |
| 1900 | /// bit that makes every eligible single-reference inter block carry a |
| 1901 | /// `motion_mode` symbol. Same contract as `tx_select` above: a test |
| 1902 | /// decoding `tile` directly must pass it along or it desyncs at the |
| 1903 | /// first eligible block. |
| 1904 | pub(crate) switchable_motion_mode: bool, |
| 1905 | /// The CDF state this frame's tile writer started from -- the defaults |
| 1906 | /// for a key frame and for the first inter frame, and the previous |
| 1907 | /// frame's stored tables after that. A test that decodes `tile` directly |
| 1908 | /// must feed the decoder this, exactly as `decode_stream` feeds it what |
| 1909 | /// the frame's `primary_ref_frame` slot holds (same class as |
| 1910 | /// `tx_select`: a header bit a raw tile decode cannot guess). |
| 1911 | pub(crate) start_cdfs: CdfSnapshot, |
| 1912 | /// What this frame stores into the slots it refreshes (spec 7.20, |
| 1913 | /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the |
| 1914 | /// counts reset when `disable_frame_end_update_cdf` is off, and what it |
| 1915 | /// started from when it is on. |
| 1916 | pub(crate) next_cdfs: CdfSnapshot, |
| 1917 | /// This frame header's chosen deblocking parameters |
| 1918 | /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the |
| 1919 | /// picture the decoder produces UNDER them, so a test that decodes |
| 1920 | /// `tile` directly must pass these along, exactly as it must `tx_select` |
| 1921 | /// (class: test asserts against a stale header). |
| 1922 | pub(crate) loop_filter: LoopFilterParams, |
| 1923 | /// This frame header's chosen CDEF parameters, threaded for the same |
| 1924 | /// reason as `loop_filter`. |
| 1925 | pub(crate) cdef: CdefParams, |
| 1926 | /// This frame header's `allow_screen_content_tools` |
| 1927 | /// ([`screen_content`]) -- every intra block of the tile carries the two |
| 1928 | /// palette-mode symbols under it, so a raw tile decode that guessed |
| 1929 | /// `false` would desync at the first block (same class as `tx_select`). |
| 1930 | pub(crate) screen: bool, |
| 1931 | /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that |
| 1932 | /// picks the inter `tx_type` alphabets AND, on an inter block, the |
| 1933 | /// allowance the chroma transform's inherited type reduces against |
| 1934 | /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile |
| 1935 | /// decode that guesses `true` here mis-derives every inherited chroma |
| 1936 | /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as |
| 1937 | /// `tx_select`/`screen` above). |
| 1938 | pub(crate) reduced_tx_set: bool, |
| 1939 | /// This frame header's chosen loop restoration parameters, threaded for |
| 1940 | /// the same reason as `loop_filter` -- and doubly so: the per-unit |
| 1941 | /// filters themselves are coded in `tile`, so a decode of it under a |
| 1942 | /// stale `RESTORE_NONE` header desyncs at the first superblock. |
| 1943 | pub(crate) loop_restoration: LoopRestorationParams, |
| 1944 | /// This frame header's `allow_intrabc` -- every intra block of the tile |
| 1945 | /// carries a `use_intrabc` symbol under it, so a raw tile decode that |
| 1946 | /// guessed `false` would desync at the first block (same class as |
| 1947 | /// `screen`/`tx_select`). |
| 1948 | pub(crate) allow_intrabc: bool, |
| 1949 | /// This frame header's `delta_q_params`/`delta_lf_params` (spec |
| 1950 | /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first |
| 1951 | /// coded block carries a `delta_qindex` symbol group, so a raw tile |
| 1952 | /// decode that guessed the defaults desyncs at the first superblock |
| 1953 | /// (same class as `screen`/`tx_select`). |
| 1954 | pub(crate) delta: ec_av1_syntax::DeltaParams, |
| 1955 | } |
| 1956 | |
| 1957 | thread_local! { |
| 1958 | /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat |
| 1959 | /// for on the last key frame encoded on this thread -- read by the gates, |
| 1960 | /// which print it beside the block counts (class `gate-blind-to-feature`). |
| 1961 | static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) }; |
| 1962 | } |
| 1963 | |
| 1964 | /// [`IBC_SHARE`] for the last key frame encoded on this thread. |
| 1965 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 1966 | pub(crate) fn intrabc_source_share() -> f64 { |
| 1967 | IBC_SHARE.with(std::cell::Cell::get) |
| 1968 | } |
| 1969 | |
| 1970 | thread_local! { |
| 1971 | /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence |
| 1972 | /// header offers the per-frame `allow_screen_content_tools` bit at all. |
| 1973 | /// Armed once by the key frame ([`encode_key_frame_inner`], from |
| 1974 | /// [`screen_content`]) and read by every header builder after it, so that |
| 1975 | /// the inter frames of a screen sequence lay their headers out the same |
| 1976 | /// way the sequence header the key frame wrote says they do -- a per-call |
| 1977 | /// parameter would have to thread through `inter_frame_headers`' four |
| 1978 | /// public entry points and every hand-built-stream test that calls them. |
| 1979 | /// A sequence with no screen content leaves this false and writes exactly |
| 1980 | /// the bits it wrote before this lane. |
| 1981 | static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 1982 | } |
| 1983 | |
| 1984 | thread_local! { |
| 1985 | /// Overrides [`screen_content`] for the calling thread, which is what the |
| 1986 | /// intra-MODE ablations use: on a two-colour synthetic picture the palette |
| 1987 | /// codes every block losslessly, so both arms of a mode ablation reach |
| 1988 | /// infinite PSNR and the ablation measures nothing at all (the |
| 1989 | /// `fixture-proves-the-symbol-not-the-signal` class). An environment |
| 1990 | /// variable cannot do this -- the tests run in one process, in parallel. |
| 1991 | static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 1992 | } |
| 1993 | |
| 1994 | thread_local! { |
| 1995 | /// What the last [`encode_sequence_with_ctx`] call on this thread coded |
| 1996 | /// under, AFTER the content gate: the pyramid, or `None` for a stream |
| 1997 | /// that stayed flat. Read by the BD gates, which print the requested and |
| 1998 | /// the effective pyramid side by side -- a screen clip requests one and |
| 1999 | /// codes flat, and that difference is the gate (class |
| 2000 | /// `gate-blind-to-feature`). |
| 2001 | static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> = |
| 2002 | const { std::cell::Cell::new(None) }; |
| 2003 | } |
| 2004 | |
| 2005 | /// The pyramid the last sequence coded on this thread was EFFECTIVELY under. |
| 2006 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 2007 | pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> { |
| 2008 | LAST_SEQ_PYRAMID.with(std::cell::Cell::get) |
| 2009 | } |
| 2010 | |
| 2011 | #[cfg(test)] |
| 2012 | pub(crate) fn force_screen(value: Option<bool>) { |
| 2013 | SCREEN_FORCE.with(|c| c.set(value)); |
| 2014 | } |
| 2015 | |
| 2016 | // lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE |
| 2017 | // ablation can measure the mode search alone. Setting it also clears the |
| 2018 | // sequence header's own `enable_filter_intra` bit, so the stream the arm |
| 2019 | // writes is exactly the one this encoder wrote before the lane. |
| 2020 | #[cfg(test)] |
| 2021 | thread_local! { |
| 2022 | static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 2023 | } |
| 2024 | |
| 2025 | #[cfg(test)] |
| 2026 | pub(crate) fn force_filter_intra(value: Option<bool>) { |
| 2027 | FILTER_INTRA_FORCE.with(|c| c.set(value)); |
| 2028 | } |
| 2029 | |
| 2030 | pub(crate) fn arm_seq_screen(on: bool) { |
| 2031 | SEQ_SCREEN.with(|c| c.set(on)); |
| 2032 | } |
| 2033 | |
| 2034 | fn seq_screen() -> bool { |
| 2035 | SEQ_SCREEN.with(std::cell::Cell::get) |
| 2036 | } |
| 2037 | |
| 2038 | /// How many distinct colours a 16x16 luma block may hold and still count as |
| 2039 | /// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own |
| 2040 | /// `av1_set_screen_content_options` bound is 4, which separates nothing on |
| 2041 | /// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against |
| 2042 | /// the variance floor below on the five gate clips at BOTH the native crop |
| 2043 | /// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of |
| 2044 | /// the frame is the widest-margin split of those ten rows -- every |
| 2045 | /// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5 |
| 2046 | /// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6% |
| 2047 | /// native and 17.9% scaled. |
| 2048 | fn screen_colors() -> usize { |
| 2049 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 2050 | *N.get_or_init(|| { |
| 2051 | std::env::var("EC_AV1_SCREEN_COLORS") |
| 2052 | .ok() |
| 2053 | .and_then(|v| v.parse().ok()) |
| 2054 | .unwrap_or(16) |
| 2055 | }) |
| 2056 | } |
| 2057 | |
| 2058 | /// The reciprocal of the frame area those blocks must cover, in tenths -- |
| 2059 | /// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth; |
| 2060 | /// 8 (an eighth) is the midpoint of the two populations |
| 2061 | /// `probe_screen_detect` measures at the colour bound and variance floor |
| 2062 | /// around it. `EC_AV1_SCREEN_PCT`. |
| 2063 | fn screen_pct() -> usize { |
| 2064 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 2065 | *N.get_or_init(|| { |
| 2066 | std::env::var("EC_AV1_SCREEN_PCT") |
| 2067 | .ok() |
| 2068 | .and_then(|v| v.parse().ok()) |
| 2069 | .unwrap_or(10) |
| 2070 | }) |
| 2071 | } |
| 2072 | |
| 2073 | /// The per-pixel variance a few-colour block must clear before it counts as |
| 2074 | /// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its |
| 2075 | /// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it |
| 2076 | /// a smooth dark film frame is all few-colour blocks and reads as a desktop |
| 2077 | /// capture -- which is exactly what this detector did until 2026-09-07, when |
| 2078 | /// it called BOTH real films screen content on 48/48 frames, priced every |
| 2079 | /// coefficient against the default CDFs and ran the palette search over |
| 2080 | /// film. `probe_screen_detect`: at 16 colours the floor takes both films |
| 2081 | /// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to |
| 2082 | /// 23.6%. |
| 2083 | fn screen_var() -> u64 { |
| 2084 | static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); |
| 2085 | *N.get_or_init(|| { |
| 2086 | std::env::var("EC_AV1_SCREEN_VAR") |
| 2087 | .ok() |
| 2088 | .and_then(|v| v.parse().ok()) |
| 2089 | .unwrap_or(16) |
| 2090 | }) |
| 2091 | } |
| 2092 | |
| 2093 | /// How many frames [`screen_content`] said yes/no to, so a gate can print |
| 2094 | /// whether the detector fired at all (class `gate-blind-to-feature`). |
| 2095 | pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] = |
| 2096 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 2097 | |
| 2098 | /// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count |
| 2099 | /// the distinct colours of every 16x16 block and turn the screen-content |
| 2100 | /// tools on when the blocks holding between 2 and [`screen_colors`] of them |
| 2101 | /// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the |
| 2102 | /// frame. `width` is the plane's |
| 2103 | /// stride, `true_*` the frame's real (decodable) extent. |
| 2104 | fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool { |
| 2105 | if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) { |
| 2106 | SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2107 | return forced; |
| 2108 | } |
| 2109 | if let Ok(v) = std::env::var("EC_AV1_SCREEN") { |
| 2110 | let on = v != "0"; |
| 2111 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2112 | return on; |
| 2113 | } |
| 2114 | let (blk, limit, floor) = (16usize, screen_colors(), screen_var()); |
| 2115 | let mut counted = 0usize; |
| 2116 | for by in (0..true_height).step_by(blk) { |
| 2117 | for bx in (0..true_width).step_by(blk) { |
| 2118 | let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk)); |
| 2119 | let mut seen = [false; 256]; |
| 2120 | let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64); |
| 2121 | for row in 0..h { |
| 2122 | for col in 0..w { |
| 2123 | let v = y[(by + row) * width + bx + col]; |
| 2124 | sum += u64::from(v); |
| 2125 | sq += u64::from(v) * u64::from(v); |
| 2126 | if !seen[usize::from(v)] { |
| 2127 | seen[usize::from(v)] = true; |
| 2128 | colors += 1; |
| 2129 | } |
| 2130 | } |
| 2131 | } |
| 2132 | // Per-pixel variance over the block's real (edge-clipped) extent. |
| 2133 | let n = (h * w) as u64; |
| 2134 | let var = (sq - sum * sum / n) / n; |
| 2135 | if colors > 1 && colors <= limit && var > floor { |
| 2136 | counted += 1; |
| 2137 | } |
| 2138 | } |
| 2139 | } |
| 2140 | let on = counted * blk * blk * screen_pct() > true_width * true_height; |
| 2141 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2142 | on |
| 2143 | } |
| 2144 | |
| 2145 | /// Whether this SOURCE picture reads as screen content, for a caller that has |
| 2146 | /// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`] |
| 2147 | /// gates its coding pyramid on this (a desktop capture keeps the flat |
| 2148 | /// one-in-one-out structure the BD gate measured it on, camera material takes |
| 2149 | /// the mini-GOP). The key frame runs the same detector again when it builds |
| 2150 | /// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to |
| 2151 | /// count, so this probe undoes its own tick and leaves the gate prints |
| 2152 | /// reading one detection per coded frame. |
| 2153 | pub(crate) fn picture_is_screen(picture: &Picture) -> bool { |
| 2154 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 2155 | let on = screen_content(&y, picture.width, picture.width, picture.height); |
| 2156 | SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); |
| 2157 | on |
| 2158 | } |
| 2159 | |
| 2160 | /// The sequence and frame headers a picture of this size is coded under: one |
| 2161 | /// tile, one transform size per block, no in-loop filter parameters yet |
| 2162 | /// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and |
| 2163 | /// CDEF strengths in once the tile is coded), no CDF adaptation |
| 2164 | /// and no tool the tile writer does not code. |
| 2165 | /// |
| 2166 | /// # Errors |
| 2167 | /// Returns an error when the picture is larger than the 16-bit frame size the |
| 2168 | /// sequence header carries. |
| 2169 | pub fn key_frame_headers( |
| 2170 | width: usize, |
| 2171 | height: usize, |
| 2172 | base_q_idx: u8, |
| 2173 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 2174 | key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config()) |
| 2175 | } |
| 2176 | |
| 2177 | /// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and |
| 2178 | /// studio (limited) range: what this crate's sequence header carried before |
| 2179 | /// [`crate::encoder`]'s facade could configure it, and what |
| 2180 | /// [`key_frame_headers`] still asks for. |
| 2181 | fn unspecified_color_config() -> ColorConfig { |
| 2182 | ColorConfig { |
| 2183 | bit_depth: 8, |
| 2184 | mono_chrome: false, |
| 2185 | num_planes: 3, |
| 2186 | color_primaries: 2, |
| 2187 | transfer_characteristics: 2, |
| 2188 | matrix_coefficients: 2, |
| 2189 | color_range: false, |
| 2190 | subsampling_x: 1, |
| 2191 | subsampling_y: 1, |
| 2192 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 2193 | separate_uv_delta_q: false, |
| 2194 | } |
| 2195 | } |
| 2196 | |
| 2197 | /// [`key_frame_headers`] with the sequence header's colour config named |
| 2198 | /// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`, |
| 2199 | /// `transfer_characteristics`, `matrix_coefficients` and `color_range`, |
| 2200 | /// which is all a player picks a colour transform from and which |
| 2201 | /// [`crate::encoder::Colour`] is the facade's own name for. |
| 2202 | /// |
| 2203 | /// # Errors |
| 2204 | /// The same as [`key_frame_headers`]. |
| 2205 | pub(crate) fn key_frame_headers_colour( |
| 2206 | width: usize, |
| 2207 | height: usize, |
| 2208 | base_q_idx: u8, |
| 2209 | color_config: ColorConfig, |
| 2210 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 2211 | let bits = |n: usize| -> Result<u32> { |
| 2212 | let n = u32::try_from(n).map_err(|_| too_large())?; |
| 2213 | if n == 0 || n > 1 << 16 { |
| 2214 | return Err(too_large()); |
| 2215 | } |
| 2216 | Ok((32 - (n - 1).leading_zeros()).max(1)) |
| 2217 | }; |
| 2218 | let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?); |
| 2219 | let (w, h) = (width as u32, height as u32); |
| 2220 | let seq = SequenceHeader { |
| 2221 | seq_profile: 0, |
| 2222 | operating_points: vec![OperatingPoint { |
| 2223 | seq_level_idx: 8, |
| 2224 | ..OperatingPoint::default() |
| 2225 | }], |
| 2226 | frame_width_bits, |
| 2227 | frame_height_bits, |
| 2228 | max_frame_width: w, |
| 2229 | max_frame_height: h, |
| 2230 | use_128x128_superblock: sb128_on(), |
| 2231 | // lane-fintra: the encoder's intra search offers the five recursive |
| 2232 | // filter-intra modes on eligible blocks, so the sequence bit is set |
| 2233 | // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both |
| 2234 | // off and restores the streams this encoder wrote before the lane). |
| 2235 | enable_filter_intra: filter_intra_on(), |
| 2236 | enable_intra_edge_filter: false, |
| 2237 | enable_order_hint: true, |
| 2238 | order_hint_bits: 7, |
| 2239 | enable_superres: false, |
| 2240 | // spec 5.9.19: with the sequence bit set every frame header carries |
| 2241 | // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength |
| 2242 | // pair for the whole frame, chosen by `crate::filter_search` -- so no |
| 2243 | // `cdef_idx` literal is coded in the tile and a frame that wants no |
| 2244 | // CDEF simply carries zero strengths. |
| 2245 | enable_cdef: true, |
| 2246 | enable_restoration: true, |
| 2247 | // SELECT (2) when this sequence's key frame detected screen content |
| 2248 | // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit |
| 2249 | // is then coded in every frame header, and only the frames that want |
| 2250 | // the palette syntax set it. 0 -- the forced-off form, no bit at all |
| 2251 | // -- otherwise, which is what every non-screen stream this encoder |
| 2252 | // writes still carries. |
| 2253 | seq_force_screen_content_tools: if seq_screen() { |
| 2254 | ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS |
| 2255 | } else { |
| 2256 | 0 |
| 2257 | }, |
| 2258 | seq_force_integer_mv: 0, |
| 2259 | color_config, |
| 2260 | still_picture: false, |
| 2261 | reduced_still_picture_header: false, |
| 2262 | timing_info: None, |
| 2263 | decoder_model_info: None, |
| 2264 | initial_display_delay_present_flag: false, |
| 2265 | operating_point: 0, |
| 2266 | operating_point_idc: 0, |
| 2267 | frame_id_numbers_present_flag: false, |
| 2268 | delta_frame_id_length: 0, |
| 2269 | additional_frame_id_length: 0, |
| 2270 | enable_interintra_compound: false, |
| 2271 | enable_masked_compound: false, |
| 2272 | // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on |
| 2273 | // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence |
| 2274 | // header is byte-identical to the streams before this lane. |
| 2275 | enable_warped_motion: warp_on(), |
| 2276 | enable_dual_filter: false, |
| 2277 | enable_jnt_comp: false, |
| 2278 | enable_ref_frame_mvs: false, |
| 2279 | film_grain_params_present: false, |
| 2280 | }; |
| 2281 | // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's |
| 2282 | // own (true, unpadded) width and height, not from any block-grid |
| 2283 | // alignment — a decoder derives these straight from `frame_width`/ |
| 2284 | // `frame_height` below, so this must match it exactly. |
| 2285 | let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3)); |
| 2286 | let header = FrameHeader { |
| 2287 | frame_type: FrameType::Key, |
| 2288 | frame_is_intra: true, |
| 2289 | show_frame: true, |
| 2290 | error_resilient_mode: true, |
| 2291 | // The tile writer keeps the same CDF state the decoder does and |
| 2292 | // updates it in the same order, so the frame lets the decoder adapt. |
| 2293 | disable_cdf_update: false, |
| 2294 | // Nothing reads the state this frame leaves behind: a key frame always |
| 2295 | // starts from the defaults, and this encoder emits one frame. |
| 2296 | disable_frame_end_update_cdf: true, |
| 2297 | force_integer_mv: true, |
| 2298 | refresh_frame_flags: 0xFF, |
| 2299 | primary_ref_frame: PRIMARY_REF_NONE, |
| 2300 | frame_width: w, |
| 2301 | frame_height: h, |
| 2302 | upscaled_width: w, |
| 2303 | render_width: w, |
| 2304 | render_height: h, |
| 2305 | mi_cols, |
| 2306 | mi_rows, |
| 2307 | tile_info: TileInfo { |
| 2308 | uniform_spacing: true, |
| 2309 | cols: 1, |
| 2310 | rows: 1, |
| 2311 | mi_col_starts: vec![0, mi_cols], |
| 2312 | mi_row_starts: vec![0, mi_rows], |
| 2313 | tile_size_bytes: 1, |
| 2314 | ..TileInfo::default() |
| 2315 | }, |
| 2316 | quantization: QuantizationParams { |
| 2317 | base_q_idx, |
| 2318 | ..QuantizationParams::default() |
| 2319 | }, |
| 2320 | tx_mode: TxMode::Largest, |
| 2321 | // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every |
| 2322 | // intra transform below 32x32, not only 16x16 -- the set this crate |
| 2323 | // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`). |
| 2324 | // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`), |
| 2325 | // so a decoder honouring the header picks the same CDF the writer |
| 2326 | // used only if this is set here too, not only on the inter variant |
| 2327 | // below -- an r14 lane-av1-rect fix: a key frame's own header used to |
| 2328 | // default this to `false`, so `av1_get_ext_tx_set_type` picked the |
| 2329 | // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the |
| 2330 | // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging |
| 2331 | // the arithmetic coder's `rng` register from the very first 8x8-leaf |
| 2332 | // luma transform onward with no symbol value ever differing. |
| 2333 | reduced_tx_set: true, |
| 2334 | ..FrameHeader::default() |
| 2335 | }; |
| 2336 | Ok((seq, header)) |
| 2337 | } |
| 2338 | |
| 2339 | /// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the |
| 2340 | /// key frame refreshes all eight slots, each inter frame only slot 0, so slot |
| 2341 | /// 1 still holds the key frame however long the GOP runs. |
| 2342 | pub const GOLDEN_SLOT: u8 = 1; |
| 2343 | |
| 2344 | /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter |
| 2345 | /// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the |
| 2346 | /// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR -- |
| 2347 | /// one filter for the whole frame, which is what libaom does on this content |
| 2348 | /// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own |
| 2349 | /// stream, so a per-BLOCK filter search has no bits to win). The kernel |
| 2350 | /// reaches the search, the trials and the recon through |
| 2351 | /// `FrameCtx::interp_filter`, so the stream a decoder reads and the |
| 2352 | /// prediction the search priced are the same one. |
| 2353 | /// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the |
| 2354 | /// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has: |
| 2355 | /// the witness that has to see a non-REGULAR kernel coded and decoded turns |
| 2356 | /// it on through this while holding [`crate::speed::knob_write`]. |
| 2357 | static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 2358 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 2359 | |
| 2360 | /// Sets [`INTERP_OVERRIDE`]; `None` clears it. |
| 2361 | #[allow(dead_code)] // set only from the `#[cfg(test)]` gates |
| 2362 | pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) { |
| 2363 | INTERP_OVERRIDE.store( |
| 2364 | filter.map_or(u8::MAX, |f| f as u8), |
| 2365 | std::sync::atomic::Ordering::Relaxed, |
| 2366 | ); |
| 2367 | } |
| 2368 | |
| 2369 | fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter { |
| 2370 | use ec_av1_syntax::InterpolationFilter as F; |
| 2371 | match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 2372 | 0 => return F::Eighttap, |
| 2373 | 1 => return F::EighttapSmooth, |
| 2374 | 2 => return F::EighttapSharp, |
| 2375 | _ => {} |
| 2376 | } |
| 2377 | static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| { |
| 2378 | crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() { |
| 2379 | "smooth" => F::EighttapSmooth, |
| 2380 | "sharp" => F::EighttapSharp, |
| 2381 | _ => F::Eighttap, |
| 2382 | }) |
| 2383 | }); |
| 2384 | ENV.unwrap_or(F::Eighttap) |
| 2385 | } |
| 2386 | |
| 2387 | /// The frame header for a shown inter frame that predicts from the single |
| 2388 | /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that |
| 2389 | /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s, |
| 2390 | /// reused verbatim: an inter frame never changes the sequence. |
| 2391 | /// |
| 2392 | /// # Errors |
| 2393 | /// Returns an error under the same conditions as [`key_frame_headers`]. |
| 2394 | pub fn inter_frame_headers( |
| 2395 | width: usize, |
| 2396 | height: usize, |
| 2397 | base_q_idx: u8, |
| 2398 | order_hint: u32, |
| 2399 | last_slot: u8, |
| 2400 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 2401 | inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot) |
| 2402 | } |
| 2403 | |
| 2404 | /// [`inter_frame_headers`] with the three slots named apart: the one read as |
| 2405 | /// `LAST_FRAME`, the one this frame refreshes, and the one read as |
| 2406 | /// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2 |
| 2407 | /// so that the frame two back is still intact in the slot this one is about |
| 2408 | /// to overwrite -- read before write, spec 7.20's decode order. |
| 2409 | /// |
| 2410 | /// # Errors |
| 2411 | /// As [`inter_frame_headers`]. |
| 2412 | pub fn inter_frame_headers_slots( |
| 2413 | width: usize, |
| 2414 | height: usize, |
| 2415 | base_q_idx: u8, |
| 2416 | order_hint: u32, |
| 2417 | last_slot: u8, |
| 2418 | self_slot: u8, |
| 2419 | altref_slot: u8, |
| 2420 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 2421 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; |
| 2422 | let header = FrameHeader { |
| 2423 | frame_type: FrameType::Inter, |
| 2424 | frame_is_intra: false, |
| 2425 | show_frame: true, |
| 2426 | error_resilient_mode: false, |
| 2427 | disable_cdf_update: false, |
| 2428 | // The tile writer hands its end-of-tile tables to the next frame |
| 2429 | // (`encode_sequence_with_ctx`), so the frame stores them the way the |
| 2430 | // decoder will load them (spec 7.20). |
| 2431 | disable_frame_end_update_cdf: false, |
| 2432 | force_integer_mv: false, |
| 2433 | order_hint, |
| 2434 | primary_ref_frame: 0, |
| 2435 | refresh_frame_flags: 1 << self_slot, |
| 2436 | // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`) |
| 2437 | // names the slot this frame both predicts from and refreshes; |
| 2438 | // GOLDEN names slot 1, which the key frame wrote when it refreshed |
| 2439 | // all eight and which no inter frame ever overwrites, so it holds |
| 2440 | // the key frame's own picture for the whole GOP. |
| 2441 | ref_frame_idx: { |
| 2442 | let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME]; |
| 2443 | idx[3] = GOLDEN_SLOT; |
| 2444 | idx[6] = altref_slot; |
| 2445 | idx |
| 2446 | }, |
| 2447 | // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`: |
| 2448 | // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's |
| 2449 | // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in |
| 2450 | // every frame this constructor builds, so no further guard is needed. |
| 2451 | allow_high_precision_mv: high_precision_mv_at(base_q_idx), |
| 2452 | // A FIXED frame-level filter, so no block codes an `interp_filter` |
| 2453 | // symbol. lane-obmc3 instrumented whether that costs anything: a |
| 2454 | // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window |
| 2455 | // (45941 B, the same point `lanes/libcen.report.md` matched) read |
| 2456 | // back through `EC_AV1_BITCENSUS=1 syntax_census` codes |
| 2457 | // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed |
| 2458 | // frame filter here too, so there are ZERO per-block filter bits at |
| 2459 | // stake on this content and the per-block switchable search was not |
| 2460 | // built (the charter's premise that libaom codes switchable interp |
| 2461 | // per block on film B is refuted by its own stream). |
| 2462 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, |
| 2463 | // lane-av1obmc: with this bit set every single-reference inter block |
| 2464 | // libaom's `motion_mode_allowed` accepts carries a `motion_mode` |
| 2465 | // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion` |
| 2466 | // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied |
| 2467 | // to the OBMC knob rather than always on: with every block choosing |
| 2468 | // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the |
| 2469 | // gate clip), so the DEFAULT path writes no motion_mode syntax at all |
| 2470 | // and stays byte-identical to the streams before this lane. |
| 2471 | // lane-av1obmc2: the warp knob joins that disjunction, and turns on |
| 2472 | // `allow_warped_motion` besides -- which is what makes an eligible |
| 2473 | // block read the 3-symbol `motion_mode_cdf` alphabet instead of the |
| 2474 | // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`). |
| 2475 | is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") |
| 2476 | || warp_on(), |
| 2477 | allow_warped_motion: warp_on(), |
| 2478 | use_ref_frame_mvs: false, |
| 2479 | // Forces `get_tx_set` (spec 5.11.48) to the two-symbol |
| 2480 | // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only |
| 2481 | // set this crate carries a table for at 16x16 (see |
| 2482 | // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter |
| 2483 | // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already |
| 2484 | // reads `TX_SET_INTER_3` regardless of this flag). An intra transform |
| 2485 | // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect: |
| 2486 | // the earlier claim here was wrong and desynced the 8x8-leaf straddle |
| 2487 | // path) -- with this flag set, `get_tx_set`'s intra branch returns |
| 2488 | // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads |
| 2489 | // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`. |
| 2490 | reduced_tx_set: true, |
| 2491 | ..key |
| 2492 | }; |
| 2493 | Ok((seq, header)) |
| 2494 | } |
| 2495 | |
| 2496 | fn too_large() -> Error { |
| 2497 | Error::unsupported( |
| 2498 | "AV1 encode", |
| 2499 | "the picture is larger than a frame size can carry", |
| 2500 | ) |
| 2501 | } |
| 2502 | |
| 2503 | /// One plane of the picture being coded, and the reconstruction being built |
| 2504 | /// beside it. |
| 2505 | /// What one committed 4x4 cell left behind for the coefficient contexts of |
| 2506 | /// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which |
| 2507 | /// is the same state decode.rs records. |
| 2508 | #[derive(Clone, Copy, Default, PartialEq, Eq)] |
| 2509 | struct CoefCtx { |
| 2510 | /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7. |
| 2511 | level: u8, |
| 2512 | /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when |
| 2513 | /// the DC itself was zero (tile.rs `dc_vote`). |
| 2514 | dc: i8, |
| 2515 | } |
| 2516 | |
| 2517 | /// One plane's coefficient contexts, committed in CODING ORDER: the search |
| 2518 | /// prices partition TREES, so the neighbour state a candidate reads has to be |
| 2519 | /// whatever the blocks coded before it left -- the parent's committed |
| 2520 | /// neighbours for a tree's first child, the just-committed sibling for the |
| 2521 | /// later ones. Keeping the map as a full per-4x4-cell grid rather than the |
| 2522 | /// writer's two running bands is what makes that fall out: a trial commits |
| 2523 | /// over its own rectangle ([`Plane::commit`]) and a losing trial is undone |
| 2524 | /// with the pixels ([`Plane::restore`]), so what a candidate reads above and |
| 2525 | /// to its left is exactly what the tile writer's `Neighbours` bands will hold |
| 2526 | /// when it gets there. |
| 2527 | /// |
| 2528 | /// Before this map the pricer took both contexts as zero, which is exact for |
| 2529 | /// a luma transform covering its whole block and the largest remaining row of |
| 2530 | /// the pricer census everywhere else (all-zero chroma under-priced 41-81%). |
| 2531 | #[derive(Default)] |
| 2532 | struct CoefCtxMap { |
| 2533 | cells: Vec<CoefCtx>, |
| 2534 | stride: usize, |
| 2535 | /// Whether the transforms being priced right now are SMALLER than the |
| 2536 | /// block they sit in -- a `TxMode::Select` depth split |
| 2537 | /// ([`Plane::code_tx_depth`]) or an inter var-tx split |
| 2538 | /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a |
| 2539 | /// trial cannot tell, and it is what decides whether luma reads context 0 |
| 2540 | /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`). |
| 2541 | tu_split: bool, |
| 2542 | } |
| 2543 | |
| 2544 | /// Whether [`Plane::block_sse`] scores a block the true frame edge cuts |
| 2545 | /// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the |
| 2546 | /// padding-inclusive score the search used before lane-sse, which is how the |
| 2547 | /// before/after arms of the straddling gate rows are read off ONE binary. |
| 2548 | fn edge_sse() -> bool { |
| 2549 | static ENV: std::sync::LazyLock<Option<bool>> = |
| 2550 | std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0")); |
| 2551 | ENV.unwrap_or(true) |
| 2552 | } |
| 2553 | |
| 2554 | /// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts |
| 2555 | /// through and the share of their raw squared error that sat in the padding |
| 2556 | /// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for |
| 2557 | /// it, but the numbers are an instrument, not a decision (class |
| 2558 | /// `gate-blind-to-feature` -- both gate films are superblock-aligned, so |
| 2559 | /// without this census no gate row can say the clip fires at all). |
| 2560 | fn edge_census() -> bool { |
| 2561 | static ENV: std::sync::LazyLock<bool> = |
| 2562 | std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1")); |
| 2563 | *ENV |
| 2564 | } |
| 2565 | |
| 2566 | /// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is |
| 2567 | /// 128x128): how many scores clipped, the inside squared error they kept and |
| 2568 | /// the padding squared error they dropped. |
| 2569 | static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] = |
| 2570 | [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8]; |
| 2571 | |
| 2572 | /// One clipped score, for [`take_edge_census`]. |
| 2573 | fn record_edge_score(side: usize, inside: u64, padding: u64) { |
| 2574 | let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)]; |
| 2575 | row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2576 | row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed); |
| 2577 | row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed); |
| 2578 | } |
| 2579 | |
| 2580 | /// The straddling-block census since the last call, and zero it: one |
| 2581 | /// `(side, scores, inside_sse, padding_sse)` row per block size that fired. |
| 2582 | #[must_use] |
| 2583 | pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> { |
| 2584 | EDGE_SCORES |
| 2585 | .iter() |
| 2586 | .enumerate() |
| 2587 | .filter_map(|(log2, row)| { |
| 2588 | let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed); |
| 2589 | let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed); |
| 2590 | let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed); |
| 2591 | (n != 0).then_some((1usize << log2, n, inside, padding)) |
| 2592 | }) |
| 2593 | .collect() |
| 2594 | } |
| 2595 | |
| 2596 | struct Plane<'a> { |
| 2597 | source: &'a [u8], |
| 2598 | reconstruction: Vec<u8>, |
| 2599 | width: usize, |
| 2600 | height: usize, |
| 2601 | /// The frame's true, decodable extent in this plane's own units -- |
| 2602 | /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples, |
| 2603 | /// not `width`/`height` above, which is the padded coding-surface size. |
| 2604 | /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_ |
| 2605 | /// right_edge`/`mb_to_bottom_edge` clamps (libaom's |
| 2606 | /// `av1/common/reconintra.c` `build_intra_predictors`) never see past |
| 2607 | /// this bound, even though the padded reconstruction buffer holds real |
| 2608 | /// (if never-decoded-by-a-real-decoder) samples out there -- reading |
| 2609 | /// those instead of stopping here is what desyncs prediction at the true |
| 2610 | /// edge. |
| 2611 | true_width: usize, |
| 2612 | true_height: usize, |
| 2613 | /// This plane's own tile's pixel bounds, in this plane's units -- the |
| 2614 | /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra |
| 2615 | /// prediction never reaches across a tile edge even though the |
| 2616 | /// neighbouring tile's real samples sit right there in the shared |
| 2617 | /// reconstruction. `(0, 0, width, height)` is the single-tile case and |
| 2618 | /// leaves every edge exactly as it was before tiles existed. |
| 2619 | tile_x0: usize, |
| 2620 | tile_y0: usize, |
| 2621 | tile_x1: usize, |
| 2622 | tile_y1: usize, |
| 2623 | /// [`CoefCtxMap`]: what the blocks already committed left for the |
| 2624 | /// coefficient contexts of the ones still being priced. Sized on the |
| 2625 | /// first commit, so a plane literal does not have to know its own extent |
| 2626 | /// twice. |
| 2627 | ctx: CoefCtxMap, |
| 2628 | } |
| 2629 | |
| 2630 | impl Plane<'_> { |
| 2631 | /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]), |
| 2632 | /// called at every superblock of the frame-raster search with the rect |
| 2633 | /// of the tile that superblock belongs to. |
| 2634 | fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { |
| 2635 | self.tile_x0 = x0; |
| 2636 | self.tile_y0 = y0; |
| 2637 | self.tile_x1 = x1.min(self.width); |
| 2638 | self.tile_y1 = y1.min(self.height); |
| 2639 | } |
| 2640 | /// The reconstructed samples a block at `(x, y)` predicts from: the row |
| 2641 | /// above it, the column to its left and the sample between them, each |
| 2642 | /// missing where the block sits against an edge of the frame. |
| 2643 | /// |
| 2644 | /// `reach` says whether the samples above the block's right and below its |
| 2645 | /// left are decoded, which is what a directional mode reads into; where |
| 2646 | /// they are not, or where the frame ends first, the edge is shorter and |
| 2647 | /// the predictor repeats its last sample, exactly as the decoder's clamp |
| 2648 | /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2). |
| 2649 | /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and |
| 2650 | /// a free per mode per block, on the search's hottest path -- while an |
| 2651 | /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same |
| 2652 | /// samples, on the caller's stack. |
| 2653 | fn edges_into<'a>( |
| 2654 | &self, |
| 2655 | x: usize, |
| 2656 | y: usize, |
| 2657 | side: usize, |
| 2658 | reach: Reach, |
| 2659 | above_buf: &'a mut [u8; 2 * SUPERBLOCK], |
| 2660 | left_buf: &'a mut [u8; 2 * SUPERBLOCK], |
| 2661 | ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) { |
| 2662 | // Even a block's *own* edge is clamped to the true frame bound, not |
| 2663 | // just a `reach` extension: libaom's `av1_predict_intra_block` |
| 2664 | // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from |
| 2665 | // this block's own right/bottom to the frame edge -- from |
| 2666 | // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from |
| 2667 | // `mi_cols`/`mi_rows` (the true, decodable extent), never from any |
| 2668 | // padded coding surface. `n_top_px`/`n_left_px` (how many *real* |
| 2669 | // samples the row/column above/left holds before the decoder starts |
| 2670 | // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/ |
| 2671 | // `leftLimit`) is `min(side, xr + side)` even for a block whose own |
| 2672 | // extent straddles that edge legally (`has_half`) -- the transform |
| 2673 | // still covers the whole block, but prediction does not get to read |
| 2674 | // real reconstructed pixels past the true edge for its own row/column, |
| 2675 | // only for the padded tail it invents. |
| 2676 | let own_across = x + side.min(self.true_width.saturating_sub(x)); |
| 2677 | let across = if reach.above_right { |
| 2678 | own_across + side.min(self.true_width.saturating_sub(own_across)) |
| 2679 | } else { |
| 2680 | own_across |
| 2681 | } |
| 2682 | .min(self.width); |
| 2683 | let own_down = y + side.min(self.true_height.saturating_sub(y)); |
| 2684 | let down = if reach.below_left { |
| 2685 | own_down + side.min(self.true_height.saturating_sub(own_down)) |
| 2686 | } else { |
| 2687 | own_down |
| 2688 | } |
| 2689 | .min(self.height); |
| 2690 | // `across`/`down` can still fall at or below `x`/`y` for a sub-block |
| 2691 | // whose own origin already sits past the true edge -- only reachable |
| 2692 | // through a partition trial priced for comparison on a split this |
| 2693 | // frame's straddling quadrant will go on to refuse (see |
| 2694 | // `a_picture_off_the_block_grid_is_refused`), never through a block |
| 2695 | // this encoder actually commits. Such a block has no true-edge |
| 2696 | // samples above or left of it at all, same as `y == 0`/`x == 0`. |
| 2697 | let across = across.min(self.tile_x1); |
| 2698 | let down = down.min(self.tile_y1); |
| 2699 | let above_n = (y > self.tile_y0 && across > x).then(|| across - x); |
| 2700 | if let Some(n) = above_n { |
| 2701 | above_buf[..n] |
| 2702 | .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]); |
| 2703 | } |
| 2704 | let left_n = (x > self.tile_x0 && down > y).then(|| down - y); |
| 2705 | if let Some(n) = left_n { |
| 2706 | for (d, row) in left_buf[..n].iter_mut().zip(y..down) { |
| 2707 | *d = self.reconstruction[row * self.width + x - 1]; |
| 2708 | } |
| 2709 | } |
| 2710 | let corner = (x > self.tile_x0 && y > self.tile_y0) |
| 2711 | .then(|| self.reconstruction[(y - 1) * self.width + x - 1]); |
| 2712 | ( |
| 2713 | above_n.map(|n| &above_buf[..n]), |
| 2714 | left_n.map(|n| &left_buf[..n]), |
| 2715 | corner, |
| 2716 | ) |
| 2717 | } |
| 2718 | |
| 2719 | /// Codes one block under one mode without committing it: hands back the |
| 2720 | /// levels, the block the decoder would reconstruct, the squared error |
| 2721 | /// against the source and an estimate of what the levels cost in bits. |
| 2722 | fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial { |
| 2723 | self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx) |
| 2724 | } |
| 2725 | |
| 2726 | /// [`Self::trial`] under a named transform type -- what an intra chroma |
| 2727 | /// block gets, since chroma codes no `tx_type` symbol and the decoder |
| 2728 | /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`, |
| 2729 | /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps |
| 2730 | /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. |
| 2731 | #[allow(clippy::too_many_arguments)] |
| 2732 | /// Sum of absolute differences between the source block at `(x, y)` and a |
| 2733 | /// `side x side` prediction, as the whole number it is. |
| 2734 | /// |
| 2735 | /// Bit-identical to the `f64` accumulation it replaces: every partial sum |
| 2736 | /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds |
| 2737 | /// exactly, so no add here rounds and the order of the adds cannot change |
| 2738 | /// the result. Dropping the per-pixel `i / side` and `i % side` -- an |
| 2739 | /// integer division per sample -- is what lets the row walk vectorize. |
| 2740 | fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 { |
| 2741 | let mut sad = 0u32; |
| 2742 | for row in 0..side { |
| 2743 | let source = &self.source[(y + row) * self.width + x..][..side]; |
| 2744 | for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) { |
| 2745 | sad += u32::from(s.abs_diff(p)); |
| 2746 | } |
| 2747 | } |
| 2748 | f64::from(sad) |
| 2749 | } |
| 2750 | |
| 2751 | /// Squared error between the source block at `(x, y)` and a reconstruction |
| 2752 | /// of it, over the part of the block that is INSIDE the true frame. |
| 2753 | /// Exact for the same reason [`Self::block_sad`] is: the largest total is |
| 2754 | /// `255^2 * 64 * 64`, under 2^28. |
| 2755 | /// |
| 2756 | /// A block the frame edge cuts through is still coded whole -- the |
| 2757 | /// decoder reconstructs its outside samples too and the display crop |
| 2758 | /// throws them away -- so scoring the padding would rank a mode, a |
| 2759 | /// transform or a partition tree by how well it codes samples the source |
| 2760 | /// does not have (libaom clips the same way: `av1_dist_block` measures |
| 2761 | /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated |
| 2762 | /// edge pixels, so predicting it is nearly free, but coding coefficients |
| 2763 | /// for it spends real bits. Both gate films are superblock-aligned; this |
| 2764 | /// only reaches arbitrary export sizes (lane-sse, generalising |
| 2765 | /// lane-b64b's 64-root-only rescore of the 64 root). |
| 2766 | fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 { |
| 2767 | let inside_rows = side.min(self.true_height.saturating_sub(y)); |
| 2768 | let inside_cols = side.min(self.true_width.saturating_sub(x)); |
| 2769 | let straddles = inside_rows < side || inside_cols < side; |
| 2770 | // The knob is read only for a block the edge cuts, so the interior |
| 2771 | // path -- the hot one -- carries no extra load at all. |
| 2772 | let (rows, cols) = match straddles && !edge_sse() { |
| 2773 | true => (side, side), |
| 2774 | false => (inside_rows, inside_cols), |
| 2775 | }; |
| 2776 | let mut sse = 0u64; |
| 2777 | for row in 0..rows { |
| 2778 | let source = &self.source[(y + row) * self.width + x..][..cols]; |
| 2779 | for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) { |
| 2780 | let d = u32::from(s.abs_diff(r)); |
| 2781 | sse += u64::from(d * d); |
| 2782 | } |
| 2783 | } |
| 2784 | if straddles && edge_census() { |
| 2785 | let (mut inside, mut whole) = (0u64, 0u64); |
| 2786 | for row in 0..side { |
| 2787 | let source = &self.source[(y + row) * self.width + x..][..side]; |
| 2788 | for (col, (&s, &r)) in |
| 2789 | source.iter().zip(&reconstruction[row * side..][..side]).enumerate() |
| 2790 | { |
| 2791 | let d = u64::from(u32::from(s.abs_diff(r)).pow(2)); |
| 2792 | whole += d; |
| 2793 | if row < inside_rows && col < inside_cols { |
| 2794 | inside += d; |
| 2795 | } |
| 2796 | } |
| 2797 | } |
| 2798 | record_edge_score(side, inside, whole - inside); |
| 2799 | } |
| 2800 | sse as f64 |
| 2801 | } |
| 2802 | |
| 2803 | fn trial_typed( |
| 2804 | &self, |
| 2805 | at: At, |
| 2806 | mode: u8, |
| 2807 | // This block's `angle_delta_y`/`angle_delta_uv` (spec |
| 2808 | // `read_intra_angle_info`, -3..=3), zero for every non-directional |
| 2809 | // mode -- the predictor's own `angle_delta` argument. |
| 2810 | angle_delta: i32, |
| 2811 | base_q_idx: u8, |
| 2812 | deadzone: f64, |
| 2813 | tx_type: TxType, |
| 2814 | fctx: &crate::decode::FrameCtx, |
| 2815 | ) -> Trial { |
| 2816 | let At { |
| 2817 | x, y, side, reach, .. |
| 2818 | } = at; |
| 2819 | let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); |
| 2820 | let (above, left, corner) = |
| 2821 | self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); |
| 2822 | // Per-candidate scratch on the search's hottest path, so both buffers |
| 2823 | // live on the stack -- `side` is at most `BLOCK` -- rather than |
| 2824 | // costing a malloc/free pair per trial (`mc_trial` already does this). |
| 2825 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 2826 | let prediction = &mut prediction[..side * side]; |
| 2827 | intra_predict_u8( |
| 2828 | mode, |
| 2829 | angle_delta, |
| 2830 | above, |
| 2831 | left, |
| 2832 | corner, |
| 2833 | side, |
| 2834 | side, |
| 2835 | false, |
| 2836 | false, |
| 2837 | prediction, fctx, |
| 2838 | ); |
| 2839 | |
| 2840 | let mut residual = [0i32; BLOCK * BLOCK]; |
| 2841 | let residual = &mut residual[..side * side]; |
| 2842 | for row in 0..side { |
| 2843 | for col in 0..side { |
| 2844 | residual[row * side + col] = |
| 2845 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 2846 | - i32::from(prediction[row * side + col]); |
| 2847 | } |
| 2848 | } |
| 2849 | #[cfg(test)] |
| 2850 | let t = stage_start(); |
| 2851 | // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the |
| 2852 | // reconstruction below and the price further down are both of the |
| 2853 | // grid this trial would really code. |
| 2854 | let (levels, rdoq_bits) = if rdoq_on() { |
| 2855 | let (mut levels, scaled) = forward_and_quantize_typed_scaled( |
| 2856 | residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, |
| 2857 | ); |
| 2858 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); |
| 2859 | let bits = crate::tile::rdoq( |
| 2860 | &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(), |
| 2861 | tx_type, |
| 2862 | ); |
| 2863 | (levels, Some(bits)) |
| 2864 | } else { |
| 2865 | ( |
| 2866 | forward_and_quantize_typed( |
| 2867 | residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, |
| 2868 | ), |
| 2869 | None, |
| 2870 | ) |
| 2871 | }; |
| 2872 | // lane-av1speed2: 60% of the transform units of an inter stream carry |
| 2873 | // no coefficient at all, and the square entry point re-inflates that |
| 2874 | // case into `side * side` zeros (one allocate-and-memset per trial) |
| 2875 | // only for the sum below to add them to the prediction. The `_wh` |
| 2876 | // entry hands back the empty all-zero marker instead, and a zero |
| 2877 | // residual reconstructs to the prediction itself -- `clamp(p + 0)` is |
| 2878 | // `p` for a `u8`, so the bytes are the same. |
| 2879 | let coded = dequant_and_inverse_typed_wh( |
| 2880 | &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, None, |
| 2881 | ); |
| 2882 | #[cfg(test)] |
| 2883 | stage_since(2, t); |
| 2884 | |
| 2885 | let reconstruction: Vec<u8> = if coded.is_empty() { |
| 2886 | prediction.to_vec() |
| 2887 | } else { |
| 2888 | prediction |
| 2889 | .iter() |
| 2890 | .zip(&coded) |
| 2891 | .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) |
| 2892 | .collect() |
| 2893 | }; |
| 2894 | let sse = self.block_sse(x, y, side, &reconstruction); |
| 2895 | // What the levels cost is priced through the same CDFs the tile writer |
| 2896 | // will code them with, so the search ranks modes -- and the partition |
| 2897 | // trial ranks trees -- by the bits they actually spend. |
| 2898 | #[cfg(test)] |
| 2899 | let t = stage_start(); |
| 2900 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 2901 | // What the search used before it could price a block exactly: a |
| 2902 | // level costs its magnitude's width plus a sign and a run. Kept |
| 2903 | // reachable from the sweep so the two rate terms can be compared |
| 2904 | // on one build. |
| 2905 | levels |
| 2906 | .iter() |
| 2907 | .filter(|&&level| level != 0) |
| 2908 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 2909 | .sum() |
| 2910 | } else if let Some(bits) = rdoq_bits { |
| 2911 | // Already priced, against the grid the pass settled on. |
| 2912 | bits |
| 2913 | } else { |
| 2914 | { |
| 2915 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); |
| 2916 | crate::tile::coeff_bits_typed( |
| 2917 | &levels, |
| 2918 | at.set, |
| 2919 | crate::decode::q_ctx_of(base_q_idx), |
| 2920 | skip_ctx, |
| 2921 | sign_ctx, |
| 2922 | tx_type, |
| 2923 | ) |
| 2924 | } |
| 2925 | }; |
| 2926 | #[cfg(test)] |
| 2927 | stage_since(3, t); |
| 2928 | Trial { |
| 2929 | levels, |
| 2930 | reconstruction, |
| 2931 | sse, |
| 2932 | bits, |
| 2933 | } |
| 2934 | } |
| 2935 | |
| 2936 | /// [`Self::trial`] with the prediction already built, so that an inter |
| 2937 | /// block's motion-compensated prediction can go through the same |
| 2938 | /// residual/quantize/reconstruct path an intra block's does. `skip` |
| 2939 | /// takes the prediction as the reconstruction outright, coding no |
| 2940 | /// residual at all — what a `NEARESTMV` block that names no coefficients |
| 2941 | /// codes. |
| 2942 | #[allow(clippy::too_many_arguments)] |
| 2943 | fn code_from_prediction( |
| 2944 | &self, |
| 2945 | x: usize, |
| 2946 | y: usize, |
| 2947 | side: usize, |
| 2948 | prediction: &[u8], |
| 2949 | skip: bool, |
| 2950 | base_q_idx: u8, |
| 2951 | deadzone: f64, |
| 2952 | set: TxbSet, |
| 2953 | ) -> Trial { |
| 2954 | self.code_from_prediction_typed( |
| 2955 | x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct, |
| 2956 | ) |
| 2957 | } |
| 2958 | |
| 2959 | /// [`Self::code_from_prediction`] coding the residual with a NAMED |
| 2960 | /// transform type (lane-txset2): the inter luma sets carry a two-type |
| 2961 | /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes |
| 2962 | /// a symbol for, and [`commit_inter_luma`] prices both through this. |
| 2963 | #[allow(clippy::too_many_arguments)] |
| 2964 | fn code_from_prediction_typed( |
| 2965 | &self, |
| 2966 | x: usize, |
| 2967 | y: usize, |
| 2968 | side: usize, |
| 2969 | prediction: &[u8], |
| 2970 | skip: bool, |
| 2971 | base_q_idx: u8, |
| 2972 | deadzone: f64, |
| 2973 | set: TxbSet, |
| 2974 | tx_type: TxType, |
| 2975 | ) -> Trial { |
| 2976 | if skip { |
| 2977 | let sse = self.block_sse(x, y, side, prediction); |
| 2978 | return Trial { |
| 2979 | levels: vec![0i32; side * side], |
| 2980 | reconstruction: prediction.to_vec(), |
| 2981 | sse, |
| 2982 | bits: 0.0, |
| 2983 | }; |
| 2984 | } |
| 2985 | // A 64x64 root's residual is four times the scratch every other |
| 2986 | // block coder here sizes for [`BLOCK`]; only that one case pays for |
| 2987 | // a heap buffer, so the 4x4..32x32 path keeps its stack array. |
| 2988 | let mut small = [0i32; BLOCK * BLOCK]; |
| 2989 | let mut big = if side > BLOCK { |
| 2990 | vec![0i32; side * side] |
| 2991 | } else { |
| 2992 | Vec::new() |
| 2993 | }; |
| 2994 | let residual: &mut [i32] = if side > BLOCK { |
| 2995 | &mut big |
| 2996 | } else { |
| 2997 | &mut small[..side * side] |
| 2998 | }; |
| 2999 | for row in 0..side { |
| 3000 | for col in 0..side { |
| 3001 | residual[row * side + col] = |
| 3002 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 3003 | - i32::from(prediction[row * side + col]); |
| 3004 | } |
| 3005 | } |
| 3006 | #[cfg(test)] |
| 3007 | let t = stage_start(); |
| 3008 | // lane-rdoq, as in [`Self::trial_typed`]. |
| 3009 | let (levels, rdoq_bits) = if rdoq_on() { |
| 3010 | let (mut levels, scaled) = |
| 3011 | forward_and_quantize_typed_scaled( |
| 3012 | residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, |
| 3013 | ); |
| 3014 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); |
| 3015 | let bits = crate::tile::rdoq( |
| 3016 | &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(), |
| 3017 | tx_type, |
| 3018 | ); |
| 3019 | (levels, Some(bits)) |
| 3020 | } else { |
| 3021 | ( |
| 3022 | forward_and_quantize_typed( |
| 3023 | residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, |
| 3024 | ), |
| 3025 | None, |
| 3026 | ) |
| 3027 | }; |
| 3028 | // The same all-zero shortcut [`Self::trial_typed`] takes. |
| 3029 | let coded = dequant_and_inverse_typed_wh( |
| 3030 | &levels, |
| 3031 | side, |
| 3032 | side, |
| 3033 | 8, |
| 3034 | i32::from(base_q_idx), |
| 3035 | 0, |
| 3036 | 0, |
| 3037 | tx_type, |
| 3038 | None, |
| 3039 | ); |
| 3040 | #[cfg(test)] |
| 3041 | stage_since(2, t); |
| 3042 | let reconstruction: Vec<u8> = if coded.is_empty() { |
| 3043 | prediction.to_vec() |
| 3044 | } else { |
| 3045 | prediction |
| 3046 | .iter() |
| 3047 | .zip(&coded) |
| 3048 | .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) |
| 3049 | .collect() |
| 3050 | }; |
| 3051 | let sse = self.block_sse(x, y, side, &reconstruction); |
| 3052 | // A 64-point transform codes only its top-left 32x32 corner (spec |
| 3053 | // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the |
| 3054 | // key frame writer takes a 32x32 level grid for one). The inverse |
| 3055 | // above reads the whole 64x64 array, but the price below and the |
| 3056 | // levels the writer takes are that corner. |
| 3057 | let levels = if side > BLOCK { |
| 3058 | coded_corner(&levels, side, BLOCK) |
| 3059 | } else { |
| 3060 | levels |
| 3061 | }; |
| 3062 | #[cfg(test)] |
| 3063 | let t = stage_start(); |
| 3064 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 3065 | levels |
| 3066 | .iter() |
| 3067 | .filter(|&&level| level != 0) |
| 3068 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 3069 | .sum() |
| 3070 | } else if let Some(bits) = rdoq_bits { |
| 3071 | bits |
| 3072 | } else { |
| 3073 | { |
| 3074 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); |
| 3075 | crate::tile::coeff_bits_typed( |
| 3076 | &levels, |
| 3077 | set, |
| 3078 | crate::decode::q_ctx_of(base_q_idx), |
| 3079 | skip_ctx, |
| 3080 | sign_ctx, |
| 3081 | tx_type, |
| 3082 | ) |
| 3083 | } |
| 3084 | }; |
| 3085 | #[cfg(test)] |
| 3086 | stage_since(3, t); |
| 3087 | Trial { |
| 3088 | levels, |
| 3089 | reconstruction, |
| 3090 | sse, |
| 3091 | bits, |
| 3092 | } |
| 3093 | } |
| 3094 | |
| 3095 | /// Codes this block's luma at transform depth `depth`: the |
| 3096 | /// `(side >> depth)^2` transform units in raster order, each predicted |
| 3097 | /// from the reconstruction the units before it left behind -- exactly |
| 3098 | /// what the decoder's multi-transform-unit branch does (decode.rs |
| 3099 | /// `decode_block`, `tu_reach`) -- and each transformed, quantised and |
| 3100 | /// reconstructed on its own. Commits the result and hands back the |
| 3101 | /// block-coordinate levels, the block's squared error and what its |
| 3102 | /// coefficients cost. |
| 3103 | #[allow(clippy::too_many_arguments)] |
| 3104 | fn code_tx_depth( |
| 3105 | &mut self, |
| 3106 | at: At, |
| 3107 | mode: u8, |
| 3108 | angle_delta: i32, |
| 3109 | depth: usize, |
| 3110 | // This block's `filter_intra_mode` when it is coded with one, in |
| 3111 | // which case every transform unit predicts recursively off the |
| 3112 | // reconstruction the units before it left -- what the decoder does |
| 3113 | // per unit (decode.rs `decode_block`, `push_intra_rect`'s |
| 3114 | // `filter_intra`), not once over the whole block. |
| 3115 | filter_intra: Option<u8>, |
| 3116 | search: &Search, fctx: &crate::decode::FrameCtx, |
| 3117 | ) -> (Vec<i32>, f64, f64, Vec<TxType>) { |
| 3118 | let At { x, y, side, reach, .. } = at; |
| 3119 | let tx = side >> depth; |
| 3120 | let n = 1usize << depth; |
| 3121 | let set = luma_set_for( |
| 3122 | match tx { |
| 3123 | 32 => TxbSet::Luma32, |
| 3124 | 16 => TxbSet::Luma16, |
| 3125 | 8 => TxbSet::Luma8, |
| 3126 | _ => TxbSet::Luma4, |
| 3127 | }, |
| 3128 | search.screen, |
| 3129 | ); |
| 3130 | let mut levels = vec![0i32; side * side]; |
| 3131 | census_add(4, n * n); |
| 3132 | // A unit smaller than its block reads the neighbour magnitude table |
| 3133 | // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]). |
| 3134 | self.ctx.tu_split = n > 1; |
| 3135 | let (mut sse, mut bits) = (0.0, 0.0); |
| 3136 | // One entry per unit at its own `tu_row * n + tu_col`, which is how |
| 3137 | // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the |
| 3138 | // frame edge cuts away is never coded there, so a compacted list |
| 3139 | // would slide every later unit's type onto the wrong transform. |
| 3140 | let mut tx_types = vec![TxType::DctDct; n * n]; |
| 3141 | for tu_row in 0..n { |
| 3142 | for tu_col in 0..n { |
| 3143 | let (col_off, row_off) = (tu_col * tx, tu_row * tx); |
| 3144 | let tu = At { |
| 3145 | x: x + col_off, |
| 3146 | y: y + row_off, |
| 3147 | side: tx, |
| 3148 | reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach), |
| 3149 | set, |
| 3150 | }; |
| 3151 | let trial = match filter_intra { |
| 3152 | Some(fi) => { |
| 3153 | let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); |
| 3154 | let (above, left, corner) = |
| 3155 | self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf); |
| 3156 | let mut prediction = vec![0u8; tx * tx]; |
| 3157 | filter_intra_predict_u8( |
| 3158 | usize::from(fi), |
| 3159 | above, |
| 3160 | left, |
| 3161 | corner, |
| 3162 | tx, |
| 3163 | &mut prediction, |
| 3164 | fctx, |
| 3165 | ); |
| 3166 | self.code_from_prediction( |
| 3167 | tu.x, |
| 3168 | tu.y, |
| 3169 | tx, |
| 3170 | &prediction, |
| 3171 | false, |
| 3172 | search.base_q_idx, |
| 3173 | search.deadzone, |
| 3174 | set, |
| 3175 | ) |
| 3176 | } |
| 3177 | None => { |
| 3178 | // lane-txset: the unit picks its own transform type |
| 3179 | // out of the set the writer can name it in, priced |
| 3180 | // through the same RDOQ'd trial path (its `bits` |
| 3181 | // already carry the `tx_type` symbol itself). |
| 3182 | let mut best: Option<(f64, TxType, Trial)> = None; |
| 3183 | for &tx_type in tx_type_candidates(set, search.screen) { |
| 3184 | let candidate = self.trial_typed( |
| 3185 | tu, mode, angle_delta, search.base_q_idx, search.deadzone, |
| 3186 | tx_type, fctx, |
| 3187 | ); |
| 3188 | // lane-txi: a non-`DCT_DCT` type is charged its |
| 3189 | // bits at `EC_AV1_TXRD_LAMBDA` times the mode |
| 3190 | // search's weight (default 1 = unchanged). The |
| 3191 | // film rows buy 0.04 dB for 1.2% more bytes at |
| 3192 | // weight 1 on every frame and every PLANE, key |
| 3193 | // frame included -- a rate term this decision |
| 3194 | // under-charges (class |
| 3195 | // `rd-rate-term-calibration`), not the |
| 3196 | // propagation loss the leaves would have shown. |
| 3197 | let cost = candidate.sse |
| 3198 | + search.lambda * candidate.bits |
| 3199 | + non_dct_surcharge(search.lambda, tx_type, candidate.bits); |
| 3200 | if best.as_ref().is_none_or(|(best, _, _)| cost < *best) { |
| 3201 | best = Some((cost, tx_type, candidate)); |
| 3202 | } |
| 3203 | } |
| 3204 | let (_, tx_type, trial) = |
| 3205 | best.expect("the candidate list is never empty"); |
| 3206 | tx_types[tu_row * n + tu_col] = tx_type; |
| 3207 | TX_TYPE_HITS[tx_type as usize] |
| 3208 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3209 | trial |
| 3210 | } |
| 3211 | }; |
| 3212 | sse += trial.sse; |
| 3213 | bits += trial.bits; |
| 3214 | self.commit(tu.x, tu.y, tx, &trial); |
| 3215 | for row in 0..tx { |
| 3216 | levels[(row_off + row) * side + col_off..][..tx] |
| 3217 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 3218 | } |
| 3219 | } |
| 3220 | } |
| 3221 | self.ctx.tu_split = false; |
| 3222 | (levels, sse, bits, tx_types) |
| 3223 | } |
| 3224 | |
| 3225 | /// Writes a trial's reconstruction back into the plane, and the |
| 3226 | /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]). |
| 3227 | fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { |
| 3228 | for row in 0..side { |
| 3229 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 3230 | .copy_from_slice(&trial.reconstruction[row * side..][..side]); |
| 3231 | } |
| 3232 | self.commit_ctx(x, y, side, &trial.levels); |
| 3233 | } |
| 3234 | |
| 3235 | /// Publishes one committed transform's own context over every 4x4 cell it |
| 3236 | /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`, |
| 3237 | /// which is what the writer will read when it reaches the next block. |
| 3238 | fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) { |
| 3239 | if self.ctx.cells.is_empty() { |
| 3240 | self.ctx.stride = self.width.div_ceil(4); |
| 3241 | self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)]; |
| 3242 | } |
| 3243 | let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8; |
| 3244 | let state = CoefCtx { |
| 3245 | level: cul, |
| 3246 | dc: match levels[0].signum() { |
| 3247 | 0 => 0, |
| 3248 | -1 => -1, |
| 3249 | _ => 1, |
| 3250 | }, |
| 3251 | }; |
| 3252 | let n = (side / 4).max(1); |
| 3253 | // Only up to the frame's TRUE extent: the writer's own |
| 3254 | // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high` |
| 3255 | // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`) |
| 3256 | // and leaves the cells past it uncoded even mid-block, so a |
| 3257 | // straddling block publishes context for its inside part only. |
| 3258 | let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4)); |
| 3259 | let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4)); |
| 3260 | for row in 0..rows { |
| 3261 | let start = (y / 4 + row) * self.ctx.stride + x / 4; |
| 3262 | let end = (start + cols).min(self.ctx.cells.len()); |
| 3263 | if start < end { |
| 3264 | self.ctx.cells[start..end].fill(state); |
| 3265 | } |
| 3266 | } |
| 3267 | } |
| 3268 | |
| 3269 | /// A block committed without any residual at all ([`ibc_commit`]): the |
| 3270 | /// cells it covers coded nothing, and leaving an earlier trial's state |
| 3271 | /// there would price its neighbours off a block that was never coded. |
| 3272 | fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) { |
| 3273 | self.commit_ctx(x, y, side, &[0i32]); |
| 3274 | } |
| 3275 | |
| 3276 | /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this |
| 3277 | /// plane reads, off what the blocks before it in coding order committed |
| 3278 | /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether |
| 3279 | /// the above/left neighbours coded anything (tile.rs |
| 3280 | /// `write_block_planes`), luma reads context 0 when its transform covers |
| 3281 | /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour |
| 3282 | /// magnitude tiers when it does not (tile.rs `write_luma_tus` / |
| 3283 | /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of |
| 3284 | /// the same neighbours (tile.rs `dc_sign_ctx`). |
| 3285 | /// |
| 3286 | /// A neighbour outside this plane's own TILE does not exist, exactly as |
| 3287 | /// the writer's per-tile `Neighbours` bands start blank. |
| 3288 | /// |
| 3289 | /// CLOSED (lane-av1straddle): the decisions this price changes used to |
| 3290 | /// make `decode_stream_round_trips_an_odd_size_gop` and |
| 3291 | /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction` |
| 3292 | /// fail at 216x96. Never this map: the writer coded the phantom |
| 3293 | /// transform units of a right-edge-straddling 32x32 (tile.rs |
| 3294 | /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows` |
| 3295 | /// like decode.rs and libaom), which libdav1d and libaom both refused |
| 3296 | /// outright while a decision change was what first walked into it. |
| 3297 | fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) { |
| 3298 | if self.ctx.cells.is_empty() { |
| 3299 | return (0, 0); |
| 3300 | } |
| 3301 | let n = (side / 4).max(1); |
| 3302 | let (cx, cy) = (x / 4, y / 4); |
| 3303 | let (mut top, mut left) = (0u8, 0u8); |
| 3304 | let mut vote = 0i32; |
| 3305 | if y > self.tile_y0 && cy > 0 { |
| 3306 | for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] { |
| 3307 | top |= cell.level; |
| 3308 | vote += i32::from(cell.dc); |
| 3309 | } |
| 3310 | } |
| 3311 | if x > self.tile_x0 && cx > 0 { |
| 3312 | for row in 0..n { |
| 3313 | let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1]; |
| 3314 | left |= cell.level; |
| 3315 | vote += i32::from(cell.dc); |
| 3316 | } |
| 3317 | } |
| 3318 | let skip_ctx = if set.is_chroma() { |
| 3319 | usize::from(top != 0) + usize::from(left != 0) |
| 3320 | } else if self.ctx.tu_split { |
| 3321 | crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] |
| 3322 | } else { |
| 3323 | 0 |
| 3324 | }; |
| 3325 | let sign_ctx = match vote.signum() { |
| 3326 | 0 => 0, |
| 3327 | -1 => 1, |
| 3328 | _ => 2, |
| 3329 | }; |
| 3330 | (skip_ctx, sign_ctx) |
| 3331 | } |
| 3332 | |
| 3333 | /// The source samples of one square, contiguous — what a motion search |
| 3334 | /// compares its candidates' predictions against ([`motion::search`]'s |
| 3335 | /// `source`), since [`Self::source`] itself is the whole plane, strided |
| 3336 | /// by [`Self::width`]. |
| 3337 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 3338 | rows_of(self.source, self.width, x, y, side) |
| 3339 | } |
| 3340 | |
| 3341 | /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128 |
| 3342 | /// root's own HORZ/VERT motion search. |
| 3343 | fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> { |
| 3344 | let mut out = vec![0u8; w * h]; |
| 3345 | for row in 0..h { |
| 3346 | out[row * w..][..w] |
| 3347 | .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]); |
| 3348 | } |
| 3349 | out |
| 3350 | } |
| 3351 | |
| 3352 | /// The reconstructed samples of one square, so that a partition trial can |
| 3353 | /// be undone. |
| 3354 | /// The reconstructed samples of one square AND the coefficient contexts |
| 3355 | /// its cells hold, so that a partition trial can be undone whole: a |
| 3356 | /// losing trial that left its own nz/DC state behind would price the |
| 3357 | /// blocks after it off a block the tile writer never codes. |
| 3358 | fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) { |
| 3359 | ( |
| 3360 | rows_of(&self.reconstruction, self.width, x, y, side), |
| 3361 | self.ctx_rows(x, y, side), |
| 3362 | ) |
| 3363 | } |
| 3364 | |
| 3365 | fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> { |
| 3366 | if self.ctx.cells.is_empty() { |
| 3367 | return Vec::new(); |
| 3368 | } |
| 3369 | let n = (side / 4).max(1); |
| 3370 | (0..n) |
| 3371 | .flat_map(|row| { |
| 3372 | let start = (y / 4 + row) * self.ctx.stride + x / 4; |
| 3373 | self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec() |
| 3374 | }) |
| 3375 | .collect() |
| 3376 | } |
| 3377 | |
| 3378 | /// Puts a snapshot back. |
| 3379 | fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) { |
| 3380 | for row in 0..side { |
| 3381 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 3382 | .copy_from_slice(&saved.0[row * side..][..side]); |
| 3383 | } |
| 3384 | if saved.1.is_empty() { |
| 3385 | return; |
| 3386 | } |
| 3387 | let n = (side / 4).max(1); |
| 3388 | for row in 0..n { |
| 3389 | let start = (y / 4 + row) * self.ctx.stride + x / 4; |
| 3390 | let end = (start + n).min(self.ctx.cells.len()); |
| 3391 | if start < end { |
| 3392 | self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]); |
| 3393 | } |
| 3394 | } |
| 3395 | } |
| 3396 | |
| 3397 | /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates |
| 3398 | /// by, exposed so [`search_inter_block`]'s intra-candidate loop can |
| 3399 | /// prescreen by the identical rule rather than a second one that could |
| 3400 | /// drift from it. |
| 3401 | fn intra_scores( |
| 3402 | &self, |
| 3403 | at: At, |
| 3404 | modes: &[u8], |
| 3405 | mode_bits: &[f64; 13], |
| 3406 | lambda: f64, fctx: &crate::decode::FrameCtx, |
| 3407 | ) -> Vec<(f64, u8)> { |
| 3408 | let At { |
| 3409 | x, y, side, reach, .. |
| 3410 | } = at; |
| 3411 | let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); |
| 3412 | let (above, left, corner) = |
| 3413 | self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); |
| 3414 | modes |
| 3415 | .iter() |
| 3416 | .map(|&mode| { |
| 3417 | let mut prediction = vec![0u8; side * side]; |
| 3418 | intra_predict_u8( |
| 3419 | mode, |
| 3420 | 0, |
| 3421 | above, |
| 3422 | left, |
| 3423 | corner, |
| 3424 | side, |
| 3425 | side, |
| 3426 | false, |
| 3427 | false, |
| 3428 | &mut prediction, fctx, |
| 3429 | ); |
| 3430 | let sad = self.block_sad(x, y, side, &prediction); |
| 3431 | (sad + lambda * mode_bits[usize::from(mode)], mode) |
| 3432 | }) |
| 3433 | .collect() |
| 3434 | } |
| 3435 | |
| 3436 | /// Codes one block under every mode the search offers (or, when |
| 3437 | /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD |
| 3438 | /// pre-pass plus DC) and commits the one whose squared error and |
| 3439 | /// estimated rate come out cheapest. |
| 3440 | /// |
| 3441 | /// The prediction is built once per mode regardless -- the full RD trial |
| 3442 | /// needs it too -- so ranking modes by SAD on that same prediction before |
| 3443 | /// running the expensive part (forward transform, quantize, reconstruct, |
| 3444 | /// `coeff_bits`) on only the survivors costs nothing extra to predict, |
| 3445 | /// only to sum. |
| 3446 | fn search_block( |
| 3447 | &mut self, |
| 3448 | at: At, |
| 3449 | search: &Search, |
| 3450 | mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, |
| 3451 | ) -> (Vec<Coeff>, u8, i32, f64, TxType) { |
| 3452 | let At { |
| 3453 | x, y, side, reach, .. |
| 3454 | } = at; |
| 3455 | let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); |
| 3456 | let (above, left, corner) = |
| 3457 | self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf); |
| 3458 | // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or |
| 3459 | // the census reports it), so summing it under the default unpruned |
| 3460 | // search is `side * side` absolute differences per mode spent on a |
| 3461 | // number no one reads. |
| 3462 | let want_sad = search.top_k.is_some() || census_on(); |
| 3463 | let mut scored: Vec<(f64, u8, Vec<u8>)> = search |
| 3464 | .modes |
| 3465 | .iter() |
| 3466 | .map(|&mode| { |
| 3467 | let mut prediction = vec![0u8; side * side]; |
| 3468 | intra_predict_u8( |
| 3469 | mode, |
| 3470 | 0, |
| 3471 | above, |
| 3472 | left, |
| 3473 | corner, |
| 3474 | side, |
| 3475 | side, |
| 3476 | false, |
| 3477 | false, |
| 3478 | &mut prediction, fctx, |
| 3479 | ); |
| 3480 | let sad = if want_sad { |
| 3481 | self.block_sad(x, y, side, &prediction) |
| 3482 | } else { |
| 3483 | 0.0 |
| 3484 | }; |
| 3485 | ( |
| 3486 | sad + search.lambda * mode_bits[usize::from(mode)], |
| 3487 | mode, |
| 3488 | prediction, |
| 3489 | ) |
| 3490 | }) |
| 3491 | .collect(); |
| 3492 | if let Some(k) = search.top_k { |
| 3493 | if k < scored.len() { |
| 3494 | let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); |
| 3495 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 3496 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 3497 | scored.truncate(if dc_entry.is_some() { |
| 3498 | k.saturating_sub(1) |
| 3499 | } else { |
| 3500 | k |
| 3501 | }); |
| 3502 | if let Some(dc_entry) = dc_entry { |
| 3503 | scored.push(dc_entry); |
| 3504 | } |
| 3505 | } |
| 3506 | } |
| 3507 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 3508 | scored.iter().map(|&(score, mode, _)| (score, mode)).collect() |
| 3509 | } else { |
| 3510 | Vec::new() |
| 3511 | }; |
| 3512 | census_add(0, 1); |
| 3513 | census_add(1, scored.len()); |
| 3514 | let mut best: Option<(f64, u8, Trial)> = None; |
| 3515 | for (_, mode, prediction) in scored { |
| 3516 | let trial = self.code_from_prediction( |
| 3517 | x, |
| 3518 | y, |
| 3519 | side, |
| 3520 | &prediction, |
| 3521 | false, |
| 3522 | search.base_q_idx, |
| 3523 | search.deadzone, |
| 3524 | at.set, |
| 3525 | ); |
| 3526 | let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); |
| 3527 | if best |
| 3528 | .as_ref() |
| 3529 | .is_none_or(|(best_cost, _, _)| cost < *best_cost) |
| 3530 | { |
| 3531 | best = Some((cost, mode, trial)); |
| 3532 | } |
| 3533 | } |
| 3534 | let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode"); |
| 3535 | // `angle_delta_y` (spec `read_intra_angle_info`): the eight |
| 3536 | // directional modes each carry a -3..=3 delta, three degrees a step, |
| 3537 | // which the writer has always coded as ZERO because nothing searched |
| 3538 | // it. Refined on the winning mode only -- libaom's own ordering, and |
| 3539 | // six extra trials on the directional blocks instead of on every |
| 3540 | // block times every mode. The edges are the ones the base angle |
| 3541 | // already read (`enable_intra_edge_filter` is off in this encoder's |
| 3542 | // sequence header, so no delta changes which samples exist), and the |
| 3543 | // predictor is the decoder's, `angle_delta` argument and all. |
| 3544 | let mut angle_delta = 0i32; |
| 3545 | // Not on a screen frame: measured on the 5-row native gate, the |
| 3546 | // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the |
| 3547 | // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture -- |
| 3548 | // synthetic edges land on the base angles, so every delta there buys |
| 3549 | // a symbol and no prediction. Same `search.screen` gate palette and |
| 3550 | // intrabc already stand behind. |
| 3551 | if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) { |
| 3552 | let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)]; |
| 3553 | let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO); |
| 3554 | let mut prediction = vec![0u8; side * side]; |
| 3555 | for delta in [-3i32, -2, -1, 1, 2, 3] { |
| 3556 | intra_predict_u8( |
| 3557 | mode, |
| 3558 | delta, |
| 3559 | above, |
| 3560 | left, |
| 3561 | corner, |
| 3562 | side, |
| 3563 | side, |
| 3564 | false, |
| 3565 | false, |
| 3566 | &mut prediction, fctx, |
| 3567 | ); |
| 3568 | let candidate = self.code_from_prediction( |
| 3569 | x, |
| 3570 | y, |
| 3571 | side, |
| 3572 | &prediction, |
| 3573 | false, |
| 3574 | search.base_q_idx, |
| 3575 | search.deadzone, |
| 3576 | at.set, |
| 3577 | ); |
| 3578 | let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize) |
| 3579 | - zero_bits; |
| 3580 | let cost_d = candidate.sse |
| 3581 | + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits); |
| 3582 | if cost_d < cost { |
| 3583 | cost = cost_d; |
| 3584 | angle_delta = delta; |
| 3585 | trial = candidate; |
| 3586 | } |
| 3587 | } |
| 3588 | ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize] |
| 3589 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3590 | } |
| 3591 | // lane-txset: the block's own transform type, searched on the mode |
| 3592 | // and angle the trials above settled -- the same ordering the angle |
| 3593 | // refinement uses, and the same RD terms. |
| 3594 | let mut tx_type = TxType::DctDct; |
| 3595 | for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) { |
| 3596 | let candidate = self.trial_typed( |
| 3597 | at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx, |
| 3598 | ); |
| 3599 | let cost_t = |
| 3600 | candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]); |
| 3601 | // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is |
| 3602 | // `DCT_DCT` and pays none of it, so the returned `cost` stays the |
| 3603 | // block's true one for the caller's own decision. |
| 3604 | if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost { |
| 3605 | cost = cost_t; |
| 3606 | tx_type = candidate_type; |
| 3607 | trial = candidate; |
| 3608 | } |
| 3609 | } |
| 3610 | TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3611 | if census_on() { |
| 3612 | LUMA_RANK[sad_rank(&ranking, mode).min(12)] |
| 3613 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3614 | } |
| 3615 | self.commit(x, y, side, &trial); |
| 3616 | // A 64-point transform codes only its top-left 32x32 corner, which is |
| 3617 | // the grid `code_from_prediction` hands back (lane-i64). |
| 3618 | (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type) |
| 3619 | } |
| 3620 | } |
| 3621 | |
| 3622 | /// Where one block sits in its plane, and how far past its own edges its |
| 3623 | /// prediction may read. |
| 3624 | #[derive(Clone, Copy)] |
| 3625 | struct At { |
| 3626 | x: usize, |
| 3627 | y: usize, |
| 3628 | side: usize, |
| 3629 | reach: Reach, |
| 3630 | /// Which of the tile writer's coefficient tables this block's levels are |
| 3631 | /// coded with, and so which the search prices them through. |
| 3632 | set: TxbSet, |
| 3633 | } |
| 3634 | |
| 3635 | /// Which of the samples past a block's own edges the decoder has decoded by |
| 3636 | /// the time it predicts the block, and so which a directional mode may read. |
| 3637 | /// |
| 3638 | /// The decoder derives these from its `BlockDecoded` flags, which are cleared |
| 3639 | /// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry |
| 3640 | /// that map, this reads the answer the same way libaom and rav1e do: for a |
| 3641 | /// block whose transform covers it whole, whether the samples above its right |
| 3642 | /// (or below its left) are decoded depends only on where the block sits inside |
| 3643 | /// its 64x64 superblock, which is a pinned table per block size. |
| 3644 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 3645 | pub(crate) struct Reach { |
| 3646 | pub(crate) above_right: bool, |
| 3647 | pub(crate) below_left: bool, |
| 3648 | } |
| 3649 | |
| 3650 | /// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in |
| 3651 | /// libaom): for a block that is neither in the superblock's top row nor its |
| 3652 | /// rightmost column, whether the block above and to its right is coded before |
| 3653 | /// it. Indexed by the block's position in the superblock, in blocks of its own |
| 3654 | /// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's |
| 3655 | /// 128, not this crate's 64 superblock -- bit by bit from the low end. |
| 3656 | const HAS_TOP_RIGHT: [&[u8]; 4] = [ |
| 3657 | &[255, 85, 119, 85, 127, 85, 119, 85], |
| 3658 | &[95, 87], |
| 3659 | // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16 |
| 3660 | // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes. |
| 3661 | &[ |
| 3662 | 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, |
| 3663 | 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, |
| 3664 | ], |
| 3665 | |
| 3666 | // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) -- |
| 3667 | // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128 |
| 3668 | // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here |
| 3669 | // with side 4 outside a TX4 split; without their own row they clamped |
| 3670 | // into the 8x8 table and read above-right samples the decoder has not |
| 3671 | // written yet (all-zero pixels in the bottom-right triangle of a |
| 3672 | // directional 4x4 leaf). |
| 3673 | &[ |
| 3674 | 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, |
| 3675 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, |
| 3676 | 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, |
| 3677 | 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, |
| 3678 | 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, |
| 3679 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, |
| 3680 | 119, 119, 119, 119, 85, 85, 85, 85, |
| 3681 | ], |
| 3682 | ]; |
| 3683 | |
| 3684 | /// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the |
| 3685 | /// left. |
| 3686 | const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ |
| 3687 | &[84, 16, 84, 0, 84, 16, 84, 0], |
| 3688 | &[4, 4], |
| 3689 | // has_bl_8x8 (libaom av1/common/reconintra.c) |
| 3690 | &[ |
| 3691 | 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, |
| 3692 | 84, 85, 16, 17, 84, 85, 0, 0, |
| 3693 | ], |
| 3694 | |
| 3695 | // has_bl_4x4 (same source, same order). |
| 3696 | &[ |
| 3697 | 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, |
| 3698 | 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, |
| 3699 | 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, |
| 3700 | 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, |
| 3701 | 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, |
| 3702 | 85, 85, 0, 0, 0, 0, |
| 3703 | ], |
| 3704 | ]; |
| 3705 | |
| 3706 | /// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by |
| 3707 | /// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a |
| 3708 | /// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR |
| 3709 | /// rather than in raster order, so the bottom-left square's top-right |
| 3710 | /// neighbour is the partition's own right-hand rectangle -- not yet decoded. |
| 3711 | /// libaom switches tables on the partition type (`get_has_tr_table`); the |
| 3712 | /// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0: |
| 3713 | /// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case |
| 3714 | /// lane-part32 r5 caught reading undecoded samples. |
| 3715 | const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [ |
| 3716 | // has_tr_vert_16x16 |
| 3717 | &[255, 0, 119, 0, 127, 0, 119, 0], |
| 3718 | // has_tr_vert_32x32 |
| 3719 | &[15, 7], |
| 3720 | // has_tr_vert_8x8 |
| 3721 | &[ |
| 3722 | 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119, |
| 3723 | 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, |
| 3724 | ], |
| 3725 | ]; |
| 3726 | |
| 3727 | /// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`. |
| 3728 | const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [ |
| 3729 | // has_bl_vert_16x16 |
| 3730 | &[254, 16, 254, 0, 254, 16, 254, 0], |
| 3731 | // has_bl_vert_32x32 |
| 3732 | &[14, 14], |
| 3733 | // has_bl_vert_8x8 |
| 3734 | &[ |
| 3735 | 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254, |
| 3736 | 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, |
| 3737 | ], |
| 3738 | ]; |
| 3739 | |
| 3740 | thread_local! { |
| 3741 | /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks |
| 3742 | /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition |
| 3743 | /// type down into `has_top_right`/`has_bottom_left` as an argument, and |
| 3744 | /// threading one bool through this crate's already twenty-argument |
| 3745 | /// `decode_block` would touch every call site instead of the two arms |
| 3746 | /// that need it. |
| 3747 | static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 3748 | } |
| 3749 | |
| 3750 | /// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made. |
| 3751 | pub(crate) struct VertAbGuard(bool); |
| 3752 | |
| 3753 | impl Drop for VertAbGuard { |
| 3754 | fn drop(&mut self) { |
| 3755 | VERT_AB_PARTITION.with(|c| c.set(self.0)); |
| 3756 | } |
| 3757 | } |
| 3758 | |
| 3759 | /// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this |
| 3760 | /// decoder codes (libaom `reconintra.c`, generated from the oracle's source |
| 3761 | /// so no byte is retyped). Each is indexed by |
| 3762 | /// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride |
| 3763 | /// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel |
| 3764 | /// superblock grid; on this crate's 64-pixel superblock the highest index a |
| 3765 | /// shape can reach stays inside its own table, so no wrap is involved. |
| 3766 | /// |
| 3767 | /// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/ |
| 3768 | /// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed |
| 3769 | /// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at |
| 3770 | /// 10 of the 21 reachable superblock positions for above-right and 7 for |
| 3771 | /// below-left. |
| 3772 | /// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`). |
| 3773 | 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]; |
| 3774 | /// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`). |
| 3775 | 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]; |
| 3776 | /// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`). |
| 3777 | 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]; |
| 3778 | /// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`). |
| 3779 | 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]; |
| 3780 | /// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). |
| 3781 | const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119]; |
| 3782 | /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`). |
| 3783 | const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; |
| 3784 | /// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). |
| 3785 | const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; |
| 3786 | /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`). |
| 3787 | const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0]; |
| 3788 | /// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`). |
| 3789 | const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; |
| 3790 | /// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`). |
| 3791 | const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; |
| 3792 | /// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`). |
| 3793 | const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; |
| 3794 | /// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`). |
| 3795 | const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; |
| 3796 | /// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`). |
| 3797 | const HAS_TR_32X64: [u8; 1] = [127]; |
| 3798 | /// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`). |
| 3799 | const HAS_BL_32X64: [u8; 1] = [0]; |
| 3800 | /// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`). |
| 3801 | const HAS_TR_64X32: [u8; 1] = [19]; |
| 3802 | /// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`). |
| 3803 | const HAS_BL_64X32: [u8; 1] = [34]; |
| 3804 | /// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`). |
| 3805 | 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]; |
| 3806 | /// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`). |
| 3807 | 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]; |
| 3808 | /// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`). |
| 3809 | 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]; |
| 3810 | /// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`). |
| 3811 | 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]; |
| 3812 | /// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`). |
| 3813 | const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; |
| 3814 | /// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`). |
| 3815 | const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; |
| 3816 | /// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`). |
| 3817 | const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; |
| 3818 | /// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`). |
| 3819 | const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; |
| 3820 | /// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`). |
| 3821 | const HAS_TR_16X64: [u8; 2] = [255, 127]; |
| 3822 | /// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`). |
| 3823 | const HAS_BL_16X64: [u8; 2] = [0, 0]; |
| 3824 | /// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`). |
| 3825 | const HAS_TR_64X16: [u8; 2] = [3, 1]; |
| 3826 | /// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`). |
| 3827 | const HAS_BL_64X16: [u8; 2] = [42, 42]; |
| 3828 | |
| 3829 | /// The `has_tr_*`/`has_bl_*` row for one rectangular block shape. |
| 3830 | fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { |
| 3831 | match (bw, bh) { |
| 3832 | (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), |
| 3833 | (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), |
| 3834 | (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), |
| 3835 | (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), |
| 3836 | (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), |
| 3837 | (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), |
| 3838 | (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), |
| 3839 | (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), |
| 3840 | (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), |
| 3841 | (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), |
| 3842 | (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), |
| 3843 | (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), |
| 3844 | (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), |
| 3845 | (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), |
| 3846 | _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), |
| 3847 | } |
| 3848 | } |
| 3849 | |
| 3850 | impl Reach { |
| 3851 | /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a |
| 3852 | /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose |
| 3853 | /// own answer is `block` -- a different rule from the standalone-block |
| 3854 | /// tables, because a unit's neighbours are mostly its own block's |
| 3855 | /// already-reconstructed units: |
| 3856 | /// * top-right: available while the unit to the right is still inside |
| 3857 | /// the block (`col_off + tx < bw`); otherwise only the block's top row |
| 3858 | /// of units reaches past it, through the block-level answer |
| 3859 | /// (libaom's `row_off > 0` branch returns exactly |
| 3860 | /// `col_off + txw < plane_bw`). |
| 3861 | /// * bottom-left: a unit outside the block's left column has none |
| 3862 | /// (libaom returns 0 for `col_off > 0`); inside the block |
| 3863 | /// (`row_off + tx < bh`) they are the left unit's, already |
| 3864 | /// reconstructed; the bottom row falls back to the block-level answer. |
| 3865 | pub(crate) fn of_tu( |
| 3866 | bw: usize, |
| 3867 | bh: usize, |
| 3868 | col_off: usize, |
| 3869 | row_off: usize, |
| 3870 | // The unit's own width and height in pixels; equal for a square |
| 3871 | // transform, different for the rect unit a 1:4 strip's first split |
| 3872 | // produces (lane-rectsplitx r1). |
| 3873 | tx_w: usize, |
| 3874 | tx_h: usize, |
| 3875 | block: Self, |
| 3876 | ) -> Self { |
| 3877 | // A block wider than 64 is coded in 64x64 "mu" chunks in raster |
| 3878 | // order, so both libaom predicates special-case it (lane-sb128c r10); |
| 3879 | // without this the last unit column of every chunk of a 128x64 block |
| 3880 | // predicts from a chunk libaom has not decoded yet. |
| 3881 | let wide = bw > 64; |
| 3882 | Self { |
| 3883 | above_right: if row_off > 0 { |
| 3884 | // `has_top_right`'s `row_off > 0` branch: the offset is taken |
| 3885 | // modulo the 64-wide chunk, except for the one unit whose |
| 3886 | // top-right corner is the centre of a 128x128 block. |
| 3887 | if wide { |
| 3888 | (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64 |
| 3889 | } else { |
| 3890 | col_off + tx_w < bw |
| 3891 | } |
| 3892 | } else if col_off + tx_w < bw { |
| 3893 | true |
| 3894 | } else { |
| 3895 | block.above_right |
| 3896 | }, |
| 3897 | below_left: if wide && col_off > 0 && col_off % 64 == 0 { |
| 3898 | // `has_bottom_left`: at the left edge of a right-hand chunk |
| 3899 | // the bottom-left pixels are in the already-coded left chunk, |
| 3900 | // provided they stay inside it. |
| 3901 | (row_off % 64) + tx_h < bh.min(64) |
| 3902 | } else if col_off > 0 { |
| 3903 | false |
| 3904 | } else if row_off + tx_h < bh { |
| 3905 | true |
| 3906 | } else { |
| 3907 | block.below_left |
| 3908 | }, |
| 3909 | } |
| 3910 | } |
| 3911 | |
| 3912 | /// What a block of `side` samples at `(x, y)` may read past its own edges, |
| 3913 | /// in a frame of `width` by `height`. |
| 3914 | pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self { |
| 3915 | Self { |
| 3916 | above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx), |
| 3917 | below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx), |
| 3918 | } |
| 3919 | } |
| 3920 | |
| 3921 | /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp |
| 3922 | /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the |
| 3923 | /// block's own width for the row stride and by its own height for the |
| 3924 | /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`), |
| 3925 | /// unlike the square [`Self::of`] which uses one `side` for everything. |
| 3926 | pub(crate) fn of_rect( |
| 3927 | bw: usize, |
| 3928 | bh: usize, |
| 3929 | x: usize, |
| 3930 | y: usize, |
| 3931 | width: usize, |
| 3932 | height: usize, fctx: &crate::decode::FrameCtx, |
| 3933 | ) -> Self { |
| 3934 | Self { |
| 3935 | above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx), |
| 3936 | below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx), |
| 3937 | } |
| 3938 | } |
| 3939 | |
| 3940 | /// [`Self::of`] for one transform unit of a square block whose transform |
| 3941 | /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with |
| 3942 | /// non-zero `row_off`/`col_off`): interior units answer from the block's |
| 3943 | /// own geometry, and only a unit on the block's top row (resp. left |
| 3944 | /// column) reaches the table -- which is the BLOCK's table read at the |
| 3945 | /// BLOCK's position, never a table row for the transform's size. Letting |
| 3946 | /// the unit stand in for a block of its own size agrees with libaom for |
| 3947 | /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has |
| 3948 | /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4 |
| 3949 | /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a |
| 3950 | /// real `--enable-tx-size-search=1` stream (lane-ab16 r2). |
| 3951 | /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0, |
| 3952 | /// the transform covering the whole block, luma): everything before the |
| 3953 | /// table lookup is that function's own early-exit ladder. |
| 3954 | fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 3955 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 3956 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 3957 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 3958 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 3959 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 3960 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 3961 | // Top row of the superblock: the top-right pixels are in the (already |
| 3962 | // decoded) superblock above. |
| 3963 | if blk_row == 0 { |
| 3964 | return true; |
| 3965 | } |
| 3966 | // Rightmost column: they fall in the superblock to the right. |
| 3967 | if ((blk_col + 1) << bw_log2) >= sb_mi { |
| 3968 | return false; |
| 3969 | } |
| 3970 | let table = rect_reach_tables(bw, bh).0; |
| 3971 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 3972 | } |
| 3973 | |
| 3974 | /// libaom `has_top_right`'s own index arithmetic: |
| 3975 | /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and |
| 3976 | /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a |
| 3977 | /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5: |
| 3978 | /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but |
| 3979 | /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a |
| 3980 | /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main). |
| 3981 | /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it. |
| 3982 | fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { |
| 3983 | (blk_row << (5 - bw_log2)) + blk_col |
| 3984 | } |
| 3985 | |
| 3986 | /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`]. |
| 3987 | fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 3988 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 3989 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 3990 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 3991 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 3992 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 3993 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 3994 | // Leftmost column of the superblock: the bottom-left pixels are in |
| 3995 | // the left superblock iff they stay inside its height. |
| 3996 | if blk_col == 0 { |
| 3997 | return (blk_row << bh_log2) + (bh / 4) < sb_mi; |
| 3998 | } |
| 3999 | // Bottom row (and not the leftmost column): they fall in the |
| 4000 | // superblock below, which is not decoded yet. |
| 4001 | if ((blk_row + 1) << bh_log2) >= sb_mi { |
| 4002 | return false; |
| 4003 | } |
| 4004 | let table = rect_reach_tables(bw, bh).1; |
| 4005 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 4006 | } |
| 4007 | |
| 4008 | /// Marks every [`Reach::of`] made until the returned guard drops as being |
| 4009 | /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` / |
| 4010 | /// `get_has_bl_table` partition argument). Rectangular sub-blocks are |
| 4011 | /// unaffected: libaom's own comment says vertical rectangles keep their |
| 4012 | /// non-vert table, which is what [`Reach::of_rect`] already reads. |
| 4013 | /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded |
| 4014 | /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller |
| 4015 | /// can count the sub-block work that partition creates (lane-ab16). |
| 4016 | pub(crate) fn in_vert_ab() -> bool { |
| 4017 | VERT_AB_PARTITION.with(std::cell::Cell::get) |
| 4018 | } |
| 4019 | |
| 4020 | pub(crate) fn vert_ab_partition() -> VertAbGuard { |
| 4021 | VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) |
| 4022 | } |
| 4023 | |
| 4024 | /// Neither, which is all a mode that reads no further than its own edges |
| 4025 | /// needs. |
| 4026 | pub(crate) fn none() -> Self { |
| 4027 | Self { |
| 4028 | above_right: false, |
| 4029 | below_left: false, |
| 4030 | } |
| 4031 | } |
| 4032 | |
| 4033 | /// `has_top_right` for a block whose transform covers it whole: the top |
| 4034 | /// row of a superblock reads into the superblock above, which is decoded; |
| 4035 | /// the rightmost column would read into the superblock to the right, which |
| 4036 | /// is not; and everything between is the table's to answer. |
| 4037 | fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 4038 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 4039 | if row == 0 { |
| 4040 | return true; |
| 4041 | } |
| 4042 | if col + 1 == per_side { |
| 4043 | return false; |
| 4044 | } |
| 4045 | // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row |
| 4046 | // (the clamp corner-cut that used to live here is gone); sides |
| 4047 | // 16/32/64 share row 0 exactly as libaom's tables repeat. |
| 4048 | // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block |
| 4049 | // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table |
| 4050 | // -- a reach over-estimate (extra above-right reference pixels), |
| 4051 | // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` / |
| 4052 | // `has_bl_vert_4x4` and extend the VERT tables to four rows. |
| 4053 | // NB: named `table_row`, not `row` -- `row` above is the block's |
| 4054 | // position inside the superblock and is what the bit index below |
| 4055 | // steps by (a merge that shadowed it desynced every block size). |
| 4056 | let table_row = Self::table(side); |
| 4057 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { |
| 4058 | HAS_TOP_RIGHT_VERT[table_row] |
| 4059 | } else { |
| 4060 | HAS_TOP_RIGHT[table_row] |
| 4061 | }; |
| 4062 | Self::bit( |
| 4063 | table, |
| 4064 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 4065 | ) |
| 4066 | } |
| 4067 | |
| 4068 | /// `has_bottom_left` for such a block: the leftmost column of a superblock |
| 4069 | /// reads into the superblock to its left, which is decoded only as far |
| 4070 | /// down as its own bottom; the bottom row would read into the superblock |
| 4071 | /// below, which is not decoded at all; and the table answers the rest. |
| 4072 | fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 4073 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 4074 | if col == 0 { |
| 4075 | return row * side + side < reach_sb_px(fctx); |
| 4076 | } |
| 4077 | if row + 1 == per_side { |
| 4078 | return false; |
| 4079 | } |
| 4080 | // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row |
| 4081 | // (the clamp corner-cut that used to live here is gone); sides |
| 4082 | // 16/32/64 share row 0 exactly as libaom's tables repeat. |
| 4083 | // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block |
| 4084 | // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table |
| 4085 | // -- a reach over-estimate (extra above-right reference pixels), |
| 4086 | // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` / |
| 4087 | // `has_bl_vert_4x4` and extend the VERT tables to four rows. |
| 4088 | // NB: named `table_row`, not `row` -- `row` above is the block's |
| 4089 | // position inside the superblock and is what the bit index below |
| 4090 | // steps by (a merge that shadowed it desynced every block size). |
| 4091 | let table_row = Self::table(side); |
| 4092 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { |
| 4093 | HAS_BOTTOM_LEFT_VERT[table_row] |
| 4094 | } else { |
| 4095 | HAS_BOTTOM_LEFT[table_row] |
| 4096 | }; |
| 4097 | Self::bit( |
| 4098 | table, |
| 4099 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 4100 | ) |
| 4101 | } |
| 4102 | |
| 4103 | /// Where a block sits inside its superblock, in blocks of its own size, |
| 4104 | /// and how many of them a superblock is across. |
| 4105 | fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) { |
| 4106 | let sb = reach_sb_px(fctx); |
| 4107 | ((y % sb) / side, (x % sb) / side, sb / side) |
| 4108 | } |
| 4109 | |
| 4110 | /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins |
| 4111 | /// these tables to its compile-time maximum superblock (128, spec |
| 4112 | /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock |
| 4113 | /// size an encode actually uses, so a block's row in the bit index steps |
| 4114 | /// by 128 / `side` even though this crate only ever codes a 64 |
| 4115 | /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative) |
| 4116 | /// here instead indexes the wrong bit for every block size but the one |
| 4117 | /// where 64 and 128 give the same stride. |
| 4118 | fn table_stride(side: usize) -> usize { |
| 4119 | 128 / side |
| 4120 | } |
| 4121 | |
| 4122 | /// Which of the three block sizes the encoder codes a table row is for. |
| 4123 | fn table(side: usize) -> usize { |
| 4124 | if side == BLOCK { |
| 4125 | 1 |
| 4126 | } else if side == 8 { |
| 4127 | 2 |
| 4128 | } else if side == 4 { |
| 4129 | 3 |
| 4130 | } else { |
| 4131 | 0 |
| 4132 | } |
| 4133 | } |
| 4134 | |
| 4135 | /// One bit of a table, counting from the low end of its first byte. |
| 4136 | fn bit(table: &[u8], index: usize) -> bool { |
| 4137 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 4138 | } |
| 4139 | } |
| 4140 | |
| 4141 | /// What one symbol costs against a CDF, in bits. |
| 4142 | /// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the |
| 4143 | /// search, the frame header's `allow_warped_motion` and the sequence's |
| 4144 | /// `enable_warped_motion`, all three together. ON by default since |
| 4145 | /// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at |
| 4146 | /// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header |
| 4147 | /// bits -- back off for an A/B on one build. |
| 4148 | pub(crate) fn warp_on() -> bool { |
| 4149 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 4150 | crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off")) |
| 4151 | }); |
| 4152 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP)) |
| 4153 | } |
| 4154 | |
| 4155 | /// The smallest LEAF an OBMC candidate is offered for, so the census can |
| 4156 | /// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 -- |
| 4157 | /// every leaf; 16 or 32 turn the smaller leaves off). Only read when |
| 4158 | /// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate. |
| 4159 | /// |
| 4160 | /// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e |
| 4161 | /// (12 frames, four quantizers, the standing keep table): |
| 4162 | /// |
| 4163 | /// | min side | film 1080p | film 2160p | screen | |
| 4164 | /// |---|---|---|---| |
| 4165 | /// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 | |
| 4166 | /// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 | |
| 4167 | /// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 | |
| 4168 | /// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 | |
| 4169 | /// |
| 4170 | /// So the leaves are not the thing that was holding OBMC back: at 8x8 the |
| 4171 | /// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p |
| 4172 | /// film -- 85% of them, far past libaom's own rate -- and costs another 0.3 |
| 4173 | /// BD points on top of the 0.4 the 32x32 candidate already costs. A tool |
| 4174 | /// that wins the local RD on five blocks in six and loses ladder bytes is |
| 4175 | /// the `local-RD-on-references` class again, not a missing footprint. |
| 4176 | /// |
| 4177 | /// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8): |
| 4178 | /// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with |
| 4179 | /// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point |
| 4180 | /// loss on the 1080p film became a 0.3-point win and the other two rows went |
| 4181 | /// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half |
| 4182 | /// of the "local win, ladder loss" it was charged with was the rate weight. |
| 4183 | /// It still does not meet the keep rule (two down, one flat, both columns). |
| 4184 | /// The tool stays OFF by default; the upgrade path is the price, not the size |
| 4185 | /// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8 |
| 4186 | /// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the |
| 4187 | /// 1080p film up, i.e. the same disagreement between the two gates). |
| 4188 | /// |
| 4189 | /// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept |
| 4190 | /// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1, |
| 4191 | /// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads |
| 4192 | /// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p |
| 4193 | /// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference |
| 4194 | /// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at |
| 4195 | /// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and |
| 4196 | /// the margin's gain are the same bytes. It stays OFF. |
| 4197 | /// |
| 4198 | /// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every |
| 4199 | /// judgement above was taken when the gate's "film" rows were the `testsrc2` |
| 4200 | /// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is |
| 4201 | /// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures, |
| 4202 | /// the standing native keep table (`bd_rate_screen_native`): |
| 4203 | /// |
| 4204 | /// | arm | film A | film B | screen | OBMC fire A/B | |
| 4205 | /// |---|---|---|---|---| |
| 4206 | /// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% | |
| 4207 | /// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% | |
| 4208 | /// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% | |
| 4209 | /// |
| 4210 | /// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B |
| 4211 | /// only), where the anchors' non-skip area is the known gap: |
| 4212 | /// |
| 4213 | /// | arm | film B long GOP | wall ours | |
| 4214 | /// |---|---|---| |
| 4215 | /// | off (control) | +89.8 / +9.1 | 477.5s | |
| 4216 | /// | min side 8 | +89.6 / +9.0 | 514.1s | |
| 4217 | /// |
| 4218 | /// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12 |
| 4219 | /// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way |
| 4220 | /// only at min side 16, which is exactly where film B loses 0.7 on both |
| 4221 | /// columns. Nothing here meets the keep rule (both films down on both |
| 4222 | /// columns, or one down >=0.5 with the other flat), and the long-GOP gain |
| 4223 | /// costs +7.7% wall. OBMC stays OFF at every preset. |
| 4224 | fn obmc_min_side() -> usize { |
| 4225 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 4226 | *N.get_or_init(|| { |
| 4227 | std::env::var("EC_AV1_OBMC_MIN") |
| 4228 | .ok() |
| 4229 | .and_then(|v| v.parse().ok()) |
| 4230 | .unwrap_or(8) |
| 4231 | }) |
| 4232 | } |
| 4233 | |
| 4234 | /// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables |
| 4235 | /// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the |
| 4236 | /// same frame-CDF price the coefficients of a non-screen frame are estimated |
| 4237 | /// with, not the static default table. |
| 4238 | /// The same price for whichever alphabet the writer will really use for this |
| 4239 | /// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice |
| 4240 | /// (`allow_warped_motion` and at least one warp sample), otherwise the |
| 4241 | /// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the |
| 4242 | /// search pay it, so the alphabet cancels out of a comparison and only its |
| 4243 | /// per-value spread decides. |
| 4244 | fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 { |
| 4245 | let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else { |
| 4246 | return 0.0; |
| 4247 | }; |
| 4248 | match warp_alphabet { |
| 4249 | true => crate::tile::motion_mode_symbol_bits(row, motion), |
| 4250 | false => crate::tile::obmc_symbol_bits(row, motion == 1), |
| 4251 | } |
| 4252 | } |
| 4253 | |
| 4254 | /// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the |
| 4255 | /// candidate, the header's `allow_warped_motion` and the sequence's |
| 4256 | /// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing |
| 4257 | /// native keep table, against the same build with the knob off: |
| 4258 | /// |
| 4259 | /// | clip | warp on | off | |
| 4260 | /// |---|---|---| |
| 4261 | /// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 | |
| 4262 | /// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 | |
| 4263 | /// | screen | +59.2 / -9.9 | +59.4 / -10.0 | |
| 4264 | /// |
| 4265 | /// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and |
| 4266 | /// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so |
| 4267 | /// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2 |
| 4268 | /// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool |
| 4269 | /// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol |
| 4270 | /// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so |
| 4271 | /// this is a measured loss, not an inert knob. Same shape as the OBMC |
| 4272 | /// candidate above it (`obmc_min_side`): a local RD win that does not convert |
| 4273 | /// into ladder bytes. |
| 4274 | /// |
| 4275 | /// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, |
| 4276 | /// because a tool whose gain is local and whose cost is the rate it adds is |
| 4277 | /// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN: |
| 4278 | /// |
| 4279 | /// | clip | warp on | off (both at lambda 0.05) | |
| 4280 | /// |---|---|---| |
| 4281 | /// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 | |
| 4282 | /// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 | |
| 4283 | /// | screen | +51.3 / -14.3 | +51.6 / -14.2 | |
| 4284 | /// |
| 4285 | /// two rows down against libaom (0.3 each) with the third flat, and the rav1e |
| 4286 | /// column inside 0.1 everywhere -- which reads as a keep rather than the |
| 4287 | /// 0.7/0.9 loss it was. |
| 4288 | /// |
| 4289 | /// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table |
| 4290 | /// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5, |
| 4291 | /// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and |
| 4292 | /// ran the conformance shape the lambda lane deferred: every warp stream |
| 4293 | /// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1` |
| 4294 | /// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside |
| 4295 | /// a 16-tile frame, sample walk and all), and tile bytes still do not depend |
| 4296 | /// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks |
| 4297 | /// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it, |
| 4298 | /// `allow_warped_motion` and `enable_warped_motion` back off together. |
| 4299 | /// |
| 4300 | /// The WARPED_CAUSAL prediction of one square single-reference block: the |
| 4301 | /// decoder's own warp-sample walk (`decode::find_samples` + |
| 4302 | /// `warp::select_samples`), least-squares model (`warp::find_projection`) and |
| 4303 | /// affine predictor (`warp::warp_affine`), driven off the encoder's own mi |
| 4304 | /// grid -- never a second implementation of any of the three. `None` when the |
| 4305 | /// block would code no motion_mode symbol at all, when it has no warp sample |
| 4306 | /// (the writer then codes the 2-symbol alphabet, which has no WARPED value), |
| 4307 | /// or when the projection is not filter-representable (the decoder would then |
| 4308 | /// predict translationally, so the mode is pure cost). |
| 4309 | #[allow(clippy::too_many_arguments)] |
| 4310 | fn warp_prediction( |
| 4311 | grid: &MiGrid, |
| 4312 | (mi_row, mi_col): (usize, usize), |
| 4313 | (mi_rows, mi_cols): (usize, usize), |
| 4314 | (x, y): (usize, usize), |
| 4315 | side: usize, |
| 4316 | mv: (i32, i32), |
| 4317 | ref_frame: i8, |
| 4318 | ref_planes: [(&[u16], usize, usize, usize); 3], |
| 4319 | fctx: &crate::decode::FrameCtx, |
| 4320 | ) -> Option<[Vec<u8>; 3]> { |
| 4321 | let n4 = side / 4; |
| 4322 | if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) { |
| 4323 | return None; |
| 4324 | } |
| 4325 | let mut samples = crate::decode::find_samples( |
| 4326 | grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx, |
| 4327 | ); |
| 4328 | if samples.is_empty() { |
| 4329 | return None; |
| 4330 | } |
| 4331 | if samples.len() > 1 { |
| 4332 | crate::warp::select_samples(mv, &mut samples, side as i32, side as i32); |
| 4333 | } |
| 4334 | let params = crate::warp::find_projection( |
| 4335 | &samples, |
| 4336 | side as i32, |
| 4337 | side as i32, |
| 4338 | mv.1, |
| 4339 | mv.0, |
| 4340 | mi_row as i32, |
| 4341 | mi_col as i32, |
| 4342 | )?; |
| 4343 | let mut pred = [ |
| 4344 | vec![0u16; side * side], |
| 4345 | vec![0u16; side * side / 4], |
| 4346 | vec![0u16; side * side / 4], |
| 4347 | ]; |
| 4348 | // The translational prediction first, exactly as the decoder builds it, |
| 4349 | // then the affine one over the planes whose OWN block is at least 8x8 |
| 4350 | // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's |
| 4351 | // 4x4 chroma stays translational). |
| 4352 | for (i, r) in ref_planes.into_iter().enumerate() { |
| 4353 | let luma_plane = i == 0; |
| 4354 | let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) }; |
| 4355 | let s = if luma_plane { side } else { side / 2 }; |
| 4356 | mc::predict( |
| 4357 | r.0, |
| 4358 | r.1, |
| 4359 | r.2, |
| 4360 | r.3, |
| 4361 | mv_to_q4(px, mv.1, luma_plane), |
| 4362 | mv_to_q4(py, mv.0, luma_plane), |
| 4363 | s, |
| 4364 | s, |
| 4365 | &mut pred[i], |
| 4366 | fctx, |
| 4367 | ); |
| 4368 | if crate::decode::warp_plane_allowed(s, s) { |
| 4369 | let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32); |
| 4370 | crate::warp::warp_affine( |
| 4371 | ¶ms, |
| 4372 | r.0, |
| 4373 | r.2 as i32, |
| 4374 | r.3 as i32, |
| 4375 | r.1 as i32, |
| 4376 | &mut pred[i], |
| 4377 | px as i32, |
| 4378 | py as i32, |
| 4379 | cside, |
| 4380 | cside, |
| 4381 | cside, |
| 4382 | sub, |
| 4383 | sub, |
| 4384 | fctx, |
| 4385 | ); |
| 4386 | } |
| 4387 | } |
| 4388 | let [py_buf, pu_buf, pv_buf] = pred; |
| 4389 | let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>(); |
| 4390 | Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)]) |
| 4391 | } |
| 4392 | |
| 4393 | /// What tile.rs' `write_compound_ref_frames` pays for the pair |
| 4394 | /// `(ref0, ref1)`, symbol for symbol, each at the context its own |
| 4395 | /// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx` |
| 4396 | /// derives from the block's above/left neighbours -- plus the `comp_mode` |
| 4397 | /// symbol itself at `reference_mode_ctx`. |
| 4398 | /// |
| 4399 | /// Before lane-ctx this was four constants at CDF row 0 that assumed the pair |
| 4400 | /// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or |
| 4401 | /// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the |
| 4402 | /// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN. |
| 4403 | pub(crate) fn compound_ref_bits( |
| 4404 | (ref0, ref1): (i8, i8), |
| 4405 | stack: &crate::mvstack::MvStack, |
| 4406 | ) -> f64 { |
| 4407 | use crate::mvstack::{ |
| 4408 | ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 4409 | comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx, |
| 4410 | single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, |
| 4411 | uni_comp_ref_p1_ctx, |
| 4412 | }; |
| 4413 | let (a, a1) = stack.above_refs; |
| 4414 | let (l, l1) = stack.left_refs; |
| 4415 | let unidir = is_uni_comp_ref(ref0, ref1); |
| 4416 | let comp_mode = symbol_bits( |
| 4417 | &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)], |
| 4418 | 1, |
| 4419 | ); |
| 4420 | let ref_type = symbol_bits( |
| 4421 | &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)], |
| 4422 | usize::from(!unidir), |
| 4423 | ); |
| 4424 | if unidir { |
| 4425 | let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME); |
| 4426 | let p0 = symbol_bits( |
| 4427 | &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0], |
| 4428 | usize::from(both_backward), |
| 4429 | ); |
| 4430 | if both_backward { |
| 4431 | return comp_mode + ref_type + p0; |
| 4432 | } |
| 4433 | let past_last2 = ref1 != LAST2_FRAME; |
| 4434 | let p1 = symbol_bits( |
| 4435 | &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1], |
| 4436 | usize::from(past_last2), |
| 4437 | ); |
| 4438 | let p2 = if past_last2 { |
| 4439 | symbol_bits( |
| 4440 | &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2], |
| 4441 | usize::from(ref1 == GOLDEN_FRAME), |
| 4442 | ) |
| 4443 | } else { |
| 4444 | 0.0 |
| 4445 | }; |
| 4446 | return comp_mode + ref_type + p0 + p1 + p2; |
| 4447 | } |
| 4448 | let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME; |
| 4449 | let fwd = symbol_bits( |
| 4450 | &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0], |
| 4451 | usize::from(far), |
| 4452 | ) + if far { |
| 4453 | symbol_bits( |
| 4454 | &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2], |
| 4455 | usize::from(ref0 == GOLDEN_FRAME), |
| 4456 | ) |
| 4457 | } else { |
| 4458 | symbol_bits( |
| 4459 | &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1], |
| 4460 | usize::from(ref0 == LAST2_FRAME), |
| 4461 | ) |
| 4462 | }; |
| 4463 | let is_altref = ref1 == ALTREF_FRAME; |
| 4464 | let bwd = symbol_bits( |
| 4465 | &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0], |
| 4466 | usize::from(is_altref), |
| 4467 | ) + if is_altref { |
| 4468 | 0.0 |
| 4469 | } else { |
| 4470 | symbol_bits( |
| 4471 | &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1], |
| 4472 | usize::from(ref1 == ALTREF2_FRAME), |
| 4473 | ) |
| 4474 | }; |
| 4475 | comp_mode + ref_type + fwd + bwd |
| 4476 | } |
| 4477 | |
| 4478 | /// What the `skip` symbol costs at the context tile.rs really codes it with |
| 4479 | /// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now |
| 4480 | /// carries) instead of row 0 -- the pricer's skip-versus-residual margin is |
| 4481 | /// exactly the difference between this symbol's two values, so the row it is |
| 4482 | /// read from moves that decision (class pricer-context-zero, lane-ctx). |
| 4483 | pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 { |
| 4484 | let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip); |
| 4485 | symbol_bits(&cdf::SKIP[ctx], usize::from(skip)) |
| 4486 | } |
| 4487 | |
| 4488 | /// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the |
| 4489 | /// neighbours' intra/inter state, with an out-of-tile side contributing |
| 4490 | /// nothing, off the same two cells (lane-ctx). |
| 4491 | pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 { |
| 4492 | let ctx = crate::tile::intra_inter_ctx( |
| 4493 | stack.above_nbr.is_some(), |
| 4494 | stack.left_nbr.is_some(), |
| 4495 | stack.above_nbr.is_some_and(|n| n.is_inter), |
| 4496 | stack.left_nbr.is_some_and(|n| n.is_inter), |
| 4497 | ); |
| 4498 | symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter)) |
| 4499 | } |
| 4500 | |
| 4501 | /// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a |
| 4502 | /// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own |
| 4503 | /// context -- zero on a frame that carries no `reference_select` bit, where |
| 4504 | /// the writer codes no symbol at all. |
| 4505 | fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 { |
| 4506 | if !reference_select() { |
| 4507 | return 0.0; |
| 4508 | } |
| 4509 | symbol_bits( |
| 4510 | &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)], |
| 4511 | 0, |
| 4512 | ) |
| 4513 | } |
| 4514 | |
| 4515 | /// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol, |
| 4516 | /// each at the context that symbol's own `single_ref_p*_ctx` derives from the |
| 4517 | /// block's above/left neighbours -- plus the `comp_mode = 0` symbol |
| 4518 | /// `write_comp_mode` codes ahead of it on a `reference_select` frame. |
| 4519 | /// LAST is p1=0,p3=0,p4=0, |
| 4520 | /// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1, |
| 4521 | /// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1. |
| 4522 | /// Before lane-pricer every BACKWARD reference was priced as LAST -- three |
| 4523 | /// symbols off the wrong CDFs -- which is what made the search believe an |
| 4524 | /// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is |
| 4525 | /// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one |
| 4526 | /// paid nothing at all, so compound was overcharged by the whole symbol. |
| 4527 | pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 { |
| 4528 | use crate::mvstack::{ |
| 4529 | ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 4530 | single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, |
| 4531 | single_ref_p5_ctx, single_ref_p6_ctx, |
| 4532 | }; |
| 4533 | let (a, a1) = stack.above_refs; |
| 4534 | let (l, l1) = stack.left_refs; |
| 4535 | let comp_mode = comp_mode_single_bits(stack); |
| 4536 | let backward = ref_frame >= BWDREF_FRAME; |
| 4537 | let p1 = symbol_bits( |
| 4538 | &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0], |
| 4539 | usize::from(backward), |
| 4540 | ); |
| 4541 | if backward { |
| 4542 | let is_altref = ref_frame == ALTREF_FRAME; |
| 4543 | let p2 = symbol_bits( |
| 4544 | &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1], |
| 4545 | usize::from(is_altref), |
| 4546 | ); |
| 4547 | return comp_mode |
| 4548 | + p1 |
| 4549 | + p2 |
| 4550 | + if is_altref { |
| 4551 | 0.0 |
| 4552 | } else { |
| 4553 | symbol_bits( |
| 4554 | &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5], |
| 4555 | usize::from(ref_frame == ALTREF2_FRAME), |
| 4556 | ) |
| 4557 | }; |
| 4558 | } |
| 4559 | let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME; |
| 4560 | comp_mode + p1 + symbol_bits( |
| 4561 | &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2], |
| 4562 | usize::from(far), |
| 4563 | ) + if far { |
| 4564 | symbol_bits( |
| 4565 | &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4], |
| 4566 | usize::from(ref_frame == GOLDEN_FRAME), |
| 4567 | ) |
| 4568 | } else { |
| 4569 | symbol_bits( |
| 4570 | &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3], |
| 4571 | usize::from(ref_frame == LAST2_FRAME), |
| 4572 | ) |
| 4573 | } |
| 4574 | } |
| 4575 | |
| 4576 | pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { |
| 4577 | let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; |
| 4578 | let width = cdf[symbol] - low; |
| 4579 | // lane-av1speed: a CDF interval is a 15-bit width, so there are only |
| 4580 | // 32769 prices a symbol can carry; the `log2` behind each is computed |
| 4581 | // once instead of per call (libm's `__log2_fma` was 5% of the encoder's |
| 4582 | // profile -- this function is called for every symbol of every candidate |
| 4583 | // the RD search prices). Each entry is exactly the expression this used |
| 4584 | // to evaluate, so every price is bit-identical. |
| 4585 | static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new(); |
| 4586 | PRICES.get_or_init(|| { |
| 4587 | (0..=32768u32) |
| 4588 | .map(|w| -(f64::from(w) / 32768.0).log2()) |
| 4589 | .collect() |
| 4590 | })[usize::from(width)] |
| 4591 | } |
| 4592 | |
| 4593 | /// What the tile writer spends to say a block is coded in each of the thirteen |
| 4594 | /// modes, given the modes of the blocks above it and to its left: the luma mode |
| 4595 | /// symbol against the CDF those two neighbours pick, the angle delta a |
| 4596 | /// directional mode carries, and the chroma mode symbol, whose CDF the luma |
| 4597 | /// mode itself indexes. |
| 4598 | /// |
| 4599 | /// Without this the search is blind to what a mode costs to name, which is not |
| 4600 | /// a rounding error: a directional mode on a picture that does not run that way |
| 4601 | /// is a rate loss the squared error never sees. |
| 4602 | /// Codes one square of the picture as a single block: searches the luma mode, |
| 4603 | /// codes both chroma planes DC, and hands back the block and what it cost -- |
| 4604 | /// squared error plus lambda times the bits its symbols spend. |
| 4605 | /// How many halvings of a `side`-square block's transform the `tx_depth` |
| 4606 | /// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two |
| 4607 | /// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform. |
| 4608 | fn max_tx_depth(side: usize) -> usize { |
| 4609 | match side { |
| 4610 | 8 => 1, |
| 4611 | 16 | 32 => 2, |
| 4612 | _ => 0, |
| 4613 | } |
| 4614 | } |
| 4615 | |
| 4616 | /// What the `tx_depth` symbol itself costs, off the size category's own CDF. |
| 4617 | /// Priced at context row 0 -- the writer picks the real row from its |
| 4618 | /// neighbours' transform sizes, which the search has no view of; the term is |
| 4619 | /// the same for every depth of one block either way, so it only shifts the |
| 4620 | /// depth-0-versus-split margin, never the ordering between two splits. |
| 4621 | fn tx_depth_bits(side: usize, depth: usize) -> f64 { |
| 4622 | match side { |
| 4623 | 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth), |
| 4624 | 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth), |
| 4625 | 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth), |
| 4626 | _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth), |
| 4627 | } |
| 4628 | } |
| 4629 | |
| 4630 | /// lane-split: a multiplier on the RATE term of the transform-SPLIT trial |
| 4631 | /// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the |
| 4632 | /// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control |
| 4633 | /// (the mode search's own weight); below 1 the split trial is charged less |
| 4634 | /// for its bits and fires more often. |
| 4635 | /// |
| 4636 | /// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the |
| 4637 | /// `tx_depth` SYMBOL price correct and every film row got worse, because the |
| 4638 | /// correct row is a one-sided push away from splitting (depth 0 up to 1.5 |
| 4639 | /// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) -- |
| 4640 | /// so what is mis-calibrated is the weight the split's rate is judged under, |
| 4641 | /// not the price. `EC_AV1_SPLIT_LAMBDA`. |
| 4642 | pub(crate) fn split_lambda_mult() -> f64 { |
| 4643 | static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| { |
| 4644 | crate::envflags::var("EC_AV1_SPLIT_LAMBDA") |
| 4645 | .ok() |
| 4646 | .and_then(|v| v.parse().ok()) |
| 4647 | .unwrap_or(SPLIT_LAMBDA) |
| 4648 | }); |
| 4649 | *M |
| 4650 | } |
| 4651 | |
| 4652 | /// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for |
| 4653 | /// the sweep that chose it. |
| 4654 | const SPLIT_LAMBDA: f64 = 1.0; |
| 4655 | |
| 4656 | /// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself, |
| 4657 | /// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type |
| 4658 | /// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket: |
| 4659 | /// trials offered, trials the split won, then the (rate, distortion) of the |
| 4660 | /// split and flat arms summed apart for the split-won and flat-won trials -- |
| 4661 | /// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is. |
| 4662 | static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] = |
| 4663 | [const { std::sync::atomic::AtomicU64::new(0) }; 160]; |
| 4664 | |
| 4665 | /// Whether [`SPLIT_CENSUS`] is armed, read once. |
| 4666 | pub(crate) fn split_census_on() -> bool { |
| 4667 | static ON: std::sync::LazyLock<bool> = |
| 4668 | std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS")); |
| 4669 | *ON |
| 4670 | } |
| 4671 | |
| 4672 | /// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`]. |
| 4673 | /// Sides below 8 and above 64 fold into the end rows, which no caller offers. |
| 4674 | fn split_census_base(site: usize, key: bool, side: usize) -> usize { |
| 4675 | let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3); |
| 4676 | ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10 |
| 4677 | } |
| 4678 | |
| 4679 | /// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each |
| 4680 | /// `(rate in bits, distortion as squared error)`. |
| 4681 | fn split_census( |
| 4682 | site: usize, |
| 4683 | key: bool, |
| 4684 | side: usize, |
| 4685 | split_won: bool, |
| 4686 | split: (f64, f64), |
| 4687 | flat: (f64, f64), |
| 4688 | ) { |
| 4689 | use std::sync::atomic::Ordering::Relaxed; |
| 4690 | let base = split_census_base(site, key, side); |
| 4691 | let add = |i: usize, v: u64| { |
| 4692 | SPLIT_CENSUS[base + i].fetch_add(v, Relaxed); |
| 4693 | }; |
| 4694 | add(0, 1); |
| 4695 | let off = if split_won { |
| 4696 | add(1, 1); |
| 4697 | 2 |
| 4698 | } else { |
| 4699 | 6 |
| 4700 | }; |
| 4701 | let (win, lose) = if split_won { (split, flat) } else { (flat, split) }; |
| 4702 | add(off, (win.0 * 64.0).max(0.0) as u64); |
| 4703 | add(off + 1, win.1.max(0.0) as u64); |
| 4704 | add(off + 2, (lose.0 * 64.0).max(0.0) as u64); |
| 4705 | add(off + 3, lose.1.max(0.0) as u64); |
| 4706 | } |
| 4707 | |
| 4708 | /// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at |
| 4709 | /// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the |
| 4710 | /// last table a run prints is the whole encode's total (there is no flush |
| 4711 | /// hook the encoder API guarantees to reach). |
| 4712 | pub(crate) fn dump_split_census() { |
| 4713 | use std::sync::atomic::Ordering::Relaxed; |
| 4714 | eprintln!( |
| 4715 | "SPLITCENSUS site frame side offered split share% \ |
| 4716 | win_rate win_dist lose_rate lose_dist" |
| 4717 | ); |
| 4718 | for site in 0..2 { |
| 4719 | for key in [true, false] { |
| 4720 | for side_idx in 0..4 { |
| 4721 | let base = split_census_base(site, key, 8 << side_idx); |
| 4722 | let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed)); |
| 4723 | if v[0] == 0 { |
| 4724 | continue; |
| 4725 | } |
| 4726 | let (n, s) = (v[0] as f64, v[1] as f64); |
| 4727 | // Winner terms live at 2,3 (split won) and 6,7 (flat won), |
| 4728 | // loser terms at 4,5 and 8,9 -- so each mean is one sum over |
| 4729 | // all `n` trials, not a mean of two means. |
| 4730 | eprintln!( |
| 4731 | "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \ |
| 4732 | {:>9.2} {:>9.0} {:>9.2} {:>9.0}", |
| 4733 | if site == 0 { "intra" } else { "inter" }, |
| 4734 | if key { "key " } else { "inter" }, |
| 4735 | 8 << side_idx, |
| 4736 | v[0], |
| 4737 | v[1], |
| 4738 | 100.0 * s / n, |
| 4739 | (v[2] + v[6]) as f64 / n / 64.0, |
| 4740 | (v[3] + v[7]) as f64 / n, |
| 4741 | (v[4] + v[8]) as f64 / n / 64.0, |
| 4742 | (v[5] + v[9]) as f64 / n, |
| 4743 | ); |
| 4744 | } |
| 4745 | } |
| 4746 | } |
| 4747 | } |
| 4748 | |
| 4749 | /// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter |
| 4750 | /// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not |
| 4751 | /// its mode/reference syntax and not the search's own cost function |
| 4752 | /// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the |
| 4753 | /// control; below 1 a coded vector is charged less and `NEWMV` wins more |
| 4754 | /// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`. |
| 4755 | pub(crate) fn mv_lambda_mult() -> f64 { |
| 4756 | static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| { |
| 4757 | crate::envflags::var("EC_AV1_MV_LAMBDA") |
| 4758 | .ok() |
| 4759 | .and_then(|v| v.parse().ok()) |
| 4760 | .unwrap_or(MV_LAMBDA) |
| 4761 | }); |
| 4762 | *M |
| 4763 | } |
| 4764 | |
| 4765 | /// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md. |
| 4766 | const MV_LAMBDA: f64 = 1.0; |
| 4767 | |
| 4768 | /// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax |
| 4769 | /// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits, |
| 4770 | /// which the RD cost multiplies by lambda). Zero at the default weight. |
| 4771 | fn mv_rate_surcharge(mv_bits: f64) -> f64 { |
| 4772 | (mv_lambda_mult() - 1.0) * mv_bits |
| 4773 | } |
| 4774 | |
| 4775 | /// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV` |
| 4776 | /// decision, bucketed by block side (8/16/32/64). Eight counters per bucket: |
| 4777 | /// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the |
| 4778 | /// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD |
| 4779 | /// cost it won by, 4 the summed cost it lost by, 5 the summed |
| 4780 | /// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched |
| 4781 | /// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as |
| 4782 | /// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra- |
| 4783 | /// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf |
| 4784 | /// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`]. |
| 4785 | static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] = |
| 4786 | [const { std::sync::atomic::AtomicU64::new(0) }; 36]; |
| 4787 | |
| 4788 | /// Whether [`NEWMV_CENSUS`] is armed, read once. |
| 4789 | pub(crate) fn newmv_census_on() -> bool { |
| 4790 | static ON: std::sync::LazyLock<bool> = |
| 4791 | std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS")); |
| 4792 | *ON |
| 4793 | } |
| 4794 | |
| 4795 | /// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36). |
| 4796 | fn newmv_census_global(i: usize) { |
| 4797 | if newmv_census_on() { |
| 4798 | NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4799 | } |
| 4800 | } |
| 4801 | |
| 4802 | /// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost` |
| 4803 | /// is the best cost the block had WITHOUT the `NEWMV` candidate (its |
| 4804 | /// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV` |
| 4805 | /// candidate's own; both `f64::INFINITY` is a block that offered neither. |
| 4806 | fn newmv_census_block( |
| 4807 | side: usize, |
| 4808 | offered: bool, |
| 4809 | new_cost: f64, |
| 4810 | other_cost: f64, |
| 4811 | mv: (i32, i32), |
| 4812 | nearest: (i32, i32), |
| 4813 | mv_bits: f64, |
| 4814 | ) { |
| 4815 | if !newmv_census_on() { |
| 4816 | return; |
| 4817 | } |
| 4818 | use std::sync::atomic::Ordering::Relaxed; |
| 4819 | let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8; |
| 4820 | let add = |i: usize, v: u64| { |
| 4821 | NEWMV_CENSUS[base + i].fetch_add(v, Relaxed); |
| 4822 | }; |
| 4823 | add(0, 1); |
| 4824 | if !offered { |
| 4825 | return; |
| 4826 | } |
| 4827 | add(1, 1); |
| 4828 | if new_cost < other_cost { |
| 4829 | add(2, 1); |
| 4830 | add(3, (other_cost - new_cost).max(0.0) as u64); |
| 4831 | } else { |
| 4832 | add(4, (new_cost - other_cost).max(0.0) as u64); |
| 4833 | } |
| 4834 | add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64); |
| 4835 | if mv == nearest { |
| 4836 | add(6, 1); |
| 4837 | } |
| 4838 | add(7, (mv_bits * 64.0).max(0.0) as u64); |
| 4839 | } |
| 4840 | |
| 4841 | /// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the |
| 4842 | /// same guard [`dump_split_census`] rides (cumulative, so the last table a |
| 4843 | /// run prints is the whole encode's). |
| 4844 | pub(crate) fn dump_newmv_census() { |
| 4845 | use std::sync::atomic::Ordering::Relaxed; |
| 4846 | eprintln!( |
| 4847 | "NEWMVCENSUS side searched offered won won% win_margin lose_margin \ |
| 4848 | mv_dist_q3 mv==nearest% mv_bits" |
| 4849 | ); |
| 4850 | for side_idx in 0..4 { |
| 4851 | let base = side_idx * 8; |
| 4852 | let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed)); |
| 4853 | if v[0] == 0 { |
| 4854 | continue; |
| 4855 | } |
| 4856 | let off = v[1].max(1) as f64; |
| 4857 | eprintln!( |
| 4858 | "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}", |
| 4859 | 8 << side_idx, |
| 4860 | v[0], |
| 4861 | v[1], |
| 4862 | v[2], |
| 4863 | 100.0 * v[2] as f64 / off, |
| 4864 | v[3] as f64 / v[2].max(1) as f64, |
| 4865 | v[4] as f64 / (v[1] - v[2]).max(1) as f64, |
| 4866 | v[5] as f64 / off, |
| 4867 | 100.0 * v[6] as f64 / off, |
| 4868 | v[7] as f64 / off / 64.0, |
| 4869 | ); |
| 4870 | } |
| 4871 | // lane-hpmv: how many mv components this encode coded an eighth-pel bit |
| 4872 | // for, and how many of those named a vector no non-hp frame can code. |
| 4873 | let (hp_all, hp_eighth) = crate::tile::hp_symbols(); |
| 4874 | eprintln!( |
| 4875 | "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)", |
| 4876 | 100.0 * hp_eighth as f64 / hp_all.max(1) as f64, |
| 4877 | ); |
| 4878 | let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed)); |
| 4879 | eprintln!( |
| 4880 | "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \ |
| 4881 | leaf second reference {}/{} ({:.1}%)", |
| 4882 | g[1], |
| 4883 | g[0], |
| 4884 | 100.0 * g[1] as f64 / g[0].max(1) as f64, |
| 4885 | g[3], |
| 4886 | g[2], |
| 4887 | 100.0 * g[3] as f64 / g[2].max(1) as f64, |
| 4888 | ); |
| 4889 | let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] = |
| 4890 | crate::motion::take_census(); |
| 4891 | let per = |n: u64| n as f64 / calls.max(1) as f64; |
| 4892 | eprintln!( |
| 4893 | "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \ |
| 4894 | winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \ |
| 4895 | moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)", |
| 4896 | per(evals), |
| 4897 | per(rounds), |
| 4898 | 100.0 * near_pred as f64 / calls.max(1) as f64, |
| 4899 | 100.0 * unmoved as f64 / calls.max(1) as f64, |
| 4900 | 100.0 * widest as f64 / calls.max(1) as f64, |
| 4901 | per(widest_moves), |
| 4902 | ); |
| 4903 | } |
| 4904 | |
| 4905 | /// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so |
| 4906 | /// the intra witness's fire count stays its own. |
| 4907 | pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = |
| 4908 | [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; |
| 4909 | |
| 4910 | /// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision |
| 4911 | /// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight). |
| 4912 | /// `0` compares types on reconstruction error alone, which is what separates |
| 4913 | /// a rate-term calibration (class `rd-rate-term-calibration`) from a |
| 4914 | /// distortion the trial mis-measures. |
| 4915 | pub(crate) fn tx_type_lambda_mult() -> f64 { |
| 4916 | static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| { |
| 4917 | crate::envflags::var("EC_AV1_TXRD_LAMBDA") |
| 4918 | .ok() |
| 4919 | .and_then(|v| v.parse().ok()) |
| 4920 | .unwrap_or(1.0) |
| 4921 | }); |
| 4922 | *M |
| 4923 | } |
| 4924 | |
| 4925 | /// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own |
| 4926 | /// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the |
| 4927 | /// default weight of 1 and for `DCT_DCT` itself. The instrument the film |
| 4928 | /// question needs: at weight 1 the five-type intra search spends 1.2% more |
| 4929 | /// bytes for 0.04 dB on both film rows, so what it under-charges is the rate |
| 4930 | /// of the type it picks. |
| 4931 | pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 { |
| 4932 | if tx_type == TxType::DctDct { |
| 4933 | 0.0 |
| 4934 | } else { |
| 4935 | lambda * (tx_type_lambda_mult() - 1.0) * bits |
| 4936 | } |
| 4937 | } |
| 4938 | |
| 4939 | /// lane-txrd instrument: over the FLAT inter luma decision, the summed |
| 4940 | /// reconstruction error and priced bits of the type the search chose against |
| 4941 | /// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an |
| 4942 | /// integer counter. `EC_AV1_TXRD_CENSUS`. |
| 4943 | pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [ |
| 4944 | std::sync::atomic::AtomicU64::new(0), |
| 4945 | std::sync::atomic::AtomicU64::new(0), |
| 4946 | std::sync::atomic::AtomicU64::new(0), |
| 4947 | std::sync::atomic::AtomicU64::new(0), |
| 4948 | std::sync::atomic::AtomicU64::new(0), |
| 4949 | std::sync::atomic::AtomicU64::new(0), |
| 4950 | std::sync::atomic::AtomicU64::new(0), |
| 4951 | ]; |
| 4952 | |
| 4953 | /// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib |
| 4954 | /// build would warn `dead_code` (class from lane-txset2's `coeff_bits`). |
| 4955 | #[cfg(test)] |
| 4956 | pub(crate) fn take_txrd_stats() -> [u64; 7] { |
| 4957 | std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4958 | } |
| 4959 | |
| 4960 | /// Reads [`INTER_TX_TYPE_HITS`] and zeroes it. |
| 4961 | #[cfg(test)] |
| 4962 | pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] { |
| 4963 | std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4964 | } |
| 4965 | |
| 4966 | /// How many luma transform units resolved to each [`TxType`], indexed by the |
| 4967 | /// enum's own discriminant (lane-txset): the fire count a witness asserts on, |
| 4968 | /// and the instrument that says which types the search actually reaches. |
| 4969 | pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] = |
| 4970 | [const { std::sync::atomic::AtomicUsize::new(0) }; 16]; |
| 4971 | |
| 4972 | /// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the |
| 4973 | /// counts to its own encode. |
| 4974 | #[cfg(test)] |
| 4975 | pub(crate) fn take_tx_type_hits() -> [usize; 16] { |
| 4976 | std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4977 | } |
| 4978 | |
| 4979 | /// How many blocks resolved to each `tx_depth`, the fire count that says |
| 4980 | /// whether the depth search below reaches its candidates at all. |
| 4981 | static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = |
| 4982 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 4983 | |
| 4984 | /// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts |
| 4985 | /// to its own encode. |
| 4986 | #[cfg(test)] |
| 4987 | pub(crate) fn take_tx_depth_hits() -> [usize; 3] { |
| 4988 | std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 4989 | } |
| 4990 | |
| 4991 | /// How many inter blocks resolved to each var-tx depth (0 = one transform |
| 4992 | /// over the whole block, 1 = its four halves), the fire count a gate prints |
| 4993 | /// to see the split search reach its candidates at all. Indexed |
| 4994 | /// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census |
| 4995 | /// says which of the four block classes the split reaches -- the 32x32 root |
| 4996 | /// and the compound blocks are this lane's two new ones. |
| 4997 | static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 4998 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 4999 | |
| 5000 | /// Whether a 32x32 inter winner searches its own var-tx depth (the four |
| 5001 | /// 16x16 units against the flat transform) instead of coding depth 0 blind. |
| 5002 | /// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off. |
| 5003 | /// |
| 5004 | /// Rejected three times on the bars rows of the native gate (flat to +0.3). |
| 5005 | /// lane-av1resweep re-judged it on the two REAL film crops at |
| 5006 | /// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file |
| 5007 | /// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`): |
| 5008 | /// |
| 5009 | /// | clip | shipped | tx32 depth | + [`compound_var_tx`] | |
| 5010 | /// |---|---|---|---| |
| 5011 | /// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 | |
| 5012 | /// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 | |
| 5013 | /// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 | |
| 5014 | /// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 | |
| 5015 | /// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 | |
| 5016 | /// |
| 5017 | /// The bars rows are ~90% zero-intra-cost cells, so the split never had |
| 5018 | /// residual to reach there -- the tool was being judged on content that |
| 5019 | /// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`. |
| 5020 | fn tx32_depth_search() -> bool { |
| 5021 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 5022 | crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off")) |
| 5023 | }); |
| 5024 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH)) |
| 5025 | } |
| 5026 | |
| 5027 | /// Whether a COMPOUND inter winner is offered the var-tx split at all: its |
| 5028 | /// trial units have to be predicted from BOTH references |
| 5029 | /// ([`mc_trial_compound`]) or the split would re-predict them by single- |
| 5030 | /// reference translation, which is not what the decoder reconstructs. |
| 5031 | /// ON by default (the table on [`tx32_depth_search`]: on real film it is |
| 5032 | /// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the |
| 5033 | /// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off. |
| 5034 | /// `EC_AV1_COMP_VARTX`. |
| 5035 | fn compound_var_tx() -> bool { |
| 5036 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 5037 | crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off")) |
| 5038 | }); |
| 5039 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX)) |
| 5040 | } |
| 5041 | |
| 5042 | /// How many 32x32-and-below inter blocks each reference frame won, indexed by |
| 5043 | /// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the |
| 5044 | /// fire count a gate prints to see an extra reference reach a block at all |
| 5045 | /// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never |
| 5046 | /// chosen is a pyramid that costs bytes and buys nothing). |
| 5047 | static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 5048 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 5049 | |
| 5050 | /// Reads [`REF_FRAME_HITS`] and zeroes it. |
| 5051 | #[cfg(test)] |
| 5052 | pub(crate) fn take_ref_frame_hits() -> [usize; 8] { |
| 5053 | std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 5054 | } |
| 5055 | |
| 5056 | /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it. |
| 5057 | #[cfg(test)] |
| 5058 | pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] { |
| 5059 | std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 5060 | } |
| 5061 | |
| 5062 | /// What the `txfm_split` symbols of one inter block cost at `depth`, priced |
| 5063 | /// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0 |
| 5064 | /// is one flag, depth 1 is a split root plus one unsplit flag per child |
| 5065 | /// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH` |
| 5066 | /// or a 4x4 sub-size). |
| 5067 | fn txfm_split_bits(side: usize, depth: usize) -> f64 { |
| 5068 | let max_tx = side.min(64); |
| 5069 | let ctx = |tx: usize| { |
| 5070 | crate::decode::txfm_partition_ctx_rect( |
| 5071 | crate::decode::TXFM_CTX_INIT, |
| 5072 | crate::decode::TXFM_CTX_INIT, |
| 5073 | side, |
| 5074 | tx, |
| 5075 | tx, |
| 5076 | ) |
| 5077 | }; |
| 5078 | if depth == 0 { |
| 5079 | return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0); |
| 5080 | } |
| 5081 | symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1) |
| 5082 | + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0) |
| 5083 | } |
| 5084 | |
| 5085 | /// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform |
| 5086 | /// type is never coded -- the decoder takes the LUMA type of the block's |
| 5087 | /// chroma-reference position and reduces it to the set the chroma size allows |
| 5088 | /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder |
| 5089 | /// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every |
| 5090 | /// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a |
| 5091 | /// basis they were never produced for: on the bars gate row the luma of the |
| 5092 | /// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70 |
| 5093 | /// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD |
| 5094 | /// collapse two lanes attributed to the type PRICE (class |
| 5095 | /// `parsed then discarded` / `override slot on one arm`: a decoder-derived |
| 5096 | /// field the encoder never mirrored). |
| 5097 | /// |
| 5098 | /// Re-codes the two chroma planes of a committed inter block at the type the |
| 5099 | /// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and |
| 5100 | /// the trials the caller already holds are right. |
| 5101 | #[allow(clippy::too_many_arguments)] |
| 5102 | fn recode_inter_chroma( |
| 5103 | chroma: &[Plane; 2], |
| 5104 | (x, y): (usize, usize), |
| 5105 | side: usize, |
| 5106 | mv: (i32, i32), |
| 5107 | refs: [(&[u16], usize, usize, usize); 2], |
| 5108 | second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>, |
| 5109 | search: &Search, |
| 5110 | set: TxbSet, |
| 5111 | luma_tx_type: TxType, |
| 5112 | fctx: &crate::decode::FrameCtx, |
| 5113 | ) -> Option<[Trial; 2]> { |
| 5114 | let c = side / 2; |
| 5115 | let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx); |
| 5116 | if tx == TxType::DctDct { |
| 5117 | return None; |
| 5118 | } |
| 5119 | Some([0usize, 1].map(|p| match second { |
| 5120 | Some((mv1, r1)) => mc_trial_compound_typed( |
| 5121 | &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx, |
| 5122 | search.deadzone, set, tx, fctx, |
| 5123 | ), |
| 5124 | None => mc_trial_typed( |
| 5125 | &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3, |
| 5126 | false, search.base_q_idx, search.deadzone, set, tx, fctx, |
| 5127 | ), |
| 5128 | })) |
| 5129 | } |
| 5130 | |
| 5131 | /// The inter block's own var-tx decision, once its motion vector is settled: |
| 5132 | /// its residual as ONE transform over the whole block, or as the four |
| 5133 | /// transforms of half the side the tree's first halving names. The prediction |
| 5134 | /// is the same motion compensation either way, so the split trial |
| 5135 | /// re-transforms the identical residual in four pieces -- it wins where four |
| 5136 | /// small transforms carry a locally varying residual cheaper than one big |
| 5137 | /// one. Commits the winner into `luma` and hands back its block-coordinate |
| 5138 | /// levels, the depth the writer codes and the cost the winner adds to (or |
| 5139 | /// takes off) the caller's already-computed flat cost. |
| 5140 | /// |
| 5141 | /// Only for a block wholly inside the frame: past the true edge the reader's |
| 5142 | /// var-tx recursion skips the units that fall outside |
| 5143 | /// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would |
| 5144 | /// leave the residual units this writes unpaired. |
| 5145 | #[allow(clippy::too_many_arguments)] |
| 5146 | fn commit_inter_luma( |
| 5147 | luma: &mut Plane, |
| 5148 | (x, y): (usize, usize), |
| 5149 | side: usize, |
| 5150 | mv: (i32, i32), |
| 5151 | reference: (&[u16], usize, usize, usize), |
| 5152 | search: &Search, |
| 5153 | flat: &Trial, |
| 5154 | skip: bool, |
| 5155 | // A COMPOUND winner's second half: the vector and reference planes the |
| 5156 | // trial units are blended from ([`mc_trial_compound`], the decoder's own |
| 5157 | // `comp_group_idx == 0` average). `None` is the single-reference block. |
| 5158 | second: Option<((i32, i32), (&[u16], usize, usize, usize))>, |
| 5159 | fctx: &crate::decode::FrameCtx, |
| 5160 | ) -> (Vec<i32>, u8, f64, Vec<TxType>) { |
| 5161 | // lane-txset2 step 1: the whole-block (depth 0) residual picks its own |
| 5162 | // type out of the two-type inter set the writer already codes a symbol |
| 5163 | // for, priced the same way the intra search is (sse + lambda * bits, the |
| 5164 | // bits carrying the `tx_type` symbol itself through RDOQ). A skipped |
| 5165 | // block codes no residual and the 64-point transform names no type. |
| 5166 | let mut flat_typed: Option<Trial> = None; |
| 5167 | let mut flat_type = TxType::DctDct; |
| 5168 | if !skip { |
| 5169 | // lane-intertx: on a `reduced_tx_set = 0` frame the search names the |
| 5170 | // Set1 alphabet the writer codes into ([`luma_set_for`], the shape |
| 5171 | // the intra search already takes), which is what makes the wider |
| 5172 | // seven-type candidate list below reachable -- and prices every |
| 5173 | // candidate, `IDTX` included, in the alphabet its symbol is really |
| 5174 | // coded into. |
| 5175 | if let Some(fset) = |
| 5176 | inter_luma_set(side).map(|set| luma_set_for(set, search.screen)) |
| 5177 | { |
| 5178 | let lambda = search.lambda * tx_type_lambda_mult(); |
| 5179 | let cost = |t: &Trial| t.sse + lambda * t.bits; |
| 5180 | for &tx_type in inter_tx_type_candidates(fset, search.screen) { |
| 5181 | if tx_type == TxType::DctDct { |
| 5182 | continue; |
| 5183 | } |
| 5184 | let candidate = match second { |
| 5185 | Some((mv1, ref1)) => mc_trial_compound_typed( |
| 5186 | luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx, |
| 5187 | search.deadzone, fset, tx_type, fctx, |
| 5188 | ), |
| 5189 | None => mc_trial_typed( |
| 5190 | luma, x, y, side, mv, true, reference.0, reference.1, reference.2, |
| 5191 | reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type, |
| 5192 | fctx, |
| 5193 | ), |
| 5194 | }; |
| 5195 | if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) { |
| 5196 | flat_type = tx_type; |
| 5197 | flat_typed = Some(candidate); |
| 5198 | } |
| 5199 | } |
| 5200 | } |
| 5201 | } |
| 5202 | // Counted at the return points, so the census names the types the block |
| 5203 | // really CODES -- a split unit's winner that the flat cost then beats was |
| 5204 | // never written (class `counter from refused stream`). |
| 5205 | let count = |types: &[TxType]| { |
| 5206 | for &t in types { |
| 5207 | INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 5208 | } |
| 5209 | }; |
| 5210 | let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat); |
| 5211 | if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip { |
| 5212 | use std::sync::atomic::Ordering::Relaxed; |
| 5213 | TXRD_STATS[0].fetch_add(1, Relaxed); |
| 5214 | TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed); |
| 5215 | TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed); |
| 5216 | TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed); |
| 5217 | TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed); |
| 5218 | // Is the `DCT_DCT` baseline the search compares against the trial |
| 5219 | // THIS function would build for the same block? A stale or |
| 5220 | // differently-predicted baseline is what would let a candidate win on |
| 5221 | // both terms at once (class `local-rd-on-references` vs a real |
| 5222 | // pricing defect); re-predicting it here is the only way to tell. |
| 5223 | if let Some(fset) = inter_luma_set(side) { |
| 5224 | let here = match second { |
| 5225 | Some((mv1, ref1)) => mc_trial_compound_typed( |
| 5226 | luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx, |
| 5227 | search.deadzone, fset, TxType::DctDct, fctx, |
| 5228 | ), |
| 5229 | None => mc_trial_typed( |
| 5230 | luma, x, y, side, mv, true, reference.0, reference.1, reference.2, |
| 5231 | reference.3, false, search.base_q_idx, search.deadzone, fset, |
| 5232 | TxType::DctDct, fctx, |
| 5233 | ), |
| 5234 | }; |
| 5235 | TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed); |
| 5236 | TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed); |
| 5237 | static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 5238 | let n = TXRD_STATS[0].load(Relaxed); |
| 5239 | if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 { |
| 5240 | eprintln!( |
| 5241 | "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \ |
| 5242 | flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \ |
| 5243 | sse={:.0} bits={:.1}", |
| 5244 | second.is_some(), flat.sse, flat.bits, here.sse, here.bits, |
| 5245 | flat_ref.sse, flat_ref.bits, |
| 5246 | ); |
| 5247 | } |
| 5248 | } |
| 5249 | } |
| 5250 | // What the caller's already-counted `flat` cost has to be corrected by |
| 5251 | // when a non-`DCT_DCT` type won it, the same way the split delta below is. |
| 5252 | let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits) |
| 5253 | - (flat.sse + search.lambda * flat.bits); |
| 5254 | let eligible = tx_select() |
| 5255 | && tx_select_inter() |
| 5256 | && !skip |
| 5257 | && side >= 16 |
| 5258 | && (second.is_none() || compound_var_tx()) |
| 5259 | && (side != BLOCK || tx32_depth_search()) |
| 5260 | && x + side <= luma.true_width |
| 5261 | && y + side <= luma.true_height; |
| 5262 | if !eligible { |
| 5263 | luma.commit(x, y, side, flat_ref); |
| 5264 | count(&[flat_type]); |
| 5265 | return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]); |
| 5266 | } |
| 5267 | let tx = side / 2; |
| 5268 | let set = luma_set_for( |
| 5269 | if tx >= 32 { |
| 5270 | // lane-b64b: the 64x64 root's halved transform is TX_32X32. |
| 5271 | TxbSet::Luma32Inter |
| 5272 | } else if tx >= 16 { |
| 5273 | TxbSet::Luma16Inter |
| 5274 | } else { |
| 5275 | TxbSet::Luma8Inter |
| 5276 | }, |
| 5277 | search.screen, |
| 5278 | ); |
| 5279 | let mut levels = vec![0i32; side * side]; |
| 5280 | let (mut sse, mut bits) = (0.0, 0.0); |
| 5281 | let mut units = Vec::with_capacity(4); |
| 5282 | // The split units are smaller than their block, so their `txb_skip` |
| 5283 | // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and |
| 5284 | // each unit's own commit publishes what the next one reads, coding order. |
| 5285 | luma.ctx.tu_split = true; |
| 5286 | // One type per unit in the writer's own raster order (tile.rs |
| 5287 | // `write_luma_tus`), all `DCT_DCT` when nothing else is offered. |
| 5288 | let mut split_types = vec![TxType::DctDct; 4]; |
| 5289 | for tu_row in 0..2 { |
| 5290 | for tu_col in 0..2 { |
| 5291 | let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); |
| 5292 | let unit = |tx_type: TxType| match second { |
| 5293 | Some((mv1, ref1)) => mc_trial_compound_typed( |
| 5294 | luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1, |
| 5295 | search.base_q_idx, search.deadzone, set, tx_type, fctx, |
| 5296 | ), |
| 5297 | None => mc_trial_typed( |
| 5298 | luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, |
| 5299 | reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx, |
| 5300 | ), |
| 5301 | }; |
| 5302 | let mut best: Option<(f64, TxType, Trial)> = None; |
| 5303 | for &tx_type in inter_tx_type_candidates(set, search.screen) { |
| 5304 | let candidate = unit(tx_type); |
| 5305 | let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits; |
| 5306 | if best.as_ref().is_none_or(|(b, _, _)| cost < *b) { |
| 5307 | best = Some((cost, tx_type, candidate)); |
| 5308 | } |
| 5309 | } |
| 5310 | let (_, tx_type, trial) = best.expect("the candidate list is never empty"); |
| 5311 | split_types[tu_row * 2 + tu_col] = tx_type; |
| 5312 | sse += trial.sse; |
| 5313 | bits += trial.bits; |
| 5314 | for row in 0..tx { |
| 5315 | levels[(tu_row * tx + row) * side + tu_col * tx..][..tx] |
| 5316 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 5317 | } |
| 5318 | units.push((tu_x, tu_y, trial)); |
| 5319 | } |
| 5320 | } |
| 5321 | luma.ctx.tu_split = false; |
| 5322 | let split_rate = bits + txfm_split_bits(side, 1); |
| 5323 | let flat_rate = flat_ref.bits + txfm_split_bits(side, 0); |
| 5324 | let split_cost = sse + search.lambda * split_lambda_mult() * split_rate; |
| 5325 | let flat_cost = flat_ref.sse + search.lambda * flat_rate; |
| 5326 | if split_census_on() { |
| 5327 | split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse)); |
| 5328 | } |
| 5329 | let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2; |
| 5330 | // The depth census has a leaf row and a 32x32 row and no 64 one, so the |
| 5331 | // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing |
| 5332 | // in the leaf row (class `gate-blind-to-feature`). |
| 5333 | let counted = side <= BLOCK; |
| 5334 | if split_cost < flat_cost { |
| 5335 | for (tu_x, tu_y, trial) in &units { |
| 5336 | luma.commit(*tu_x, *tu_y, tx, trial); |
| 5337 | } |
| 5338 | if counted { |
| 5339 | INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 5340 | } |
| 5341 | count(&split_types); |
| 5342 | return (levels, 1, flat_gain + split_cost - flat_cost, split_types); |
| 5343 | } |
| 5344 | if counted { |
| 5345 | INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 5346 | } |
| 5347 | luma.commit(x, y, side, flat_ref); |
| 5348 | count(&[flat_type]); |
| 5349 | (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]) |
| 5350 | } |
| 5351 | |
| 5352 | /// The largest distinct-colour count a block may hold and still be offered a |
| 5353 | /// palette candidate at all: past it the k-means quantisation costs more |
| 5354 | /// error than the map saves rate, and every trial is wasted wall. |
| 5355 | /// |
| 5356 | /// Swept on the gate's own screen capture (lane-av1pal2, the |
| 5357 | /// `unswept-decision-constants` class): 32 (the value this lane inherited) |
| 5358 | /// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64 |
| 5359 | /// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores |
| 5360 | /// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound |
| 5361 | /// binds on nothing this content holds. 128 ships: best BD against both |
| 5362 | /// references and no wall cost at all (6.1s, the same as at 32, because the |
| 5363 | /// blocks it newly admits are ones the RD then keeps). |
| 5364 | /// `EC_AV1_PAL_MAXCOLORS`. |
| 5365 | fn palette_max_colors() -> usize { |
| 5366 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 5367 | *N.get_or_init(|| { |
| 5368 | std::env::var("EC_AV1_PAL_MAXCOLORS") |
| 5369 | .ok() |
| 5370 | .and_then(|v| v.parse().ok()) |
| 5371 | .unwrap_or(128) |
| 5372 | }) |
| 5373 | } |
| 5374 | |
| 5375 | /// The palettes worth trying for one block's luma, in the shape libaom's |
| 5376 | /// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE` |
| 5377 | /// distinct colours takes them ALL (the prediction is then exact and the |
| 5378 | /// residual empty), and a busier one is quantised to 8 and to 4 colours by a |
| 5379 | /// one-dimensional Lloyd iteration seeded evenly across its range -- both |
| 5380 | /// offered, because which wins is an RD question the caller answers. |
| 5381 | /// `block` is `side*side` source samples, row-major. |
| 5382 | fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> { |
| 5383 | let mut histogram = [0u32; 256]; |
| 5384 | for &v in block { |
| 5385 | histogram[usize::from(v)] += 1; |
| 5386 | } |
| 5387 | let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect(); |
| 5388 | if present.len() < 2 { |
| 5389 | return Vec::new(); |
| 5390 | } |
| 5391 | let exact = |colors: &[u16]| -> crate::tile::PaletteY { |
| 5392 | let mut base = [0u16; 8]; |
| 5393 | base[..colors.len()].copy_from_slice(colors); |
| 5394 | let map = block |
| 5395 | .iter() |
| 5396 | .map(|&v| { |
| 5397 | colors |
| 5398 | .iter() |
| 5399 | .enumerate() |
| 5400 | .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) |
| 5401 | .map(|(i, _)| i as u8) |
| 5402 | .expect("a palette holds at least two colours") |
| 5403 | }) |
| 5404 | .collect(); |
| 5405 | crate::tile::PaletteY { size: colors.len() as u8, colors: base, map } |
| 5406 | }; |
| 5407 | if present.len() <= 8 { |
| 5408 | return vec![exact(&present)]; |
| 5409 | } |
| 5410 | if present.len() > palette_max_colors() { |
| 5411 | return Vec::new(); |
| 5412 | } |
| 5413 | let (lo, hi) = ( |
| 5414 | i32::from(present[0]), |
| 5415 | i32::from(present[present.len() - 1]), |
| 5416 | ); |
| 5417 | let mut out = Vec::with_capacity(2); |
| 5418 | for n in [8usize, 4] { |
| 5419 | // Even seeding across the block's own range, then four Lloyd passes |
| 5420 | // over the histogram (256 bins, not `side*side` pixels). |
| 5421 | let mut centres: Vec<f64> = (0..n) |
| 5422 | .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) |
| 5423 | .collect(); |
| 5424 | for _ in 0..4 { |
| 5425 | let mut sums = vec![0f64; n]; |
| 5426 | let mut counts = vec![0u32; n]; |
| 5427 | for (v, &count) in histogram.iter().enumerate() { |
| 5428 | if count == 0 { |
| 5429 | continue; |
| 5430 | } |
| 5431 | let k = (0..n) |
| 5432 | .min_by(|&a, &b| { |
| 5433 | (centres[a] - v as f64) |
| 5434 | .abs() |
| 5435 | .total_cmp(&(centres[b] - v as f64).abs()) |
| 5436 | }) |
| 5437 | .expect("n >= 2"); |
| 5438 | sums[k] += (v as u32 * count) as f64; |
| 5439 | counts[k] += count; |
| 5440 | } |
| 5441 | for k in 0..n { |
| 5442 | if counts[k] > 0 { |
| 5443 | centres[k] = sums[k] / f64::from(counts[k]); |
| 5444 | } |
| 5445 | } |
| 5446 | } |
| 5447 | let mut colors: Vec<u16> = centres |
| 5448 | .iter() |
| 5449 | .map(|&c| c.round().clamp(0.0, 255.0) as u16) |
| 5450 | .collect(); |
| 5451 | colors.sort_unstable(); |
| 5452 | colors.dedup(); |
| 5453 | if colors.len() >= 2 { |
| 5454 | out.push(exact(&colors)); |
| 5455 | } |
| 5456 | } |
| 5457 | out |
| 5458 | } |
| 5459 | |
| 5460 | #[allow(clippy::too_many_arguments)] |
| 5461 | // --------------------------------------------------------------------------- |
| 5462 | // lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV |
| 5463 | // validity). A key frame that detected screen content and finds enough exact |
| 5464 | // repeats in its own source sets `allow_intrabc`, which the spec forces every |
| 5465 | // in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns |
| 5466 | // its place when the copied blocks pay back the deblock/CDEF/LR the frame |
| 5467 | // gives up. `EC_AV1_INTRABC=0` turns the whole arm off. |
| 5468 | // --------------------------------------------------------------------------- |
| 5469 | |
| 5470 | /// Whether intra block copy is offered at all. **Off by default** -- |
| 5471 | /// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against |
| 5472 | /// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`), |
| 5473 | /// but on the gate's real screen capture it MEASURED WORSE: setting |
| 5474 | /// `allow_intrabc` costs the key frame its deblocking, CDEF and loop |
| 5475 | /// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay |
| 5476 | /// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc, |
| 5477 | /// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame |
| 5478 | /// that detected no screen content. |
| 5479 | fn intrabc_enabled() -> bool { |
| 5480 | if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) { |
| 5481 | return forced; |
| 5482 | } |
| 5483 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 5484 | *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1")) |
| 5485 | } |
| 5486 | |
| 5487 | thread_local! { |
| 5488 | /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation |
| 5489 | /// probe runs both arms in one process, and the suite is one process, so |
| 5490 | /// an environment variable cannot separate them (same reason |
| 5491 | /// [`SCREEN_FORCE`] exists). |
| 5492 | static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 5493 | } |
| 5494 | |
| 5495 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5496 | pub(crate) fn force_intrabc(value: Option<bool>) { |
| 5497 | INTRABC_FORCE.with(|c| c.set(value)); |
| 5498 | } |
| 5499 | |
| 5500 | /// How many of a screen frame's 16x16 blocks must have an exact repeat |
| 5501 | /// somewhere else in the source before `allow_intrabc` is worth the in-loop |
| 5502 | /// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision- |
| 5503 | /// constant class: `probe_intrabc_threshold` measures the arm at several |
| 5504 | /// values. |
| 5505 | fn intrabc_pct() -> usize { |
| 5506 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 5507 | *N.get_or_init(|| { |
| 5508 | std::env::var("EC_AV1_INTRABC_PCT") |
| 5509 | .ok() |
| 5510 | .and_then(|v| v.parse().ok()) |
| 5511 | .unwrap_or(10) |
| 5512 | }) |
| 5513 | } |
| 5514 | |
| 5515 | /// The pixel grid intrabc source positions are hashed on |
| 5516 | /// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it, |
| 5517 | /// which keeps the block-hash table (and so the search) linear in the frame |
| 5518 | /// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies |
| 5519 | /// at `dv / 2` full pel, so an odd DV would land half-pel and need the |
| 5520 | /// bilinear interpolation decode.rs applies but this encoder does not. |
| 5521 | fn intrabc_step() -> usize { |
| 5522 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 5523 | *N.get_or_init(|| { |
| 5524 | let n: usize = std::env::var("EC_AV1_INTRABC_STEP") |
| 5525 | .ok() |
| 5526 | .and_then(|v| v.parse().ok()) |
| 5527 | .unwrap_or(4); |
| 5528 | if n % 2 == 0 { n.max(2) } else { 4 } |
| 5529 | }) |
| 5530 | } |
| 5531 | |
| 5532 | /// The side of the luma square the block-hash table is keyed on. |
| 5533 | const IBC_HASH: usize = 16; |
| 5534 | |
| 5535 | /// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind |
| 5536 | /// the current one the source's bottom-right corner must already be. Under |
| 5537 | /// 128 superblocks the same 256 pixels are two superblocks, which |
| 5538 | /// [`Ibc::dv_valid`] derives from the size itself. |
| 5539 | const INTRABC_DELAY_SB64: i32 = 4; |
| 5540 | |
| 5541 | /// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`. |
| 5542 | fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 { |
| 5543 | let mut h: u64 = 0xcbf2_9ce4_8422_2325; |
| 5544 | for row in 0..IBC_HASH { |
| 5545 | let base = (y + row) * width + x; |
| 5546 | for &v in &plane[base..base + IBC_HASH] { |
| 5547 | h ^= u64::from(v); |
| 5548 | h = h.wrapping_mul(0x100_0000_01b3); |
| 5549 | } |
| 5550 | } |
| 5551 | h |
| 5552 | } |
| 5553 | |
| 5554 | /// Every `intrabc_step()`-aligned position of `plane` inside |
| 5555 | /// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`]. |
| 5556 | fn ibc_index( |
| 5557 | table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>, |
| 5558 | plane: &[u8], |
| 5559 | width: usize, |
| 5560 | (x0, y0): (usize, usize), |
| 5561 | (x1, y1): (usize, usize), |
| 5562 | ) { |
| 5563 | let step = intrabc_step(); |
| 5564 | if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH { |
| 5565 | return; |
| 5566 | } |
| 5567 | let mut y = y0.next_multiple_of(step); |
| 5568 | while y + IBC_HASH <= y1 { |
| 5569 | let mut x = x0.next_multiple_of(step); |
| 5570 | while x + IBC_HASH <= x1 { |
| 5571 | table |
| 5572 | .entry(ibc_hash(plane, width, x, y)) |
| 5573 | .or_default() |
| 5574 | .push((x as u32, y as u32)); |
| 5575 | x += step; |
| 5576 | } |
| 5577 | y += step; |
| 5578 | } |
| 5579 | } |
| 5580 | |
| 5581 | /// Whether `screen`-detected source `y` repeats itself enough to be worth |
| 5582 | /// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact |
| 5583 | /// content appears at some other position, against [`intrabc_pct`]. Returns |
| 5584 | /// the share as well, for the gate's own print. |
| 5585 | fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) { |
| 5586 | if true_width < 4 * 64 || true_height < 2 * 64 { |
| 5587 | return (false, 0.0); |
| 5588 | } |
| 5589 | let mut table = std::collections::HashMap::new(); |
| 5590 | ibc_index(&mut table, y, width, (0, 0), (true_width, true_height)); |
| 5591 | let (mut total, mut matched) = (0usize, 0usize); |
| 5592 | let mut by = 0; |
| 5593 | while by + IBC_HASH <= true_height { |
| 5594 | let mut bx = 0; |
| 5595 | while bx + IBC_HASH <= true_width { |
| 5596 | total += 1; |
| 5597 | if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) { |
| 5598 | if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) { |
| 5599 | matched += 1; |
| 5600 | } |
| 5601 | } |
| 5602 | bx += IBC_HASH; |
| 5603 | } |
| 5604 | by += IBC_HASH; |
| 5605 | } |
| 5606 | let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 }; |
| 5607 | (share * 100.0 >= intrabc_pct() as f64, share) |
| 5608 | } |
| 5609 | |
| 5610 | /// One tile's intrabc search state: a block-hash table over the part of the |
| 5611 | /// tile's own reconstruction that is already final (whole superblock rows -- |
| 5612 | /// the in-loop filters are off on this frame, so a coded superblock row never |
| 5613 | /// changes again), plus the last DV chosen, which the RD price uses as its |
| 5614 | /// predictor estimate. |
| 5615 | struct Ibc { |
| 5616 | /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the |
| 5617 | /// source repeats exactly where a lossily coded reconstruction only |
| 5618 | /// nearly does, so an exact-match table over the reconstruction finds |
| 5619 | /// almost nothing. The candidate is then SCORED against the |
| 5620 | /// reconstruction ([`ibc_sse`]), which is what a decoder will copy. |
| 5621 | table: std::collections::HashMap<u64, Vec<(u32, u32)>>, |
| 5622 | /// The tile's own luma rect, in samples. |
| 5623 | tile: (usize, usize, usize, usize), |
| 5624 | /// The DV the previous intrabc block of this tile took -- the *estimate* |
| 5625 | /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken |
| 5626 | /// against. The writer computes the true predictor off its own mi grid |
| 5627 | /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost |
| 5628 | /// a slightly mispriced candidate, never a wrong bitstream. |
| 5629 | last_dv: Option<(i32, i32)>, |
| 5630 | /// How many blocks took intrabc, and how many hash lookups found at least |
| 5631 | /// one valid candidate -- the gate's own fire counts. |
| 5632 | hits: usize, |
| 5633 | lookups: usize, |
| 5634 | found: usize, |
| 5635 | } |
| 5636 | |
| 5637 | impl Ibc { |
| 5638 | fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self { |
| 5639 | let mut table = std::collections::HashMap::new(); |
| 5640 | ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3)); |
| 5641 | Self { |
| 5642 | table, |
| 5643 | tile, |
| 5644 | last_dv: None, |
| 5645 | hits: 0, |
| 5646 | lookups: 0, |
| 5647 | found: 0, |
| 5648 | } |
| 5649 | } |
| 5650 | |
| 5651 | /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv` |
| 5652 | /// (1/8 pel), with this lane's own extra restriction on top: the source |
| 5653 | /// must lie entirely in a COMPLETED superblock row, which is exactly the |
| 5654 | /// region [`Self::fill_to`] indexes and a strict subset of what the spec |
| 5655 | /// allows. corner-cut, ceiling named: same-superblock-row sources (the |
| 5656 | /// wavefront's own diagonal) are legal and not searched; the upgrade path |
| 5657 | /// is to index the current row's finished superblocks too. |
| 5658 | fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool { |
| 5659 | let (dr, dc) = (dv.0 / 8, dv.1 / 8); |
| 5660 | if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 { |
| 5661 | return false; |
| 5662 | } |
| 5663 | let (tx0, ty0, tx1, ty1) = ( |
| 5664 | self.tile.0 as i32, |
| 5665 | self.tile.1 as i32, |
| 5666 | self.tile.2 as i32, |
| 5667 | self.tile.3 as i32, |
| 5668 | ); |
| 5669 | let (sx, sy) = (x as i32 + dc, y as i32 + dr); |
| 5670 | let (w, h) = (w as i32, h as i32); |
| 5671 | if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 { |
| 5672 | return false; |
| 5673 | } |
| 5674 | // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the |
| 5675 | // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB = |
| 5676 | // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here). |
| 5677 | // Counting 64s under a 128 superblock let the search take a source |
| 5678 | // from a 64 row the 128 visit order had not reconstructed yet. |
| 5679 | let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 }; |
| 5680 | let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 }; |
| 5681 | let active_sb_row = (y as i32 - ty0) >> sb_log2; |
| 5682 | let active_sb_col = (x as i32 - tx0) >> sb_log2; |
| 5683 | let src_sb_row = (sy + h - 1 - ty0) >> sb_log2; |
| 5684 | let src_sb_col = (sx + w - 1 - tx0) >> sb_log2; |
| 5685 | // This lane's own restriction (see the doc comment). |
| 5686 | if src_sb_row >= active_sb_row { |
| 5687 | return false; |
| 5688 | } |
| 5689 | let total = ((tx1 - tx0 - 1) >> sb_log2) + 1; |
| 5690 | if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay { |
| 5691 | return false; |
| 5692 | } |
| 5693 | // libaom's wavefront: only the top-left cone of the frame is legal. |
| 5694 | let wf = (1 + delay) * (active_sb_row - src_sb_row); |
| 5695 | src_sb_col < active_sb_col - delay + wf |
| 5696 | } |
| 5697 | } |
| 5698 | |
| 5699 | /// How many block searches ran, how many found at least one VALID candidate, |
| 5700 | /// and how many won on rate-distortion -- the hash hit rate a gate prints |
| 5701 | /// (class `gate-blind-to-feature`: "the search ran" and "the search found |
| 5702 | /// something" and "the block took it" are three different claims). |
| 5703 | static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] = |
| 5704 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 5705 | |
| 5706 | impl Drop for Ibc { |
| 5707 | fn drop(&mut self) { |
| 5708 | for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() { |
| 5709 | IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 5710 | } |
| 5711 | } |
| 5712 | } |
| 5713 | |
| 5714 | /// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to |
| 5715 | /// its own encode. |
| 5716 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 5717 | pub(crate) fn take_intrabc_search() -> [usize; 3] { |
| 5718 | std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 5719 | } |
| 5720 | |
| 5721 | /// [`crate::tile::write_dv_component`]'s static price -- the same shape as |
| 5722 | /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv` |
| 5723 | /// infers rather than codes. |
| 5724 | fn dv_component_bits(diff: i32) -> f64 { |
| 5725 | let z = diff.unsigned_abs() as i32 - 1; |
| 5726 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 5727 | let class = mv_class_of(z); |
| 5728 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 5729 | let local = z - mv_class_base(class); |
| 5730 | if class == 0 { |
| 5731 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize); |
| 5732 | } else { |
| 5733 | let d = local >> 3; |
| 5734 | for i in 0..class { |
| 5735 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 5736 | } |
| 5737 | } |
| 5738 | bits |
| 5739 | } |
| 5740 | |
| 5741 | /// What one block vector costs against `pred`, plus the `skip` and |
| 5742 | /// `use_intrabc` flags the block carries and the ordinary intra block does |
| 5743 | /// not pay in this currency. |
| 5744 | fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 { |
| 5745 | let diff = (dv.0 - pred.0, dv.1 - pred.1); |
| 5746 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 5747 | (false, false) => 0, |
| 5748 | (false, true) => 1, |
| 5749 | (true, false) => 2, |
| 5750 | (true, true) => 3, |
| 5751 | }; |
| 5752 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0; |
| 5753 | if diff.0 != 0 { |
| 5754 | bits += dv_component_bits(diff.0); |
| 5755 | } |
| 5756 | if diff.1 != 0 { |
| 5757 | bits += dv_component_bits(diff.1); |
| 5758 | } |
| 5759 | bits |
| 5760 | } |
| 5761 | |
| 5762 | /// The squared error of copying the `side`-square block at `(sx, sy)` of each |
| 5763 | /// plane's reconstruction onto the source block at `(x, y)`, luma and both |
| 5764 | /// chroma planes together -- what an intrabc block's whole (residual-free) |
| 5765 | /// distortion is. |
| 5766 | fn ibc_sse( |
| 5767 | luma: &Plane, |
| 5768 | chroma: &[Plane; 2], |
| 5769 | (x, y): (usize, usize), |
| 5770 | (sx, sy): (usize, usize), |
| 5771 | side: usize, |
| 5772 | ) -> f64 { |
| 5773 | // Inside the true frame only, for the reason [`Plane::block_sse`] is |
| 5774 | // (lane-sse): an intrabc block at the edge would otherwise be ranked by |
| 5775 | // how well it copies the padding. |
| 5776 | let mut sse = 0.0f64; |
| 5777 | let clip = |whole: usize, inside: usize| match edge_sse() { |
| 5778 | true => whole.min(inside), |
| 5779 | false => whole, |
| 5780 | }; |
| 5781 | let rows = clip(side, luma.true_height.saturating_sub(y)); |
| 5782 | let cols = clip(side, luma.true_width.saturating_sub(x)); |
| 5783 | for row in 0..rows { |
| 5784 | let src = &luma.source[(y + row) * luma.width + x..][..cols]; |
| 5785 | let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols]; |
| 5786 | for (&s, &r) in src.iter().zip(rec) { |
| 5787 | let d = f64::from(i32::from(s) - i32::from(r)); |
| 5788 | sse += d * d; |
| 5789 | } |
| 5790 | } |
| 5791 | let half = side / 2; |
| 5792 | for plane in chroma { |
| 5793 | let rows = clip(half, plane.true_height.saturating_sub(y / 2)); |
| 5794 | let cols = clip(half, plane.true_width.saturating_sub(x / 2)); |
| 5795 | for row in 0..rows { |
| 5796 | let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols]; |
| 5797 | let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols]; |
| 5798 | for (&s, &r) in src.iter().zip(rec) { |
| 5799 | let d = f64::from(i32::from(s) - i32::from(r)); |
| 5800 | sse += d * d; |
| 5801 | } |
| 5802 | } |
| 5803 | } |
| 5804 | sse |
| 5805 | } |
| 5806 | |
| 5807 | /// Copies the `side`-square block at `(sx, sy)` of each plane's |
| 5808 | /// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction, |
| 5809 | /// since it carries no residual (`skip`). Full-pel in both planes by |
| 5810 | /// construction ([`intrabc_step`] keeps every DV even), which is what makes |
| 5811 | /// this a plain copy where decode.rs runs the bilinear kernel over the same |
| 5812 | /// samples. |
| 5813 | fn ibc_commit( |
| 5814 | luma: &mut Plane, |
| 5815 | chroma: &mut [Plane; 2], |
| 5816 | (x, y): (usize, usize), |
| 5817 | (sx, sy): (usize, usize), |
| 5818 | side: usize, |
| 5819 | ) { |
| 5820 | for row in 0..side { |
| 5821 | let from = (sy + row) * luma.width + sx; |
| 5822 | let to = (y + row) * luma.width + x; |
| 5823 | let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec(); |
| 5824 | luma.reconstruction[to..to + side].copy_from_slice(&copied); |
| 5825 | } |
| 5826 | let half = side / 2; |
| 5827 | for plane in chroma { |
| 5828 | for row in 0..half { |
| 5829 | let from = (sy / 2 + row) * plane.width + sx / 2; |
| 5830 | let to = (y / 2 + row) * plane.width + x / 2; |
| 5831 | let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec(); |
| 5832 | plane.reconstruction[to..to + half].copy_from_slice(&copied); |
| 5833 | } |
| 5834 | plane.commit_ctx_zero(x / 2, y / 2, half); |
| 5835 | } |
| 5836 | luma.commit_ctx_zero(x, y, side); |
| 5837 | } |
| 5838 | |
| 5839 | /// Searches this block's own DV: every hash-table position whose 16x16 luma |
| 5840 | /// square equals the block's source square, plus the previous block's DV as a |
| 5841 | /// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns |
| 5842 | /// the winning `(dv, cost)`, or `None` when nothing valid was found. |
| 5843 | fn ibc_search( |
| 5844 | ibc: &mut Ibc, |
| 5845 | luma: &Plane, |
| 5846 | chroma: &[Plane; 2], |
| 5847 | (x, y): (usize, usize), |
| 5848 | side: usize, |
| 5849 | lambda: f64, |
| 5850 | ) -> Option<((i32, i32), f64, (usize, usize))> { |
| 5851 | let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8)); |
| 5852 | let mut best: Option<((i32, i32), f64, (usize, usize))> = None; |
| 5853 | let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| { |
| 5854 | let dv = ( |
| 5855 | (sy as i32 - y as i32) * 8, |
| 5856 | (sx as i32 - x as i32) * 8, |
| 5857 | ); |
| 5858 | if !ibc.dv_valid(x, y, side, side, dv) { |
| 5859 | return; |
| 5860 | } |
| 5861 | let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred); |
| 5862 | if best.as_ref().is_none_or(|b| cost < b.1) { |
| 5863 | *best = Some((dv, cost, (sx, sy))); |
| 5864 | } |
| 5865 | }; |
| 5866 | ibc.lookups += 1; |
| 5867 | let key = ibc_hash(luma.source, luma.width, x, y); |
| 5868 | // The table is filled in raster order, so the entries BEFORE this block's |
| 5869 | // own position are exactly the already-coded ones -- and the nearest of |
| 5870 | // them costs the fewest DV bits. Walking backwards from the block's own |
| 5871 | // slot is what makes the search look up-and-left; taking the newest |
| 5872 | // entries outright only ever finds candidates below and to the right, |
| 5873 | // every one of which `dv_valid` rejects. |
| 5874 | let hits: Vec<(u32, u32)> = ibc |
| 5875 | .table |
| 5876 | .get(&key) |
| 5877 | .map(|h| { |
| 5878 | let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32)); |
| 5879 | h[..end].iter().rev().take(32).copied().collect() |
| 5880 | }) |
| 5881 | .unwrap_or_default(); |
| 5882 | for (hx, hy) in hits { |
| 5883 | consider(&*ibc, hx as usize, hy as usize, &mut best); |
| 5884 | } |
| 5885 | if let Some(dv) = ibc.last_dv { |
| 5886 | let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8); |
| 5887 | if sx >= 0 && sy >= 0 { |
| 5888 | consider(&*ibc, sx as usize, sy as usize, &mut best); |
| 5889 | } |
| 5890 | } |
| 5891 | if best.is_some() { |
| 5892 | ibc.found += 1; |
| 5893 | } |
| 5894 | best |
| 5895 | } |
| 5896 | |
| 5897 | fn code_square( |
| 5898 | luma: &mut Plane, |
| 5899 | chroma: &mut [Plane; 2], |
| 5900 | (x, y): (usize, usize), |
| 5901 | side: usize, |
| 5902 | search: &Search, |
| 5903 | mode_bits: &[f64; 13], |
| 5904 | // The frame header's `tx_mode == TxMode::Select`: the block then searches |
| 5905 | // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one |
| 5906 | // transform over its whole side. |
| 5907 | tx_select: bool, |
| 5908 | // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose |
| 5909 | // header did not set `allow_intrabc`. |
| 5910 | ibc: Option<&mut Ibc>, |
| 5911 | // Whether this is a KEY frame's block, read only by the split census |
| 5912 | // ([`SPLIT_CENSUS`]): the two frame types split at very different rates, |
| 5913 | // which is this lane's whole finding. |
| 5914 | census_key: bool, |
| 5915 | fctx: &crate::decode::FrameCtx, |
| 5916 | ) -> (BlockCoeffs, f64) { |
| 5917 | let (luma_set, chroma_set) = if side == SUPERBLOCK { |
| 5918 | // A whole superblock coded as ONE intra block (lane-i64): one |
| 5919 | // TX_64X64 luma transform, whose coded quarter is the 32x32 corner |
| 5920 | // `code_from_prediction` hands back, and one TX_32X32 per chroma |
| 5921 | // plane -- the same three sets the key frame writer's |
| 5922 | // `Superblock::Whole` arm codes, and the same the inter 64x64 root |
| 5923 | // uses (`search_skip_64`). |
| 5924 | (TxbSet::Luma64, TxbSet::Chroma32) |
| 5925 | } else if side == BLOCK { |
| 5926 | (TxbSet::Luma32, TxbSet::Chroma16) |
| 5927 | } else if side == 8 { |
| 5928 | // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction: |
| 5929 | // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is |
| 5930 | // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at |
| 5931 | // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet |
| 5932 | // (this branch is still unreached), so leaving `Chroma8` here would |
| 5933 | // silently wire the wrong table the moment one does; `Chroma4` is |
| 5934 | // what a real caller needs. |
| 5935 | (TxbSet::Luma8, TxbSet::Chroma4) |
| 5936 | } else { |
| 5937 | (TxbSet::Luma16, TxbSet::Chroma8) |
| 5938 | }; |
| 5939 | let at = At { |
| 5940 | x, |
| 5941 | y, |
| 5942 | side, |
| 5943 | reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), |
| 5944 | set: luma_set_for(luma_set, search.screen), |
| 5945 | }; |
| 5946 | let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) = |
| 5947 | luma.search_block(at, search, mode_bits, fctx); |
| 5948 | let mut luma_tx_types = vec![tx_type]; |
| 5949 | // The depth search runs on the mode the whole-block transform picked -- |
| 5950 | // libaom's own ordering, and the reason it costs one extra pass per depth |
| 5951 | // rather than one per (mode, depth) pair. |
| 5952 | let mut tx_depth = 0u8; |
| 5953 | // A 64x64 block has no depth to search (`max_tx_depth`), but the writer |
| 5954 | // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent |
| 5955 | // pays that zero exactly as a 32x32's depth search makes it pay |
| 5956 | // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison |
| 5957 | // below hands the root a symbol for free. |
| 5958 | if tx_select && side == SUPERBLOCK { |
| 5959 | cost += search.lambda * tx_depth_bits(side, 0); |
| 5960 | } |
| 5961 | if tx_select && max_tx_depth(side) > 0 { |
| 5962 | let mut best = ( |
| 5963 | cost + search.lambda * tx_depth_bits(side, 0), |
| 5964 | 0usize, |
| 5965 | luma.snapshot(x, y, side), |
| 5966 | luma_coeffs, |
| 5967 | ); |
| 5968 | let mut best_types = std::mem::take(&mut luma_tx_types); |
| 5969 | // The census wants the flat arm's own (rate, distortion), which |
| 5970 | // `search_block` only hands back folded into one cost -- so under the |
| 5971 | // env flag alone it is re-coded at depth 0 and the plane restored. |
| 5972 | let census_flat = split_census_on().then(|| { |
| 5973 | let kept = luma.snapshot(x, y, side); |
| 5974 | let (_, sse, bits, _) = |
| 5975 | luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx); |
| 5976 | luma.restore(x, y, side, &kept); |
| 5977 | (bits + tx_depth_bits(side, 0), sse) |
| 5978 | }); |
| 5979 | let mut census_split: Option<(f64, f64)> = None; |
| 5980 | for depth in 1..=max_tx_depth(side) { |
| 5981 | let (levels, sse, bits, types) = |
| 5982 | luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx); |
| 5983 | let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth); |
| 5984 | let cost_d = sse + search.lambda * split_lambda_mult() * rate; |
| 5985 | if census_flat.is_some() { |
| 5986 | let c = (bits + tx_depth_bits(side, depth), sse); |
| 5987 | if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0) |
| 5988 | { |
| 5989 | census_split = Some(c); |
| 5990 | } |
| 5991 | } |
| 5992 | if cost_d < best.0 { |
| 5993 | best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side)); |
| 5994 | best_types = types; |
| 5995 | } |
| 5996 | } |
| 5997 | if let (Some(flat), Some(split)) = (census_flat, census_split) { |
| 5998 | split_census(0, census_key, side, best.1 > 0, split, flat); |
| 5999 | } |
| 6000 | luma_tx_types = best_types; |
| 6001 | luma.restore(x, y, side, &best.2); |
| 6002 | cost = best.0; |
| 6003 | tx_depth = best.1 as u8; |
| 6004 | luma_coeffs = best.3; |
| 6005 | TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 6006 | } |
| 6007 | // The palette candidate is priced against the mode the luma search (and |
| 6008 | // its transform-depth search) already settled on, so a block only takes |
| 6009 | // one when it beats the best ordinary intra coding of the same pixels. |
| 6010 | // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its |
| 6011 | // prediction is the colour map, not the DC of its neighbours. |
| 6012 | let mut mode = mode; |
| 6013 | let mut angle_delta = angle_delta; |
| 6014 | let mut palette = None; |
| 6015 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 6016 | let source: Vec<u8> = (y..y + side) |
| 6017 | .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) |
| 6018 | .collect(); |
| 6019 | let kept = luma.snapshot(x, y, side); |
| 6020 | // spec 5.11.50: a block cut by the frame's right/bottom edge codes |
| 6021 | // its map over the ON-SCREEN corner only and the decoder replicates |
| 6022 | // that outward, so the searched map is folded the same way here -- |
| 6023 | // the prediction priced, the reconstruction committed and the symbols |
| 6024 | // `write_color_index_map` writes are then one and the same map |
| 6025 | // (lane-palw). |
| 6026 | let on = ( |
| 6027 | side.min(luma.true_width.saturating_sub(x)), |
| 6028 | side.min(luma.true_height.saturating_sub(y)), |
| 6029 | ); |
| 6030 | for mut pal in palette_candidates(&source) { |
| 6031 | let n = usize::from(pal.size); |
| 6032 | crate::decode::palette_replicate(&mut pal.map, side, side, on); |
| 6033 | let prediction: Vec<u8> = pal |
| 6034 | .map |
| 6035 | .iter() |
| 6036 | .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) |
| 6037 | .collect(); |
| 6038 | let trial = luma.code_from_prediction( |
| 6039 | x, |
| 6040 | y, |
| 6041 | side, |
| 6042 | &prediction, |
| 6043 | false, |
| 6044 | search.base_q_idx, |
| 6045 | search.deadzone, |
| 6046 | luma_set, |
| 6047 | ); |
| 6048 | let cost_p = trial.sse |
| 6049 | + search.lambda |
| 6050 | * (trial.bits |
| 6051 | + mode_bits[DC_PRED as usize] |
| 6052 | + crate::tile::palette_bits(&pal, side, on) |
| 6053 | + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); |
| 6054 | if cost_p < cost { |
| 6055 | cost = cost_p; |
| 6056 | mode = DC_PRED as u8; |
| 6057 | angle_delta = 0; |
| 6058 | tx_depth = 0; |
| 6059 | luma_coeffs = coeffs(&trial.levels, side.min(BLOCK)); |
| 6060 | luma.commit(x, y, side, &trial); |
| 6061 | palette = Some(pal); |
| 6062 | } |
| 6063 | } |
| 6064 | if palette.is_none() { |
| 6065 | luma.restore(x, y, side, &kept); |
| 6066 | } |
| 6067 | } |
| 6068 | |
| 6069 | // The five recursive filter-intra modes (spec 5.11.14), priced against |
| 6070 | // whatever the mode, transform-depth and palette searches settled on -- |
| 6071 | // the same "one candidate loop after the incumbent is known" shape the |
| 6072 | // palette above uses. A block that takes one is `DC_PRED` with no palette |
| 6073 | // by construction (`av1_filter_intra_allowed`), and its luma transform |
| 6074 | // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`). |
| 6075 | // |
| 6076 | // lane-fitu: on a SCREEN frame the candidate is priced at every transform |
| 6077 | // depth the ordinary intra search runs, each unit predicting recursively |
| 6078 | // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra` |
| 6079 | // arm), so a block whose ordinary winner wanted a split transform is |
| 6080 | // compared against a filter arm that may split too. |
| 6081 | // |
| 6082 | // Measured (native BD table, lane-fitu): searching the depths on EVERY |
| 6083 | // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves |
| 6084 | // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a |
| 6085 | // locally cheaper reconstruction that the film rows go on to predict from |
| 6086 | // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen |
| 6087 | // content is where it pays, and a non-screen frame keeps the depth-0-only |
| 6088 | // arm, byte for byte. |
| 6089 | let mut filter_intra: Option<u8> = None; |
| 6090 | if filter_intra_on() |
| 6091 | && palette.is_none() |
| 6092 | && let Some(class) = crate::decode::filter_intra_size_class(side) |
| 6093 | { |
| 6094 | let row = &cdf::FILTER_INTRA[class]; |
| 6095 | // With the sequence bit on, EVERY `DC_PRED` block without a luma |
| 6096 | // palette carries the flag, so the incumbent pays its zero before the |
| 6097 | // comparison -- otherwise the candidate is charged a bit the block |
| 6098 | // spends either way (class `price-the-narrowing-not-the-table`). |
| 6099 | if mode == DC_PRED { |
| 6100 | cost += search.lambda * symbol_bits(row, 0); |
| 6101 | } |
| 6102 | let one_bits = symbol_bits(row, 1); |
| 6103 | let kept = luma.snapshot(x, y, side); |
| 6104 | let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 }; |
| 6105 | let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None; |
| 6106 | for fi in 0..5u8 { |
| 6107 | for depth in 0..=max_depth { |
| 6108 | // A filter-intra block's units are coded through |
| 6109 | // `code_from_prediction`, which is `DCT_DCT` throughout, so |
| 6110 | // this arm keeps the empty (all-`DCT_DCT`) type list. |
| 6111 | let (levels, sse, bits, _) = |
| 6112 | luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx); |
| 6113 | let cost_f = sse |
| 6114 | + search.lambda |
| 6115 | * (bits |
| 6116 | + mode_bits[DC_PRED as usize] |
| 6117 | + one_bits |
| 6118 | + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi)) |
| 6119 | + if tx_select { tx_depth_bits(side, depth) } else { 0.0 }); |
| 6120 | if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) { |
| 6121 | best = Some(( |
| 6122 | cost_f, |
| 6123 | fi, |
| 6124 | depth, |
| 6125 | luma.snapshot(x, y, side), |
| 6126 | coeffs(&levels, side), |
| 6127 | )); |
| 6128 | } |
| 6129 | } |
| 6130 | } |
| 6131 | if let Some((cost_f, fi, depth, snapshot, levels)) = best { |
| 6132 | cost = cost_f; |
| 6133 | mode = DC_PRED; |
| 6134 | angle_delta = 0; |
| 6135 | tx_depth = depth as u8; |
| 6136 | luma_coeffs = levels; |
| 6137 | luma.restore(x, y, side, &snapshot); |
| 6138 | filter_intra = Some(fi); |
| 6139 | } else { |
| 6140 | luma.restore(x, y, side, &kept); |
| 6141 | } |
| 6142 | } |
| 6143 | |
| 6144 | // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both |
| 6145 | // planes; what it costs still counts towards the partition decision. |
| 6146 | let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) = |
| 6147 | search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx); |
| 6148 | cost += chroma_cost; |
| 6149 | |
| 6150 | // The intrabc arm is priced against the WHOLE block -- luma and both |
| 6151 | // chroma planes, residual-free -- so it is compared after the chroma |
| 6152 | // search has added its own cost, not against the luma decision alone. |
| 6153 | if let Some(ibc) = ibc { |
| 6154 | if let Some((dv, cost_ibc, src)) = |
| 6155 | ibc_search(ibc, luma, chroma, (x, y), side, search.lambda) |
| 6156 | { |
| 6157 | if cost_ibc < cost { |
| 6158 | ibc_commit(luma, chroma, (x, y), src, side); |
| 6159 | ibc.last_dv = Some(dv); |
| 6160 | ibc.hits += 1; |
| 6161 | return ( |
| 6162 | BlockCoeffs { |
| 6163 | skip: true, |
| 6164 | dv: Some(dv), |
| 6165 | ..BlockCoeffs::default() |
| 6166 | }, |
| 6167 | cost_ibc, |
| 6168 | ); |
| 6169 | } |
| 6170 | } |
| 6171 | } |
| 6172 | // A palette or filter-intra block's luma was recoded through `DCT_DCT` |
| 6173 | // (its levels came from `code_from_prediction`), so the searched types |
| 6174 | // belong to a block this one no longer is. |
| 6175 | if palette.is_some() || filter_intra.is_some() { |
| 6176 | luma_tx_types = Vec::new(); |
| 6177 | } |
| 6178 | ( |
| 6179 | BlockCoeffs { |
| 6180 | u, |
| 6181 | v, |
| 6182 | luma: luma_coeffs, |
| 6183 | mode, |
| 6184 | uv_mode, |
| 6185 | tx_depth, |
| 6186 | palette, |
| 6187 | palette_uv, |
| 6188 | filter_intra, |
| 6189 | cfl_alphas, |
| 6190 | angle_delta_y: angle_delta as i8, |
| 6191 | luma_tx_types, |
| 6192 | ..BlockCoeffs::default() |
| 6193 | }, |
| 6194 | cost, |
| 6195 | ) |
| 6196 | } |
| 6197 | |
| 6198 | /// The chroma modes the search offers, and the only ones it may offer: each |
| 6199 | /// predicts from the row directly above and the column directly to the left |
| 6200 | /// and nothing further, so none of them needs the above-right/below-left |
| 6201 | /// `Reach` a chroma block is coded with `Reach::none()` for. The eight |
| 6202 | /// directional modes do read past that, and `UV_CFL_PRED` needs the luma |
| 6203 | /// reconstruction and its own alpha syntax; both are left out here. |
| 6204 | const CHROMA_MODES: [u8; 7] = [ |
| 6205 | DC_PRED, |
| 6206 | V_PRED, |
| 6207 | H_PRED, |
| 6208 | SMOOTH_PRED, |
| 6209 | SMOOTH_V_PRED, |
| 6210 | SMOOTH_H_PRED, |
| 6211 | PAETH_PRED, |
| 6212 | ]; |
| 6213 | |
| 6214 | /// The thirteen intra mode names, for the chroma fire count's print. |
| 6215 | #[cfg(test)] |
| 6216 | const UV_MODE_NAMES: [&str; 14] = [ |
| 6217 | "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", |
| 6218 | "SMOOTH_H", "PAETH", "CFL", |
| 6219 | ]; |
| 6220 | |
| 6221 | /// How many blocks each chroma mode has won, indexed by the mode itself -- |
| 6222 | /// the fire count that says whether the search below reaches its candidates |
| 6223 | /// at all (the `gate-blind-to-feature` class), printed once per gate run. |
| 6224 | static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] = |
| 6225 | [const { std::sync::atomic::AtomicUsize::new(0) }; 14]; |
| 6226 | |
| 6227 | /// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has |
| 6228 | /// won, summed over both chroma planes -- the alpha histogram the gate prints |
| 6229 | /// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one |
| 6230 | /// magnitude only is a search that never left its first candidate). |
| 6231 | static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] = |
| 6232 | [const { std::sync::atomic::AtomicUsize::new(0) }; 17]; |
| 6233 | |
| 6234 | /// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha |
| 6235 | /// zero on a CfL block", `1..=16` the magnitudes. |
| 6236 | #[cfg(test)] |
| 6237 | pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] { |
| 6238 | std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 6239 | } |
| 6240 | |
| 6241 | /// How many directional luma blocks won at each `angle_delta_y`, indexed |
| 6242 | /// `delta + 3` -- the histogram that says whether the refinement below ever |
| 6243 | /// leaves zero (`gate-blind-to-feature`). |
| 6244 | static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] = |
| 6245 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 6246 | |
| 6247 | /// Reads [`ANGLE_DELTA_HITS`] and zeroes it. |
| 6248 | #[cfg(test)] |
| 6249 | pub(crate) fn take_angle_delta_hits() -> [usize; 7] { |
| 6250 | std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 6251 | } |
| 6252 | |
| 6253 | /// Whether the luma search refines a directional winner's `angle_delta_y` |
| 6254 | /// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair). |
| 6255 | fn angle_delta_on() -> bool { |
| 6256 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 6257 | crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0") |
| 6258 | }); |
| 6259 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE)) |
| 6260 | } |
| 6261 | |
| 6262 | /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0` |
| 6263 | /// switches it off, which is how the lane measured its own on/off pair). |
| 6264 | fn cfl_on() -> bool { |
| 6265 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 6266 | crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0") |
| 6267 | }); |
| 6268 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL)) |
| 6269 | } |
| 6270 | |
| 6271 | /// Whether the intra search offers the five recursive filter-intra modes at |
| 6272 | /// all, and with them whether the sequence header sets `enable_filter_intra` |
| 6273 | /// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured |
| 6274 | /// its own on/off pair -- and how every byte pin written before it still |
| 6275 | /// reproduces). It is also a speed lever: on at preset 0, off above it. |
| 6276 | // lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns |
| 6277 | // it off for the whole process (a sequence-header field, so it cannot change |
| 6278 | // mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses. |
| 6279 | // NOT an `EncoderConfig` field: that struct is built by 90 literal sites in |
| 6280 | // this workspace. |
| 6281 | |
| 6282 | /// Whether a sequence codes 128x128 superblocks when the environment says |
| 6283 | /// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE` |
| 6284 | /// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure |
| 6285 | /// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the |
| 6286 | /// 128x128 block in it every row of the native BD gate is down or flat on |
| 6287 | /// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames): |
| 6288 | /// |
| 6289 | /// | row | 64 superblocks | 128 + the 128 root | |
| 6290 | /// |---|---|---| |
| 6291 | /// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** | |
| 6292 | /// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** | |
| 6293 | /// | film A | +20.3 / -5.0 | **+20.1 / -5.2** | |
| 6294 | /// | film B | +24.6 / -2.0 | **+24.3 / -2.2** | |
| 6295 | /// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** | |
| 6296 | /// |
| 6297 | /// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B |
| 6298 | /// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base. |
| 6299 | /// |
| 6300 | /// ON since lane-b128m closed the eleven 128-superblock desyncs that held it |
| 6301 | /// off (the delta_q unit at the 128 superblock, the superblock size travelling |
| 6302 | /// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV |
| 6303 | /// predictor and wavefront, and seven test harnesses that handed the encoder a |
| 6304 | /// 64-superblock context). `EC_AV1_SB128=0` turns it off. |
| 6305 | pub(crate) const SB128_DEFAULT: bool = true; |
| 6306 | |
| 6307 | /// Whether this process's sequences code 128x128 superblocks. An ENCODER |
| 6308 | /// knob (like `speed::SPEED`), never read by a decode: read through a |
| 6309 | /// process-global (not a thread-local) because the tile writers run on |
| 6310 | /// worker threads; `2` is "the environment has not been read yet". |
| 6311 | static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); |
| 6312 | |
| 6313 | /// Whether this process's sequences code 128x128 superblocks. |
| 6314 | pub(crate) fn sb128_on() -> bool { |
| 6315 | use std::sync::atomic::Ordering::Relaxed; |
| 6316 | match ENC_SB128.load(Relaxed) { |
| 6317 | 2 => { |
| 6318 | let on = crate::envflags::var("EC_AV1_SB128") |
| 6319 | .ok() |
| 6320 | .map_or(SB128_DEFAULT, |v| v != "0"); |
| 6321 | ENC_SB128.store(u8::from(on), Relaxed); |
| 6322 | on |
| 6323 | } |
| 6324 | v => v == 1, |
| 6325 | } |
| 6326 | } |
| 6327 | |
| 6328 | /// Forces [`sb128_on`] for the rest of the process -- the superblock size is |
| 6329 | /// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`), |
| 6330 | /// exactly like the speed-preset gates. |
| 6331 | #[cfg(test)] |
| 6332 | pub(crate) fn force_sb128(on: bool) { |
| 6333 | ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed); |
| 6334 | } |
| 6335 | |
| 6336 | /// The luma loop-restoration unit size this sequence codes: a 128 superblock |
| 6337 | /// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there, |
| 6338 | /// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is |
| 6339 | /// 128), which is the one filter parameter the superblock size moves. |
| 6340 | pub(crate) fn lr_unit() -> u32 { |
| 6341 | if sb128_on() { 128 } else { 64 } |
| 6342 | } |
| 6343 | |
| 6344 | pub(crate) fn filter_intra_on() -> bool { |
| 6345 | #[cfg(test)] |
| 6346 | if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) { |
| 6347 | return forced; |
| 6348 | } |
| 6349 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| 6350 | crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0") |
| 6351 | }); |
| 6352 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA)) |
| 6353 | } |
| 6354 | |
| 6355 | /// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts |
| 6356 | /// to its own encode. |
| 6357 | #[cfg(test)] |
| 6358 | pub(crate) fn take_uv_mode_hits() -> [usize; 14] { |
| 6359 | std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 6360 | } |
| 6361 | |
| 6362 | /// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode -- |
| 6363 | /// `uv_mode` is a single symbol covering U and V -- and commits the cheapest. |
| 6364 | /// Returns each plane's levels, the mode, and what the pair cost (squared |
| 6365 | /// error plus lambda times bits, the same currency the luma search speaks). |
| 6366 | /// |
| 6367 | /// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`], |
| 6368 | /// which is what the luma mode decision was taken against, so what a |
| 6369 | /// candidate owes here is only the *difference* from that -- plus, for `V`/`H` |
| 6370 | /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the |
| 6371 | /// writer then has to code. |
| 6372 | #[allow(clippy::too_many_arguments)] |
| 6373 | /// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on, |
| 6374 | /// ranked by the SAD of their predictions summed over both planes (`DC_PRED` |
| 6375 | /// always kept, the same rule [`prune_by_sad`] applies to luma). `None` |
| 6376 | /// trials all seven, as before this lever. |
| 6377 | /// |
| 6378 | /// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was |
| 6379 | /// the search's largest trial population by far -- seven modes times two |
| 6380 | /// planes for every intra block, against 3.7 luma trials -- and the RD |
| 6381 | /// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three |
| 6382 | /// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build. |
| 6383 | fn chroma_top_k() -> Option<usize> { |
| 6384 | static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| { |
| 6385 | crate::envflags::var("EC_AV1_CHROMA_K") |
| 6386 | .ok() |
| 6387 | .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0)) |
| 6388 | }); |
| 6389 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K)) |
| 6390 | } |
| 6391 | |
| 6392 | /// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD |
| 6393 | /// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3): |
| 6394 | /// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/ |
| 6395 | /// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better) |
| 6396 | /// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The |
| 6397 | /// BD swings by about a point in either direction as near-tie chroma modes |
| 6398 | /// flip, which is the measurement's own sensitivity, not a trend: nothing |
| 6399 | /// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned. |
| 6400 | /// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: |
| 6401 | /// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's |
| 6402 | /// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`. |
| 6403 | pub(crate) const CHROMA_TOP_K: Option<usize> = None; |
| 6404 | |
| 6405 | fn search_chroma( |
| 6406 | chroma: &mut [Plane; 2], |
| 6407 | // The luma plane's RECONSTRUCTION under this block, already committed by |
| 6408 | // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales. |
| 6409 | luma: &Plane, |
| 6410 | (x, y): (usize, usize), |
| 6411 | side: usize, |
| 6412 | set: TxbSet, |
| 6413 | search: &Search, |
| 6414 | luma_mode: u8, |
| 6415 | fctx: &crate::decode::FrameCtx, |
| 6416 | ) -> ( |
| 6417 | [Vec<Coeff>; 2], |
| 6418 | u8, |
| 6419 | f64, |
| 6420 | Option<crate::tile::PaletteUv>, |
| 6421 | Option<(i32, i32)>, |
| 6422 | ) { |
| 6423 | let at = At { |
| 6424 | x: x / 2, |
| 6425 | y: y / 2, |
| 6426 | side: side / 2, |
| 6427 | reach: Reach::none(), |
| 6428 | set, |
| 6429 | }; |
| 6430 | // The census's cheap proxy for a chroma mode: the SAD of its prediction |
| 6431 | // summed over both planes, ranked by the same rule the luma histogram |
| 6432 | // uses. Only built under `EC_AV1_CENSUS`. |
| 6433 | // The SAD of each mode's prediction, summed over both planes -- the |
| 6434 | // census's ranking rule, and what [`chroma_top_k`] prunes by. |
| 6435 | let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> { |
| 6436 | let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 6437 | let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 6438 | u.iter() |
| 6439 | .zip(v.iter()) |
| 6440 | .map(|(&(us, mode), &(vs, _))| (us + vs, mode)) |
| 6441 | .collect() |
| 6442 | }; |
| 6443 | let modes: Vec<u8> = match chroma_top_k() { |
| 6444 | Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k), |
| 6445 | _ => CHROMA_MODES.to_vec(), |
| 6446 | }; |
| 6447 | let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; |
| 6448 | let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); |
| 6449 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 6450 | sad_scores(chroma) |
| 6451 | } else { |
| 6452 | Vec::new() |
| 6453 | }; |
| 6454 | census_add(2, 1); |
| 6455 | census_add(3, modes.len()); |
| 6456 | let mut best: Option<(f64, u8, Trial, Trial)> = None; |
| 6457 | for mode in modes { |
| 6458 | let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; |
| 6459 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 6460 | bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); |
| 6461 | } |
| 6462 | // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at |
| 6463 | // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32 |
| 6464 | // chroma of a 64x64 block is `DCT_DCT` whatever |
| 6465 | // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm |
| 6466 | // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32 |
| 6467 | // points. |
| 6468 | let tx_type = if at.side >= 32 { |
| 6469 | TxType::DctDct |
| 6470 | } else { |
| 6471 | crate::decode::default_intra_tx_type(mode) |
| 6472 | }; |
| 6473 | let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 6474 | let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 6475 | let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits); |
| 6476 | if best.as_ref().is_none_or(|(b, ..)| cost < *b) { |
| 6477 | best = Some((cost, mode, u, v)); |
| 6478 | } |
| 6479 | } |
| 6480 | let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); |
| 6481 | // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over |
| 6482 | // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is |
| 6483 | // what keeps `u_colors` ascending and distinct the way |
| 6484 | // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as |
| 6485 | // each cluster's own mean, since the colour-index map is SHARED by the |
| 6486 | // two planes. Priced against the best ordinary chroma mode above, so a |
| 6487 | // block only takes one when it beats it; a palette block's chroma mode is |
| 6488 | // `UV_DC_PRED` by construction. |
| 6489 | let mut palette_uv = None; |
| 6490 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 6491 | debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); |
| 6492 | let plane_source = |p: &Plane| -> Vec<u8> { |
| 6493 | (at.y..at.y + at.side) |
| 6494 | .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) |
| 6495 | .collect() |
| 6496 | }; |
| 6497 | let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); |
| 6498 | // The luma on-screen extent carried into this plane exactly as the |
| 6499 | // reader does it (`decode::palette_onscreen_uv`); see the luma arm. |
| 6500 | let on_uv = crate::decode::palette_onscreen_uv( |
| 6501 | (side, side), |
| 6502 | ( |
| 6503 | side.min(luma.true_width.saturating_sub(x)), |
| 6504 | side.min(luma.true_height.saturating_sub(y)), |
| 6505 | ), |
| 6506 | (at.side, at.side), |
| 6507 | // The encoder writes 4:2:0 only (`palette_uv_side` above). |
| 6508 | (1, 1), |
| 6509 | ); |
| 6510 | for mut pal in palette_candidates(&u_source) { |
| 6511 | let n = usize::from(pal.size); |
| 6512 | crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv); |
| 6513 | // V's base colour per cluster: the mean of the samples the shared |
| 6514 | // map assigns to it (an empty cluster cannot happen -- every |
| 6515 | // colour `palette_candidates` returns is some pixel's nearest). |
| 6516 | let mut sums = [0u32; 8]; |
| 6517 | let mut counts = [0u32; 8]; |
| 6518 | for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { |
| 6519 | let k = usize::from(i).min(n - 1); |
| 6520 | sums[k] += u32::from(sample); |
| 6521 | counts[k] += 1; |
| 6522 | } |
| 6523 | let mut v_colors = [0u16; 8]; |
| 6524 | for k in 0..n { |
| 6525 | v_colors[k] = if counts[k] > 0 { |
| 6526 | ((sums[k] + counts[k] / 2) / counts[k]) as u16 |
| 6527 | } else { |
| 6528 | 0 |
| 6529 | }; |
| 6530 | } |
| 6531 | let candidate = crate::tile::PaletteUv { |
| 6532 | size: pal.size, |
| 6533 | u_colors: pal.colors, |
| 6534 | v_colors, |
| 6535 | map: pal.map, |
| 6536 | }; |
| 6537 | let predict = |colors: &[u16; 8]| -> Vec<u8> { |
| 6538 | candidate |
| 6539 | .map |
| 6540 | .iter() |
| 6541 | .map(|&i| colors[usize::from(i).min(n - 1)] as u8) |
| 6542 | .collect() |
| 6543 | }; |
| 6544 | let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); |
| 6545 | let u_trial = chroma[0].code_from_prediction( |
| 6546 | at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, |
| 6547 | ); |
| 6548 | let v_trial = chroma[1].code_from_prediction( |
| 6549 | at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, |
| 6550 | ); |
| 6551 | let cost_p = u_trial.sse |
| 6552 | + v_trial.sse |
| 6553 | + search.lambda |
| 6554 | * (u_trial.bits |
| 6555 | + v_trial.bits |
| 6556 | + crate::tile::palette_uv_bits(&candidate, side, on_uv)); |
| 6557 | if cost_p < cost { |
| 6558 | cost = cost_p; |
| 6559 | mode = DC_PRED; |
| 6560 | u = u_trial; |
| 6561 | v = v_trial; |
| 6562 | palette_uv = Some(candidate); |
| 6563 | } |
| 6564 | } |
| 6565 | } |
| 6566 | // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`): |
| 6567 | // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then |
| 6568 | // nudges every sample by `alpha_q3` times the block's subsampled, |
| 6569 | // average-subtracted luma reconstruction. Offered only where |
| 6570 | // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 -- |
| 6571 | // and priced against the best ordinary chroma mode above, palette |
| 6572 | // included, so a block only takes it when it beats both. |
| 6573 | let mut cfl_alphas = None; |
| 6574 | if side <= 32 && cfl_on() { |
| 6575 | // The AC signal, through the decoder's own |
| 6576 | // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body. |
| 6577 | let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| { |
| 6578 | i32::from(luma.reconstruction[ly * luma.width + lx]) |
| 6579 | }); |
| 6580 | let dc_prediction = |plane: &Plane| -> Vec<u8> { |
| 6581 | let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]); |
| 6582 | let (above, left, corner) = |
| 6583 | plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf); |
| 6584 | let mut prediction = vec![0u8; at.side * at.side]; |
| 6585 | intra_predict_u8( |
| 6586 | DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction, |
| 6587 | fctx, |
| 6588 | ); |
| 6589 | prediction |
| 6590 | }; |
| 6591 | let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])]; |
| 6592 | // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then |
| 6593 | // add the residual -- which is what [`Plane::code_from_prediction`] |
| 6594 | // does with what this returns. |
| 6595 | let apply = |base: &[u8], alpha: i32| -> Vec<u8> { |
| 6596 | base.iter() |
| 6597 | .zip(ac.iter()) |
| 6598 | .map(|(&b, &a)| { |
| 6599 | (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8 |
| 6600 | }) |
| 6601 | .collect() |
| 6602 | }; |
| 6603 | // The least-squares alpha, then its two neighbours: minimising |
| 6604 | // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one |
| 6605 | // dot-product ratio, and the quantised optimum is one of the two |
| 6606 | // integers around it (the clamp and the Q6 rounding are what the SSE |
| 6607 | // check below re-decides). libaom sweeps all sixteen magnitudes under |
| 6608 | // full RD; three predictions per plane buy nearly the same alpha for a |
| 6609 | // thirtieth of the search. |
| 6610 | let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 { |
| 6611 | let (mut num, mut den) = (0.0f64, 0.0f64); |
| 6612 | for row in 0..at.side { |
| 6613 | for col in 0..at.side { |
| 6614 | let i = row * at.side + col; |
| 6615 | let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col]) |
| 6616 | - f64::from(base[i]); |
| 6617 | num += d * f64::from(ac[i]); |
| 6618 | den += f64::from(ac[i]) * f64::from(ac[i]); |
| 6619 | } |
| 6620 | } |
| 6621 | if den == 0.0 { |
| 6622 | return 0; |
| 6623 | } |
| 6624 | let ideal = 64.0 * num / den; |
| 6625 | let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32); |
| 6626 | for alpha in [ideal.floor() as i64, ideal.ceil() as i64] { |
| 6627 | let alpha = alpha.clamp(-16, 16) as i32; |
| 6628 | if alpha == 0 { |
| 6629 | continue; |
| 6630 | } |
| 6631 | let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha)); |
| 6632 | if sse < best.0 { |
| 6633 | best = (sse, alpha); |
| 6634 | } |
| 6635 | } |
| 6636 | best.1 |
| 6637 | }; |
| 6638 | let picked = [ |
| 6639 | pick_alpha(&chroma[0], &bases[0]), |
| 6640 | pick_alpha(&chroma[1], &bases[1]), |
| 6641 | ]; |
| 6642 | if picked != [0, 0] { |
| 6643 | let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits; |
| 6644 | let trial = |plane_idx: usize, alpha: i32| -> Trial { |
| 6645 | let prediction = if alpha == 0 { |
| 6646 | bases[plane_idx].clone() |
| 6647 | } else { |
| 6648 | apply(&bases[plane_idx], alpha) |
| 6649 | }; |
| 6650 | chroma[plane_idx].code_from_prediction( |
| 6651 | at.x, |
| 6652 | at.y, |
| 6653 | at.side, |
| 6654 | &prediction, |
| 6655 | false, |
| 6656 | search.base_q_idx, |
| 6657 | search.deadzone, |
| 6658 | set, |
| 6659 | ) |
| 6660 | }; |
| 6661 | // At least one alpha must be nonzero: `cfl_alpha_signs` has no |
| 6662 | // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]). |
| 6663 | let combos: [(i32, i32); 3] = [ |
| 6664 | (picked[0], picked[1]), |
| 6665 | (picked[0], 0), |
| 6666 | (0, picked[1]), |
| 6667 | ]; |
| 6668 | for &(alpha_u, alpha_v) in &combos { |
| 6669 | if (alpha_u, alpha_v) == (0, 0) { |
| 6670 | continue; |
| 6671 | } |
| 6672 | let cu = trial(0, alpha_u); |
| 6673 | let cv = trial(1, alpha_v); |
| 6674 | let bits = |
| 6675 | cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits; |
| 6676 | let cost_cfl = cu.sse + cv.sse + search.lambda * bits; |
| 6677 | if cost_cfl < cost { |
| 6678 | cost = cost_cfl; |
| 6679 | mode = crate::tile::UV_CFL_PRED as u8; |
| 6680 | u = cu; |
| 6681 | v = cv; |
| 6682 | palette_uv = None; |
| 6683 | cfl_alphas = Some((alpha_u, alpha_v)); |
| 6684 | } |
| 6685 | } |
| 6686 | } |
| 6687 | } |
| 6688 | if let Some((alpha_u, alpha_v)) = cfl_alphas { |
| 6689 | for alpha in [alpha_u, alpha_v] { |
| 6690 | CFL_ALPHA_HITS[alpha.unsigned_abs() as usize] |
| 6691 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 6692 | } |
| 6693 | } |
| 6694 | if census_on() { |
| 6695 | CHROMA_RANK[sad_rank(&ranking, mode).min(6)] |
| 6696 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 6697 | } |
| 6698 | UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 6699 | chroma[0].commit(at.x, at.y, at.side, &u); |
| 6700 | chroma[1].commit(at.x, at.y, at.side, &v); |
| 6701 | ( |
| 6702 | [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], |
| 6703 | mode, |
| 6704 | cost, |
| 6705 | palette_uv, |
| 6706 | cfl_alphas, |
| 6707 | ) |
| 6708 | } |
| 6709 | |
| 6710 | /// Codes one leaf of a straddling quadrant as whichever costs least of intra |
| 6711 | /// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at |
| 6712 | /// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`] |
| 6713 | /// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a |
| 6714 | /// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under |
| 6715 | /// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`] |
| 6716 | /// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not |
| 6717 | /// attempted here: these leaves only ever fill the sliver of real content a |
| 6718 | /// true edge lands in the middle of a larger block, not a leaf worth a full |
| 6719 | /// search, so `NEARESTMV`-or-intra is this function's deliberate first cut |
| 6720 | /// (see `write_inter_frame_leaf`'s doc comment). |
| 6721 | #[allow(clippy::too_many_arguments)] |
| 6722 | /// The compound MV stack of each `LAST` + extra-reference pair at one leaf, |
| 6723 | /// as [`code_square_inter`] wants them: empty on a frame that codes no |
| 6724 | /// `reference_select`, or when the leaf compound candidates are switched off. |
| 6725 | /// One helper because THREE leaf call sites need it -- the split quadrants |
| 6726 | /// and, since lane-av1comp4, both straddling-edge sites, which used to pass |
| 6727 | /// `&[]` and so coded no compound block anywhere along the frame's true edge. |
| 6728 | #[allow(clippy::too_many_arguments)] |
| 6729 | fn leaf_compound_stacks<'a>( |
| 6730 | grid: &MiGrid, |
| 6731 | mi_row: usize, |
| 6732 | mi_col: usize, |
| 6733 | bw4: usize, |
| 6734 | bh4: usize, |
| 6735 | mi_cols: usize, |
| 6736 | mi_rows: usize, |
| 6737 | reference_select: bool, |
| 6738 | golden: Option<&'a Picture>, |
| 6739 | altref: Option<&'a Picture>, |
| 6740 | ) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> { |
| 6741 | if !(reference_select && leaf_compound()) { |
| 6742 | return Vec::new(); |
| 6743 | } |
| 6744 | [ |
| 6745 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 6746 | (crate::mvstack::ALTREF_FRAME, altref), |
| 6747 | ] |
| 6748 | .into_iter() |
| 6749 | .filter_map(|(r, pic)| { |
| 6750 | pic.map(|p| { |
| 6751 | ( |
| 6752 | r, |
| 6753 | p, |
| 6754 | crate::mvstack::find_mv_stack_compound( |
| 6755 | grid, mi_row, mi_col, bw4, bh4, |
| 6756 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 6757 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 6758 | ), |
| 6759 | ) |
| 6760 | }) |
| 6761 | }) |
| 6762 | .collect() |
| 6763 | } |
| 6764 | |
| 6765 | /// The OBMC prediction of one square single-reference block: this block's own |
| 6766 | /// translation prediction (`mc::predict`) with every bordering above/left |
| 6767 | /// neighbour blended into the overlap strips by the DECODER's own plan and |
| 6768 | /// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what |
| 6769 | /// the search prices is what a decoder reconstructs -- never a second |
| 6770 | /// implementation of the blend. `None` when the block has no overlappable |
| 6771 | /// neighbour at all (the writer would then code no `motion_mode` symbol) or |
| 6772 | /// when the plan cannot be built (a neighbour naming a reference this encode |
| 6773 | /// does not hold). |
| 6774 | #[allow(clippy::too_many_arguments)] |
| 6775 | fn obmc_prediction( |
| 6776 | grid: &MiGrid, |
| 6777 | (mi_row, mi_col): (usize, usize), |
| 6778 | (mi_rows, mi_cols): (usize, usize), |
| 6779 | (x, y): (usize, usize), |
| 6780 | side: usize, |
| 6781 | mv: (i32, i32), |
| 6782 | refs: &[Option<&Picture>; 8], |
| 6783 | // This block's OWN reference planes, luma then both chroma, each as |
| 6784 | // (samples, stride, true width, true height). |
| 6785 | ref_planes: [(&[u16], usize, usize, usize); 3], |
| 6786 | frame_width: usize, |
| 6787 | fctx: &crate::decode::FrameCtx, |
| 6788 | ) -> Option<[Vec<u8>; 3]> { |
| 6789 | let n4 = side / 4; |
| 6790 | if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) { |
| 6791 | return None; |
| 6792 | } |
| 6793 | let refpix = crate::decode::RefPix::ready(*refs); |
| 6794 | let plan = crate::decode::obmc_plan( |
| 6795 | grid, |
| 6796 | &[], |
| 6797 | &[], |
| 6798 | mi_row, |
| 6799 | mi_col, |
| 6800 | n4, |
| 6801 | n4, |
| 6802 | mi_rows, |
| 6803 | mi_cols, |
| 6804 | side, |
| 6805 | side, |
| 6806 | side, |
| 6807 | crate::decode::ss_x(fctx), |
| 6808 | crate::decode::ss_y(fctx), |
| 6809 | side / 2, |
| 6810 | x, |
| 6811 | y, |
| 6812 | x / 2, |
| 6813 | y / 2, |
| 6814 | &refpix, |
| 6815 | Some(fctx.interp_filter.get()), |
| 6816 | frame_width, |
| 6817 | ) |
| 6818 | .ok()?; |
| 6819 | let mut pred = [ |
| 6820 | vec![0u16; side * side], |
| 6821 | vec![0u16; side * side / 4], |
| 6822 | vec![0u16; side * side / 4], |
| 6823 | ]; |
| 6824 | for (i, r) in ref_planes.into_iter().enumerate() { |
| 6825 | let luma_plane = i == 0; |
| 6826 | let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) }; |
| 6827 | let s = if luma_plane { side } else { side / 2 }; |
| 6828 | mc::predict( |
| 6829 | r.0, |
| 6830 | r.1, |
| 6831 | r.2, |
| 6832 | r.3, |
| 6833 | mv_to_q4(px, mv.1, luma_plane), |
| 6834 | mv_to_q4(py, mv.0, luma_plane), |
| 6835 | s, |
| 6836 | s, |
| 6837 | &mut pred[i], |
| 6838 | fctx, |
| 6839 | ); |
| 6840 | } |
| 6841 | let [mut py_buf, mut pu_buf, mut pv_buf] = pred; |
| 6842 | crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx); |
| 6843 | let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>(); |
| 6844 | Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)]) |
| 6845 | } |
| 6846 | |
| 6847 | fn code_square_inter( |
| 6848 | luma: &mut Plane, |
| 6849 | chroma: &mut [Plane; 2], |
| 6850 | (x, y): (usize, usize), |
| 6851 | side: usize, |
| 6852 | search: &Search, |
| 6853 | mode_bits: &[f64; 13], |
| 6854 | reference: &Picture, |
| 6855 | stack: &MvStack, |
| 6856 | // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS |
| 6857 | // leaf's own `bw4`/`bh4` (empty on a frame that does not code |
| 6858 | // `reference_select`, and at the straddling call sites). |
| 6859 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 6860 | // lane-av1obmc2: the mi grid this leaf's neighbours were published into |
| 6861 | // (`record_mi`, in the writer's own coding order) and this leaf's place in |
| 6862 | // it -- what the OBMC candidate's eligibility walk and neighbour plan |
| 6863 | // read, the same state the tile writer reads when it codes the leaf's |
| 6864 | // `motion_mode` symbol. |
| 6865 | grid: &MiGrid, |
| 6866 | (mi_row, mi_col): (usize, usize), |
| 6867 | (mi_rows, mi_cols): (usize, usize), |
| 6868 | // Every picture an OBMC neighbour can name: a leaf only searches LAST, |
| 6869 | // but the neighbours it blends may be GOLDEN/ALTREF blocks. |
| 6870 | refs: &[Option<&Picture>; 8], |
| 6871 | fctx: &crate::decode::FrameCtx, |
| 6872 | ) -> (BlockCoeffs, f64) { |
| 6873 | // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra |
| 6874 | // candidate at all -- `intra_cost` stays at infinity, so every |
| 6875 | // comparison below takes an inter candidate and the fallback arm at the |
| 6876 | // tail is unreachable. The planes hold what the caller snapshotted until |
| 6877 | // the winner commits: the intra trial used to commit here and be |
| 6878 | // overwritten by the inter commit, so skipping it changes no committed |
| 6879 | // sample, only work. |
| 6880 | let (intra_block, intra_cost) = if search.arf_leaf_intra { |
| 6881 | code_square( |
| 6882 | luma, |
| 6883 | chroma, |
| 6884 | (x, y), |
| 6885 | side, |
| 6886 | search, |
| 6887 | mode_bits, |
| 6888 | tx_select() && tx_select_inter(), |
| 6889 | None, |
| 6890 | false, |
| 6891 | fctx, |
| 6892 | ) |
| 6893 | } else { |
| 6894 | arfmode_hit(0); |
| 6895 | (BlockCoeffs::default(), f64::INFINITY) |
| 6896 | }; |
| 6897 | let luma_set = if side == 8 { |
| 6898 | TxbSet::Luma8Inter |
| 6899 | } else { |
| 6900 | TxbSet::Luma16Inter |
| 6901 | }; |
| 6902 | let chroma_set = if side == 8 { |
| 6903 | TxbSet::Chroma4 |
| 6904 | } else { |
| 6905 | TxbSet::Chroma8 |
| 6906 | }; |
| 6907 | |
| 6908 | let skip_bits = |skip: bool| skip_bits_at(stack, skip); |
| 6909 | let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter); |
| 6910 | let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); |
| 6911 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV |
| 6912 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero |
| 6913 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV |
| 6914 | |
| 6915 | let mv = stack.nearest_mv; |
| 6916 | let ref_luma = ( |
| 6917 | &reference.y, |
| 6918 | reference.width, |
| 6919 | luma.true_width, |
| 6920 | luma.true_height, |
| 6921 | ); |
| 6922 | let ref_u = ( |
| 6923 | &reference.u, |
| 6924 | reference.width / 2, |
| 6925 | chroma[0].true_width, |
| 6926 | chroma[0].true_height, |
| 6927 | ); |
| 6928 | let ref_v = ( |
| 6929 | &reference.v, |
| 6930 | reference.width / 2, |
| 6931 | chroma[1].true_width, |
| 6932 | chroma[1].true_height, |
| 6933 | ); |
| 6934 | let luma_trial = mc_trial( |
| 6935 | luma, |
| 6936 | x, |
| 6937 | y, |
| 6938 | side, |
| 6939 | mv, |
| 6940 | true, |
| 6941 | ref_luma.0, |
| 6942 | ref_luma.1, |
| 6943 | ref_luma.2, |
| 6944 | ref_luma.3, |
| 6945 | false, |
| 6946 | search.base_q_idx, |
| 6947 | search.deadzone, |
| 6948 | luma_set, fctx, |
| 6949 | ); |
| 6950 | let u = mc_trial( |
| 6951 | &chroma[0], |
| 6952 | x / 2, |
| 6953 | y / 2, |
| 6954 | side / 2, |
| 6955 | mv, |
| 6956 | false, |
| 6957 | ref_u.0, |
| 6958 | ref_u.1, |
| 6959 | ref_u.2, |
| 6960 | ref_u.3, |
| 6961 | false, |
| 6962 | search.base_q_idx, |
| 6963 | search.deadzone, |
| 6964 | chroma_set, fctx, |
| 6965 | ); |
| 6966 | let v = mc_trial( |
| 6967 | &chroma[1], |
| 6968 | x / 2, |
| 6969 | y / 2, |
| 6970 | side / 2, |
| 6971 | mv, |
| 6972 | false, |
| 6973 | ref_v.0, |
| 6974 | ref_v.1, |
| 6975 | ref_v.2, |
| 6976 | ref_v.3, |
| 6977 | false, |
| 6978 | search.base_q_idx, |
| 6979 | search.deadzone, |
| 6980 | chroma_set, fctx, |
| 6981 | ); |
| 6982 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 6983 | && u.levels.iter().all(|&l| l == 0) |
| 6984 | && v.levels.iter().all(|&l| l == 0); |
| 6985 | let inter_cost = luma_trial.sse |
| 6986 | + u.sse |
| 6987 | + v.sse |
| 6988 | + search.lambda |
| 6989 | * (skip_bits(skip) |
| 6990 | + intra_inter_bits(true) |
| 6991 | + single_ref_bits |
| 6992 | + mode_bits_inter |
| 6993 | + if skip { |
| 6994 | 0.0 |
| 6995 | } else { |
| 6996 | luma_trial.bits + u.bits + v.bits |
| 6997 | }); |
| 6998 | |
| 6999 | // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's |
| 7000 | // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's |
| 7001 | // extended row/col scan, invisible at 8-mi-only geometry (the immediate |
| 7002 | // scan's own coverage already reached as far) but a real gap at 4-mi |
| 7003 | // leaf geometry. r3 ported the extended scan and, while proving it a |
| 7004 | // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`, |
| 7005 | // `mvstack.rs`), found and fixed a second bug the extended scan's |
| 7006 | // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an |
| 7007 | // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/ |
| 7008 | // `scan_col_mbmi` advance coverage from any candidate's `bsize`, |
| 7009 | // regardless of whether it also casts a ref-frame-matching vote) -- |
| 7010 | // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else` |
| 7011 | // branches), which is what made 8-mi geometry a true no-op instead of |
| 7012 | // one that only held when every neighbour happened to be inter. |
| 7013 | // A motion search of this leaf's own (lane-av1rd2): before it, a leaf |
| 7014 | // only ever took the stack's NEARESTMV candidate or went intra, so a |
| 7015 | // 32x32 block splitting because its four quarters MOVE differently could |
| 7016 | // not code the movement it split for. Same candidate `search_inter_block` |
| 7017 | // prices for a whole block -- `motion::search` from `pred_mv`, rounded to |
| 7018 | // a vector the residual syntax can name -- at this leaf's own side. |
| 7019 | let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None); |
| 7020 | // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC |
| 7021 | // re-price below can hand it back as the winner's own mode info. |
| 7022 | let nearest_info = InterInfo { |
| 7023 | ref1: None, |
| 7024 | mv1: (0, 0), |
| 7025 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7026 | mode: InterMode::NearestMv, |
| 7027 | mv, |
| 7028 | ref_mv_idx: 0, |
| 7029 | }; |
| 7030 | // What the current SINGLE-REFERENCE winner pays in mode/reference/mv |
| 7031 | // syntax, apart from its residual: the OBMC candidate re-prices the same |
| 7032 | // syntax against a different prediction, so both sides of that comparison |
| 7033 | // carry it. |
| 7034 | let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter; |
| 7035 | // This leaf's own `NEWMV` vector, kept whether or not it won the |
| 7036 | // single-reference comparison: it seeds the compound half-new candidate |
| 7037 | // below, exactly as `search_inter_block` seeds its own from the searches |
| 7038 | // it already ran. |
| 7039 | let mut searched_new: Option<(i32, i32)> = None; |
| 7040 | // What that search cost, kept for the second reference's own early-out |
| 7041 | // below (`None` when this leaf ran no search at all). |
| 7042 | let mut searched_new_cost: Option<f64> = None; |
| 7043 | let source_block = luma.source_block(x, y, side); |
| 7044 | if leaf_new_mv() { |
| 7045 | let (seeds, seed_n) = mv_seeds(stack); |
| 7046 | let found = motion::search( |
| 7047 | ref_luma.0, |
| 7048 | ref_luma.1, |
| 7049 | ref_luma.2, |
| 7050 | ref_luma.3, |
| 7051 | &source_block, |
| 7052 | x, |
| 7053 | y, |
| 7054 | side, |
| 7055 | side, |
| 7056 | stack.pred_mv, |
| 7057 | &seeds[..seed_n], |
| 7058 | search.lambda, fctx, |
| 7059 | 1, |
| 7060 | ); |
| 7061 | let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 7062 | searched_new_cost = Some(found.cost); |
| 7063 | let mv_residual = mv_residual_bits(new_mv, stack.pred_mv); |
| 7064 | if mv_residual.is_none() { |
| 7065 | // lane-newmv: a vector the writer cannot name never reaches RD. |
| 7066 | newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0); |
| 7067 | } |
| 7068 | if let Some(mv_bits) = mv_residual { |
| 7069 | searched_new = Some(new_mv); |
| 7070 | // Same reuse as `search_inter_block`: a NEWMV equal to the |
| 7071 | // stack's NEARESTMV is the same three trials, already run above. |
| 7072 | let (luma_new, u_new, v_new) = if new_mv == mv { |
| 7073 | (luma_trial.clone(), u.clone(), v.clone()) |
| 7074 | } else { |
| 7075 | ( |
| 7076 | mc_trial( |
| 7077 | luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2, |
| 7078 | ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx, |
| 7079 | ), |
| 7080 | mc_trial( |
| 7081 | &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1, |
| 7082 | ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 7083 | fctx, |
| 7084 | ), |
| 7085 | mc_trial( |
| 7086 | &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1, |
| 7087 | ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 7088 | fctx, |
| 7089 | ), |
| 7090 | ) |
| 7091 | }; |
| 7092 | let skip_new = luma_new.levels.iter().all(|&l| l == 0) |
| 7093 | && u_new.levels.iter().all(|&l| l == 0) |
| 7094 | && v_new.levels.iter().all(|&l| l == 0); |
| 7095 | let drl_bits = if stack.entries.len() > 1 { |
| 7096 | symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) |
| 7097 | } else { |
| 7098 | 0.0 |
| 7099 | }; |
| 7100 | let cost_new = luma_new.sse |
| 7101 | + u_new.sse |
| 7102 | + v_new.sse |
| 7103 | + search.lambda |
| 7104 | * (skip_bits(skip_new) |
| 7105 | + intra_inter_bits(true) |
| 7106 | + single_ref_bits |
| 7107 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 7108 | + drl_bits |
| 7109 | + mv_bits |
| 7110 | + mv_rate_surcharge(mv_bits) |
| 7111 | + if skip_new { |
| 7112 | 0.0 |
| 7113 | } else { |
| 7114 | luma_new.bits + u_new.bits + v_new.bits |
| 7115 | }); |
| 7116 | newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits); |
| 7117 | if cost_new < best.0 { |
| 7118 | single_syntax = intra_inter_bits(true) |
| 7119 | + single_ref_bits |
| 7120 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 7121 | + drl_bits |
| 7122 | + mv_bits; |
| 7123 | best = ( |
| 7124 | cost_new, |
| 7125 | Some(( |
| 7126 | luma_new, |
| 7127 | u_new, |
| 7128 | v_new, |
| 7129 | skip_new, |
| 7130 | InterInfo { |
| 7131 | ref1: None, |
| 7132 | mv1: (0, 0), |
| 7133 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7134 | mode: InterMode::NewMv, |
| 7135 | mv: new_mv, |
| 7136 | ref_mv_idx: 0, |
| 7137 | }, |
| 7138 | )), |
| 7139 | ); |
| 7140 | } |
| 7141 | } |
| 7142 | } |
| 7143 | |
| 7144 | // The COMPOUND candidates at this leaf (lane-av1comp3), the same set |
| 7145 | // `search_inter_block` prices for a whole 32x32 block: |
| 7146 | // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector |
| 7147 | // this leaf already searched, and -- since lane-av1comp4 gave the leaf a |
| 7148 | // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV` |
| 7149 | // too. Priced with the same static-CDF approximation, plus the |
| 7150 | // compound-only syntax the writer emits. |
| 7151 | if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() { |
| 7152 | // lane-arfmode: arm 4 drops this leaf's compound set (counted once |
| 7153 | // per leaf, not once per pair); the single-reference candidates |
| 7154 | // above stay. |
| 7155 | arfmode_hit(2); |
| 7156 | } |
| 7157 | for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound() && search.arf_leaf_compound) { |
| 7158 | let (ref1, g) = (*ref1, *g); |
| 7159 | // The whole `comp_mode` + reference-pair tree at the writer's own |
| 7160 | // contexts, for THIS pair (lane-ctx). |
| 7161 | let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack); |
| 7162 | let mode_ctx = |
| 7163 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 7164 | let mode_bits_of = |
| 7165 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 7166 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 7167 | ( |
| 7168 | cstack.nearest_mv, |
| 7169 | mode_bits_of(0), |
| 7170 | InterInfo { |
| 7171 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7172 | mode: InterMode::NearestNearestMv, |
| 7173 | mv: cstack.nearest_mv.0, |
| 7174 | mv1: cstack.nearest_mv.1, |
| 7175 | ref1: Some(ref1), |
| 7176 | ref_mv_idx: 0, |
| 7177 | }, |
| 7178 | ), |
| 7179 | ( |
| 7180 | ((0, 0), (0, 0)), |
| 7181 | mode_bits_of(6), |
| 7182 | InterInfo { |
| 7183 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7184 | mode: InterMode::GlobalGlobalMv, |
| 7185 | mv: (0, 0), |
| 7186 | mv1: (0, 0), |
| 7187 | ref1: Some(ref1), |
| 7188 | ref_mv_idx: 0, |
| 7189 | }, |
| 7190 | ), |
| 7191 | ]; |
| 7192 | // Every compound MV residual here is priced against compound stack |
| 7193 | // entry 0, which is what `assign_compound_mv` predicts from at |
| 7194 | // `ref_mv_idx = 0` -- so it is also what the second-reference search |
| 7195 | // below seeds from and rounds to, and no candidate it finds can then |
| 7196 | // fail `mv_residual_bits`. |
| 7197 | let cbase = cstack |
| 7198 | .entries |
| 7199 | .first() |
| 7200 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 7201 | // This leaf's SECOND-reference motion search (lane-av1comp4). Without |
| 7202 | // it a leaf could only name a stack vector for the second half, and |
| 7203 | // screen capture showed the consequence: every leaf compound block |
| 7204 | // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s |
| 7205 | // extra-reference `NEWMV`, when this reference's own |
| 7206 | // `NEAREST_NEARESTMV` vector already prices `margin` times better |
| 7207 | // than the `LAST` search of this same leaf did -- one candidate |
| 7208 | // evaluation standing in for a whole search. |
| 7209 | let margin = leaf_second_new_margin(); |
| 7210 | let mut second_new: Option<(i32, i32)> = None; |
| 7211 | if leaf_second_new_mv() { |
| 7212 | newmv_census_global(2); |
| 7213 | let skip = margin > 0.0 |
| 7214 | && searched_new_cost.is_some_and(|last| { |
| 7215 | motion::cost_at( |
| 7216 | &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, |
| 7217 | side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx, |
| 7218 | ) * margin |
| 7219 | <= last |
| 7220 | }); |
| 7221 | if skip { |
| 7222 | newmv_census_global(3); |
| 7223 | } |
| 7224 | if !skip { |
| 7225 | let mut seeds = [(0, 0); 4]; |
| 7226 | let mut seed_n = 1; |
| 7227 | for e in cstack.entries.iter().take(3) { |
| 7228 | seeds[seed_n] = e.mv1; |
| 7229 | seed_n += 1; |
| 7230 | } |
| 7231 | let found = motion::search( |
| 7232 | &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side, |
| 7233 | side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1), |
| 7234 | ); |
| 7235 | second_new = Some(round_to_valid_mv(found.mv, cbase.1)); |
| 7236 | } |
| 7237 | } |
| 7238 | if let Some(new_mv) = searched_new { |
| 7239 | if let Some(b0) = mv_residual_bits(new_mv, cbase.0) { |
| 7240 | ccands.push(( |
| 7241 | (new_mv, cstack.nearest_mv.1), |
| 7242 | mode_bits_of(3) + b0, |
| 7243 | InterInfo { |
| 7244 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7245 | mode: InterMode::NewNearestMv, |
| 7246 | mv: new_mv, |
| 7247 | mv1: cstack.nearest_mv.1, |
| 7248 | ref1: Some(ref1), |
| 7249 | ref_mv_idx: 0, |
| 7250 | }, |
| 7251 | )); |
| 7252 | } |
| 7253 | } |
| 7254 | // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two |
| 7255 | // searches this leaf ran, each residual priced against `cbase`. |
| 7256 | if let Some(mv1) = second_new { |
| 7257 | if let Some(b1) = mv_residual_bits(mv1, cbase.1) { |
| 7258 | ccands.push(( |
| 7259 | (cstack.nearest_mv.0, mv1), |
| 7260 | mode_bits_of(2) + b1, |
| 7261 | InterInfo { |
| 7262 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7263 | mode: InterMode::NearestNewMv, |
| 7264 | mv: cstack.nearest_mv.0, |
| 7265 | mv1, |
| 7266 | ref1: Some(ref1), |
| 7267 | ref_mv_idx: 0, |
| 7268 | }, |
| 7269 | )); |
| 7270 | if let Some((new_mv, b0)) = |
| 7271 | searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b))) |
| 7272 | { |
| 7273 | ccands.push(( |
| 7274 | (new_mv, mv1), |
| 7275 | mode_bits_of(7) + b0 + b1, |
| 7276 | InterInfo { |
| 7277 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7278 | mode: InterMode::NewNewMv, |
| 7279 | mv: new_mv, |
| 7280 | mv1, |
| 7281 | ref1: Some(ref1), |
| 7282 | ref_mv_idx: 0, |
| 7283 | }, |
| 7284 | )); |
| 7285 | } |
| 7286 | } |
| 7287 | } |
| 7288 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 7289 | ccands.dedup_by_key(|c| c.0); |
| 7290 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 7291 | let g_u = ( |
| 7292 | g.u.as_slice(), |
| 7293 | g.width / 2, |
| 7294 | chroma[0].true_width, |
| 7295 | chroma[0].true_height, |
| 7296 | ); |
| 7297 | let g_v = ( |
| 7298 | g.v.as_slice(), |
| 7299 | g.width / 2, |
| 7300 | chroma[1].true_width, |
| 7301 | chroma[1].true_height, |
| 7302 | ); |
| 7303 | for (mvs, bits, info) in ccands { |
| 7304 | let luma_c = mc_trial_compound( |
| 7305 | luma, x, y, side, mvs, true, |
| 7306 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 7307 | search.base_q_idx, search.deadzone, luma_set, fctx, |
| 7308 | ); |
| 7309 | let u_c = mc_trial_compound( |
| 7310 | &chroma[0], x / 2, y / 2, side / 2, mvs, false, |
| 7311 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 7312 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 7313 | ); |
| 7314 | let v_c = mc_trial_compound( |
| 7315 | &chroma[1], x / 2, y / 2, side / 2, mvs, false, |
| 7316 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 7317 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 7318 | ); |
| 7319 | let skip_c = luma_c.levels.iter().all(|&l| l == 0) |
| 7320 | && u_c.levels.iter().all(|&l| l == 0) |
| 7321 | && v_c.levels.iter().all(|&l| l == 0); |
| 7322 | let cost_c = luma_c.sse |
| 7323 | + u_c.sse |
| 7324 | + v_c.sse |
| 7325 | + search.lambda |
| 7326 | * (skip_bits(skip_c) |
| 7327 | + intra_inter_bits(true) |
| 7328 | + bits |
| 7329 | + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits }); |
| 7330 | if cost_c < best.0 { |
| 7331 | best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info))); |
| 7332 | } |
| 7333 | } |
| 7334 | } |
| 7335 | |
| 7336 | // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec |
| 7337 | // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference |
| 7338 | // winner -- libaom's `motion_mode_allowed` refuses a compound block, and |
| 7339 | // the writer codes no symbol for one. The prediction is the decoder's own |
| 7340 | // plan and blend over the neighbours this leaf's `grid` already carries |
| 7341 | // (published by `record_mi` in the writer's coding order), so the |
| 7342 | // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc |
| 7343 | // offered this only at 32x32, which is not where libaom cashes its OBMC |
| 7344 | // gain. |
| 7345 | let mut motion_won = 0u8; |
| 7346 | let single = match &best.1 { |
| 7347 | None => Some(nearest_info), |
| 7348 | Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info), |
| 7349 | Some(_) => None, |
| 7350 | }; |
| 7351 | if let Some(info) = single.filter(|i| { |
| 7352 | (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on()) |
| 7353 | && i.ref_frame == crate::mvstack::LAST_FRAME |
| 7354 | }) { |
| 7355 | let planes = [ |
| 7356 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 7357 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 7358 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 7359 | ]; |
| 7360 | // Which alphabet this block's writer will code the symbol against |
| 7361 | // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the |
| 7362 | // 3-symbol one only under `allow_warped_motion` and at least one warp |
| 7363 | // sample. Mirrored here so the candidates are priced against the |
| 7364 | // table the tile really narrows. |
| 7365 | let warp_alphabet = warp_on() |
| 7366 | && crate::decode::num_proj_ref( |
| 7367 | grid, |
| 7368 | mi_row, |
| 7369 | mi_col, |
| 7370 | side / 4, |
| 7371 | side / 4, |
| 7372 | mi_cols, |
| 7373 | mi_rows, |
| 7374 | info.ref_frame, |
| 7375 | fctx, |
| 7376 | ) >= 1; |
| 7377 | let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet); |
| 7378 | let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new(); |
| 7379 | if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() { |
| 7380 | if let Some(pred) = obmc_prediction( |
| 7381 | grid, |
| 7382 | (mi_row, mi_col), |
| 7383 | (mi_rows, mi_cols), |
| 7384 | (x, y), |
| 7385 | side, |
| 7386 | info.mv, |
| 7387 | refs, |
| 7388 | planes, |
| 7389 | reference.width, |
| 7390 | fctx, |
| 7391 | ) { |
| 7392 | candidates.push((1, pred)); |
| 7393 | } |
| 7394 | } |
| 7395 | if warp_alphabet { |
| 7396 | if let Some(pred) = warp_prediction( |
| 7397 | grid, |
| 7398 | (mi_row, mi_col), |
| 7399 | (mi_rows, mi_cols), |
| 7400 | (x, y), |
| 7401 | side, |
| 7402 | info.mv, |
| 7403 | info.ref_frame, |
| 7404 | planes, |
| 7405 | fctx, |
| 7406 | ) { |
| 7407 | candidates.push((2, pred)); |
| 7408 | } |
| 7409 | } |
| 7410 | for (motion, pred) in candidates { |
| 7411 | let luma_o = luma.code_from_prediction( |
| 7412 | x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set, |
| 7413 | ); |
| 7414 | let u_o = chroma[0].code_from_prediction( |
| 7415 | x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone, |
| 7416 | chroma_set, |
| 7417 | ); |
| 7418 | let v_o = chroma[1].code_from_prediction( |
| 7419 | x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone, |
| 7420 | chroma_set, |
| 7421 | ); |
| 7422 | let skip_o = luma_o.levels.iter().all(|&l| l == 0) |
| 7423 | && u_o.levels.iter().all(|&l| l == 0) |
| 7424 | && v_o.levels.iter().all(|&l| l == 0); |
| 7425 | let cost_o = luma_o.sse |
| 7426 | + u_o.sse |
| 7427 | + v_o.sse |
| 7428 | + search.lambda |
| 7429 | * (skip_bits(skip_o) |
| 7430 | + single_syntax |
| 7431 | + mm(motion) |
| 7432 | + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits }); |
| 7433 | // The incumbent pays the motion_mode symbol IT would code, so |
| 7434 | // both sides of the comparison carry that syntax. |
| 7435 | if cost_o < best.0 + search.lambda * mm(motion_won) { |
| 7436 | motion_won = motion; |
| 7437 | best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info))); |
| 7438 | } |
| 7439 | } |
| 7440 | } |
| 7441 | |
| 7442 | if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best { |
| 7443 | if cost < intra_cost { |
| 7444 | // A compound winner commits the flat trial it was priced from: |
| 7445 | // `commit_inter_luma`'s var-tx trial set is single-reference |
| 7446 | // (`mc_trial`), so a compound leaf codes `tx_depth = 0`. |
| 7447 | // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma` |
| 7448 | // predicting each half-side trial from BOTH references, verified |
| 7449 | // byte-identical to this when its split is disabled) and MEASURED |
| 7450 | // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the |
| 7451 | // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/ |
| 7452 | // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A |
| 7453 | // compound block's residual is small enough that the four extra |
| 7454 | // per-unit txb_skip/eob symbols cost more ladder bytes than this |
| 7455 | // encoder's static-CDF estimate prices them at, so the local RD |
| 7456 | // win does not convert. lane-av1txbits REBUILT it on top of a |
| 7457 | // search that prices against the tables the frame is really |
| 7458 | // written with (`tile::arm_pricing_cdfs`, the estimate error on |
| 7459 | // these very blocks measured down from +31% to +3%) and measured |
| 7460 | // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/ |
| 7461 | // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the |
| 7462 | // same build without it. The static-CDF estimate was NOT what |
| 7463 | // held the compound var-tx trial back. The flat trial stays. |
| 7464 | // An OBMC winner commits the flat trial too: `commit_inter_luma` |
| 7465 | // re-predicts each var-tx unit by plain translation, which is not |
| 7466 | // the prediction this candidate was priced from. |
| 7467 | // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE |
| 7468 | // 0.05 (both rejections above were measured at 0.1, the weight |
| 7469 | // the lambda lane showed was 2x too heavy): a compound winner is |
| 7470 | // offered the same var-tx split, its units predicted from BOTH |
| 7471 | // references (`mc_trial_compound`). RE-MEASURED native: film |
| 7472 | // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4 |
| 7473 | // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off -- |
| 7474 | // one row 0.2 down, two flat, short of the two-down-one-flat keep |
| 7475 | // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF) |
| 7476 | // rather than change the default on a single 0.2 row. It fires: |
| 7477 | // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for |
| 7478 | // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against |
| 7479 | // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is |
| 7480 | // 1.3/1.2 down there, which is where the upgrade path is if this |
| 7481 | // is picked up again. |
| 7482 | let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| { |
| 7483 | refs[r as usize].map(|g| { |
| 7484 | ( |
| 7485 | info.mv1, |
| 7486 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 7487 | ) |
| 7488 | }) |
| 7489 | }); |
| 7490 | let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0 |
| 7491 | || (info.ref1.is_some() && second.is_none()) |
| 7492 | { |
| 7493 | luma.commit(x, y, side, &luma_new); |
| 7494 | (luma_new.levels.clone(), 0, 0.0, Vec::new()) |
| 7495 | } else { |
| 7496 | commit_inter_luma( |
| 7497 | luma, (x, y), side, info.mv, |
| 7498 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 7499 | search, &luma_new, skip_new, second, fctx, |
| 7500 | ) |
| 7501 | }; |
| 7502 | // lane-txrd: chroma follows the luma type the search just chose. |
| 7503 | let [u_new, v_new] = match luma_tx_types.first().copied() { |
| 7504 | Some(t) => recode_inter_chroma( |
| 7505 | chroma, (x, y), side, info.mv, |
| 7506 | [ |
| 7507 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 7508 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 7509 | ], |
| 7510 | info.ref1.filter(|_| motion_won == 0).and_then(|r| { |
| 7511 | refs[r as usize].map(|g| { |
| 7512 | ( |
| 7513 | info.mv1, |
| 7514 | [ |
| 7515 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 7516 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 7517 | ], |
| 7518 | ) |
| 7519 | }) |
| 7520 | }), |
| 7521 | search, chroma_set, t, fctx, |
| 7522 | ) |
| 7523 | .unwrap_or([u_new, v_new]), |
| 7524 | None => [u_new, v_new], |
| 7525 | }; |
| 7526 | chroma[0].commit(x / 2, y / 2, side / 2, &u_new); |
| 7527 | chroma[1].commit(x / 2, y / 2, side / 2, &v_new); |
| 7528 | return ( |
| 7529 | BlockCoeffs { |
| 7530 | angle_delta_y: 0, |
| 7531 | cfl_alphas: None, |
| 7532 | filter_intra: None, |
| 7533 | luma: coeffs(&levels, side), |
| 7534 | u: coeffs(&u_new.levels, side / 2), |
| 7535 | v: coeffs(&v_new.levels, side / 2), |
| 7536 | mode: DC_PRED as u8, |
| 7537 | uv_mode: DC_PRED, |
| 7538 | skip: skip_new, |
| 7539 | eight: None, |
| 7540 | dv: None, |
| 7541 | palette: None, |
| 7542 | palette_uv: None, |
| 7543 | tx_depth, |
| 7544 | luma_tx_types, |
| 7545 | inter: Some(info), |
| 7546 | motion_mode: motion_won, |
| 7547 | }, |
| 7548 | cost + dcost, |
| 7549 | ); |
| 7550 | } |
| 7551 | } |
| 7552 | |
| 7553 | census_add(8, 1); |
| 7554 | if skip { |
| 7555 | census_add(10, 1); |
| 7556 | } |
| 7557 | if inter_cost >= intra_cost { |
| 7558 | census_add(9, 1); |
| 7559 | } |
| 7560 | if inter_cost < intra_cost { |
| 7561 | let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma( |
| 7562 | 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, |
| 7563 | ); |
| 7564 | // lane-txrd: chroma follows the luma type (this tail's block is |
| 7565 | // single-reference `NEARESTMV`, so no compound second half). |
| 7566 | let [u, v] = match luma_tx_types.first().copied() { |
| 7567 | Some(t) => recode_inter_chroma( |
| 7568 | chroma, (x, y), side, mv, |
| 7569 | [ |
| 7570 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 7571 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 7572 | ], |
| 7573 | None, search, chroma_set, t, fctx, |
| 7574 | ) |
| 7575 | .unwrap_or([u, v]), |
| 7576 | None => [u, v], |
| 7577 | }; |
| 7578 | chroma[0].commit(x / 2, y / 2, side / 2, &u); |
| 7579 | chroma[1].commit(x / 2, y / 2, side / 2, &v); |
| 7580 | (BlockCoeffs { |
| 7581 | luma_tx_types, |
| 7582 | angle_delta_y: 0, |
| 7583 | cfl_alphas: None, |
| 7584 | filter_intra: None, |
| 7585 | luma: coeffs(&levels, side), |
| 7586 | u: coeffs(&u.levels, side / 2), |
| 7587 | v: coeffs(&v.levels, side / 2), |
| 7588 | mode: DC_PRED as u8, |
| 7589 | uv_mode: DC_PRED, |
| 7590 | skip, |
| 7591 | eight: None, |
| 7592 | dv: None, |
| 7593 | palette: None, |
| 7594 | palette_uv: None, |
| 7595 | tx_depth, |
| 7596 | motion_mode: 0, |
| 7597 | inter: Some(InterInfo { |
| 7598 | ref1: None, |
| 7599 | mv1: (0, 0), |
| 7600 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7601 | mode: InterMode::NearestMv, |
| 7602 | mv, |
| 7603 | ref_mv_idx: 0, |
| 7604 | }), |
| 7605 | }, inter_cost + dcost) |
| 7606 | } else { |
| 7607 | (intra_block, intra_cost) |
| 7608 | } |
| 7609 | } |
| 7610 | |
| 7611 | /// Publishes one coded inter-frame block into the `mi` grid the next block's |
| 7612 | /// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra |
| 7613 | /// block casts no vote but is still a coded cell (see `code_square_inter`'s |
| 7614 | /// note on `processed_rows`/`processed_cols`). |
| 7615 | fn record_mi( |
| 7616 | grid: &mut MiGrid, |
| 7617 | mi_row: usize, |
| 7618 | mi_col: usize, |
| 7619 | size: u8, |
| 7620 | inter: Option<InterInfo>, |
| 7621 | // lane-ctx: the block's own `skip`, so the next block's MV stack can hand |
| 7622 | // the RD pricer the two cells the writer's `skip_ctx` sums. |
| 7623 | skip: bool, |
| 7624 | ) { |
| 7625 | let info = match inter { |
| 7626 | Some(info) => MiInfo { |
| 7627 | is_inter: true, |
| 7628 | ref_frame: info.ref_frame, |
| 7629 | // A COMPOUND block votes with BOTH of its references and both of |
| 7630 | // its vectors, exactly as the tile writer publishes it: recording |
| 7631 | // a compound block as a single-reference one here left the |
| 7632 | // encoder's own grid disagreeing with the writer's from the first |
| 7633 | // compound block on, so every later stack it searched against was |
| 7634 | // not the stack the decoder derives. |
| 7635 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 7636 | mv1: mv16(info.mv1), |
| 7637 | mv: mv16(info.mv), |
| 7638 | // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference |
| 7639 | // side, compound modes 2/3/7 on the other. |
| 7640 | is_new_mv: matches!( |
| 7641 | info.mode, |
| 7642 | InterMode::NewMv |
| 7643 | | InterMode::NewNewMv |
| 7644 | | InterMode::NearestNewMv |
| 7645 | | InterMode::NewNearestMv |
| 7646 | ), |
| 7647 | size, |
| 7648 | size_h: size, |
| 7649 | is_global_mv0: false, |
| 7650 | is_global_mv1: false, |
| 7651 | }, |
| 7652 | None => MiInfo { |
| 7653 | is_inter: false, |
| 7654 | ref_frame: -1, |
| 7655 | ref_frame1: NO_REF1, |
| 7656 | mv1: (0, 0), |
| 7657 | mv: (0, 0), |
| 7658 | is_new_mv: false, |
| 7659 | size, |
| 7660 | size_h: size, |
| 7661 | is_global_mv0: false, |
| 7662 | is_global_mv1: false, |
| 7663 | }, |
| 7664 | }; |
| 7665 | for dr in 0..usize::from(size) { |
| 7666 | for dc in 0..usize::from(size) { |
| 7667 | grid.set(mi_row + dr, mi_col + dc, info); |
| 7668 | grid.set_skip(mi_row + dr, mi_col + dc, skip); |
| 7669 | } |
| 7670 | } |
| 7671 | } |
| 7672 | |
| 7673 | /// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the |
| 7674 | /// writer's own `write_inter_block_128_rect` makes, so the second half of a |
| 7675 | /// HORZ/VERT 128 root searches against the stack the writer will rebuild. |
| 7676 | fn record_mi_rect( |
| 7677 | grid: &mut MiGrid, |
| 7678 | mi_row: usize, |
| 7679 | mi_col: usize, |
| 7680 | (w_mi, h_mi): (usize, usize), |
| 7681 | inter: Option<InterInfo>, |
| 7682 | skip: bool, |
| 7683 | ) { |
| 7684 | record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip); |
| 7685 | // `record_mi` stamped the square corner; widen it to the true footprint, |
| 7686 | // with the block's own (rect) size fields. |
| 7687 | let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded"); |
| 7688 | info.size = w_mi as u8; |
| 7689 | info.size_h = h_mi as u8; |
| 7690 | for dr in 0..h_mi { |
| 7691 | for dc in 0..w_mi { |
| 7692 | grid.set(mi_row + dr, mi_col + dc, info); |
| 7693 | grid.set_skip(mi_row + dr, mi_col + dc, skip); |
| 7694 | } |
| 7695 | } |
| 7696 | } |
| 7697 | |
| 7698 | /// The reconstructed samples one 32x32 square covers in all three planes, so |
| 7699 | /// that a partition trial can be undone. |
| 7700 | /// One square of a plane, row-major, the inverse of [`Plane::restore`]. |
| 7701 | /// |
| 7702 | /// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces, |
| 7703 | /// which allocated and freed a `Vec` per row of every block it copied -- |
| 7704 | /// `Plane::snapshot` runs once per partition trial. |
| 7705 | fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 7706 | let mut out = vec![0u8; side * side]; |
| 7707 | for row in 0..side { |
| 7708 | out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]); |
| 7709 | } |
| 7710 | out |
| 7711 | } |
| 7712 | |
| 7713 | fn snapshot( |
| 7714 | luma: &Plane, |
| 7715 | chroma: &[Plane; 2], |
| 7716 | (x, y): (usize, usize), |
| 7717 | side: usize, |
| 7718 | ) -> [(Vec<u8>, Vec<CoefCtx>); 3] { |
| 7719 | [ |
| 7720 | luma.snapshot(x, y, side), |
| 7721 | chroma[0].snapshot(x / 2, y / 2, side / 2), |
| 7722 | chroma[1].snapshot(x / 2, y / 2, side / 2), |
| 7723 | ] |
| 7724 | } |
| 7725 | |
| 7726 | /// Puts such a snapshot back. |
| 7727 | fn restore( |
| 7728 | luma: &mut Plane, |
| 7729 | chroma: &mut [Plane; 2], |
| 7730 | (x, y): (usize, usize), |
| 7731 | side: usize, |
| 7732 | saved: &[(Vec<u8>, Vec<CoefCtx>); 3], |
| 7733 | ) { |
| 7734 | luma.restore(x, y, side, &saved[0]); |
| 7735 | chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); |
| 7736 | chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]); |
| 7737 | } |
| 7738 | |
| 7739 | /// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set |
| 7740 | /// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own |
| 7741 | /// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`] |
| 7742 | /// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one |
| 7743 | /// rule shared with the key-frame path, not a second one that could diverge. |
| 7744 | fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { |
| 7745 | let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); |
| 7746 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 7747 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 7748 | scored.truncate(if dc_entry.is_some() { |
| 7749 | top_k.saturating_sub(1) |
| 7750 | } else { |
| 7751 | top_k |
| 7752 | }); |
| 7753 | if let Some(dc_entry) = dc_entry { |
| 7754 | scored.push(dc_entry); |
| 7755 | } |
| 7756 | let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); |
| 7757 | modes.iter().copied().filter(|m| keep.contains(m)).collect() |
| 7758 | } |
| 7759 | |
| 7760 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 7761 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 7762 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| 7763 | std::array::from_fn(|mode| { |
| 7764 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 7765 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 7766 | } else { |
| 7767 | 0.0 |
| 7768 | }; |
| 7769 | symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 7770 | }) |
| 7771 | } |
| 7772 | |
| 7773 | /// What the luma mode search picks between, and under what terms. |
| 7774 | #[derive(Clone, Copy)] |
| 7775 | struct Search<'a> { |
| 7776 | /// This frame's `allow_screen_content_tools` ([`screen_content`]): the |
| 7777 | /// luma search then offers a palette candidate beside the intra modes. |
| 7778 | screen: bool, |
| 7779 | base_q_idx: u8, |
| 7780 | deadzone: f64, |
| 7781 | lambda: f64, |
| 7782 | modes: &'a [u8], |
| 7783 | /// How many of `modes` the full RD trial (forward transform, quantize, |
| 7784 | /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD |
| 7785 | /// pre-pass on the prediction residual alone plus DC (always kept, since |
| 7786 | /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s |
| 7787 | /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every |
| 7788 | /// mode through full RD, unchanged from before this lever. |
| 7789 | top_k: Option<usize>, |
| 7790 | /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`]) |
| 7791 | /// -- `false` cuts the named candidate group from the whole-32 search |
| 7792 | /// ([`search_inter_block`]), the 16x16/8x8 leaf search |
| 7793 | /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF |
| 7794 | /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is |
| 7795 | /// the pre-lane behaviour: the mid and quarter hidden frames, the shown |
| 7796 | /// leaves and the flat path keep intra and compound, and the |
| 7797 | /// straddling-edge 8x8s are only mode-gated, never partition-gated. |
| 7798 | /// The probe's correction: with the leaf gate ALONE the film A stream |
| 7799 | /// was byte-identical to the control -- the ARF's intra area lives at |
| 7800 | /// the whole-32 level, so the intra arm must cut it there too. |
| 7801 | arf_leaf_intra: bool, |
| 7802 | arf_leaf8: bool, |
| 7803 | arf_leaf_compound: bool, |
| 7804 | } |
| 7805 | |
| 7806 | /// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what |
| 7807 | /// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the |
| 7808 | /// shipped table -- 0, bit-exact with the pre-lane encoder). |
| 7809 | fn arfmode() -> u8 { |
| 7810 | match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 7811 | u8::MAX => {} |
| 7812 | n => return n, |
| 7813 | } |
| 7814 | static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| { |
| 7815 | crate::envflags::var("EC_AV1_ARFMODE").ok().and_then(|v| v.parse().ok()) |
| 7816 | }); |
| 7817 | ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE)) |
| 7818 | } |
| 7819 | |
| 7820 | /// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it. |
| 7821 | static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); |
| 7822 | |
| 7823 | /// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a |
| 7824 | /// process constant ([`crate::envflags`]), so an in-process witness needs |
| 7825 | /// this to arm the lever. |
| 7826 | #[allow(dead_code)] // set only from the `#[cfg(test)]` witness |
| 7827 | pub(crate) fn set_arfmode(n: Option<u8>) { |
| 7828 | ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed); |
| 7829 | } |
| 7830 | |
| 7831 | /// How often each armed [`crate::speed::ARFMODE`] arm actually fired since |
| 7832 | /// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded |
| 7833 | /// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8 |
| 7834 | /// split the search would have offered and the arm refused, 2 = a top-ARF |
| 7835 | /// leaf whose compound set was dropped. A green gate over counts of zero |
| 7836 | /// proves nothing about the lever. |
| 7837 | static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [ |
| 7838 | std::sync::atomic::AtomicUsize::new(0), |
| 7839 | std::sync::atomic::AtomicUsize::new(0), |
| 7840 | std::sync::atomic::AtomicUsize::new(0), |
| 7841 | ]; |
| 7842 | |
| 7843 | /// Records one such hit. |
| 7844 | fn arfmode_hit(which: usize) { |
| 7845 | ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 7846 | } |
| 7847 | |
| 7848 | /// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer |
| 7849 | /// condition, so the counter only runs when every other prune let the split |
| 7850 | /// through and the arm alone refuses it. |
| 7851 | fn arfmode_hit_and_no() -> bool { |
| 7852 | arfmode_hit(1); |
| 7853 | false |
| 7854 | } |
| 7855 | |
| 7856 | /// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a |
| 7857 | /// probe point can print a non-zero engagement count under the env knob |
| 7858 | /// itself -- the counter the gate BD numbers are read against. |
| 7859 | pub fn take_arfmode_hits() -> [usize; 3] { |
| 7860 | [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 7861 | } |
| 7862 | |
| 7863 | fn prune_top_k() -> Option<usize> { |
| 7864 | #[cfg(test)] |
| 7865 | { |
| 7866 | if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { |
| 7867 | return k; |
| 7868 | } |
| 7869 | } |
| 7870 | let swept = std::env::var("EC_AV1_PRUNE_K") |
| 7871 | .ok() |
| 7872 | .and_then(|v| v.parse::<usize>().ok()); |
| 7873 | match swept { |
| 7874 | Some(k) if cfg!(test) => Some(k), |
| 7875 | _ => crate::speed::at(&crate::speed::PRUNE_K), |
| 7876 | } |
| 7877 | } |
| 7878 | |
| 7879 | // A per-thread override [`prune_top_k`] checks first, so one test can sweep |
| 7880 | // `top_k` in-process without mutating the environment (forbidden here -- |
| 7881 | // `#![forbid(unsafe_code)]` -- and racy across parallel tests besides). |
| 7882 | #[cfg(test)] |
| 7883 | thread_local! { |
| 7884 | static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = |
| 7885 | const { std::cell::Cell::new(None) }; |
| 7886 | } |
| 7887 | |
| 7888 | #[cfg(test)] |
| 7889 | fn set_test_top_k_override(value: Option<usize>) { |
| 7890 | TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); |
| 7891 | } |
| 7892 | |
| 7893 | /// The default: unpruned, thirteen full trials per block, same as before this |
| 7894 | /// lever. Set from the sweep in the lane report if the quality gate clears it. |
| 7895 | pub(crate) const PRUNE_TOP_K: Option<usize> = None; |
| 7896 | |
| 7897 | /// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop -- |
| 7898 | /// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths' |
| 7899 | /// quality gates were measured separately and may land on different |
| 7900 | /// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching |
| 7901 | /// [`EC_AV1_PRUNE_K`] or the key-frame path. |
| 7902 | fn prune_top_k_inter() -> Option<usize> { |
| 7903 | #[cfg(test)] |
| 7904 | { |
| 7905 | if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { |
| 7906 | return k; |
| 7907 | } |
| 7908 | } |
| 7909 | let swept = std::env::var("EC_AV1_PRUNE_K_INTER") |
| 7910 | .ok() |
| 7911 | .and_then(|v| v.parse::<usize>().ok()); |
| 7912 | match swept { |
| 7913 | Some(k) if cfg!(test) => Some(k), |
| 7914 | _ => crate::speed::at(&crate::speed::PRUNE_K_INTER), |
| 7915 | } |
| 7916 | } |
| 7917 | |
| 7918 | // A per-thread override [`prune_top_k_inter`] checks first, same reason as |
| 7919 | // [`TEST_TOP_K_OVERRIDE`]. |
| 7920 | #[cfg(test)] |
| 7921 | thread_local! { |
| 7922 | static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = |
| 7923 | const { std::cell::Cell::new(None) }; |
| 7924 | } |
| 7925 | |
| 7926 | #[cfg(test)] |
| 7927 | fn set_test_top_k_override_inter(value: Option<usize>) { |
| 7928 | TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); |
| 7929 | } |
| 7930 | |
| 7931 | /// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter` |
| 7932 | /// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the |
| 7933 | /// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes |
| 7934 | /// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest, |
| 7935 | /// `K=3`, ships as default. Unlike the key-frame path (still `None`), an |
| 7936 | /// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so |
| 7937 | /// pruning them costs less quality here. |
| 7938 | pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3); |
| 7939 | |
| 7940 | // Per-thread nanosecond counters `stage_timing_breakdown_inter` (and |
| 7941 | // [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an |
| 7942 | // inter frame's cost can be attributed to a bucket without changing what |
| 7943 | // the search actually does. Index: 0 = whole-call time inside |
| 7944 | // [`motion::search`] (includes bucket 1's time, run from inside it), 1 = |
| 7945 | // [`crate::mc::predict`] (every call, from the motion search's own |
| 7946 | // candidates and from a committed inter block's final prediction alike), |
| 7947 | // 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`. |
| 7948 | #[cfg(test)] |
| 7949 | thread_local! { |
| 7950 | static STAGE_NS: [std::cell::Cell<u64>; 4] = [ |
| 7951 | std::cell::Cell::new(0), |
| 7952 | std::cell::Cell::new(0), |
| 7953 | std::cell::Cell::new(0), |
| 7954 | std::cell::Cell::new(0), |
| 7955 | ]; |
| 7956 | } |
| 7957 | |
| 7958 | /// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and |
| 7959 | /// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran |
| 7960 | /// per transform trial and per `mc::predict` call whether or not anyone was |
| 7961 | /// reading the breakdown (the vdso clock was 1.7% of the encoder's profile). |
| 7962 | /// The clock is now read only when [`crate::par::stage_times`] is on, which |
| 7963 | /// is what prints the breakdown in the first place. |
| 7964 | #[cfg(test)] |
| 7965 | pub(crate) fn stage_start() -> Option<std::time::Instant> { |
| 7966 | crate::par::stage_times().then(std::time::Instant::now) |
| 7967 | } |
| 7968 | |
| 7969 | #[cfg(test)] |
| 7970 | pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) { |
| 7971 | if let Some(t) = t { |
| 7972 | stage_add(bucket, t.elapsed()); |
| 7973 | } |
| 7974 | } |
| 7975 | |
| 7976 | #[cfg(test)] |
| 7977 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 7978 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| 7979 | } |
| 7980 | |
| 7981 | #[cfg(test)] |
| 7982 | fn stage_reset() { |
| 7983 | crate::par::set_stage_times(true); |
| 7984 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 7985 | } |
| 7986 | |
| 7987 | #[cfg(test)] |
| 7988 | fn stage_read() -> [std::time::Duration; 4] { |
| 7989 | crate::par::set_stage_times(false); |
| 7990 | STAGE_NS.with(|c| { |
| 7991 | c.each_ref() |
| 7992 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| 7993 | }) |
| 7994 | } |
| 7995 | |
| 7996 | /// One mode's coding of one block, before it is committed. |
| 7997 | #[derive(Clone)] |
| 7998 | struct Trial { |
| 7999 | levels: Vec<i32>, |
| 8000 | reconstruction: Vec<u8>, |
| 8001 | sse: f64, |
| 8002 | bits: f64, |
| 8003 | } |
| 8004 | |
| 8005 | /// The top-left `to` x `to` corner of a `from`-sided level grid -- the part |
| 8006 | /// of a 64-point transform that is actually coded (everything outside it is |
| 8007 | /// zeroed by [`crate::transform::quantize`] already, so this only reshapes). |
| 8008 | fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> { |
| 8009 | let mut out = vec![0i32; to * to]; |
| 8010 | for row in 0..to { |
| 8011 | out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]); |
| 8012 | } |
| 8013 | out |
| 8014 | } |
| 8015 | |
| 8016 | /// The non-zero levels of a block, as the tile writer takes them. |
| 8017 | fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { |
| 8018 | levels |
| 8019 | .iter() |
| 8020 | .enumerate() |
| 8021 | .filter(|&(_, &level)| level != 0) |
| 8022 | .map(|(i, &level)| Coeff { |
| 8023 | row: (i / side) as u8, |
| 8024 | col: (i % side) as u8, |
| 8025 | level, |
| 8026 | }) |
| 8027 | .collect() |
| 8028 | } |
| 8029 | |
| 8030 | thread_local! { |
| 8031 | /// The tile grid the next frame is coded with, as `(TileColsLog2, |
| 8032 | /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its |
| 8033 | /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s |
| 8034 | /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is |
| 8035 | /// one tile per frame, what every caller that never arms anything gets |
| 8036 | /// and what every stream this crate wrote before tiles existed carries. |
| 8037 | static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) }; |
| 8038 | } |
| 8039 | |
| 8040 | /// Arms this thread's next frame encodes with a tile grid (log2 counts). |
| 8041 | pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) { |
| 8042 | TILE_LOG2.with(|c| c.set((cols_log2, rows_log2))); |
| 8043 | } |
| 8044 | |
| 8045 | fn armed_tiles() -> (u32, u32) { |
| 8046 | let armed = TILE_LOG2.with(std::cell::Cell::get); |
| 8047 | if armed != (0, 0) { |
| 8048 | return armed; |
| 8049 | } |
| 8050 | // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate |
| 8051 | // (which codes through `encode_sequence`, not the facade) can measure what |
| 8052 | // a tile grid costs without a knob of its own -- same shape as |
| 8053 | // `EC_AV1_LR`/`EC_AV1_PYRAMID`. |
| 8054 | match std::env::var("EC_AV1_TILES").ok() { |
| 8055 | Some(v) if cfg!(test) => { |
| 8056 | let mut f = v.split(':'); |
| 8057 | let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0); |
| 8058 | let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0); |
| 8059 | (cols, rows) |
| 8060 | } |
| 8061 | _ => armed, |
| 8062 | } |
| 8063 | } |
| 8064 | |
| 8065 | /// Codes a frame's `tiles` tiles, each entirely on its own (see |
| 8066 | /// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of |
| 8067 | /// the crate's own pool, and hands back their payloads in tile order plus |
| 8068 | /// whatever `code` returned for tile `store` -- the CDF state |
| 8069 | /// `context_update_tile_id` names. The result cannot depend on the thread |
| 8070 | /// count: each job writes one tile from the frame's own starting tables into |
| 8071 | /// its own slot. |
| 8072 | fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)> |
| 8073 | where |
| 8074 | F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send, |
| 8075 | { |
| 8076 | let _t = crate::par::timer(crate::par::S_TILE_WRITE); |
| 8077 | type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>; |
| 8078 | let threads = crate::par::tile_threads().min(tiles); |
| 8079 | let mut slots: Vec<Slot> = Vec::new(); |
| 8080 | if threads <= 1 { |
| 8081 | for index in 0..tiles { |
| 8082 | slots.push(Some(code(index))); |
| 8083 | } |
| 8084 | } else { |
| 8085 | let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 8086 | { |
| 8087 | let batch = crate::par::Batch::new("ec-av1-tile"); |
| 8088 | for (from, to) in crate::par::bands(tiles, threads) { |
| 8089 | let done = &done; |
| 8090 | let code = &code; |
| 8091 | batch.submit(move || { |
| 8092 | for index in from..to { |
| 8093 | let coded = code(index); |
| 8094 | done.lock().expect("tile slots")[index] = Some(coded); |
| 8095 | } |
| 8096 | }); |
| 8097 | } |
| 8098 | } |
| 8099 | slots = done.into_inner().expect("tile slots"); |
| 8100 | } |
| 8101 | let mut out = Vec::with_capacity(tiles); |
| 8102 | let mut stored = None; |
| 8103 | for (index, slot) in slots.into_iter().enumerate() { |
| 8104 | let (bytes, cdfs) = slot.expect("every tile was coded")?; |
| 8105 | if index == store { |
| 8106 | stored = cdfs; |
| 8107 | } |
| 8108 | out.push(bytes); |
| 8109 | } |
| 8110 | Ok((out, stored)) |
| 8111 | } |
| 8112 | |
| 8113 | /// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS` |
| 8114 | /// workers, and returns the results in tile order. The counterpart of |
| 8115 | /// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of |
| 8116 | /// state the search mutates (its own reconstruction planes, its own `MiGrid`, |
| 8117 | /// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and |
| 8118 | /// availability is already tile-relative (`clip_planes_to_tile`, |
| 8119 | /// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which |
| 8120 | /// other tiles have run -- gated by |
| 8121 | /// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now |
| 8122 | /// covers the search as well as the write. |
| 8123 | /// |
| 8124 | /// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync` |
| 8125 | /// by design) and moved into the worker, exactly as [`crate::par::run_bands`] |
| 8126 | /// does it for the decoder's filter bands. |
| 8127 | fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>> |
| 8128 | where |
| 8129 | T: Send, |
| 8130 | F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync, |
| 8131 | { |
| 8132 | let _t = crate::par::timer(crate::par::S_TILE_SEARCH); |
| 8133 | let threads = crate::par::tile_threads().min(tiles); |
| 8134 | if threads <= 1 { |
| 8135 | return (0..tiles).map(|index| job(index, fctx)).collect(); |
| 8136 | } |
| 8137 | type Slot<T> = Option<Result<T>>; |
| 8138 | let done: std::sync::Mutex<Vec<Slot<T>>> = |
| 8139 | std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 8140 | { |
| 8141 | let batch = crate::par::Batch::new("ec-av1-tile-search"); |
| 8142 | for (from, to) in crate::par::bands(tiles, threads) { |
| 8143 | let done = &done; |
| 8144 | let job = &job; |
| 8145 | let ctx = crate::decode::filter_ctx_copy(fctx); |
| 8146 | batch.submit(move || { |
| 8147 | for index in from..to { |
| 8148 | let searched = job(index, &ctx); |
| 8149 | done.lock().expect("tile slots")[index] = Some(searched); |
| 8150 | } |
| 8151 | }); |
| 8152 | } |
| 8153 | } |
| 8154 | done.into_inner() |
| 8155 | .expect("tile slots") |
| 8156 | .into_iter() |
| 8157 | .map(|slot| slot.expect("every tile was searched")) |
| 8158 | .collect() |
| 8159 | } |
| 8160 | |
| 8161 | /// One tile job's own copy of a plane: the frame's source, a blank |
| 8162 | /// reconstruction of the frame's size, and the frame's own bounds -- narrowed |
| 8163 | /// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy |
| 8164 | /// of the frame's reconstruction because a tile's prediction never reads a |
| 8165 | /// sample outside its own rectangle, and every sample inside it is written |
| 8166 | /// before it is read. |
| 8167 | fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> { |
| 8168 | Plane { |
| 8169 | source, |
| 8170 | reconstruction: vec![128; source.len()], |
| 8171 | width, |
| 8172 | height, |
| 8173 | true_width, |
| 8174 | true_height, |
| 8175 | tile_x0: 0, |
| 8176 | tile_y0: 0, |
| 8177 | tile_x1: width, |
| 8178 | tile_y1: height, |
| 8179 | ctx: CoefCtxMap::default(), |
| 8180 | } |
| 8181 | } |
| 8182 | |
| 8183 | /// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into |
| 8184 | /// the frame's plane, through the [`crate::par::Shared`] every job holds. |
| 8185 | /// |
| 8186 | /// corner-cut: the disjointness that makes the aliasing sound is the caller's |
| 8187 | /// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile |
| 8188 | /// rectangles partition it -- checked end-to-end by |
| 8189 | /// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow |
| 8190 | /// checker, exactly the contract `Shared`'s own doc names. Upgrade path is |
| 8191 | /// row-range `split_at_mut` plumbing through `Plane`, which would have to |
| 8192 | /// thread an origin offset through every prediction and transform call site |
| 8193 | /// for the same bytes. |
| 8194 | #[allow(unsafe_code)] |
| 8195 | fn copy_rect( |
| 8196 | dst: crate::par::Shared<'_, Vec<u8>>, |
| 8197 | src: &[u8], |
| 8198 | stride: usize, |
| 8199 | x0: usize, |
| 8200 | y0: usize, |
| 8201 | x1: usize, |
| 8202 | y1: usize, |
| 8203 | ) { |
| 8204 | // SAFETY: this job touches only its own tile rectangle (see above). |
| 8205 | let dst = unsafe { dst.get() }; |
| 8206 | for y in y0..y1 { |
| 8207 | let (a, b) = (y * stride + x0, y * stride + x1); |
| 8208 | dst[a..b].copy_from_slice(&src[a..b]); |
| 8209 | } |
| 8210 | } |
| 8211 | |
| 8212 | /// The frame header's `tile_info` (spec 5.9.15) for `layout`: |
| 8213 | /// `context_update_tile_id` names the largest tile, whose end-of-tile CDF |
| 8214 | /// tables the frame stores (spec 7.20), which is what |
| 8215 | /// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops |
| 8216 | /// below publish. |
| 8217 | fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo { |
| 8218 | ec_av1_syntax::TileInfo { |
| 8219 | uniform_spacing: true, |
| 8220 | cols: layout.cols(), |
| 8221 | rows: layout.rows(), |
| 8222 | cols_log2: layout.cols_log2, |
| 8223 | rows_log2: layout.rows_log2, |
| 8224 | mi_col_starts: layout.mi_col_starts(), |
| 8225 | mi_row_starts: layout.mi_row_starts(), |
| 8226 | context_update_tile_id: layout.largest_tile() as u32, |
| 8227 | tile_size_bytes, |
| 8228 | } |
| 8229 | } |
| 8230 | |
| 8231 | /// Clips the three planes' intra edge reads to `rect`, the tile the |
| 8232 | /// superblock about to be searched belongs to (the encoder side of the |
| 8233 | /// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame |
| 8234 | /// raster order -- which is a linear extension of every tile's own coding |
| 8235 | /// order, so a block still only ever predicts from samples already |
| 8236 | /// reconstructed -- and only availability is tile-relative. |
| 8237 | fn clip_planes_to_tile( |
| 8238 | luma: &mut Plane<'_>, |
| 8239 | chroma: &mut [Plane<'_>; 2], |
| 8240 | rect: crate::tile::TileRect, |
| 8241 | ) { |
| 8242 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 8243 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 8244 | luma.set_tile(x0, y0, x1, y1); |
| 8245 | for plane in chroma.iter_mut() { |
| 8246 | plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); |
| 8247 | } |
| 8248 | } |
| 8249 | |
| 8250 | /// Encodes one picture as a key frame. |
| 8251 | /// |
| 8252 | /// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer |
| 8253 | /// picks its coefficient CDFs from one of four q contexts by that index. |
| 8254 | /// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and |
| 8255 | /// smaller values trade fidelity for rate. |
| 8256 | /// |
| 8257 | /// The picture may be any even width and height: the encoder pads it by edge |
| 8258 | /// replication to a whole number of 32x32 blocks internally, and the frame it |
| 8259 | /// writes crops back to the picture's own size (`render_width`/ |
| 8260 | /// `render_height`), so [`Encoded::reconstruction`] is always the picture's |
| 8261 | /// own size, never the padded one. |
| 8262 | /// |
| 8263 | /// # Errors |
| 8264 | /// Returns an error when the picture's width or height is zero or odd, or |
| 8265 | /// when its planes are not 4:2:0 of that size. |
| 8266 | /// Codes one picture as a whole key frame, at `base_q_idx`, and returns its |
| 8267 | /// stream. The per-frame decode state this needs lives for exactly this call. |
| 8268 | /// |
| 8269 | /// # Errors |
| 8270 | /// Returns an error under the same conditions |
| 8271 | /// [`encode_key_frame_with_modes`] does. |
| 8272 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 8273 | encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder()) |
| 8274 | } |
| 8275 | |
| 8276 | /// [`encode_key_frame`] with the per-block intra modes given rather than |
| 8277 | /// searched. |
| 8278 | /// |
| 8279 | /// # Errors |
| 8280 | /// Returns an error when `picture`'s dimensions are odd or zero, when `modes` |
| 8281 | /// is empty, or when a block's coefficients do not fit the coded frame. |
| 8282 | pub fn encode_key_frame_with_modes( |
| 8283 | picture: &Picture, |
| 8284 | base_q_idx: u8, |
| 8285 | deadzone: f64, |
| 8286 | modes: &[u8], |
| 8287 | ) -> Result<Encoded> { |
| 8288 | encode_key_frame_with_modes_with_ctx( |
| 8289 | picture, |
| 8290 | base_q_idx, |
| 8291 | deadzone, |
| 8292 | modes, |
| 8293 | &crate::decode::FrameCtx::for_encoder(), |
| 8294 | ) |
| 8295 | } |
| 8296 | |
| 8297 | /// Codes `pictures` as one key frame followed by inter frames. |
| 8298 | /// |
| 8299 | /// Camera material is coded under [`crate::encoder::Pyramid::default`] since |
| 8300 | /// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a |
| 8301 | /// `show_existing_frame` header, so `stream` is in CODING order while |
| 8302 | /// `frames` stays in display order (`EncodedSequence::coding_order` is the |
| 8303 | /// map). Screen content codes flat, decided once per sequence by the same |
| 8304 | /// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0` |
| 8305 | /// puts every stream back on the flat path for an A/B. |
| 8306 | /// |
| 8307 | /// # Errors |
| 8308 | /// Returns an error under the same conditions [`encode_key_frame`] and the |
| 8309 | /// inter frame path do. |
| 8310 | pub fn encode_sequence( |
| 8311 | pictures: &[Picture], |
| 8312 | base_q_idx: u8, |
| 8313 | deadzone: f64, |
| 8314 | ) -> Result<EncodedSequence> { |
| 8315 | encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder()) |
| 8316 | } |
| 8317 | |
| 8318 | pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> { |
| 8319 | encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx) |
| 8320 | } |
| 8321 | |
| 8322 | /// Encodes one picture as a key frame, choosing each block's luma mode from |
| 8323 | /// `modes` alone. |
| 8324 | /// |
| 8325 | /// This is what an ablation measures against: `&[DC_PRED]` is the encoder |
| 8326 | /// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the |
| 8327 | /// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`] |
| 8328 | /// uses. |
| 8329 | /// |
| 8330 | /// # Errors |
| 8331 | /// The same as [`encode_key_frame`], and additionally when `modes` is empty or |
| 8332 | /// names a mode [`crate::intra::predict`] does not predict. |
| 8333 | pub(crate) fn encode_key_frame_with_modes_with_ctx( |
| 8334 | picture: &Picture, |
| 8335 | base_q_idx: u8, |
| 8336 | deadzone: f64, |
| 8337 | modes: &[u8], fctx: &crate::decode::FrameCtx, |
| 8338 | ) -> Result<Encoded> { |
| 8339 | picture.check_even()?; |
| 8340 | let padded = picture.padded_to(BLOCK); |
| 8341 | let encoded = encode_key_frame_inner( |
| 8342 | &padded, |
| 8343 | base_q_idx, |
| 8344 | deadzone, |
| 8345 | modes, |
| 8346 | split_blocks(), |
| 8347 | (picture.width, picture.height), |
| 8348 | unspecified_color_config(), fctx, |
| 8349 | )?; |
| 8350 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 8351 | } |
| 8352 | |
| 8353 | /// [`encode_key_frame_with_modes`] with the partition decision forced, which is |
| 8354 | /// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is |
| 8355 | /// already padded to a whole number of 32x32 blocks; `render` is the real |
| 8356 | /// (pre-pad) size the frame header tells a decoder to crop back to. |
| 8357 | pub(crate) fn encode_key_frame_inner( |
| 8358 | picture: &Picture, |
| 8359 | base_q_idx: u8, |
| 8360 | deadzone: f64, |
| 8361 | modes: &[u8], |
| 8362 | split_blocks: bool, |
| 8363 | render: (usize, usize), |
| 8364 | color_config: ColorConfig, fctx: &crate::decode::FrameCtx, |
| 8365 | ) -> Result<Encoded> { |
| 8366 | // lane-refs: an intra frame runs no motion compensation, and the |
| 8367 | // context is shared across the sequence -- put the kernel back to the |
| 8368 | // default so nothing reads the previous inter frame's. |
| 8369 | fctx.interp_filter.set(mc::InterpFilterKind::Regular); |
| 8370 | picture.check()?; |
| 8371 | if modes.is_empty() { |
| 8372 | return Err(Error::unsupported( |
| 8373 | "AV1 encode", |
| 8374 | "a mode search needs at least one mode to choose from", |
| 8375 | )); |
| 8376 | } |
| 8377 | if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { |
| 8378 | return Err(Error::unsupported( |
| 8379 | "AV1 encode", |
| 8380 | format!("intra mode {bad} is not one the encoder predicts"), |
| 8381 | )); |
| 8382 | } |
| 8383 | // The header carries the frame's true (unpadded) size as `frame_width`/ |
| 8384 | // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/ |
| 8385 | // `mi_rows` derived from that same true size (spec `compute_image_size`). |
| 8386 | // `render_width`/`render_height` come out equal to it too, so |
| 8387 | // `render_and_frame_size_different` is false and no render_size bits are |
| 8388 | // written, mirroring libaom/rav1e: the padded `picture` below is only the |
| 8389 | // internal coding surface, never what the header names. |
| 8390 | // Screen-content detection runs on the SOURCE luma, before any header is |
| 8391 | // built: it decides this sequence's `seq_force_screen_content_tools` (and |
| 8392 | // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as |
| 8393 | // this frame's own `allow_screen_content_tools`. |
| 8394 | let screen = screen_content( |
| 8395 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 8396 | picture.width, |
| 8397 | (picture.width).min(render.0), |
| 8398 | (picture.height).min(render.1), |
| 8399 | ); |
| 8400 | arm_seq_screen(screen); |
| 8401 | // A key frame's writer really does start from the defaults, and a search |
| 8402 | // worker may be carrying an inter frame's armed tables (lane-av1txbits): |
| 8403 | // disarm, or a key frame's bits would depend on which thread searched it. |
| 8404 | crate::tile::arm_pricing_cdfs(None, false); |
| 8405 | // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit |
| 8406 | // forces deblocking, CDEF and loop restoration OFF for this frame |
| 8407 | // (frame.rs:194/210/252/272), so it is only set when the source repeats |
| 8408 | // itself enough for the copied blocks to pay that back |
| 8409 | // ([`intrabc_worth_it`]). |
| 8410 | // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi |
| 8411 | // grid across every tile while this writer builds one per tile, so a |
| 8412 | // multi-tile allow_intrabc frame would predict its DVs off a different |
| 8413 | // grid than the decoder does. corner-cut, ceiling named: the upgrade |
| 8414 | // path is a frame-scoped grid shared by the tile writers. |
| 8415 | let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) { |
| 8416 | intrabc_worth_it( |
| 8417 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 8418 | picture.width, |
| 8419 | picture.width.min(render.0), |
| 8420 | picture.height.min(render.1), |
| 8421 | ) |
| 8422 | } else { |
| 8423 | (false, 0.0) |
| 8424 | }; |
| 8425 | IBC_SHARE.with(|c| c.set(ibc_share)); |
| 8426 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 8427 | header.allow_screen_content_tools = screen; |
| 8428 | // lane-txi: the wider `tx_type` alphabets, gated by the same content |
| 8429 | // rule the type search itself stands behind ([`wide_tx_set`]). |
| 8430 | header.reduced_tx_set = !wide_tx_set(screen); |
| 8431 | header.allow_intrabc = allow_intrabc; |
| 8432 | header.render_width = render.0 as u32; |
| 8433 | header.render_height = render.1 as u32; |
| 8434 | // `TxMode::Select`: every block codes a `tx_depth` symbol and may split |
| 8435 | // its luma transform below its own side (`crate::tile::write_luma_select`). |
| 8436 | // Set here rather than in `key_frame_headers_colour` so the header |
| 8437 | // builders' other callers -- the hand-built tile writers, which code no |
| 8438 | // depth symbol -- keep the `TxMode::Largest` stream they are written for. |
| 8439 | let tx_select = tx_select(); |
| 8440 | if tx_select { |
| 8441 | header.tx_mode = TxMode::Select; |
| 8442 | } |
| 8443 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 8444 | |
| 8445 | // Prediction reads no further than this, in each plane's own units -- |
| 8446 | // see `Plane::true_width`/`true_height`. |
| 8447 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 8448 | // lane-palw: the encoder's own in-process reconstruct reads its palette |
| 8449 | // colour-index maps back through `decode::palette_onscreen`, which takes |
| 8450 | // the frame's mi dims off the `FrameCtx` -- a real decode gets them from |
| 8451 | // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish |
| 8452 | // them here so the reconstruct clamps a block cut by the frame edge |
| 8453 | // exactly as the writer now does. |
| 8454 | let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize); |
| 8455 | fctx.seg_mi_dims.set(frame_mi_dims); |
| 8456 | // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's |
| 8457 | // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by |
| 8458 | // design (see `intra_predict_u8`'s doc comment), so narrow the source |
| 8459 | // once here. |
| 8460 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 8461 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 8462 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 8463 | let mut luma = Plane { |
| 8464 | source: &picture_y8, |
| 8465 | reconstruction: vec![128; picture_y8.len()], |
| 8466 | width: picture.width, |
| 8467 | height: picture.height, |
| 8468 | true_width, |
| 8469 | true_height, |
| 8470 | tile_x0: 0, |
| 8471 | tile_y0: 0, |
| 8472 | tile_x1: picture.width, |
| 8473 | tile_y1: picture.height, |
| 8474 | ctx: CoefCtxMap::default(), |
| 8475 | }; |
| 8476 | let mut chroma = [ |
| 8477 | Plane { |
| 8478 | source: &picture_u8, |
| 8479 | reconstruction: vec![128; picture_u8.len()], |
| 8480 | width: picture.width / 2, |
| 8481 | height: picture.height / 2, |
| 8482 | true_width: true_width / 2, |
| 8483 | true_height: true_height / 2, |
| 8484 | tile_x0: 0, |
| 8485 | tile_y0: 0, |
| 8486 | tile_x1: picture.width / 2, |
| 8487 | tile_y1: picture.height / 2, |
| 8488 | ctx: CoefCtxMap::default(), |
| 8489 | }, |
| 8490 | Plane { |
| 8491 | source: &picture_v8, |
| 8492 | reconstruction: vec![128; picture_v8.len()], |
| 8493 | width: picture.width / 2, |
| 8494 | height: picture.height / 2, |
| 8495 | true_width: true_width / 2, |
| 8496 | true_height: true_height / 2, |
| 8497 | tile_x0: 0, |
| 8498 | tile_y0: 0, |
| 8499 | tile_x1: picture.width / 2, |
| 8500 | tile_y1: picture.height / 2, |
| 8501 | ctx: CoefCtxMap::default(), |
| 8502 | }, |
| 8503 | ]; |
| 8504 | |
| 8505 | // The search trades a bit for the squared error it saves, in the units the |
| 8506 | // reconstruction is measured in: one step of the quantizer, squared. |
| 8507 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 8508 | let search = Search { |
| 8509 | base_q_idx, |
| 8510 | deadzone, |
| 8511 | lambda: lambda_scale() * key_lambda_factor() * step * step, |
| 8512 | modes, |
| 8513 | top_k: prune_top_k(), |
| 8514 | screen, |
| 8515 | arf_leaf_intra: true, |
| 8516 | arf_leaf8: true, |
| 8517 | arf_leaf_compound: true, |
| 8518 | }; |
| 8519 | |
| 8520 | // The block grid this frame is coded over: [`crate::tile::block_grid`]'s |
| 8521 | // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`, |
| 8522 | // which may be fewer columns/rows than the padded picture has room for |
| 8523 | // -- a block whose origin sits past the true bound is not coded at all, |
| 8524 | // matching what a decoder derives from `frame_width`/`frame_height` and |
| 8525 | // so never visits either. |
| 8526 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 8527 | let (cols, rows) = (cols as usize, rows as usize); |
| 8528 | // The luma mode of the block above and of the block to the left, which is |
| 8529 | // what picks the CDF the next block's mode is coded against -- the same |
| 8530 | // bookkeeping the tile writer keeps, so that the search is costing the |
| 8531 | // symbol the writer will actually write. |
| 8532 | // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on, |
| 8533 | // because a 32x32 block may be split into four 16x16 ones. |
| 8534 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 8535 | // This frame's tile grid (one tile unless the facade armed more). |
| 8536 | let layout = |
| 8537 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 8538 | header.tile_info = tile_info_of(&layout, 1); |
| 8539 | // The filter search re-decodes this frame's tiles; the decoder derives |
| 8540 | // every tile's own rect from this same `tile_info` (its `mi_col_starts`/ |
| 8541 | // `mi_row_starts`), which is what makes the writer's rects and the |
| 8542 | // reader's the same rects. |
| 8543 | let header_tile_info = header.tile_info.clone(); |
| 8544 | // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not |
| 8545 | // once over the whole frame. Each tile job builds its own reconstruction |
| 8546 | // planes and its own `above_mode`/`left_mode` bands, which is also what |
| 8547 | // the tile writer reads -- a tile resets its neighbour contexts (spec |
| 8548 | // 5.11.1), so a block at a tile's left edge must cost its mode against |
| 8549 | // the default context, not against whatever the tile to its west left in |
| 8550 | // that row. At one tile the bands are the frame's, exactly as before. |
| 8551 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 8552 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 8553 | let [cb, cr] = &mut chroma; |
| 8554 | let chroma_out = [ |
| 8555 | crate::par::Shared::new(&mut cb.reconstruction), |
| 8556 | crate::par::Shared::new(&mut cr.reconstruction), |
| 8557 | ]; |
| 8558 | let search_tile = |index: usize, |
| 8559 | fctx: &crate::decode::FrameCtx| |
| 8560 | -> Result<Vec<(usize, Superblock, Vec<u8>)>> { |
| 8561 | crate::tile::arm_pricing_cdfs(None, false); |
| 8562 | let rect = layout.rect(index); |
| 8563 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 8564 | let mut chroma = [ |
| 8565 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 8566 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 8567 | ]; |
| 8568 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 8569 | let mut above_mode = vec![DC_PRED; cols * 2]; |
| 8570 | let mut left_mode = vec![DC_PRED; rows * 2]; |
| 8571 | let mut ibc = allow_intrabc.then(|| { |
| 8572 | Ibc::new( |
| 8573 | ( |
| 8574 | rect.mi_col0 as usize * 4, |
| 8575 | rect.mi_row0 as usize * 4, |
| 8576 | (rect.mi_col1 as usize * 4).min(true_width), |
| 8577 | (rect.mi_row1 as usize * 4).min(true_height), |
| 8578 | ), |
| 8579 | &picture_y8, |
| 8580 | frame_width, |
| 8581 | ) |
| 8582 | }); |
| 8583 | let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new(); |
| 8584 | for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 8585 | for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 8586 | let mut modes = Vec::with_capacity(4); |
| 8587 | // The quadrants of a superblock are coded in the order the decoder |
| 8588 | // walks them, which for a 64x64 split into 32x32 blocks is raster |
| 8589 | // order among the quadrants that are inside the frame. |
| 8590 | let mut blocks = Vec::with_capacity(4); |
| 8591 | // lane-i64: the whole superblock as ONE 64x64 intra block, tried |
| 8592 | // BEFORE its quadrants (so both start from the same |
| 8593 | // reconstruction) and compared against the four of them below -- |
| 8594 | // the shape the inter frame's own 64 root takes |
| 8595 | // (`search_skip_64`). A frame that allows intrabc is refused |
| 8596 | // outright ([`I64_ROOT`]) because the quadrant searches below |
| 8597 | // carry DV state a discarded trial would desync. |
| 8598 | let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK); |
| 8599 | // lane-corner LIFTED the two guards this root shipped with: the |
| 8600 | // frame no longer has to be a whole number of superblocks, and |
| 8601 | // the superblock no longer has to be wholly inside the frame. |
| 8602 | // The desync the guards were written for (a 248x152 corner's |
| 8603 | // chroma disagreeing three ways) does NOT reproduce at this |
| 8604 | // revision -- see |
| 8605 | // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`, |
| 8606 | // which pins all three planes of the encoder's reconstruction, |
| 8607 | // our decoder and ffmpeg on four straddling sizes, three of them |
| 8608 | // cut on BOTH axes, with the edge fire count asserted. What the |
| 8609 | // guards cost was every key-frame root on an arbitrary export |
| 8610 | // size (the `aligned` line switched the whole feature off on, for |
| 8611 | // instance, a 1920x792 frame). |
| 8612 | let whole_inside = x64 + SUPERBLOCK <= luma.true_width |
| 8613 | && y64 + SUPERBLOCK <= luma.true_height; |
| 8614 | // lane-corner: and the superblock the true frame edge CUTS |
| 8615 | // THROUGH with more than half of each axis still inside, which is |
| 8616 | // all AV1 asks of a `PARTITION_NONE` root (spec |
| 8617 | // `decode_partition`'s `has_cols`/`has_rows`, the same pair the |
| 8618 | // key writer's `Superblock::Whole` arm checks) -- the shape the |
| 8619 | // inter root already takes ([`b64_edge`]). |
| 8620 | let edge_inside = edge_root_enabled() |
| 8621 | && crate::tile::has_half( |
| 8622 | sb_col as u32 * crate::tile::SB_MI, |
| 8623 | crate::tile::SB_MI, |
| 8624 | header.mi_cols, |
| 8625 | ) |
| 8626 | && crate::tile::has_half( |
| 8627 | sb_row as u32 * crate::tile::SB_MI, |
| 8628 | crate::tile::SB_MI, |
| 8629 | header.mi_rows, |
| 8630 | ); |
| 8631 | let sb64_legal = i64_root() |
| 8632 | && ibc.is_none() |
| 8633 | && sb_row * 2 + 1 < rows |
| 8634 | && sb_col * 2 + 1 < cols |
| 8635 | && (whole_inside || edge_inside); |
| 8636 | let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None; |
| 8637 | if sb64_legal { |
| 8638 | I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 8639 | let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 8640 | let (c64, r64) = (sb_col * 4, sb_row * 4); |
| 8641 | let (block, cost) = code_square( |
| 8642 | &mut luma, |
| 8643 | &mut chroma, |
| 8644 | (x64, y64), |
| 8645 | SUPERBLOCK, |
| 8646 | &search, |
| 8647 | &mode_bits(above_mode[c64], left_mode[r64]), |
| 8648 | tx_select, |
| 8649 | None, |
| 8650 | true, |
| 8651 | fctx, |
| 8652 | ); |
| 8653 | let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false); |
| 8654 | let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 8655 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base); |
| 8656 | sb64 = Some((cost, block, after)); |
| 8657 | } |
| 8658 | // A superblock whose 64x64 trial already codes almost nothing per |
| 8659 | // pixel is taken outright and its quadrants are never searched -- |
| 8660 | // `split_rd_breakout` one size up, at the threshold the inter |
| 8661 | // root clamps to ([`b64_breakout_threshold`]), where this lever |
| 8662 | // BUYS wall instead of spending it. |
| 8663 | let early64 = sb64.as_ref().is_some_and(|(c, _, _)| { |
| 8664 | split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda) |
| 8665 | }); |
| 8666 | // What the four quadrants cost together, including the split |
| 8667 | // partition symbol at the superblock level, so the two arms are |
| 8668 | // one comparable number. |
| 8669 | let mut sb_cost = match sb64 { |
| 8670 | Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true), |
| 8671 | None => 0.0, |
| 8672 | }; |
| 8673 | for quadrant in 0..if early64 { 0 } else { 4 } { |
| 8674 | let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); |
| 8675 | if col >= cols || row >= rows { |
| 8676 | continue; |
| 8677 | } |
| 8678 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 8679 | let (c0, r0) = (col * 2, row * 2); |
| 8680 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 8681 | |
| 8682 | // spec `decode_partition`'s hasRows/hasCols recomputed at this |
| 8683 | // 32x32 block's own half (see `crate::tile::has_half`): the |
| 8684 | // true frame edge can fall inside a quadrant a superblock-level |
| 8685 | // check already let through. A quadrant that fails either may |
| 8686 | // not be left whole; a 16x16 sub-block that fails either (once |
| 8687 | // split) is a leaf this writer has no rectangular transform |
| 8688 | // for, so the search must not pick a split that would need one. |
| 8689 | let (has_cols32, has_rows32) = ( |
| 8690 | crate::tile::has_half( |
| 8691 | col as u32 * crate::tile::BLOCK_MI, |
| 8692 | crate::tile::BLOCK_MI, |
| 8693 | header.mi_cols, |
| 8694 | ), |
| 8695 | crate::tile::has_half( |
| 8696 | row as u32 * crate::tile::BLOCK_MI, |
| 8697 | crate::tile::BLOCK_MI, |
| 8698 | header.mi_rows, |
| 8699 | ), |
| 8700 | ); |
| 8701 | let whole_legal = has_cols32 && has_rows32; |
| 8702 | // A 16x16 sub-block's own hasCols/hasRows (spec |
| 8703 | // `decode_partition`, recomputed at this leaf's own half): |
| 8704 | // either axis false is a straddling leaf this writer codes as |
| 8705 | // the 8x8 leaves that are inside it |
| 8706 | // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes |
| 8707 | // false is the same split with the partition symbol inferred |
| 8708 | // rather than coded -- no rectangular transform is needed |
| 8709 | // (lane-av1rect). |
| 8710 | let sub_half = |sr: usize, sc: usize| { |
| 8711 | ( |
| 8712 | crate::tile::has_half( |
| 8713 | sc as u32 * crate::tile::SUB_MI, |
| 8714 | crate::tile::SUB_MI, |
| 8715 | header.mi_cols, |
| 8716 | ), |
| 8717 | crate::tile::has_half( |
| 8718 | sr as u32 * crate::tile::SUB_MI, |
| 8719 | crate::tile::SUB_MI, |
| 8720 | header.mi_rows, |
| 8721 | ), |
| 8722 | ) |
| 8723 | }; |
| 8724 | // What the whole 32x32 costs, including the partition symbol |
| 8725 | // that says it is not split. |
| 8726 | let (whole, mut cost_whole) = code_square( |
| 8727 | &mut luma, |
| 8728 | &mut chroma, |
| 8729 | (x, y), |
| 8730 | BLOCK, |
| 8731 | &search, |
| 8732 | &mode_bits(above_mode[c0], left_mode[r0]), |
| 8733 | tx_select, |
| 8734 | ibc.as_mut(), |
| 8735 | true, |
| 8736 | fctx, |
| 8737 | ); |
| 8738 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 8739 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 8740 | |
| 8741 | // What four 16x16 blocks cost instead, each searched against |
| 8742 | // the reconstruction the ones before it left. |
| 8743 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 8744 | let mut split = Vec::with_capacity(4); |
| 8745 | let mut cost_split = search.lambda |
| 8746 | * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); |
| 8747 | let mut split_modes = Vec::with_capacity(4); |
| 8748 | for sub in 0..4 { |
| 8749 | let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); |
| 8750 | // Same filter as the writer's `sub_positions` (spec |
| 8751 | // `decode_partition`'s `r >= MiRows || c >= MiCols` early |
| 8752 | // return): a sub-block whose own origin sits past the |
| 8753 | // true frame is never coded, so it must not be searched |
| 8754 | // or pushed onto `split` either, or the writer's block |
| 8755 | // count will not match what it is prepared to name. |
| 8756 | if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows |
| 8757 | || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols |
| 8758 | { |
| 8759 | continue; |
| 8760 | } |
| 8761 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 8762 | if has_cols16 && has_rows16 { |
| 8763 | let (block, cost) = code_square( |
| 8764 | &mut luma, |
| 8765 | &mut chroma, |
| 8766 | (x + (sub % 2) * SUB, y + (sub / 2) * SUB), |
| 8767 | SUB, |
| 8768 | &search, |
| 8769 | &mode_bits(above_mode[sc], left_mode[sr]), |
| 8770 | tx_select, |
| 8771 | ibc.as_mut(), |
| 8772 | true, |
| 8773 | fctx, |
| 8774 | ); |
| 8775 | cost_split += cost; |
| 8776 | split_modes.push(block.mode); |
| 8777 | above_mode[sc] = block.mode; |
| 8778 | left_mode[sr] = block.mode; |
| 8779 | split.push(block); |
| 8780 | } else { |
| 8781 | // A straddling 16x16: two (or, at a true corner, one) |
| 8782 | // 8x8 leaves, in the raster order `write_leaf8`'s |
| 8783 | // caller expects. Both leaves cost against the SAME |
| 8784 | // enclosing-slot mode context (see |
| 8785 | // `crate::tile::write_leaf8`'s doc), and neither |
| 8786 | // updates `above_mode`/`left_mode` at this SUB slot -- |
| 8787 | // the writer never does either, so the search must |
| 8788 | // not diverge from what it will actually read next. |
| 8789 | let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); |
| 8790 | let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); |
| 8791 | let mut leaves = Vec::with_capacity(2); |
| 8792 | for i in 0..4 { |
| 8793 | let leaf_x = x_sub + (i % 2) * 8; |
| 8794 | let leaf_y = y_sub + (i / 2) * 8; |
| 8795 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 8796 | continue; |
| 8797 | } |
| 8798 | let (leaf, cost) = code_square( |
| 8799 | &mut luma, |
| 8800 | &mut chroma, |
| 8801 | (leaf_x, leaf_y), |
| 8802 | 8, |
| 8803 | &search, |
| 8804 | &leaf_mode_bits, |
| 8805 | tx_select, |
| 8806 | None, |
| 8807 | true, |
| 8808 | fctx, |
| 8809 | ); |
| 8810 | cost_split += cost; |
| 8811 | split_modes.push(leaf.mode); |
| 8812 | leaves.push(leaf); |
| 8813 | } |
| 8814 | split.push(BlockCoeffs { |
| 8815 | eight: Some(leaves), |
| 8816 | ..BlockCoeffs::default() |
| 8817 | }); |
| 8818 | } |
| 8819 | } |
| 8820 | |
| 8821 | // A split whose subs are all whole 16x16 is a real quality |
| 8822 | // alternative to `whole`, exactly as before. Through r14, a |
| 8823 | // split carrying an 8x8-leaf sub was only ever forced |
| 8824 | // (`!whole_legal`), never chosen on cost, because the leaf |
| 8825 | // path was not yet proven against a real decoder; r15 proved |
| 8826 | // it against ffmpeg, and lane-av1dec r5 taught crate::decode |
| 8827 | // the read path (`decode_leaf8`), so leaf8 can now win on |
| 8828 | // cost anywhere, same as any other split. |
| 8829 | if !whole_legal || (split_blocks && cost_split < cost_whole) { |
| 8830 | sb_cost += cost_split; |
| 8831 | modes.extend_from_slice(&split_modes); |
| 8832 | blocks.push(Quadrant::Split(split)); |
| 8833 | } else { |
| 8834 | sb_cost += cost_whole; |
| 8835 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 8836 | for cell in 0..2 { |
| 8837 | above_mode[c0 + cell] = whole.mode; |
| 8838 | left_mode[r0 + cell] = whole.mode; |
| 8839 | } |
| 8840 | modes.push(whole.mode); |
| 8841 | blocks.push(Quadrant::Whole(whole)); |
| 8842 | } |
| 8843 | } |
| 8844 | let index = sb_row * sb_cols + sb_col; |
| 8845 | match sb64 { |
| 8846 | Some((cost64, block, after)) if early64 || cost64 < sb_cost => { |
| 8847 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after); |
| 8848 | for cell in 0..4 { |
| 8849 | above_mode[sb_col * 4 + cell] = block.mode; |
| 8850 | left_mode[sb_row * 4 + cell] = block.mode; |
| 8851 | } |
| 8852 | I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 8853 | if !whole_inside { |
| 8854 | I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 8855 | } |
| 8856 | let mode = block.mode; |
| 8857 | coded.push((index, Superblock::Whole(block), vec![mode])); |
| 8858 | } |
| 8859 | _ => coded.push((index, Superblock::Split(blocks), modes)), |
| 8860 | } |
| 8861 | } |
| 8862 | } |
| 8863 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 8864 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 8865 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 8866 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 8867 | copy_rect( |
| 8868 | out, |
| 8869 | &tile.reconstruction, |
| 8870 | frame_width / 2, |
| 8871 | x0 / 2, |
| 8872 | y0 / 2, |
| 8873 | x1.div_ceil(2), |
| 8874 | y1.div_ceil(2), |
| 8875 | ); |
| 8876 | } |
| 8877 | Ok(coded) |
| 8878 | }; |
| 8879 | let searched = search_tiles(layout.count(), fctx, search_tile)?; |
| 8880 | // Back into frame raster order: the tile writer indexes `superblocks` by |
| 8881 | // the frame's own superblock index, and `modes` is the coding order the |
| 8882 | // ablation drivers read. |
| 8883 | let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect(); |
| 8884 | for (at, superblock, block_modes) in searched.into_iter().flatten() { |
| 8885 | in_order[at] = Some((superblock, block_modes)); |
| 8886 | } |
| 8887 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 8888 | let mut modes = Vec::with_capacity(cols * rows); |
| 8889 | for slot in in_order { |
| 8890 | let (superblock, block_modes) = slot.expect("every superblock belongs to a tile"); |
| 8891 | superblocks.push(superblock); |
| 8892 | modes.extend_from_slice(&block_modes); |
| 8893 | } |
| 8894 | |
| 8895 | #[cfg(test)] |
| 8896 | record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); |
| 8897 | // A key frame always starts from the defaults (`primary_ref_frame` is |
| 8898 | // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf` |
| 8899 | // set, so what it stores into the slots it refreshes is exactly those |
| 8900 | // defaults again (spec 7.20's `started_from` arm) -- the first inter |
| 8901 | // frame after it therefore starts from the defaults too. |
| 8902 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 8903 | let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); |
| 8904 | // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set` |
| 8905 | // from -- `Cdfs::txb` widens every luma set under it. |
| 8906 | cdfs.reduced_tx_set = header.reduced_tx_set; |
| 8907 | let start_cdfs = CdfSnapshot(cdfs); |
| 8908 | // The luma restoration-unit grid this frame's `lr_params` implies |
| 8909 | // (`av1_lr_count_units` rounds to nearest, so a short last unit is |
| 8910 | // swallowed by the one before it), for the tile writer's own per-unit |
| 8911 | // walk. |
| 8912 | let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32; |
| 8913 | let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32; |
| 8914 | // Every tile is coded from this frame's OWN starting tables and leaves |
| 8915 | // its own end state behind (spec 5.11.1: each tile resets the CDFs, the |
| 8916 | // loop-restoration reference and its neighbour contexts), so the tiles |
| 8917 | // are independent of each other and of the order they are written in. |
| 8918 | let code_tiles = |bits: u8, |
| 8919 | sb_cols: usize, |
| 8920 | grid: &[u8], |
| 8921 | units: &[Option<crate::restoration::WienerInfo>]| |
| 8922 | -> Result<Vec<Vec<u8>>> { |
| 8923 | let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { |
| 8924 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 8925 | crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec()); |
| 8926 | crate::tile::arm_sb128(sb128_on()); |
| 8927 | let mut cdfs = start_cdfs.0.clone(); |
| 8928 | crate::tile::arm_screen(screen); |
| 8929 | crate::tile::arm_frame_mi_dims(frame_mi_dims); |
| 8930 | crate::tile::arm_filter_intra(filter_intra_on()); |
| 8931 | crate::tile::arm_intrabc(allow_intrabc); |
| 8932 | crate::tile::arm_pricing_cdfs(None, false); |
| 8933 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 8934 | mi_cols, |
| 8935 | mi_rows, |
| 8936 | base_q_idx, |
| 8937 | &superblocks, |
| 8938 | tx_select, |
| 8939 | &mut cdfs, |
| 8940 | layout.rect(index), |
| 8941 | )?; |
| 8942 | Ok((bytes, None)) |
| 8943 | })?; |
| 8944 | Ok(out) |
| 8945 | }; |
| 8946 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 8947 | // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing |
| 8948 | // the tile just coded back to the decoder under each candidate (see |
| 8949 | // `crate::filter_search`), and keep the filtered picture that wins as |
| 8950 | // the reconstruction -- what a decoder outputs, and what the next |
| 8951 | // frame predicts from. |
| 8952 | pick_and_apply_filters( |
| 8953 | &mut header, |
| 8954 | &mut luma, |
| 8955 | &mut chroma, |
| 8956 | [&picture_y8, &picture_u8, &picture_v8], |
| 8957 | // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF |
| 8958 | // and loop restoration off and codes none of their parameters |
| 8959 | // (frame.rs:194/210/252/272) -- there is no filter to search for, and |
| 8960 | // the encoder's reconstruction is already what a decoder produces. |
| 8961 | !allow_intrabc, |
| 8962 | &mut tiles, |
| 8963 | search.lambda, |
| 8964 | fctx, |
| 8965 | // A key frame codes no 128x128 root block (the writer has no intra |
| 8966 | // path at that size), so every unit carries its own literal. |
| 8967 | &[], |
| 8968 | // Every re-code starts from this frame's OWN starting tables, never |
| 8969 | // from where the first write left them: the second tile is the same |
| 8970 | // symbol sequence plus new ones, so it must adapt from the same |
| 8971 | // point the decoder will. |
| 8972 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 8973 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 8974 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 8975 | crate::decode::decode_key_frame_tiles_lr( |
| 8976 | &payloads, |
| 8977 | &header_tile_info, |
| 8978 | h.mi_cols, |
| 8979 | h.mi_rows, |
| 8980 | base_q_idx, |
| 8981 | h.frame_width, |
| 8982 | h.frame_height, |
| 8983 | seq.enable_filter_intra, |
| 8984 | cdef, |
| 8985 | lf, |
| 8986 | tx_select, |
| 8987 | h.reduced_tx_set, |
| 8988 | h.allow_screen_content_tools, |
| 8989 | h.allow_intrabc, |
| 8990 | lr, |
| 8991 | fctx, |
| 8992 | ) |
| 8993 | }, |
| 8994 | )?; |
| 8995 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 8996 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 8997 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 8998 | let mut stream = temporal_delimiter(); |
| 8999 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 9000 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 9001 | |
| 9002 | let [u, v] = chroma; |
| 9003 | Ok(Encoded { |
| 9004 | stream, |
| 9005 | modes, |
| 9006 | inter_block_share: 0.0, |
| 9007 | reconstruction: Picture { |
| 9008 | width: luma.width, |
| 9009 | height: luma.height, |
| 9010 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 9011 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 9012 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 9013 | }, |
| 9014 | tile, |
| 9015 | mi_cols: header.mi_cols, |
| 9016 | mi_rows: header.mi_rows, |
| 9017 | base_q_idx, |
| 9018 | tx_select, |
| 9019 | // A key frame codes no inter block, so no motion_mode symbol. |
| 9020 | switchable_motion_mode: false, |
| 9021 | screen, |
| 9022 | reduced_tx_set: header.reduced_tx_set, |
| 9023 | next_cdfs: start_cdfs.clone(), |
| 9024 | start_cdfs, |
| 9025 | loop_filter: header.loop_filter, |
| 9026 | cdef: header.cdef, |
| 9027 | loop_restoration: header.loop_restoration, |
| 9028 | allow_intrabc, |
| 9029 | delta: header.delta.clone(), |
| 9030 | }) |
| 9031 | } |
| 9032 | |
| 9033 | /// Chooses this frame's deblocking levels and CDEF strengths, writes them |
| 9034 | /// into `header` and |
| 9035 | /// replaces the frame's own region of the encoder's reconstruction with the |
| 9036 | /// filtered picture the decoder produced under them |
| 9037 | /// ([`crate::filter_search::pick_deblock`]). |
| 9038 | /// |
| 9039 | /// `search == false` leaves the header at level 0 (deblocking off) and the |
| 9040 | /// reconstruction untouched: the caller's stream is one this crate's own |
| 9041 | /// decoder cannot read back, so there is nothing to search against. |
| 9042 | /// |
| 9043 | /// # Errors |
| 9044 | /// The decoder's own error, when it refuses the tile the encoder just wrote |
| 9045 | /// -- that is an encoder defect, not a filter one, so it is propagated |
| 9046 | /// rather than swallowed into "no deblocking". |
| 9047 | fn pick_and_apply_filters( |
| 9048 | header: &mut FrameHeader, |
| 9049 | luma: &mut Plane<'_>, |
| 9050 | chroma: &mut [Plane<'_>; 2], |
| 9051 | source: [&[u8]; 3], |
| 9052 | search: bool, |
| 9053 | // The coded tiles, one payload per tile of the frame's grid, replaced in |
| 9054 | // place when the search chooses a per-64x64 `cdef_idx` list |
| 9055 | // (`cdef_bits > 0`): those literals live in the tile payloads, so every |
| 9056 | // tile is written a second time under `recode` and the winner |
| 9057 | // re-decoded from them. |
| 9058 | tiles: &mut Vec<Vec<u8>>, |
| 9059 | lambda: f64, |
| 9060 | fctx: &crate::decode::FrameCtx, |
| 9061 | // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles |
| 9062 | // carry -- empty (the identity map) for a frame whose every block covers |
| 9063 | // one 64x64 CDEF unit. |
| 9064 | cdef_owner: &[u32], |
| 9065 | recode: impl Fn( |
| 9066 | u8, |
| 9067 | usize, |
| 9068 | &[u8], |
| 9069 | &[Option<crate::restoration::WienerInfo>], |
| 9070 | ) -> Result<Vec<Vec<u8>>>, |
| 9071 | decode: impl Fn( |
| 9072 | &LoopFilterParams, |
| 9073 | &CdefParams, |
| 9074 | &FrameHeader, |
| 9075 | &[Vec<u8>], |
| 9076 | &LoopRestorationParams, |
| 9077 | ) -> Result<Picture>, |
| 9078 | ) -> Result<()> { |
| 9079 | if !search { |
| 9080 | return Ok(()); |
| 9081 | } |
| 9082 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 9083 | let hdr = header.clone(); |
| 9084 | // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: |
| 9085 | // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. |
| 9086 | let damping = 3 + (header.quantization.base_q_idx >> 6); |
| 9087 | let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 9088 | let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); |
| 9089 | let none_lr = LoopRestorationParams::default(); |
| 9090 | // Every candidate scores the same coded tile: decode it once and re-run |
| 9091 | // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of |
| 9092 | // the encoder's profile before this). The per-64x64 error the CDEF |
| 9093 | // preset search reads comes off the REPLAYED picture, which is the same |
| 9094 | // picture a decode produces -- that is what the replay is pinned on. |
| 9095 | crate::decode::clear_filter_replay(); |
| 9096 | // lane-av1fpar: the per-tile search is over, so every core is idle from |
| 9097 | // here to the end of the frame -- band each candidate's deblock/CDEF |
| 9098 | // replay, the capture decode's own filter chain and the loop-restoration |
| 9099 | // passes across the same workers the search used. |
| 9100 | let _bands = crate::par::override_filter_threads(crate::par::tile_threads()); |
| 9101 | let ft = crate::par::timer(crate::par::S_FILTER); |
| 9102 | let search_result = crate::filter_search::pick_filters( |
| 9103 | |lf, cdef| { |
| 9104 | if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { |
| 9105 | return Ok(picture); |
| 9106 | } |
| 9107 | crate::decode::arm_filter_replay(); |
| 9108 | let _t = crate::par::timer(crate::par::S_FIRST); |
| 9109 | decode(lf, cdef, &hdr, tiles, &none_lr) |
| 9110 | }, |
| 9111 | source, |
| 9112 | luma.width, |
| 9113 | (fw, fh), |
| 9114 | damping, |
| 9115 | (sb_cols, sb_rows), |
| 9116 | lambda, |
| 9117 | cdef_owner, |
| 9118 | ); |
| 9119 | drop(ft); |
| 9120 | let (lf, cdef, idx_grid, picture) = search_result?; |
| 9121 | header.loop_filter = lf; |
| 9122 | header.cdef = cdef; |
| 9123 | // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not |
| 9124 | // in the frame header, so a re-decode under candidate parameters cannot |
| 9125 | // search them the way deblocking and CDEF are searched above. What the |
| 9126 | // decoder hands back instead is its own filter chain's intermediates |
| 9127 | // (`crate::decode::FrameCtx::capture_stages`), and the search runs on |
| 9128 | // those, through the decoder's own Wiener kernel. |
| 9129 | // |
| 9130 | // The capture rides the decode this stage was already going to do: the |
| 9131 | // re-decode of the `cdef_idx` tile when there is one, and otherwise one |
| 9132 | // decode of the tile as it stands. That decode's header still says |
| 9133 | // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the |
| 9134 | // post-CDEF picture stands in for it at LR's 3-row stripe borders -- |
| 9135 | // an approximation inside the SEARCH only; the reconstruction this |
| 9136 | // function ends up splicing is always a real decode of the real tile. |
| 9137 | let lr_on = restoration_enabled(); |
| 9138 | // The `cdef_idx` literals live in the tile payload, so a frame that |
| 9139 | // chose a per-64x64 preset list codes its tiles a second time. |
| 9140 | if !idx_grid.is_empty() { |
| 9141 | *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?; |
| 9142 | } |
| 9143 | // lane-av1cap: that re-coded tile used to be DECODED here as well -- |
| 9144 | // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop |
| 9145 | // restoration search reads (`crate::decode::FrameCtx::capture_stages`) |
| 9146 | // and the picture this function splices. Both come out of ONE more |
| 9147 | // replay of the winning parameters on the same captured pre-filter |
| 9148 | // planes every candidate was scored on: the same two filter kernels, on |
| 9149 | // the same input, in the same order, so the same bytes. Re-coding the |
| 9150 | // tile does not move the reconstruction the replay holds -- `cdef_idx` |
| 9151 | // is an equiprobable literal, so it adapts no CDF and changes no |
| 9152 | // residual. |
| 9153 | let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx); |
| 9154 | #[cfg(test)] |
| 9155 | let replay_was_used = replayed.is_some(); |
| 9156 | let (mut filtered, mut stages) = match replayed { |
| 9157 | Some((picture, stages)) => (picture, stages), |
| 9158 | // Nothing captured (the shapes [`crate::decode::FilterReplay`] |
| 9159 | // refuses): every candidate was a full decode, so the winner's own |
| 9160 | // picture stands, and the stages still need a capturing decode. |
| 9161 | None => { |
| 9162 | fctx.capture_stages.set(lr_on); |
| 9163 | let picture = if idx_grid.is_empty() && !lr_on { |
| 9164 | picture |
| 9165 | } else { |
| 9166 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 9167 | decode(&lf, &cdef, &hdr, tiles, &none_lr)? |
| 9168 | }; |
| 9169 | fctx.capture_stages.set(false); |
| 9170 | (picture, crate::decode::take_filter_stages(fctx)) |
| 9171 | } |
| 9172 | }; |
| 9173 | #[cfg(test)] |
| 9174 | if crate::decode::verify_final_replay() && replay_was_used { |
| 9175 | fctx.capture_stages.set(lr_on); |
| 9176 | let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?; |
| 9177 | fctx.capture_stages.set(false); |
| 9178 | let want_stages = crate::decode::take_filter_stages(fctx); |
| 9179 | assert!( |
| 9180 | (want.width, want.height) == (filtered.width, filtered.height) |
| 9181 | && want.y == filtered.y |
| 9182 | && want.u == filtered.u |
| 9183 | && want.v == filtered.v, |
| 9184 | "the final filter replay is not the capture decode it stands in for", |
| 9185 | ); |
| 9186 | // Only the frame's own cropped region: the plane is padded to the |
| 9187 | // superblock grid and the columns past the mi extent are written by |
| 9188 | // nothing (the decoder's plane pool leaves whatever the last frame |
| 9189 | // put there), while the restoration search reads strictly inside |
| 9190 | // `fw x fh` -- `restoration::lr_sample` clamps its column to |
| 9191 | // `plane_w - 1` and its row to the frame's, and |
| 9192 | // `filter_search::pick_restoration`'s own SSE walk never leaves the |
| 9193 | // crop either. |
| 9194 | let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| { |
| 9195 | for row in 0..h { |
| 9196 | let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]); |
| 9197 | assert!( |
| 9198 | x == y, |
| 9199 | "{what}: the replayed filter stages are not the ones the capture \ |
| 9200 | decode returns (row {row} of {h}, width {w}, stride {stride})", |
| 9201 | ); |
| 9202 | } |
| 9203 | }; |
| 9204 | match (&want_stages, &stages) { |
| 9205 | (Some(a), Some(b)) => { |
| 9206 | assert_eq!(a.stride, b.stride, "the captured plane strides moved"); |
| 9207 | let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); |
| 9208 | for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() { |
| 9209 | region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked"); |
| 9210 | region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed"); |
| 9211 | } |
| 9212 | } |
| 9213 | (None, None) => {} |
| 9214 | _ => panic!("one path captured filter stages and the other did not"), |
| 9215 | } |
| 9216 | } |
| 9217 | // lane-av1cap2: the capture stays live past the restoration search -- |
| 9218 | // `crate::decode::replay_restoration` filters the same post-CDEF plane |
| 9219 | // rather than decoding the re-coded tile. Cleared at the end instead. |
| 9220 | let mut lr = LoopRestorationParams::default(); |
| 9221 | if lr_on { |
| 9222 | let unit = lr_unit(); |
| 9223 | let mut want = LoopRestorationParams { |
| 9224 | loop_restoration_size: [unit, unit, unit], |
| 9225 | uses_lr: true, |
| 9226 | // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so |
| 9227 | // 0 is the 64 unit and 1 the 128 one a 128 superblock forces. |
| 9228 | lr_unit_shift: u8::from(unit == 128), |
| 9229 | ..LoopRestorationParams::default() |
| 9230 | }; |
| 9231 | want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; |
| 9232 | let lrt = crate::par::timer(crate::par::S_LR); |
| 9233 | let units = match stages.take() { |
| 9234 | Some(stages) => crate::filter_search::pick_restoration( |
| 9235 | &stages, |
| 9236 | source[0], |
| 9237 | luma.width, |
| 9238 | (fw, fh), |
| 9239 | &want, |
| 9240 | lambda, |
| 9241 | fctx, |
| 9242 | ), |
| 9243 | None => Vec::new(), |
| 9244 | }; |
| 9245 | // A frame no unit restores keeps `RESTORE_NONE` on every plane |
| 9246 | // rather than paying ~1 bit per 64x64 for a tile full of |
| 9247 | // `restore_wiener = 0` symbols (the BD gate saw exactly that on the |
| 9248 | // clip whose units never take a filter). |
| 9249 | drop(lrt); |
| 9250 | if units.iter().any(Option::is_some) { |
| 9251 | let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; |
| 9252 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 9253 | // lane-av1cap2: that re-coded tile used to be DECODED here to |
| 9254 | // reach the restored reference frame -- 5.6% of a 4K frame, |
| 9255 | // for a filter that reads nothing of the tile but the per-unit |
| 9256 | // Wiener filters this stage just chose. Run the decoder's own |
| 9257 | // restoration kernel on the replay's post-CDEF plane instead |
| 9258 | // (`crate::decode::replay_restoration`), with the real |
| 9259 | // post-deblock stripe borders. |
| 9260 | match crate::decode::replay_restoration(&want, &units, fctx) { |
| 9261 | Some(y) => { |
| 9262 | #[cfg(test)] |
| 9263 | let margin = fctx |
| 9264 | .last_frame_wide_margin |
| 9265 | .with(|m| m.borrow().as_ref().map(|p| p.y.clone())); |
| 9266 | #[cfg(test)] |
| 9267 | if crate::decode::verify_final_replay() { |
| 9268 | let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?; |
| 9269 | assert!( |
| 9270 | (want_pic.width, want_pic.height) == (filtered.width, filtered.height) |
| 9271 | && want_pic.u == filtered.u |
| 9272 | && want_pic.v == filtered.v, |
| 9273 | "the restoration replay moved a chroma plane or the picture size", |
| 9274 | ); |
| 9275 | assert!( |
| 9276 | want_pic.y == y, |
| 9277 | "the restoration replay is not the decode of the re-coded tile", |
| 9278 | ); |
| 9279 | assert!( |
| 9280 | fctx.last_frame_wide_margin |
| 9281 | .with(|m| m.borrow().as_ref().map(|p| p.y.clone())) |
| 9282 | == margin, |
| 9283 | "the restoration replay's wide-margin luma is not the decode's", |
| 9284 | ); |
| 9285 | } |
| 9286 | filtered.y = y; |
| 9287 | } |
| 9288 | // Nothing captured: the winner came out of a full decode, |
| 9289 | // so this one does too. |
| 9290 | None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?, |
| 9291 | } |
| 9292 | *tiles = coded; |
| 9293 | lr = want; |
| 9294 | } |
| 9295 | } |
| 9296 | crate::decode::clear_filter_replay(); |
| 9297 | header.loop_restoration = lr; |
| 9298 | let dec_cw = filtered.width.div_ceil(2); |
| 9299 | let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); |
| 9300 | crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); |
| 9301 | crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch); |
| 9302 | crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch); |
| 9303 | Ok(()) |
| 9304 | } |
| 9305 | |
| 9306 | /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only |
| 9307 | /// group an inter frame's intra branch codes (spec `inter_frame_mode_info`), |
| 9308 | /// since every block this crate's inter tile writer codes is 32x32. |
| 9309 | const SIZE_GROUP_32: usize = 3; |
| 9310 | |
| 9311 | /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference |
| 9312 | /// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV |
| 9313 | /// stack this encoder builds is ever asked to predict against. |
| 9314 | const LAST_FRAME: i8 = 1; |
| 9315 | |
| 9316 | /// What an inter frame's intra branch spends to name each of the thirteen |
| 9317 | /// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour |
| 9318 | /// context, since an inter frame's intra blocks do not read their |
| 9319 | /// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s |
| 9320 | /// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour |
| 9321 | /// state, so it is built once per frame. |
| 9322 | fn inter_mode_bits() -> [f64; 13] { |
| 9323 | std::array::from_fn(|mode| { |
| 9324 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 9325 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 9326 | } else { |
| 9327 | 0.0 |
| 9328 | }; |
| 9329 | symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) |
| 9330 | + angle |
| 9331 | + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 9332 | }) |
| 9333 | } |
| 9334 | |
| 9335 | /// A 1/8-pel motion vector component, converted to the 1/16-pel offset |
| 9336 | /// [`mc::predict`] takes, in the units of the plane it predicts into. |
| 9337 | /// |
| 9338 | /// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is |
| 9339 | /// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same |
| 9340 | /// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel |
| 9341 | /// domain. `luma` picks which. |
| 9342 | fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { |
| 9343 | (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } |
| 9344 | } |
| 9345 | |
| 9346 | /// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to |
| 9347 | /// that module): the magnitude an `MV_CLASS_n` component's own bits start |
| 9348 | /// counting from. |
| 9349 | fn mv_class_base(class: usize) -> i32 { |
| 9350 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 9351 | } |
| 9352 | |
| 9353 | /// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring |
| 9354 | /// `tile::mv_class_of`. |
| 9355 | fn mv_class_of(z: i32) -> usize { |
| 9356 | let mut class = 0; |
| 9357 | while class < 10 && mv_class_base(class + 1) <= z { |
| 9358 | class += 1; |
| 9359 | } |
| 9360 | class |
| 9361 | } |
| 9362 | |
| 9363 | /// What [`crate::tile::write_mv_component`] (private to that module) would |
| 9364 | /// spend coding one non-zero motion vector component, against the same |
| 9365 | /// static default CDFs the writer starts a frame from — the same |
| 9366 | /// static-table approximation [`mode_bits`] costs the luma mode symbol |
| 9367 | /// through, not the tile writer's own adapting state, which this encoder has |
| 9368 | /// no way to read without duplicating it block for block. |
| 9369 | /// |
| 9370 | /// Returns `None` when `diff` needs eighth-pel precision in a frame coded |
| 9371 | /// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`] |
| 9372 | /// exists to avoid ever happening. |
| 9373 | fn mv_component_bits(diff: i32) -> Option<f64> { |
| 9374 | let hp_frame = crate::tile::high_precision_mv(); |
| 9375 | let mag = diff.unsigned_abs() as i32; |
| 9376 | let z = mag - 1; |
| 9377 | if !hp_frame && z & 1 == 0 { |
| 9378 | return None; |
| 9379 | } |
| 9380 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 9381 | let class = mv_class_of(z); |
| 9382 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 9383 | let local = z - mv_class_base(class); |
| 9384 | let hp = (local & 1) as usize; |
| 9385 | if class == 0 { |
| 9386 | let bit = (local >> 3) & 1; |
| 9387 | let fr = (local >> 1) & 3; |
| 9388 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); |
| 9389 | bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); |
| 9390 | // lane-hpmv: the writer codes the eighth-pel bit in a high-precision |
| 9391 | // frame, so the pricer charges for it there and only there. |
| 9392 | if hp_frame { |
| 9393 | bits += symbol_bits(&cdf::MV_CLASS0_HP, hp); |
| 9394 | } |
| 9395 | } else { |
| 9396 | let d = local >> 3; |
| 9397 | let fr = (local >> 1) & 3; |
| 9398 | for i in 0..class { |
| 9399 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 9400 | } |
| 9401 | bits += symbol_bits(&cdf::MV_FR, fr as usize); |
| 9402 | if hp_frame { |
| 9403 | bits += symbol_bits(&cdf::MV_HP, hp); |
| 9404 | } |
| 9405 | } |
| 9406 | Some(bits) |
| 9407 | } |
| 9408 | |
| 9409 | /// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the |
| 9410 | /// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch, |
| 9411 | /// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's |
| 9412 | /// value without the second motion search's wall. |
| 9413 | fn last2_new_mv() -> bool { |
| 9414 | match std::env::var("EC_AV1_LAST2_NEW").ok() { |
| 9415 | Some(v) => v != "0", |
| 9416 | None => true, |
| 9417 | } |
| 9418 | } |
| 9419 | |
| 9420 | /// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its |
| 9421 | /// own -- a second motion search per block against that reference's picture, |
| 9422 | /// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it |
| 9423 | /// off in a test build (what the lane measured both arms with). |
| 9424 | fn extra_ref_new_mv() -> bool { |
| 9425 | match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() { |
| 9426 | Some(v) if cfg!(test) => v != "0", |
| 9427 | _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW), |
| 9428 | } |
| 9429 | } |
| 9430 | |
| 9431 | /// The seven `ref_frame_idx` order hints of a frame coded on this crate's own |
| 9432 | /// flat slot plan (`inter_frame_headers_slots`): every reference but |
| 9433 | /// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded, |
| 9434 | /// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the |
| 9435 | /// frame two back when there is one (otherwise it, too, names the key frame's |
| 9436 | /// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes. |
| 9437 | pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] { |
| 9438 | let last = order_hint.wrapping_sub(1) & 0x7f; |
| 9439 | let alt = if has_altref { |
| 9440 | order_hint.wrapping_sub(2) & 0x7f |
| 9441 | } else { |
| 9442 | key_hint |
| 9443 | }; |
| 9444 | [last, last, last, key_hint, last, last, alt] |
| 9445 | } |
| 9446 | |
| 9447 | /// Whether an inter frame carries `reference_select` (spec 5.9.22): the |
| 9448 | /// header bit that lets each block choose between a single and a compound |
| 9449 | /// reference. Off by default until compound prediction is measured to pay; |
| 9450 | /// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate |
| 9451 | /// runs as), and every block still codes SINGLE, so the only cost is one |
| 9452 | /// `comp_mode` symbol per inter block. |
| 9453 | pub(crate) const REFERENCE_SELECT: bool = true; |
| 9454 | |
| 9455 | /// [`REFERENCE_SELECT`], with the test-build environment override. |
| 9456 | pub(crate) fn reference_select() -> bool { |
| 9457 | match std::env::var("EC_AV1_COMPOUND").ok() { |
| 9458 | Some(v) if cfg!(test) => v != "0", |
| 9459 | _ => crate::speed::at(&crate::speed::COMPOUND), |
| 9460 | } |
| 9461 | } |
| 9462 | |
| 9463 | /// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol |
| 9464 | /// per entry past `start`, `1` to advance and `0` to stop, at most two. |
| 9465 | fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { |
| 9466 | let mut bits = 0.0; |
| 9467 | let mut idx = start; |
| 9468 | while idx < start + 2 && stack.entries.len() > idx + 1 { |
| 9469 | let advance = idx < target; |
| 9470 | bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); |
| 9471 | if !advance { |
| 9472 | break; |
| 9473 | } |
| 9474 | idx += 1; |
| 9475 | } |
| 9476 | bits |
| 9477 | } |
| 9478 | |
| 9479 | /// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off |
| 9480 | /// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10 |
| 9481 | /// `assign_mv`), so the same vector costs a different residual from each. |
| 9482 | fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { |
| 9483 | let mut best: Option<(f64, u8)> = None; |
| 9484 | for idx in 0..3usize { |
| 9485 | if idx > 0 && stack.entries.len() <= idx { |
| 9486 | break; |
| 9487 | } |
| 9488 | let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); |
| 9489 | if let Some(b) = mv_residual_bits(mv, base) { |
| 9490 | let total = b + drl_bits_for(stack, 0, idx); |
| 9491 | if best.is_none_or(|(t, _)| total < t) { |
| 9492 | best = Some((total, idx as u8)); |
| 9493 | } |
| 9494 | } |
| 9495 | } |
| 9496 | best |
| 9497 | } |
| 9498 | |
| 9499 | /// The starting points [`motion::search`] gets besides `stack.pred_mv`: the |
| 9500 | /// zero vector and the stack's own candidates. A neighbour block's vector is |
| 9501 | /// where this block's motion most often already is, which is what pays for |
| 9502 | /// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points |
| 9503 | /// vs libaom for 0.2 s off a 6 s ladder). |
| 9504 | fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { |
| 9505 | let mut seeds = [(0, 0); 4]; |
| 9506 | let mut n = 1; |
| 9507 | for e in stack.entries.iter().take(3) { |
| 9508 | seeds[n] = e.mv; |
| 9509 | n += 1; |
| 9510 | } |
| 9511 | (seeds, n) |
| 9512 | } |
| 9513 | |
| 9514 | /// What [`crate::tile::write_mv`] (private to that module) would spend |
| 9515 | /// coding `mv` as a residual against `pred`: the joint symbol naming which |
| 9516 | /// components differ, then each differing component. `None` under the same |
| 9517 | /// condition [`mv_component_bits`] returns `None`. |
| 9518 | /// How many frames back `ref_frame` sits from the frame being coded, off the |
| 9519 | /// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is |
| 9520 | /// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is |
| 9521 | /// what [`crate::motion::search`] scales its starting step by. |
| 9522 | fn ref_distance(ref_frame: i8) -> u32 { |
| 9523 | let (bits, order_hint, hints) = crate::tile::order_hints(); |
| 9524 | let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize; |
| 9525 | let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i]) |
| 9526 | .unsigned_abs() |
| 9527 | .max(1); |
| 9528 | if crate::envflags::env_flag!("EC_TRACE_DIST") { |
| 9529 | eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]); |
| 9530 | } |
| 9531 | d |
| 9532 | } |
| 9533 | |
| 9534 | fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> { |
| 9535 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 9536 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 9537 | (false, false) => 0, |
| 9538 | (false, true) => 1, |
| 9539 | (true, false) => 2, |
| 9540 | (true, true) => 3, |
| 9541 | }; |
| 9542 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint); |
| 9543 | for d in [diff.0, diff.1] { |
| 9544 | if d != 0 { |
| 9545 | bits += mv_component_bits(d)?; |
| 9546 | } |
| 9547 | } |
| 9548 | Some(bits) |
| 9549 | } |
| 9550 | |
| 9551 | /// Rounds `mv` so that its residual against `pred` is one |
| 9552 | /// [`crate::tile::write_mv_component`] can actually code: each component's |
| 9553 | /// difference is either zero or has an even magnitude (the eighth-pel bit |
| 9554 | /// `allow_high_precision_mv` off always infers as one forces the coded |
| 9555 | /// magnitude odd one step further in, which comes out even here since this |
| 9556 | /// crate's motion search works in whole units of that same step). Rounding |
| 9557 | /// down keeps every coded MV — and so every `nearest_mv` a later block's |
| 9558 | /// stack votes with — built from an even displacement from `(0, 0)`, so the |
| 9559 | /// invariant holds without this function seeing the whole stack. |
| 9560 | /// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both |
| 9561 | /// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` = |
| 9562 | /// always), the shape [`set_frame_interp`] has: the witness that has to see |
| 9563 | /// `mv_hp` symbols coded turns it on through this while holding |
| 9564 | /// [`crate::speed::knob_write`]. |
| 9565 | static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); |
| 9566 | |
| 9567 | /// Sets [`HP_MV_OVERRIDE`]; `None` clears it. |
| 9568 | #[allow(dead_code)] // set only from the `#[cfg(test)]` gates |
| 9569 | pub(crate) fn set_high_precision_mv(on: Option<bool>) { |
| 9570 | HP_MV_OVERRIDE.store(on.map_or(u8::MAX, u8::from), std::sync::atomic::Ordering::Relaxed); |
| 9571 | } |
| 9572 | |
| 9573 | /// The qindex below which an inter frame codes `allow_high_precision_mv` |
| 9574 | /// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this |
| 9575 | /// crate's shipped value, i.e. high-precision motion vectors off in every |
| 9576 | /// frame -- see `lanes/hpmv.report.md` for the sweep that chose it. |
| 9577 | pub(crate) const HP_MV_QTHRESH: u8 = 0; |
| 9578 | |
| 9579 | /// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`: |
| 9580 | /// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all` |
| 9581 | /// always, any number as the threshold) so the BD gate can sweep the policy |
| 9582 | /// without a rebuild. |
| 9583 | pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool { |
| 9584 | match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 9585 | 0 => return false, |
| 9586 | 1 => return true, |
| 9587 | _ => {} |
| 9588 | } |
| 9589 | static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new(); |
| 9590 | let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() { |
| 9591 | Some("all" | "always") => 256, |
| 9592 | Some("0" | "off") => 0, |
| 9593 | Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)), |
| 9594 | None => u16::from(HP_MV_QTHRESH), |
| 9595 | }); |
| 9596 | u16::from(base_q_idx) < threshold |
| 9597 | } |
| 9598 | |
| 9599 | fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { |
| 9600 | // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel |
| 9601 | // residual is codable and there is nothing to round away. |
| 9602 | if crate::tile::high_precision_mv() { |
| 9603 | return mv; |
| 9604 | } |
| 9605 | let round = |m: i32, p: i32| { |
| 9606 | let diff = m - p; |
| 9607 | let mag = diff.unsigned_abs() as i32; |
| 9608 | let even = mag - mag % 2; |
| 9609 | if even == 0 { |
| 9610 | p |
| 9611 | } else { |
| 9612 | p + even * diff.signum() |
| 9613 | } |
| 9614 | }; |
| 9615 | (round(mv.0, pred.0), round(mv.1, pred.1)) |
| 9616 | } |
| 9617 | |
| 9618 | /// Predicts one `side`-square block by motion compensation from `reference` |
| 9619 | /// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`]. |
| 9620 | #[allow(clippy::too_many_arguments)] |
| 9621 | fn mc_trial( |
| 9622 | plane: &Plane, |
| 9623 | x: usize, |
| 9624 | y: usize, |
| 9625 | side: usize, |
| 9626 | mv: (i32, i32), |
| 9627 | luma: bool, |
| 9628 | reference: &[u16], |
| 9629 | stride: usize, |
| 9630 | ref_width: usize, |
| 9631 | ref_height: usize, |
| 9632 | skip: bool, |
| 9633 | base_q_idx: u8, |
| 9634 | deadzone: f64, |
| 9635 | set: TxbSet, |
| 9636 | fctx: &crate::decode::FrameCtx, |
| 9637 | ) -> Trial { |
| 9638 | mc_trial_typed( |
| 9639 | plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx, |
| 9640 | deadzone, set, TxType::DctDct, fctx, |
| 9641 | ) |
| 9642 | } |
| 9643 | |
| 9644 | /// [`mc_trial`] coding its residual with a named transform type (lane-txset2). |
| 9645 | #[allow(clippy::too_many_arguments)] |
| 9646 | fn mc_trial_typed( |
| 9647 | plane: &Plane, |
| 9648 | x: usize, |
| 9649 | y: usize, |
| 9650 | side: usize, |
| 9651 | mv: (i32, i32), |
| 9652 | luma: bool, |
| 9653 | reference: &[u16], |
| 9654 | stride: usize, |
| 9655 | ref_width: usize, |
| 9656 | ref_height: usize, |
| 9657 | skip: bool, |
| 9658 | base_q_idx: u8, |
| 9659 | deadzone: f64, |
| 9660 | set: TxbSet, |
| 9661 | tx_type: TxType, |
| 9662 | fctx: &crate::decode::FrameCtx, |
| 9663 | ) -> Trial { |
| 9664 | let x_q4 = mv_to_q4(x, mv.1, luma); |
| 9665 | let y_q4 = mv_to_q4(y, mv.0, luma); |
| 9666 | // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that |
| 9667 | // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is |
| 9668 | // 8-bit only this round, see `intra_predict_u8`'s doc comment). |
| 9669 | // lane-av1speed: both buffers are per-candidate scratch on the hottest |
| 9670 | // path in the encoder, so they live on the stack -- `side` is at most |
| 9671 | // `BLOCK` (32) for luma and half that for chroma. Two heap allocations |
| 9672 | // per motion-compensated trial otherwise. |
| 9673 | let mut prediction16 = [0u16; BLOCK * BLOCK]; |
| 9674 | let prediction16 = &mut prediction16[..side * side]; |
| 9675 | mc::predict( |
| 9676 | reference, |
| 9677 | stride, |
| 9678 | ref_width, |
| 9679 | ref_height, |
| 9680 | x_q4, |
| 9681 | y_q4, |
| 9682 | side, |
| 9683 | side, |
| 9684 | prediction16, fctx, |
| 9685 | ); |
| 9686 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 9687 | let prediction = &mut prediction[..side * side]; |
| 9688 | for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) { |
| 9689 | *dst = src as u8; |
| 9690 | } |
| 9691 | plane.code_from_prediction_typed( |
| 9692 | x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type, |
| 9693 | ) |
| 9694 | } |
| 9695 | |
| 9696 | /// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both |
| 9697 | /// references predict into the `CONV_BUF` intermediate domain |
| 9698 | /// ([`mc::predict_compound_intermediate`]) and are blended by |
| 9699 | /// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly |
| 9700 | /// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1` |
| 9701 | /// block, so the encoder's reconstruction is the decoder's. |
| 9702 | #[allow(clippy::too_many_arguments)] |
| 9703 | fn mc_trial_compound( |
| 9704 | plane: &Plane, |
| 9705 | x: usize, |
| 9706 | y: usize, |
| 9707 | side: usize, |
| 9708 | mvs: ((i32, i32), (i32, i32)), |
| 9709 | luma: bool, |
| 9710 | ref0: (&[u16], usize, usize, usize), |
| 9711 | ref1: (&[u16], usize, usize, usize), |
| 9712 | base_q_idx: u8, |
| 9713 | deadzone: f64, |
| 9714 | set: TxbSet, |
| 9715 | fctx: &crate::decode::FrameCtx, |
| 9716 | ) -> Trial { |
| 9717 | mc_trial_compound_typed( |
| 9718 | plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx, |
| 9719 | ) |
| 9720 | } |
| 9721 | |
| 9722 | /// [`mc_trial_compound`] coding its residual with a named transform type |
| 9723 | /// (lane-txset2). |
| 9724 | #[allow(clippy::too_many_arguments)] |
| 9725 | fn mc_trial_compound_typed( |
| 9726 | plane: &Plane, |
| 9727 | x: usize, |
| 9728 | y: usize, |
| 9729 | side: usize, |
| 9730 | (mv0, mv1): ((i32, i32), (i32, i32)), |
| 9731 | luma: bool, |
| 9732 | ref0: (&[u16], usize, usize, usize), |
| 9733 | ref1: (&[u16], usize, usize, usize), |
| 9734 | base_q_idx: u8, |
| 9735 | deadzone: f64, |
| 9736 | set: TxbSet, |
| 9737 | tx_type: TxType, |
| 9738 | fctx: &crate::decode::FrameCtx, |
| 9739 | ) -> Trial { |
| 9740 | let mut inter0 = [0i32; BLOCK * BLOCK]; |
| 9741 | let mut inter1 = [0i32; BLOCK * BLOCK]; |
| 9742 | let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]); |
| 9743 | for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] { |
| 9744 | mc::predict_compound_intermediate( |
| 9745 | r.0, |
| 9746 | r.1, |
| 9747 | r.2, |
| 9748 | r.3, |
| 9749 | mv_to_q4(x, mv.1, luma), |
| 9750 | mv_to_q4(y, mv.0, luma), |
| 9751 | mc::REF_NO_SCALE, |
| 9752 | side, |
| 9753 | side, |
| 9754 | fctx.interp_filter.get(), |
| 9755 | fctx.interp_filter.get(), |
| 9756 | dst, fctx, |
| 9757 | ); |
| 9758 | } |
| 9759 | let mut blended16 = [0u16; BLOCK * BLOCK]; |
| 9760 | let blended16 = &mut blended16[..side * side]; |
| 9761 | mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx); |
| 9762 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 9763 | let prediction = &mut prediction[..side * side]; |
| 9764 | for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { |
| 9765 | *dst = src as u8; |
| 9766 | } |
| 9767 | plane.code_from_prediction_typed( |
| 9768 | x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type, |
| 9769 | ) |
| 9770 | } |
| 9771 | |
| 9772 | /// Codes one 32x32 block of an inter frame as whichever costs least of: each |
| 9773 | /// intra mode [`Search::modes`] offers (predicted exactly as a key frame's |
| 9774 | /// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by |
| 9775 | /// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates |
| 9776 | /// coding a real residual (`skip: false`) whenever one prices out cheaper |
| 9777 | /// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s |
| 9778 | /// missing inter `tx_type` symbol (the desync this function's candidates |
| 9779 | /// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is |
| 9780 | /// fixed. |
| 9781 | /// |
| 9782 | /// The symbol costs this ranks candidates by use fixed contexts (0) for |
| 9783 | /// `skip`, `intra_inter` and `single_ref` — the tile writer's actual |
| 9784 | /// contexts for those come from its own neighbour bookkeeping |
| 9785 | /// (`tile::Neighbours`), which is private to that module and not worth |
| 9786 | /// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/ |
| 9787 | /// `drl_mode` contexts come straight from `stack`, which is exact, because |
| 9788 | /// [`find_mv_stack`] is public and this function is handed the same `MvStack` |
| 9789 | /// the tile writer derives from the same grid state. |
| 9790 | #[allow(clippy::too_many_arguments)] |
| 9791 | /// One prediction of `side` x `side` samples from `reference`, as `u8` -- |
| 9792 | /// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is |
| 9793 | /// four times the stack scratch that function sizes for [`BLOCK`]. |
| 9794 | fn predict_u8( |
| 9795 | reference: &[u16], |
| 9796 | stride: usize, |
| 9797 | ref_width: usize, |
| 9798 | ref_height: usize, |
| 9799 | (x, y): (usize, usize), |
| 9800 | side: usize, |
| 9801 | mv: (i32, i32), |
| 9802 | luma: bool, |
| 9803 | fctx: &crate::decode::FrameCtx, |
| 9804 | ) -> Vec<u8> { |
| 9805 | let mut prediction = vec![0u16; side * side]; |
| 9806 | mc::predict( |
| 9807 | reference, |
| 9808 | stride, |
| 9809 | ref_width, |
| 9810 | ref_height, |
| 9811 | mv_to_q4(x, mv.1, luma), |
| 9812 | mv_to_q4(y, mv.0, luma), |
| 9813 | side, |
| 9814 | side, |
| 9815 | &mut prediction, |
| 9816 | fctx, |
| 9817 | ); |
| 9818 | prediction.iter().map(|&v| v as u8).collect() |
| 9819 | } |
| 9820 | |
| 9821 | /// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's |
| 9822 | /// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both |
| 9823 | /// references predict into the `CONV_BUF` intermediate domain and are blended |
| 9824 | /// at the simple-average split `(8, 8)`, the same path (and so the same |
| 9825 | /// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes. |
| 9826 | fn predict_compound_u8( |
| 9827 | ref0: (&[u16], usize, usize, usize), |
| 9828 | ref1: (&[u16], usize, usize, usize), |
| 9829 | (x, y): (usize, usize), |
| 9830 | side: usize, |
| 9831 | (mv0, mv1): ((i32, i32), (i32, i32)), |
| 9832 | luma: bool, |
| 9833 | fctx: &crate::decode::FrameCtx, |
| 9834 | ) -> Vec<u8> { |
| 9835 | let mut inter = [vec![0i32; side * side], vec![0i32; side * side]]; |
| 9836 | for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) { |
| 9837 | mc::predict_compound_intermediate( |
| 9838 | r.0, |
| 9839 | r.1, |
| 9840 | r.2, |
| 9841 | r.3, |
| 9842 | mv_to_q4(x, mv.1, luma), |
| 9843 | mv_to_q4(y, mv.0, luma), |
| 9844 | mc::REF_NO_SCALE, |
| 9845 | side, |
| 9846 | side, |
| 9847 | fctx.interp_filter.get(), |
| 9848 | fctx.interp_filter.get(), |
| 9849 | dst, fctx, |
| 9850 | ); |
| 9851 | } |
| 9852 | let mut blended = vec![0u16; side * side]; |
| 9853 | mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx); |
| 9854 | blended.iter().map(|&v| v as u8).collect() |
| 9855 | } |
| 9856 | |
| 9857 | /// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128 |
| 9858 | /// superblock root, the lever cen3's L1 asks for -- one block, one mode and |
| 9859 | /// one motion vector where the four 64x64 roots below spend four of each. |
| 9860 | /// |
| 9861 | /// SKIP only (`residual: false`): a 128x128 block's residual is four |
| 9862 | /// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu |
| 9863 | /// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a |
| 9864 | /// path for -- offering one here would price a block |
| 9865 | /// [`crate::tile::write_inter_block_128`] refuses. Single reference only for |
| 9866 | /// the same reason: the compound arm at this size is untested against the |
| 9867 | /// writer's own `write_compound_block` window. |
| 9868 | /// |
| 9869 | /// Only a root whose whole 128x128 lies inside the true frame AND inside |
| 9870 | /// this tile is offered: the writer's own root codes `PARTITION_NONE` only |
| 9871 | /// where the spec's `has_rows`/`has_cols` are both set, and a straddling |
| 9872 | /// block would have to be ranked over its inside part alone. |
| 9873 | /// |
| 9874 | /// Returns `(cost, lambda, block, reconstruction)` -- the cost already |
| 9875 | /// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it |
| 9876 | /// against the four superblocks plus the SPLIT symbol. |
| 9877 | #[allow(clippy::too_many_arguments)] |
| 9878 | fn search_root_128( |
| 9879 | luma: &mut Plane, |
| 9880 | chroma: &mut [Plane; 2], |
| 9881 | grid: &crate::mvstack::MiGrid, |
| 9882 | (root_r, root_c): (usize, usize), |
| 9883 | // The 32x32-block grid this tile's `blocks` vector is indexed on. |
| 9884 | (rows, cols): (usize, usize), |
| 9885 | // The frame's own mode-info grid, which bounds the root. |
| 9886 | (mi_cols, mi_rows): (u32, u32), |
| 9887 | search: Search<'_>, |
| 9888 | tpl_factors: &Option<Vec<f64>>, |
| 9889 | sb_q: Option<&Vec<u8>>, |
| 9890 | sb_cols: usize, |
| 9891 | tpl_cells_x: usize, |
| 9892 | base_q_idx: u8, |
| 9893 | // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan, |
| 9894 | // zero when it does not -- what [`delta_q_bits_at_root`] prices with. |
| 9895 | dq_res: i32, |
| 9896 | reference: &Picture, |
| 9897 | // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window, |
| 9898 | // built by the caller off the same grid the tile writer rebuilds its |
| 9899 | // stack from (empty unless the frame carries `reference_select` and |
| 9900 | // [`b128_compound`] is on). |
| 9901 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 9902 | fctx: &crate::decode::FrameCtx, |
| 9903 | ) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> { |
| 9904 | const SIDE: usize = SUPERBLOCK * 2; |
| 9905 | const SIDE_MI: usize = SIDE / 4; |
| 9906 | let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); |
| 9907 | let (mi_row, mi_col) = (root_r * 16, root_c * 16); |
| 9908 | if root_r * 2 + 3 >= rows |
| 9909 | || root_c * 2 + 3 >= cols |
| 9910 | || (mi_row + SIDE_MI) as u32 > mi_rows |
| 9911 | || (mi_col + SIDE_MI) as u32 > mi_cols |
| 9912 | || x128 + SIDE > luma.true_width |
| 9913 | || y128 + SIDE > luma.true_height |
| 9914 | { |
| 9915 | return None; |
| 9916 | } |
| 9917 | // One lambda for the whole root, the mean of what its four superblocks |
| 9918 | // would each be searched at -- the 128-vs-four comparison weighs one cost |
| 9919 | // against four, so both sides have to be priced at the same lambda (the |
| 9920 | // same rule the 64 root's own mean-of-sixteen tpl cells follows). |
| 9921 | let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) { |
| 9922 | (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda, |
| 9923 | (None, Some(f)) => { |
| 9924 | let mean = (0..16) |
| 9925 | .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) |
| 9926 | .sum::<f64>() |
| 9927 | / 16.0; |
| 9928 | search.lambda * mean |
| 9929 | } |
| 9930 | (None, None) => search.lambda, |
| 9931 | }; |
| 9932 | let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)] |
| 9933 | .iter() |
| 9934 | .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc)) |
| 9935 | .sum::<f64>() |
| 9936 | / 4.0; |
| 9937 | // The qindex this root is really quantized at: the delta_q unit is the |
| 9938 | // 128 superblock, so the root's own top-left cell is the one coded |
| 9939 | // (lane-b128m), and the residual arm below has to quantize at exactly it. |
| 9940 | let root_search = Search { |
| 9941 | lambda, |
| 9942 | ..match sb_q { |
| 9943 | Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search), |
| 9944 | None => search, |
| 9945 | } |
| 9946 | }; |
| 9947 | let stack = find_mv_stack( |
| 9948 | grid, |
| 9949 | mi_row, |
| 9950 | mi_col, |
| 9951 | SIDE_MI, |
| 9952 | SIDE_MI, |
| 9953 | LAST_FRAME, |
| 9954 | mi_cols as usize, |
| 9955 | mi_rows as usize, |
| 9956 | ); |
| 9957 | let base = snapshot(luma, chroma, (x128, y128), SIDE); |
| 9958 | let found = search_skip_64( |
| 9959 | luma, |
| 9960 | chroma, |
| 9961 | (x128, y128), |
| 9962 | (SIDE, SIDE), |
| 9963 | &root_search, |
| 9964 | false, |
| 9965 | reference, |
| 9966 | &stack, |
| 9967 | compound, |
| 9968 | fctx, |
| 9969 | ); |
| 9970 | let (mut cost, mut block) = found?; |
| 9971 | if block.inter.is_some_and(|i| i.ref1.is_some()) { |
| 9972 | B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 9973 | } |
| 9974 | // lane-b128r: the same prediction with a REAL residual, priced against |
| 9975 | // the skip arm the search just committed to the planes (which IS the |
| 9976 | // winner's prediction, sample for sample). The block's residual is four |
| 9977 | // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its |
| 9978 | // own TX_32X32 chroma pair -- so it is coded here as twelve trials at |
| 9979 | // sides the forward network already reaches, never as one 128-point |
| 9980 | // transform. Var-tx depth 0 only: the four units ARE the tree's leaves. |
| 9981 | // |
| 9982 | // The four `txfm_partition` symbols the writer codes for them are not |
| 9983 | // priced, exactly as the 64 root does not price its own (their contexts |
| 9984 | // are only known at write time); at four symbols a root this is under a |
| 9985 | // bit against residuals of hundreds. |
| 9986 | if b128_residual() && block.skip { |
| 9987 | // Every unit's coded level grid is 32x32 (a 64-point transform codes |
| 9988 | // only its top-left corner), packed per plane into one 64-wide grid |
| 9989 | // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout |
| 9990 | // `write_inter_block_128` slices back out in the same chunk order. |
| 9991 | let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]]; |
| 9992 | let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new(); |
| 9993 | let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64); |
| 9994 | for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] { |
| 9995 | let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK); |
| 9996 | let (cx, cy) = (px / 2, py / 2); |
| 9997 | let half = SUPERBLOCK / 2; |
| 9998 | let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK); |
| 9999 | let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half); |
| 10000 | let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half); |
| 10001 | sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y) |
| 10002 | + chroma[0].block_sse(cx, cy, half, &pred_u) |
| 10003 | + chroma[1].block_sse(cx, cy, half, &pred_v); |
| 10004 | let trials = [ |
| 10005 | luma.code_from_prediction( |
| 10006 | px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx, |
| 10007 | root_search.deadzone, TxbSet::Luma64, |
| 10008 | ), |
| 10009 | chroma[0].code_from_prediction( |
| 10010 | cx, cy, half, &pred_u, false, root_search.base_q_idx, |
| 10011 | root_search.deadzone, TxbSet::Chroma32, |
| 10012 | ), |
| 10013 | chroma[1].code_from_prediction( |
| 10014 | cx, cy, half, &pred_v, false, root_search.base_q_idx, |
| 10015 | root_search.deadzone, TxbSet::Chroma32, |
| 10016 | ), |
| 10017 | ]; |
| 10018 | for (plane, trial) in trials.iter().enumerate() { |
| 10019 | sse_res += trial.sse; |
| 10020 | coeff_bits += trial.bits; |
| 10021 | for row in 0..32 { |
| 10022 | packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32] |
| 10023 | .copy_from_slice(&trial.levels[row * 32..][..32]); |
| 10024 | } |
| 10025 | } |
| 10026 | chunks.push(((cr, cc), trials)); |
| 10027 | } |
| 10028 | // `cost` is the skip arm's own `sse + lambda * syntax`; the residual |
| 10029 | // arm pays the same syntax with `skip` coded 0 instead of 1, plus its |
| 10030 | // coefficients. |
| 10031 | let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true); |
| 10032 | let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits); |
| 10033 | if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) { |
| 10034 | B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10035 | for ((cr, cc), trials) in &chunks { |
| 10036 | let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK); |
| 10037 | let half = SUPERBLOCK / 2; |
| 10038 | luma.commit(px, py, SUPERBLOCK, &trials[0]); |
| 10039 | chroma[0].commit(px / 2, py / 2, half, &trials[1]); |
| 10040 | chroma[1].commit(px / 2, py / 2, half, &trials[2]); |
| 10041 | } |
| 10042 | cost = res_cost; |
| 10043 | block.skip = false; |
| 10044 | block.tx_depth = 0; |
| 10045 | block.luma_tx_types = Vec::new(); |
| 10046 | block.luma = coeffs(&packed[0], 64); |
| 10047 | block.u = coeffs(&packed[1], 64); |
| 10048 | block.v = coeffs(&packed[2], 64); |
| 10049 | } |
| 10050 | } |
| 10051 | let after = snapshot(luma, chroma, (x128, y128), SIDE); |
| 10052 | restore(luma, chroma, (x128, y128), SIDE, &base); |
| 10053 | // lane-rectdq: a SKIPPED whole-superblock root is the one shape that |
| 10054 | // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the |
| 10055 | // residual arm above codes it like every other block does. |
| 10056 | let dq = if block.skip { |
| 10057 | 0.0 |
| 10058 | } else { |
| 10059 | delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c)) |
| 10060 | }; |
| 10061 | Some(( |
| 10062 | cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq), |
| 10063 | lambda, |
| 10064 | block, |
| 10065 | after, |
| 10066 | )) |
| 10067 | } |
| 10068 | |
| 10069 | /// lane-rectres: one rect/AB piece's REAL residual, priced against the skip |
| 10070 | /// arm the caller's [`search_skip_64`] just committed to the planes (which |
| 10071 | /// IS the winner's prediction, sample for sample -- the same rule |
| 10072 | /// [`search_root_128`]'s residual arm runs at the NONE root). The piece's |
| 10073 | /// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64 |
| 10074 | /// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square), |
| 10075 | /// each trial at sides the forward network already reaches, never a |
| 10076 | /// rectangular transform; var-tx depth 0 only -- the units ARE the tree's |
| 10077 | /// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads. |
| 10078 | /// |
| 10079 | /// The depth-0 `txfm_partition` symbols the writer codes for the units are |
| 10080 | /// not priced, exactly as [`search_root_128`] does not price its four (their |
| 10081 | /// contexts are only known at write time); at two symbols a half this is |
| 10082 | /// under a bit against residuals of hundreds. On a win (or under the witness |
| 10083 | /// force) the trials are committed to the planes, `block` is flipped to |
| 10084 | /// carry the packed level grids [`crate::tile::write_inter_block_128_rect`] |
| 10085 | /// slices back out, and the new cost is returned; otherwise `cost` passes |
| 10086 | /// through untouched. Counts [`take_b128_rectres_hits`] on a win. |
| 10087 | #[allow(clippy::too_many_arguments)] |
| 10088 | fn search_rect_residual( |
| 10089 | luma: &mut Plane, |
| 10090 | chroma: &mut [Plane; 2], |
| 10091 | // The piece's own top-left, in luma samples. |
| 10092 | (px, py): (usize, usize), |
| 10093 | // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square. |
| 10094 | (w, h): (usize, usize), |
| 10095 | cost: f64, |
| 10096 | lambda: f64, |
| 10097 | search: &Search<'_>, |
| 10098 | // The piece's own mv stack, for the skip symbol's cost either way. |
| 10099 | stack: &crate::mvstack::MvStack, |
| 10100 | block: &mut BlockCoeffs, |
| 10101 | ) -> f64 { |
| 10102 | /// The 64x64 "mu" chunk side, luma; chroma halves it. |
| 10103 | const MU: usize = SUPERBLOCK; |
| 10104 | let chunks: [(usize, usize); 2] = match (w, h) { |
| 10105 | (128, 64) => [(0, 0), (0, 1)], |
| 10106 | (64, 128) => [(0, 0), (1, 0)], |
| 10107 | _ => [(0, 0), (0, 0)], |
| 10108 | }; |
| 10109 | let n = if w.max(h) > MU { 2 } else { 1 }; |
| 10110 | // Every unit's coded level grid is 32x32 (a 64-point transform codes |
| 10111 | // only its top-left corner), packed per plane into one 64-wide grid with |
| 10112 | // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices |
| 10113 | // back out in the same chunk order. |
| 10114 | let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]]; |
| 10115 | let mut sse_skip = 0.0f64; |
| 10116 | let mut sse_res = 0.0f64; |
| 10117 | let mut coeff_bits = 0.0f64; |
| 10118 | let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n); |
| 10119 | for &(cr, cc) in &chunks[..n] { |
| 10120 | let (cxx, cyy) = (px + cc * MU, py + cr * MU); |
| 10121 | let (cx, cy) = (cxx / 2, cyy / 2); |
| 10122 | let half = MU / 2; |
| 10123 | let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU); |
| 10124 | let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half); |
| 10125 | let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half); |
| 10126 | sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y) |
| 10127 | + chroma[0].block_sse(cx, cy, half, &pred_u) |
| 10128 | + chroma[1].block_sse(cx, cy, half, &pred_v); |
| 10129 | let trials = [ |
| 10130 | luma.code_from_prediction( |
| 10131 | cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone, |
| 10132 | TxbSet::Luma64, |
| 10133 | ), |
| 10134 | chroma[0].code_from_prediction( |
| 10135 | cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone, |
| 10136 | TxbSet::Chroma32, |
| 10137 | ), |
| 10138 | chroma[1].code_from_prediction( |
| 10139 | cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone, |
| 10140 | TxbSet::Chroma32, |
| 10141 | ), |
| 10142 | ]; |
| 10143 | for (plane, trial) in trials.iter().enumerate() { |
| 10144 | sse_res += trial.sse; |
| 10145 | coeff_bits += trial.bits; |
| 10146 | for row in 0..32 { |
| 10147 | packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32] |
| 10148 | .copy_from_slice(&trial.levels[row * 32..][..32]); |
| 10149 | } |
| 10150 | } |
| 10151 | trials_per_chunk.push(trials); |
| 10152 | } |
| 10153 | // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm |
| 10154 | // pays the same syntax with `skip` coded 0 instead of 1, plus its |
| 10155 | // coefficients. |
| 10156 | let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true); |
| 10157 | let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits); |
| 10158 | if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) { |
| 10159 | for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) { |
| 10160 | let (cxx, cyy) = (px + cc * MU, py + cr * MU); |
| 10161 | let (cx, cy) = (cxx / 2, cyy / 2); |
| 10162 | let half = MU / 2; |
| 10163 | luma.commit(cxx, cyy, MU, &trials[0]); |
| 10164 | chroma[0].commit(cx, cy, half, &trials[1]); |
| 10165 | chroma[1].commit(cx, cy, half, &trials[2]); |
| 10166 | } |
| 10167 | block.skip = false; |
| 10168 | block.tx_depth = 0; |
| 10169 | block.luma_tx_types = Vec::new(); |
| 10170 | block.luma = coeffs(&packed[0], 64); |
| 10171 | block.u = coeffs(&packed[1], 64); |
| 10172 | block.v = coeffs(&packed[2], 64); |
| 10173 | B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10174 | res_cost |
| 10175 | } else { |
| 10176 | cost |
| 10177 | } |
| 10178 | } |
| 10179 | |
| 10180 | /// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole |
| 10181 | /// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the |
| 10182 | /// shipped NONE machinery halved. Skip-only by default, single reference or |
| 10183 | /// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual |
| 10184 | /// ([`search_rect_residual`]) -- exactly what |
| 10185 | /// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block` |
| 10186 | /// reads at `sb128_rect`. |
| 10187 | /// |
| 10188 | /// The FIRST half is published into `grid` before the second is searched -- |
| 10189 | /// the writer publishes it too, so a second half searched against the stale |
| 10190 | /// grid would be priced (and its mv predicted) off a stack the decoder never |
| 10191 | /// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and |
| 10192 | /// both planes are put back before returning; the caller re-applies the |
| 10193 | /// winner. |
| 10194 | /// |
| 10195 | /// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already |
| 10196 | /// carrying the root's own partition symbol so it ranks against |
| 10197 | /// [`search_root_128`] and against the four superblocks below. |
| 10198 | #[allow(clippy::too_many_arguments)] |
| 10199 | fn search_root_128_rect( |
| 10200 | luma: &mut Plane, |
| 10201 | chroma: &mut [Plane; 2], |
| 10202 | grid: &mut crate::mvstack::MiGrid, |
| 10203 | (root_r, root_c): (usize, usize), |
| 10204 | (rows, cols): (usize, usize), |
| 10205 | (mi_cols, mi_rows): (u32, u32), |
| 10206 | search: Search<'_>, |
| 10207 | tpl_factors: &Option<Vec<f64>>, |
| 10208 | sb_q: Option<&Vec<u8>>, |
| 10209 | sb_cols: usize, |
| 10210 | tpl_cells_x: usize, |
| 10211 | base_q_idx: u8, |
| 10212 | // lane-rectdq: see [`search_root_128`]'s own `dq_res`. |
| 10213 | dq_res: i32, |
| 10214 | reference: &Picture, |
| 10215 | // The `LAST` + extra-reference pairs offered at this root; only the |
| 10216 | // reference and its picture are read here, since each HALF derives its |
| 10217 | // own compound stack at its own rectangular window. |
| 10218 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 10219 | horz: bool, |
| 10220 | fctx: &crate::decode::FrameCtx, |
| 10221 | ) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> { |
| 10222 | const SIDE: usize = SUPERBLOCK * 2; |
| 10223 | const SIDE_MI: usize = SIDE / 4; |
| 10224 | let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); |
| 10225 | let (mi_row, mi_col) = (root_r * 16, root_c * 16); |
| 10226 | if root_r * 2 + 3 >= rows |
| 10227 | || root_c * 2 + 3 >= cols |
| 10228 | || (mi_row + SIDE_MI) as u32 > mi_rows |
| 10229 | || (mi_col + SIDE_MI) as u32 > mi_cols |
| 10230 | || x128 + SIDE > luma.true_width |
| 10231 | || y128 + SIDE > luma.true_height |
| 10232 | { |
| 10233 | return None; |
| 10234 | } |
| 10235 | // The root's own lambda, the mean of its four superblocks' -- the same |
| 10236 | // one [`search_root_128`] prices with, so the three root candidates and |
| 10237 | // the four-superblock arm are all comparable. |
| 10238 | let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) { |
| 10239 | (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda, |
| 10240 | (None, Some(f)) => { |
| 10241 | let mean = (0..16) |
| 10242 | .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) |
| 10243 | .sum::<f64>() |
| 10244 | / 16.0; |
| 10245 | search.lambda * mean |
| 10246 | } |
| 10247 | (None, None) => search.lambda, |
| 10248 | }; |
| 10249 | let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)] |
| 10250 | .iter() |
| 10251 | .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc)) |
| 10252 | .sum::<f64>() |
| 10253 | / 4.0; |
| 10254 | let root_search = Search { |
| 10255 | lambda, |
| 10256 | ..match sb_q { |
| 10257 | Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search), |
| 10258 | None => search, |
| 10259 | } |
| 10260 | }; |
| 10261 | let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) }; |
| 10262 | let (w_mi, h_mi) = (w / 4, h / 4); |
| 10263 | let base = snapshot(luma, chroma, (x128, y128), SIDE); |
| 10264 | let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI); |
| 10265 | let mut cost = 0.0f64; |
| 10266 | let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2); |
| 10267 | for i in 0..2usize { |
| 10268 | let (mr, mc) = if horz { |
| 10269 | (mi_row + i * 16, mi_col) |
| 10270 | } else { |
| 10271 | (mi_row, mi_col + i * 16) |
| 10272 | }; |
| 10273 | let stack = find_mv_stack( |
| 10274 | grid, |
| 10275 | mr, |
| 10276 | mc, |
| 10277 | w_mi, |
| 10278 | h_mi, |
| 10279 | LAST_FRAME, |
| 10280 | mi_cols as usize, |
| 10281 | mi_rows as usize, |
| 10282 | ); |
| 10283 | let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound |
| 10284 | .iter() |
| 10285 | .map(|&(r, pic, _)| { |
| 10286 | ( |
| 10287 | r, |
| 10288 | pic, |
| 10289 | crate::mvstack::find_mv_stack_compound( |
| 10290 | grid, |
| 10291 | mr, |
| 10292 | mc, |
| 10293 | w_mi, |
| 10294 | h_mi, |
| 10295 | (LAST_FRAME, r), |
| 10296 | mi_cols as usize, |
| 10297 | mi_rows as usize, |
| 10298 | grid.sign_bias_table(), |
| 10299 | &[(0, 0); 7], |
| 10300 | None, |
| 10301 | ), |
| 10302 | ) |
| 10303 | }) |
| 10304 | .collect(); |
| 10305 | let found = search_skip_64( |
| 10306 | luma, |
| 10307 | chroma, |
| 10308 | (mc * 4, mr * 4), |
| 10309 | (w, h), |
| 10310 | &root_search, |
| 10311 | false, |
| 10312 | reference, |
| 10313 | &stack, |
| 10314 | &half_compound, |
| 10315 | fctx, |
| 10316 | ); |
| 10317 | match found { |
| 10318 | Some((mut c, mut block)) => { |
| 10319 | // lane-rectres: the same prediction with a REAL residual, |
| 10320 | // priced against the skip arm the search just committed to |
| 10321 | // the planes -- two 64x64 mu chunks for a half. |
| 10322 | if rectres() && block.skip { |
| 10323 | c = search_rect_residual( |
| 10324 | luma, |
| 10325 | chroma, |
| 10326 | (mc * 4, mr * 4), |
| 10327 | (w, h), |
| 10328 | c, |
| 10329 | root_search.lambda, |
| 10330 | &root_search, |
| 10331 | &stack, |
| 10332 | &mut block, |
| 10333 | ); |
| 10334 | } |
| 10335 | cost += c; |
| 10336 | record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip); |
| 10337 | halves.push(block); |
| 10338 | } |
| 10339 | None => { |
| 10340 | restore(luma, chroma, (x128, y128), SIDE, &base); |
| 10341 | grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); |
| 10342 | return None; |
| 10343 | } |
| 10344 | } |
| 10345 | } |
| 10346 | let after = snapshot(luma, chroma, (x128, y128), SIDE); |
| 10347 | restore(luma, chroma, (x128, y128), SIDE, &base); |
| 10348 | grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); |
| 10349 | let symbol = if horz { 1 } else { 2 }; |
| 10350 | let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?; |
| 10351 | // lane-rectdq: the FIRST half sits at the root's own mode-info origin and |
| 10352 | // codes the delta_q group whether it is skipped or not |
| 10353 | // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second |
| 10354 | // half is at a non-origin mi and codes none. |
| 10355 | let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c)); |
| 10356 | Some(( |
| 10357 | cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq), |
| 10358 | lambda, |
| 10359 | [b0, b1], |
| 10360 | after, |
| 10361 | )) |
| 10362 | } |
| 10363 | |
| 10364 | /// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and |
| 10365 | /// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the |
| 10366 | /// decoder's own). Each piece is priced through the same `search_skip_64` |
| 10367 | /// the NONE and HORZ/VERT arms use, at its own footprint, and is published |
| 10368 | /// into `grid` before the next is searched -- the writer publishes it too, so |
| 10369 | /// a later piece searched against a stale grid would be priced (and its mv |
| 10370 | /// predicted) off a stack the decoder never derives (class |
| 10371 | /// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes |
| 10372 | /// are put back before returning; the caller re-applies the winner. |
| 10373 | /// |
| 10374 | /// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a |
| 10375 | /// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where |
| 10376 | /// libaom's own AB shapes earn their keep. |
| 10377 | /// |
| 10378 | /// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost |
| 10379 | /// already carrying the root's own partition symbol so it ranks against the |
| 10380 | /// other root candidates and against the four superblocks below. |
| 10381 | #[allow(clippy::too_many_arguments)] |
| 10382 | fn search_root_128_ab( |
| 10383 | luma: &mut Plane, |
| 10384 | chroma: &mut [Plane; 2], |
| 10385 | grid: &mut crate::mvstack::MiGrid, |
| 10386 | (root_r, root_c): (usize, usize), |
| 10387 | (rows, cols): (usize, usize), |
| 10388 | (mi_cols, mi_rows): (u32, u32), |
| 10389 | search: Search<'_>, |
| 10390 | tpl_factors: &Option<Vec<f64>>, |
| 10391 | sb_q: Option<&Vec<u8>>, |
| 10392 | sb_cols: usize, |
| 10393 | tpl_cells_x: usize, |
| 10394 | base_q_idx: u8, |
| 10395 | reference: &Picture, |
| 10396 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 10397 | // The partition symbol, 4..=7. |
| 10398 | symbol: usize, |
| 10399 | fctx: &crate::decode::FrameCtx, |
| 10400 | ) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> { |
| 10401 | const SIDE: usize = SUPERBLOCK * 2; |
| 10402 | const SIDE_MI: usize = SIDE / 4; |
| 10403 | let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); |
| 10404 | let (mi_row, mi_col) = (root_r * 16, root_c * 16); |
| 10405 | if root_r * 2 + 3 >= rows |
| 10406 | || root_c * 2 + 3 >= cols |
| 10407 | || (mi_row + SIDE_MI) as u32 > mi_rows |
| 10408 | || (mi_col + SIDE_MI) as u32 > mi_cols |
| 10409 | || x128 + SIDE > luma.true_width |
| 10410 | || y128 + SIDE > luma.true_height |
| 10411 | { |
| 10412 | return None; |
| 10413 | } |
| 10414 | // The root's own lambda, the mean of its four superblocks' -- the same one |
| 10415 | // [`search_root_128`] prices with, so every root candidate and the |
| 10416 | // four-superblock arm are comparable. |
| 10417 | let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) { |
| 10418 | (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda, |
| 10419 | (None, Some(f)) => { |
| 10420 | let mean = (0..16) |
| 10421 | .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) |
| 10422 | .sum::<f64>() |
| 10423 | / 16.0; |
| 10424 | search.lambda * mean |
| 10425 | } |
| 10426 | (None, None) => search.lambda, |
| 10427 | }; |
| 10428 | let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)] |
| 10429 | .iter() |
| 10430 | .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc)) |
| 10431 | .sum::<f64>() |
| 10432 | / 4.0; |
| 10433 | let root_search = Search { |
| 10434 | lambda, |
| 10435 | ..match sb_q { |
| 10436 | Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search), |
| 10437 | None => search, |
| 10438 | } |
| 10439 | }; |
| 10440 | let base = snapshot(luma, chroma, (x128, y128), SIDE); |
| 10441 | let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI); |
| 10442 | let mut cost = 0.0f64; |
| 10443 | let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3); |
| 10444 | for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) { |
| 10445 | let (w_mi, h_mi) = (w / 4, h / 4); |
| 10446 | let stack = find_mv_stack( |
| 10447 | grid, |
| 10448 | mr, |
| 10449 | mc, |
| 10450 | w_mi, |
| 10451 | h_mi, |
| 10452 | LAST_FRAME, |
| 10453 | mi_cols as usize, |
| 10454 | mi_rows as usize, |
| 10455 | ); |
| 10456 | let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound |
| 10457 | .iter() |
| 10458 | .map(|&(r, pic, _)| { |
| 10459 | ( |
| 10460 | r, |
| 10461 | pic, |
| 10462 | crate::mvstack::find_mv_stack_compound( |
| 10463 | grid, |
| 10464 | mr, |
| 10465 | mc, |
| 10466 | w_mi, |
| 10467 | h_mi, |
| 10468 | (LAST_FRAME, r), |
| 10469 | mi_cols as usize, |
| 10470 | mi_rows as usize, |
| 10471 | grid.sign_bias_table(), |
| 10472 | &[(0, 0); 7], |
| 10473 | None, |
| 10474 | ), |
| 10475 | ) |
| 10476 | }) |
| 10477 | .collect(); |
| 10478 | let found = search_skip_64( |
| 10479 | luma, |
| 10480 | chroma, |
| 10481 | (mc * 4, mr * 4), |
| 10482 | (w, h), |
| 10483 | &root_search, |
| 10484 | false, |
| 10485 | reference, |
| 10486 | &stack, |
| 10487 | &piece_compound, |
| 10488 | fctx, |
| 10489 | ); |
| 10490 | match found { |
| 10491 | Some((mut c, mut block)) => { |
| 10492 | // lane-rectres: the same prediction with a REAL residual, |
| 10493 | // priced against the skip arm the search just committed to |
| 10494 | // the planes -- one mu chunk for a 64x64 square, two for a |
| 10495 | // half. The 64x64 squares are where libaom's own AB shapes |
| 10496 | // earn their keep. |
| 10497 | if rectres() && block.skip { |
| 10498 | c = search_rect_residual( |
| 10499 | luma, |
| 10500 | chroma, |
| 10501 | (mc * 4, mr * 4), |
| 10502 | (w, h), |
| 10503 | c, |
| 10504 | root_search.lambda, |
| 10505 | &root_search, |
| 10506 | &stack, |
| 10507 | &mut block, |
| 10508 | ); |
| 10509 | } |
| 10510 | cost += c; |
| 10511 | record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip); |
| 10512 | pieces.push(block); |
| 10513 | } |
| 10514 | None => { |
| 10515 | restore(luma, chroma, (x128, y128), SIDE, &base); |
| 10516 | grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); |
| 10517 | return None; |
| 10518 | } |
| 10519 | } |
| 10520 | } |
| 10521 | let after = snapshot(luma, chroma, (x128, y128), SIDE); |
| 10522 | restore(luma, chroma, (x128, y128), SIDE, &base); |
| 10523 | grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); |
| 10524 | let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?; |
| 10525 | Some(( |
| 10526 | cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol), |
| 10527 | lambda, |
| 10528 | [b0, b1, b2], |
| 10529 | after, |
| 10530 | )) |
| 10531 | } |
| 10532 | |
| 10533 | /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]): |
| 10534 | /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded |
| 10535 | /// SKIP, priced through the same `symbol_bits` path every other candidate |
| 10536 | /// uses. The winner's prediction is committed to the planes (it IS the |
| 10537 | /// reconstruction -- a skip block has no residual); the caller restores them |
| 10538 | /// if the four quadrants come out cheaper. |
| 10539 | /// |
| 10540 | /// `None` when no candidate could be coded at all (a `NEWMV` residual the |
| 10541 | /// writer cannot name is simply not offered, and the other modes always are, |
| 10542 | /// so this only happens if every candidate is refused). |
| 10543 | fn search_skip_64( |
| 10544 | luma: &mut Plane, |
| 10545 | chroma: &mut [Plane; 2], |
| 10546 | (x, y): (usize, usize), |
| 10547 | // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root, |
| 10548 | // twice that at the 128 one [`search_root_128`] drives (lane-b128), and |
| 10549 | // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`] |
| 10550 | // (lane-b128hv). Every trial below tiles it into squares of its SHORTER |
| 10551 | // side (one square when it is square, two otherwise), and the residual |
| 10552 | // arm is only ever asked for at 64 -- a 128 block's residual is four |
| 10553 | // TX_64X64 units the writer has no path for. |
| 10554 | (bw, bh): (usize, usize), |
| 10555 | search: &Search, |
| 10556 | // Whether the non-skip arm is priced at all ([`b64_residual`], and off on |
| 10557 | // screen content -- see that function's doc). |
| 10558 | residual: bool, |
| 10559 | reference: &Picture, |
| 10560 | stack: &MvStack, |
| 10561 | // The COMPOUND stack of each `LAST` + extra-reference pair at THIS |
| 10562 | // superblock's 16x16-mi window, built off the same grid the tile writer |
| 10563 | // rebuilds it from (empty unless the frame carries `reference_select`). |
| 10564 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 10565 | fctx: &crate::decode::FrameCtx, |
| 10566 | ) -> Option<(f64, BlockCoeffs)> { |
| 10567 | debug_assert!( |
| 10568 | (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual, |
| 10569 | "only a 64 root has a residual arm" |
| 10570 | ); |
| 10571 | // The square units every trial below is taken on: the block itself when |
| 10572 | // it is square, its two halves otherwise. Luma first (in raster order), |
| 10573 | // then each chroma plane over the same tiling at half the side -- which is |
| 10574 | // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh. |
| 10575 | let sq = bw.min(bh); |
| 10576 | let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize) |
| 10577 | .flat_map(|plane| { |
| 10578 | let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) }; |
| 10579 | (0..bh / sq).flat_map(move |j| { |
| 10580 | (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0)) |
| 10581 | }) |
| 10582 | }) |
| 10583 | .collect(); |
| 10584 | let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 10585 | let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 10586 | let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); |
| 10587 | // What every candidate pays whatever its vector: `skip` coded 1, then |
| 10588 | // `is_inter` coded 1, then the LAST chain above. |
| 10589 | let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits; |
| 10590 | let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo { |
| 10591 | ref1: None, |
| 10592 | mv1: (0, 0), |
| 10593 | ref_frame: crate::mvstack::LAST_FRAME, |
| 10594 | mode, |
| 10595 | mv, |
| 10596 | ref_mv_idx, |
| 10597 | }; |
| 10598 | let mut cands: Vec<(f64, InterInfo)> = vec![ |
| 10599 | ( |
| 10600 | not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 10601 | info_of(InterMode::NearestMv, stack.nearest_mv, 0), |
| 10602 | ), |
| 10603 | ( |
| 10604 | not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), |
| 10605 | info_of(InterMode::GlobalMv, (0, 0), 0), |
| 10606 | ), |
| 10607 | ]; |
| 10608 | let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); |
| 10609 | for idx in 1..=2usize { |
| 10610 | if let Some(e) = stack.entries.get(idx) { |
| 10611 | cands.push(( |
| 10612 | near_bits + drl_bits_for(stack, 1, idx), |
| 10613 | info_of(InterMode::NearMv, e.mv, idx as u8), |
| 10614 | )); |
| 10615 | } |
| 10616 | } |
| 10617 | // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV` |
| 10618 | // candidate below to pair with the second reference's NEAREST half. |
| 10619 | let mut last_new_mv: Option<(i32, i32)> = None; |
| 10620 | if leaf_new_mv() { |
| 10621 | let source_block = luma.source_block_rect(x, y, bw, bh); |
| 10622 | let (seeds, seed_n) = mv_seeds(stack); |
| 10623 | let found = motion::search( |
| 10624 | &reference.y, |
| 10625 | reference.width, |
| 10626 | luma.true_width, |
| 10627 | luma.true_height, |
| 10628 | &source_block, |
| 10629 | x, |
| 10630 | y, |
| 10631 | bw, |
| 10632 | bh, |
| 10633 | stack.pred_mv, |
| 10634 | &seeds[..seed_n], |
| 10635 | search.lambda, |
| 10636 | fctx, |
| 10637 | 1, |
| 10638 | ); |
| 10639 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 10640 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 10641 | last_new_mv = Some(mv); |
| 10642 | cands.push(( |
| 10643 | symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits), |
| 10644 | info_of(InterMode::NewMv, mv, ref_mv_idx), |
| 10645 | )); |
| 10646 | } |
| 10647 | } |
| 10648 | |
| 10649 | let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None; |
| 10650 | for (bits, info) in cands { |
| 10651 | let trials: Vec<Trial> = units |
| 10652 | .iter() |
| 10653 | .map(|&(plane, px, py, s, is_luma)| { |
| 10654 | let (samples, stride, w, h) = match plane { |
| 10655 | 0 => (&reference.y, reference.width, luma.true_width, luma.true_height), |
| 10656 | 1 => ( |
| 10657 | &reference.u, |
| 10658 | reference.width / 2, |
| 10659 | chroma[0].true_width, |
| 10660 | chroma[0].true_height, |
| 10661 | ), |
| 10662 | _ => ( |
| 10663 | &reference.v, |
| 10664 | reference.width / 2, |
| 10665 | chroma[1].true_width, |
| 10666 | chroma[1].true_height, |
| 10667 | ), |
| 10668 | }; |
| 10669 | let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx); |
| 10670 | let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] }; |
| 10671 | // `skip` true: the trial is the prediction itself plus its SSE, |
| 10672 | // so no transform of any size is involved (the reason a 64x64 |
| 10673 | // root can be coded at all before a forward TX_64X64 exists). |
| 10674 | target.code_from_prediction( |
| 10675 | px, |
| 10676 | py, |
| 10677 | s, |
| 10678 | &prediction, |
| 10679 | true, |
| 10680 | search.base_q_idx, |
| 10681 | search.deadzone, |
| 10682 | TxbSet::Luma32Inter, |
| 10683 | ) |
| 10684 | }) |
| 10685 | .collect(); |
| 10686 | let cost = |
| 10687 | trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits); |
| 10688 | if best.as_ref().is_none_or(|b| cost < b.0) { |
| 10689 | best = Some((cost, fixed + bits, info, trials)); |
| 10690 | } |
| 10691 | } |
| 10692 | |
| 10693 | // lane-b64b: the COMPOUND candidates at the 64 root, the same three a |
| 10694 | // superblock can form without a second motion search ([`b64_compound`]), |
| 10695 | // priced through the same `symbol_bits` path -- `fixed` minus the single |
| 10696 | // reference's tree, plus the pair tree and the compound mode. |
| 10697 | for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) { |
| 10698 | let (ref1, g) = (*ref1, *g); |
| 10699 | // The whole `comp_mode` + reference-pair tree at the writer's own |
| 10700 | // contexts, for THIS pair (lane-ctx). |
| 10701 | let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack); |
| 10702 | let mode_ctx = |
| 10703 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 10704 | let mode_bits_of = |
| 10705 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 10706 | let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo { |
| 10707 | ref1: Some(ref1), |
| 10708 | mv1: mvs.1, |
| 10709 | ref_frame: crate::mvstack::LAST_FRAME, |
| 10710 | mode, |
| 10711 | mv: mvs.0, |
| 10712 | ref_mv_idx: 0, |
| 10713 | }; |
| 10714 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 10715 | ( |
| 10716 | cstack.nearest_mv, |
| 10717 | mode_bits_of(0), |
| 10718 | compound_info(InterMode::NearestNearestMv, cstack.nearest_mv), |
| 10719 | ), |
| 10720 | ( |
| 10721 | ((0, 0), (0, 0)), |
| 10722 | mode_bits_of(6), |
| 10723 | compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))), |
| 10724 | ), |
| 10725 | ]; |
| 10726 | // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search |
| 10727 | // above, its residual priced against compound stack entry 0 -- what |
| 10728 | // `assign_compound_mv` predicts from at `ref_mv_idx = 0`. |
| 10729 | let cbase = cstack |
| 10730 | .entries |
| 10731 | .first() |
| 10732 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 10733 | if let Some(new_mv) = last_new_mv |
| 10734 | && let Some(b0) = mv_residual_bits(new_mv, cbase.0) |
| 10735 | { |
| 10736 | let mvs = (new_mv, cstack.nearest_mv.1); |
| 10737 | ccands.push(( |
| 10738 | mvs, |
| 10739 | mode_bits_of(3) + b0, |
| 10740 | compound_info(InterMode::NewNearestMv, mvs), |
| 10741 | )); |
| 10742 | } |
| 10743 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 10744 | ccands.dedup_by_key(|c| c.0); |
| 10745 | for (mvs, bits, info) in ccands { |
| 10746 | let trials: Vec<Trial> = units |
| 10747 | .iter() |
| 10748 | .map(|&(plane, px, py, s, is_luma)| { |
| 10749 | let (r0, r1) = match plane { |
| 10750 | 0 => ( |
| 10751 | (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height), |
| 10752 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 10753 | ), |
| 10754 | 1 => ( |
| 10755 | ( |
| 10756 | reference.u.as_slice(), |
| 10757 | reference.width / 2, |
| 10758 | chroma[0].true_width, |
| 10759 | chroma[0].true_height, |
| 10760 | ), |
| 10761 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 10762 | ), |
| 10763 | _ => ( |
| 10764 | ( |
| 10765 | reference.v.as_slice(), |
| 10766 | reference.width / 2, |
| 10767 | chroma[1].true_width, |
| 10768 | chroma[1].true_height, |
| 10769 | ), |
| 10770 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 10771 | ), |
| 10772 | }; |
| 10773 | let prediction = |
| 10774 | predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx); |
| 10775 | let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] }; |
| 10776 | target.code_from_prediction( |
| 10777 | px, |
| 10778 | py, |
| 10779 | s, |
| 10780 | &prediction, |
| 10781 | true, |
| 10782 | search.base_q_idx, |
| 10783 | search.deadzone, |
| 10784 | TxbSet::Luma32Inter, |
| 10785 | ) |
| 10786 | }) |
| 10787 | .collect(); |
| 10788 | let syntax = fixed - ref_bits + bits; |
| 10789 | let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax; |
| 10790 | if best.as_ref().is_none_or(|b| cost < b.0) { |
| 10791 | best = Some((cost, syntax, info, trials)); |
| 10792 | } |
| 10793 | } |
| 10794 | } |
| 10795 | |
| 10796 | let (skip_cost, syntax, info, skip_trials) = best?; |
| 10797 | |
| 10798 | // The winner's prediction coded with a REAL residual (lane-tx64): one |
| 10799 | // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the |
| 10800 | // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per |
| 10801 | // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv |
| 10802 | // the skip arm already chose is re-coded: the prediction with the lowest |
| 10803 | // SSE is also the cheapest residual to code, and a second 64x64 motion |
| 10804 | // search per superblock is the wall this root was taken to SAVE. |
| 10805 | // |
| 10806 | // Priced against the skip arm through the same `symbol_bits` path, so the |
| 10807 | // two numbers are comparable: `fixed` charged `skip` coded 1, and this |
| 10808 | // arm charges 0 instead and adds its three planes' coefficient bits. |
| 10809 | let mut chosen = (skip_cost, true, skip_trials); |
| 10810 | // Set when [`commit_inter_luma`] already wrote the residual arm's luma |
| 10811 | // into the plane, so the tail below does not commit over its units. |
| 10812 | let mut luma_committed = false; |
| 10813 | // The residual arm's luma levels and the `txfm_split` depth the writer |
| 10814 | // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is |
| 10815 | // four TX_32X32 units in 64x64 ones. |
| 10816 | let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None; |
| 10817 | if residual { |
| 10818 | let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; |
| 10819 | // Square by construction (the `debug_assert` above), so `units` is |
| 10820 | // one entry per plane and `chosen.2[plane]` is that plane's trial. |
| 10821 | let residual_trials = [0usize, 1, 2].map(|plane| { |
| 10822 | let (target, px, py, s) = if plane == 0 { |
| 10823 | (&*luma, x, y, bw) |
| 10824 | } else { |
| 10825 | (&chroma[plane - 1], x / 2, y / 2, bw / 2) |
| 10826 | }; |
| 10827 | target.code_from_prediction( |
| 10828 | px, |
| 10829 | py, |
| 10830 | s, |
| 10831 | &chosen.2[plane].reconstruction, |
| 10832 | false, |
| 10833 | search.base_q_idx, |
| 10834 | search.deadzone, |
| 10835 | sets[plane], |
| 10836 | ) |
| 10837 | }); |
| 10838 | let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true); |
| 10839 | let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum(); |
| 10840 | // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the |
| 10841 | // four TX_32X32 units of `txfm_split = 1`, taken by the same |
| 10842 | // `commit_inter_luma` every other inter block's is (it commits the |
| 10843 | // winner and hands back the cost it took off the flat arm). |
| 10844 | let (levels, depth, gain, tx_types) = if b64_var_tx() { |
| 10845 | let second = info.ref1.and_then(|r1| { |
| 10846 | compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| { |
| 10847 | ( |
| 10848 | info.mv1, |
| 10849 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 10850 | ) |
| 10851 | }) |
| 10852 | }); |
| 10853 | luma_committed = true; |
| 10854 | commit_inter_luma( |
| 10855 | luma, |
| 10856 | (x, y), |
| 10857 | bw, |
| 10858 | info.mv, |
| 10859 | (&reference.y, reference.width, luma.true_width, luma.true_height), |
| 10860 | search, |
| 10861 | &residual_trials[0], |
| 10862 | false, |
| 10863 | second, |
| 10864 | fctx, |
| 10865 | ) |
| 10866 | } else { |
| 10867 | (residual_trials[0].levels.clone(), 0, 0.0, Vec::new()) |
| 10868 | }; |
| 10869 | let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>() |
| 10870 | + search.lambda * (syntax + unskip + coeff_bits) |
| 10871 | + gain; |
| 10872 | if cost < skip_cost { |
| 10873 | B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10874 | if depth == 1 { |
| 10875 | B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 10876 | } |
| 10877 | luma_levels = Some((levels, depth, tx_types)); |
| 10878 | chosen = (cost, false, residual_trials.to_vec()); |
| 10879 | } |
| 10880 | } |
| 10881 | |
| 10882 | let (cost, skip, trials) = chosen; |
| 10883 | // `commit_inter_luma` already wrote the residual arm's luma (its four |
| 10884 | // split units are not one 64-sided trial); a skip winner overwrites it. |
| 10885 | for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) { |
| 10886 | match plane { |
| 10887 | 0 if skip || !luma_committed => luma.commit(px, py, s, trial), |
| 10888 | 0 => {} |
| 10889 | _ => chroma[plane - 1].commit(px, py, s, trial), |
| 10890 | } |
| 10891 | } |
| 10892 | Some(( |
| 10893 | cost, |
| 10894 | BlockCoeffs { |
| 10895 | skip, |
| 10896 | inter: Some(info), |
| 10897 | // The chroma grids are whole TX_32X32; the luma one is the |
| 10898 | // 64-point transform's coded 32x32 corner at depth 0 and the |
| 10899 | // whole 64-sided block at depth 1 (lane-b64b). |
| 10900 | tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d), |
| 10901 | luma_tx_types: match (skip, &luma_levels) { |
| 10902 | (false, Some((_, _, types))) => types.clone(), |
| 10903 | _ => Vec::new(), |
| 10904 | }, |
| 10905 | luma: match (skip, &luma_levels) { |
| 10906 | (true, _) => Vec::new(), |
| 10907 | (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK), |
| 10908 | (false, Some((levels, _, _))) => coeffs(levels, BLOCK), |
| 10909 | (false, None) => coeffs(&trials[0].levels, BLOCK), |
| 10910 | }, |
| 10911 | u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) }, |
| 10912 | v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) }, |
| 10913 | ..BlockCoeffs::default() |
| 10914 | }, |
| 10915 | )) |
| 10916 | } |
| 10917 | |
| 10918 | fn search_inter_block( |
| 10919 | luma: &mut Plane, |
| 10920 | chroma: &mut [Plane; 2], |
| 10921 | (x, y): (usize, usize), |
| 10922 | search: &Search, |
| 10923 | mode_bits: &[f64; 13], |
| 10924 | reference: &Picture, |
| 10925 | stack: &MvStack, |
| 10926 | // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1 |
| 10927 | // for the whole GOP, with the stack this block derives against it. Only |
| 10928 | // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a |
| 10929 | // second motion search would double the wall of the stage that already |
| 10930 | // owns most of it. |
| 10931 | extra: &[(i8, &Picture, &MvStack)], |
| 10932 | // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by |
| 10933 | // the caller off the same MI grid the tile writer will (empty unless the |
| 10934 | // frame carries `reference_select`). |
| 10935 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 10936 | // lane-av1obmc: the mi grid this search's neighbours were published into |
| 10937 | // (`record_mi`) and this block's own place in it -- what the OBMC |
| 10938 | // candidate's eligibility walk and neighbour plan read, the same state |
| 10939 | // the tile writer will read when it codes the `motion_mode` symbol. |
| 10940 | grid: &MiGrid, |
| 10941 | (mi_row, mi_col): (usize, usize), |
| 10942 | (mi_rows, mi_cols): (usize, usize), |
| 10943 | fctx: &crate::decode::FrameCtx, |
| 10944 | ) -> (BlockCoeffs, f64) { |
| 10945 | // `luma_set` is the INTRA candidates' table; the two inter candidates |
| 10946 | // below price their coefficients through `TxbSet::Luma32Inter`, which is |
| 10947 | // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries |
| 10948 | // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1). |
| 10949 | let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); |
| 10950 | let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx); |
| 10951 | |
| 10952 | // skip / intra_inter symbol costs at a fixed context -- see this |
| 10953 | // function's doc comment. |
| 10954 | let skip_bits = |skip: bool| skip_bits_at(stack, skip); |
| 10955 | let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter); |
| 10956 | |
| 10957 | struct Candidate { |
| 10958 | cost: f64, |
| 10959 | luma: Trial, |
| 10960 | u: Trial, |
| 10961 | v: Trial, |
| 10962 | mode: u8, |
| 10963 | skip: bool, |
| 10964 | inter: Option<InterInfo>, |
| 10965 | /// The mode/mv syntax this candidate pays for, apart from its |
| 10966 | /// residual -- what the OBMC candidate below has to re-pay when it |
| 10967 | /// re-prices the winner's prediction. |
| 10968 | mode_bits: f64, |
| 10969 | } |
| 10970 | let mut best: Option<Candidate> = None; |
| 10971 | let mut consider = |candidate: Candidate| { |
| 10972 | if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { |
| 10973 | best = Some(candidate); |
| 10974 | } |
| 10975 | }; |
| 10976 | |
| 10977 | // The chroma trial an intra candidate prices does not depend on `mode` |
| 10978 | // at all -- both planes always code `DC_PRED` here (a coding choice this |
| 10979 | // search inherited, not this loop's to second-guess) at the same `reach: |
| 10980 | // Reach::none()` -- so it is the same call with the same inputs on every |
| 10981 | // one of the thirteen iterations below; run it once and reuse the result |
| 10982 | // rather than repeat an already-priced transform/quantize/entropy call |
| 10983 | // twelve times for nothing (bit-identical: the value each iteration |
| 10984 | // reads back is exactly what it used to recompute). |
| 10985 | let u_trial = chroma[0].trial( |
| 10986 | At { |
| 10987 | x: x / 2, |
| 10988 | y: y / 2, |
| 10989 | side: BLOCK / 2, |
| 10990 | reach: Reach::none(), |
| 10991 | set: chroma_set, |
| 10992 | }, |
| 10993 | DC_PRED, |
| 10994 | 0, |
| 10995 | search.base_q_idx, |
| 10996 | search.deadzone, fctx, |
| 10997 | ); |
| 10998 | let v_trial = chroma[1].trial( |
| 10999 | At { |
| 11000 | x: x / 2, |
| 11001 | y: y / 2, |
| 11002 | side: BLOCK / 2, |
| 11003 | reach: Reach::none(), |
| 11004 | set: chroma_set, |
| 11005 | }, |
| 11006 | DC_PRED, |
| 11007 | 0, |
| 11008 | search.base_q_idx, |
| 11009 | search.deadzone, fctx, |
| 11010 | ); |
| 11011 | |
| 11012 | let intra_modes: Vec<u8> = match search.top_k { |
| 11013 | Some(k) if k < search.modes.len() => { |
| 11014 | let scored = luma.intra_scores( |
| 11015 | At { |
| 11016 | x, |
| 11017 | y, |
| 11018 | side: BLOCK, |
| 11019 | reach, |
| 11020 | set: luma_set, |
| 11021 | }, |
| 11022 | search.modes, |
| 11023 | mode_bits, |
| 11024 | search.lambda, fctx, |
| 11025 | ); |
| 11026 | prune_by_sad(search.modes, scored, k) |
| 11027 | } |
| 11028 | _ => search.modes.to_vec(), |
| 11029 | }; |
| 11030 | census_add(5, 1); |
| 11031 | census_add(6, if search.arf_leaf_intra { intra_modes.len() } else { 0 }); |
| 11032 | // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the |
| 11033 | // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at |
| 11034 | // the leaves (film A arm 1 vs control byte-identical with the leaf gate |
| 11035 | // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a |
| 11036 | // hatch nothing else was using. Counted once per block. |
| 11037 | if search.arf_leaf_intra { |
| 11038 | for &mode in &intra_modes { |
| 11039 | let luma_trial = luma.trial( |
| 11040 | At { |
| 11041 | x, |
| 11042 | y, |
| 11043 | side: BLOCK, |
| 11044 | reach, |
| 11045 | set: luma_set, |
| 11046 | }, |
| 11047 | mode, |
| 11048 | 0, |
| 11049 | search.base_q_idx, |
| 11050 | search.deadzone, fctx, |
| 11051 | ); |
| 11052 | let u = u_trial.clone(); |
| 11053 | let v = v_trial.clone(); |
| 11054 | let cost = luma_trial.sse |
| 11055 | + u.sse |
| 11056 | + v.sse |
| 11057 | + search.lambda |
| 11058 | * (luma_trial.bits |
| 11059 | + u.bits |
| 11060 | + v.bits |
| 11061 | + mode_bits[usize::from(mode)] |
| 11062 | + skip_bits(false) |
| 11063 | + intra_inter_bits(false)); |
| 11064 | consider(Candidate { |
| 11065 | cost, |
| 11066 | luma: luma_trial, |
| 11067 | u, |
| 11068 | v, |
| 11069 | mode, |
| 11070 | skip: false, |
| 11071 | inter: None, |
| 11072 | mode_bits: mode_bits[usize::from(mode)], |
| 11073 | }); |
| 11074 | } |
| 11075 | } else { |
| 11076 | arfmode_hit(0); |
| 11077 | } |
| 11078 | |
| 11079 | // The reference frame buffer a spec decoder holds is exactly the true |
| 11080 | // (unpadded) coded extent -- a superblock whose partition stops early at |
| 11081 | // `has_cols`/`has_rows` never codes syntax for the padding columns/rows |
| 11082 | // beyond it, so those samples are never part of the decoded picture. |
| 11083 | // Motion compensation clamps reads to that true extent (spec 7.11.3.4's |
| 11084 | // reference sample position clamp), not to this crate's own |
| 11085 | // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height |
| 11086 | // here would let a fractional-pel read past the true edge pick up this |
| 11087 | // encoder's own uncoded padding instead of the true edge's replicated |
| 11088 | // value a decoder computes. |
| 11089 | let ref_luma = ( |
| 11090 | &reference.y, |
| 11091 | reference.width, |
| 11092 | luma.true_width, |
| 11093 | luma.true_height, |
| 11094 | ); |
| 11095 | let ref_u = ( |
| 11096 | &reference.u, |
| 11097 | reference.width / 2, |
| 11098 | chroma[0].true_width, |
| 11099 | chroma[0].true_height, |
| 11100 | ); |
| 11101 | let ref_v = ( |
| 11102 | &reference.v, |
| 11103 | reference.width / 2, |
| 11104 | chroma[1].true_width, |
| 11105 | chroma[1].true_height, |
| 11106 | ); |
| 11107 | // Every single-reference mode the writer can code (spec 5.11.24's symbol |
| 11108 | // chain, mirrored by `tile::write_inter_mode`), priced with the static |
| 11109 | // CDFs at this block's own stack contexts. A candidate is a motion |
| 11110 | // vector plus the cheapest syntax that reaches it, so two modes landing |
| 11111 | // on the same vector share one set of trials: the added modes cost |
| 11112 | // mode-bit arithmetic, not another motion compensation. |
| 11113 | let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 11114 | let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 11115 | // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry |
| 11116 | // past `start`, `1` to advance and `0` to stop, at most two. A `target` |
| 11117 | // the loop cannot reach is never offered below -- every candidate's |
| 11118 | // index is one this same loop walks to. |
| 11119 | let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); |
| 11120 | let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); |
| 11121 | let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ |
| 11122 | ( |
| 11123 | stack.nearest_mv, |
| 11124 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 11125 | InterInfo { |
| 11126 | ref1: None, |
| 11127 | mv1: (0, 0), |
| 11128 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11129 | mode: InterMode::NearestMv, |
| 11130 | mv: stack.nearest_mv, |
| 11131 | ref_mv_idx: 0, |
| 11132 | }, |
| 11133 | ), |
| 11134 | // GLOBALMV is the identity model's zero vector -- this encoder writes |
| 11135 | // no `gm_params` -- and the cheapest syntax of the four on the static |
| 11136 | // content where that vector is also the right one. |
| 11137 | ( |
| 11138 | (0, 0), |
| 11139 | last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), |
| 11140 | InterInfo { |
| 11141 | ref1: None, |
| 11142 | mv1: (0, 0), |
| 11143 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11144 | mode: InterMode::GlobalMv, |
| 11145 | mv: (0, 0), |
| 11146 | ref_mv_idx: 0, |
| 11147 | }, |
| 11148 | ), |
| 11149 | ]; |
| 11150 | let near_bits = |
| 11151 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); |
| 11152 | for idx in 1..=2usize { |
| 11153 | if let Some(e) = stack.entries.get(idx) { |
| 11154 | cands.push(( |
| 11155 | e.mv, |
| 11156 | near_bits + drl_bits(1, idx), |
| 11157 | InterInfo { |
| 11158 | ref1: None, |
| 11159 | mv1: (0, 0), |
| 11160 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11161 | mode: InterMode::NearMv, |
| 11162 | mv: e.mv, |
| 11163 | ref_mv_idx: idx as u8, |
| 11164 | }, |
| 11165 | )); |
| 11166 | } |
| 11167 | } |
| 11168 | |
| 11169 | let source_block = luma.source_block(x, y, BLOCK); |
| 11170 | let (seeds, seed_n) = mv_seeds(stack); |
| 11171 | #[cfg(test)] |
| 11172 | let t = stage_start(); |
| 11173 | let found = motion::search( |
| 11174 | ref_luma.0, |
| 11175 | ref_luma.1, |
| 11176 | ref_luma.2, |
| 11177 | ref_luma.3, |
| 11178 | &source_block, |
| 11179 | x, |
| 11180 | y, |
| 11181 | BLOCK, |
| 11182 | BLOCK, |
| 11183 | stack.pred_mv, |
| 11184 | &seeds[..seed_n], |
| 11185 | search.lambda, fctx, |
| 11186 | 1, |
| 11187 | ); |
| 11188 | #[cfg(test)] |
| 11189 | stage_since(0, t); |
| 11190 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 11191 | // lane-newmv: this block's own `NEWMV` vector and what its mv syntax |
| 11192 | // costs, for the census below (`None` when the writer cannot name it). |
| 11193 | let mut newmv_syntax: Option<((i32, i32), f64)> = None; |
| 11194 | // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so |
| 11195 | // the same vector costs a different residual from each: take the index |
| 11196 | // whose residual plus DRL bits is cheapest, not entry 0 by default. |
| 11197 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 11198 | newmv_syntax = Some((mv, bits)); |
| 11199 | cands.push(( |
| 11200 | mv, |
| 11201 | last_ref_bits |
| 11202 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 11203 | + bits |
| 11204 | + mv_rate_surcharge(bits), |
| 11205 | InterInfo { |
| 11206 | ref1: None, |
| 11207 | mv1: (0, 0), |
| 11208 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11209 | mode: InterMode::NewMv, |
| 11210 | mv, |
| 11211 | ref_mv_idx, |
| 11212 | }, |
| 11213 | )); |
| 11214 | } |
| 11215 | |
| 11216 | // Each extra reference's own `NEWMV` vector, for the compound |
| 11217 | // `NEW_NEWMV` candidate below to pair with `LAST`'s. |
| 11218 | let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new(); |
| 11219 | for &(ref_frame, g, gstack) in extra { |
| 11220 | let g_ref_bits = single_ref_bits(ref_frame, gstack); |
| 11221 | let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); |
| 11222 | cands.push(( |
| 11223 | gstack.nearest_mv, |
| 11224 | g_ref_bits |
| 11225 | + g_not_new |
| 11226 | + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) |
| 11227 | + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), |
| 11228 | InterInfo { |
| 11229 | ref1: None, |
| 11230 | mv1: (0, 0), |
| 11231 | ref_frame, |
| 11232 | mode: InterMode::NearestMv, |
| 11233 | mv: gstack.nearest_mv, |
| 11234 | ref_mv_idx: 0, |
| 11235 | }, |
| 11236 | )); |
| 11237 | cands.push(( |
| 11238 | (0, 0), |
| 11239 | g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), |
| 11240 | InterInfo { |
| 11241 | ref1: None, |
| 11242 | mv1: (0, 0), |
| 11243 | ref_frame, |
| 11244 | mode: InterMode::GlobalMv, |
| 11245 | mv: (0, 0), |
| 11246 | ref_mv_idx: 0, |
| 11247 | }, |
| 11248 | )); |
| 11249 | // A motion search of this reference's own: without it, GOLDEN/ALTREF |
| 11250 | // can only be coded at a vector some neighbour already found, which |
| 11251 | // is why they carried a third of the inter blocks at their two |
| 11252 | // search-free modes alone. |
| 11253 | // The search is skipped when this reference's own NEARESTMV already |
| 11254 | // prices out `margin` times better than LAST's best vector does -- |
| 11255 | // one candidate evaluation (`motion::cost_at`) standing in for a |
| 11256 | // whole search of ~50. |
| 11257 | // lane-last2: the SEARCH-FREE arm for the second past leaf picture |
| 11258 | // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some |
| 11259 | // neighbour already found, which is how GOLDEN/ALTREF were offered |
| 11260 | // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's |
| 11261 | // own value from the second motion search's wall. |
| 11262 | let searched = extra_ref_new_mv() |
| 11263 | && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv()); |
| 11264 | let margin = extra_new_skip_margin(); |
| 11265 | if searched { |
| 11266 | newmv_census_global(0); |
| 11267 | } |
| 11268 | let skip_search = searched |
| 11269 | && margin > 0.0 |
| 11270 | && motion::cost_at( |
| 11271 | &g.y, |
| 11272 | g.width, |
| 11273 | luma.true_width, |
| 11274 | luma.true_height, |
| 11275 | &source_block, |
| 11276 | x, |
| 11277 | y, |
| 11278 | BLOCK, |
| 11279 | BLOCK, |
| 11280 | gstack.nearest_mv, |
| 11281 | gstack.pred_mv, |
| 11282 | search.lambda, |
| 11283 | fctx, |
| 11284 | ) * margin |
| 11285 | <= found.cost; |
| 11286 | if skip_search { |
| 11287 | newmv_census_global(1); |
| 11288 | } |
| 11289 | if searched && !skip_search { |
| 11290 | let (gseeds, gn) = mv_seeds(gstack); |
| 11291 | #[cfg(test)] |
| 11292 | let t = stage_start(); |
| 11293 | let gfound = motion::search( |
| 11294 | &g.y, |
| 11295 | g.width, |
| 11296 | luma.true_width, |
| 11297 | luma.true_height, |
| 11298 | &source_block, |
| 11299 | x, |
| 11300 | y, |
| 11301 | BLOCK, |
| 11302 | BLOCK, |
| 11303 | gstack.pred_mv, |
| 11304 | &gseeds[..gn], |
| 11305 | search.lambda, fctx, |
| 11306 | ref_distance(ref_frame), |
| 11307 | ); |
| 11308 | #[cfg(test)] |
| 11309 | stage_since(0, t); |
| 11310 | let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); |
| 11311 | extra_new_mvs.push((ref_frame, gmv)); |
| 11312 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { |
| 11313 | cands.push(( |
| 11314 | gmv, |
| 11315 | g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, |
| 11316 | InterInfo { |
| 11317 | ref1: None, |
| 11318 | mv1: (0, 0), |
| 11319 | ref_frame, |
| 11320 | mode: InterMode::NewMv, |
| 11321 | mv: gmv, |
| 11322 | ref_mv_idx, |
| 11323 | }, |
| 11324 | )); |
| 11325 | } |
| 11326 | } |
| 11327 | } |
| 11328 | |
| 11329 | // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one |
| 11330 | // trial set each: both references predict the block and the two |
| 11331 | // predictions are averaged, which is what pays on content where neither |
| 11332 | // reference alone is right. Priced with the same static-CDF approximation |
| 11333 | // the single-reference candidates use, plus the compound-only symbols |
| 11334 | // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`). |
| 11335 | // The two compound-mode arms, each measured alone on the BD gate before |
| 11336 | // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8 |
| 11337 | // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not |
| 11338 | // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`. |
| 11339 | // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on: |
| 11340 | // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, |
| 11341 | // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of |
| 11342 | // the keep rule. Still behind the knob. |
| 11343 | let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR"); |
| 11344 | let half_new = true; |
| 11345 | for (ref1, g, cstack) in compound { |
| 11346 | let (ref1, g) = (*ref1, *g); |
| 11347 | // The whole `comp_mode` + reference-pair tree at the writer's own |
| 11348 | // contexts, for THIS pair (lane-ctx). |
| 11349 | let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack); |
| 11350 | let mode_ctx = |
| 11351 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 11352 | let mode_bits_of = |
| 11353 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 11354 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 11355 | ( |
| 11356 | cstack.nearest_mv, |
| 11357 | mode_bits_of(0), |
| 11358 | InterInfo { |
| 11359 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11360 | mode: InterMode::NearestNearestMv, |
| 11361 | mv: cstack.nearest_mv.0, |
| 11362 | mv1: cstack.nearest_mv.1, |
| 11363 | ref1: Some(ref1), |
| 11364 | ref_mv_idx: 0, |
| 11365 | }, |
| 11366 | ), |
| 11367 | ( |
| 11368 | ((0, 0), (0, 0)), |
| 11369 | mode_bits_of(6), |
| 11370 | InterInfo { |
| 11371 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11372 | mode: InterMode::GlobalGlobalMv, |
| 11373 | mv: (0, 0), |
| 11374 | mv1: (0, 0), |
| 11375 | ref1: Some(ref1), |
| 11376 | ref_mv_idx: 0, |
| 11377 | }, |
| 11378 | ), |
| 11379 | ]; |
| 11380 | // `NEAR_NEARMV`: both halves off compound stack entry 1 (the |
| 11381 | // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever |
| 11382 | // the stack is deep enough for that walk to read one. |
| 11383 | if let Some(e) = cstack.entries.get(1).filter(|_| near_near) { |
| 11384 | let drl = if cstack.entries.len() > 2 { |
| 11385 | symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0) |
| 11386 | } else { |
| 11387 | 0.0 |
| 11388 | }; |
| 11389 | ccands.push(( |
| 11390 | (e.mv0, e.mv1), |
| 11391 | mode_bits_of(1) + drl, |
| 11392 | InterInfo { |
| 11393 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11394 | mode: InterMode::NearNearMv, |
| 11395 | mv: e.mv0, |
| 11396 | mv1: e.mv1, |
| 11397 | ref1: Some(ref1), |
| 11398 | ref_mv_idx: 0, |
| 11399 | }, |
| 11400 | )); |
| 11401 | } |
| 11402 | // The half-new modes and `NEW_NEWMV`, all seeded from the two |
| 11403 | // single-reference searches this block already ran -- no joint search |
| 11404 | // of its own. Every residual is priced against stack entry 0, which |
| 11405 | // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`. |
| 11406 | let cbase = cstack |
| 11407 | .entries |
| 11408 | .first() |
| 11409 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 11410 | if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) { |
| 11411 | ccands.push(( |
| 11412 | (mv, cstack.nearest_mv.1), |
| 11413 | mode_bits_of(3) + b0, |
| 11414 | InterInfo { |
| 11415 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11416 | mode: InterMode::NewNearestMv, |
| 11417 | mv, |
| 11418 | mv1: cstack.nearest_mv.1, |
| 11419 | ref1: Some(ref1), |
| 11420 | ref_mv_idx: 0, |
| 11421 | }, |
| 11422 | )); |
| 11423 | } |
| 11424 | if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) { |
| 11425 | if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) { |
| 11426 | ccands.push(( |
| 11427 | (cstack.nearest_mv.0, mv1), |
| 11428 | mode_bits_of(2) + b1, |
| 11429 | InterInfo { |
| 11430 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11431 | mode: InterMode::NearestNewMv, |
| 11432 | mv: cstack.nearest_mv.0, |
| 11433 | mv1, |
| 11434 | ref1: Some(ref1), |
| 11435 | ref_mv_idx: 0, |
| 11436 | }, |
| 11437 | )); |
| 11438 | } |
| 11439 | let base = cbase; |
| 11440 | if let (Some(b0), Some(b1)) = ( |
| 11441 | mv_residual_bits(mv, base.0), |
| 11442 | mv_residual_bits(mv1, base.1), |
| 11443 | ) { |
| 11444 | ccands.push(( |
| 11445 | (mv, mv1), |
| 11446 | mode_bits_of(7) + b0 + b1, |
| 11447 | InterInfo { |
| 11448 | ref_frame: crate::mvstack::LAST_FRAME, |
| 11449 | mode: InterMode::NewNewMv, |
| 11450 | mv, |
| 11451 | mv1, |
| 11452 | ref1: Some(ref1), |
| 11453 | ref_mv_idx: 0, |
| 11454 | }, |
| 11455 | )); |
| 11456 | } |
| 11457 | } |
| 11458 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 11459 | ccands.dedup_by_key(|c| c.0); |
| 11460 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 11461 | let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height); |
| 11462 | let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height); |
| 11463 | for (mvs, bits, info) in ccands { |
| 11464 | let luma_trial = mc_trial_compound( |
| 11465 | luma, x, y, BLOCK, mvs, true, |
| 11466 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 11467 | search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, |
| 11468 | ); |
| 11469 | let u = mc_trial_compound( |
| 11470 | &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 11471 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 11472 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 11473 | ); |
| 11474 | let v = mc_trial_compound( |
| 11475 | &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 11476 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 11477 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 11478 | ); |
| 11479 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 11480 | && u.levels.iter().all(|&l| l == 0) |
| 11481 | && v.levels.iter().all(|&l| l == 0); |
| 11482 | let cost = luma_trial.sse |
| 11483 | + u.sse |
| 11484 | + v.sse |
| 11485 | + search.lambda |
| 11486 | * (skip_bits(skip) |
| 11487 | + intra_inter_bits(true) |
| 11488 | + bits |
| 11489 | + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); |
| 11490 | consider(Candidate { |
| 11491 | cost, |
| 11492 | luma: luma_trial, |
| 11493 | u, |
| 11494 | v, |
| 11495 | mode: DC_PRED, |
| 11496 | skip, |
| 11497 | mode_bits: bits, |
| 11498 | inter: Some(info), |
| 11499 | }); |
| 11500 | } |
| 11501 | } |
| 11502 | |
| 11503 | // One trial set per distinct (reference, vector) pair: sort, cheapest |
| 11504 | // syntax first, and drop the rest of each pair's run. |
| 11505 | cands.sort_by(|a, b| { |
| 11506 | (a.2.ref_frame, a.0) |
| 11507 | .cmp(&(b.2.ref_frame, b.0)) |
| 11508 | .then(a.1.total_cmp(&b.1)) |
| 11509 | }); |
| 11510 | cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); |
| 11511 | census_add(7, cands.len()); |
| 11512 | // lane-newmv: the NEWMV candidate's own RD cost against the best cost |
| 11513 | // this block reaches WITHOUT it, taken inside the one loop that prices |
| 11514 | // them all (a second pricing pass would be a second oracle). |
| 11515 | let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY); |
| 11516 | { |
| 11517 | for (mv, mode_bits_inter, info) in cands { |
| 11518 | let (ref_luma, ref_u, ref_v) = match extra |
| 11519 | .iter() |
| 11520 | .find(|(r, _, _)| *r == info.ref_frame) |
| 11521 | { |
| 11522 | Some(&(_, g, _)) => ( |
| 11523 | (&g.y, g.width, luma.true_width, luma.true_height), |
| 11524 | (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 11525 | (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 11526 | ), |
| 11527 | None => (ref_luma, ref_u, ref_v), |
| 11528 | }; |
| 11529 | let luma_trial = mc_trial( |
| 11530 | luma, |
| 11531 | x, |
| 11532 | y, |
| 11533 | BLOCK, |
| 11534 | mv, |
| 11535 | true, |
| 11536 | ref_luma.0, |
| 11537 | ref_luma.1, |
| 11538 | ref_luma.2, |
| 11539 | ref_luma.3, |
| 11540 | false, |
| 11541 | search.base_q_idx, |
| 11542 | search.deadzone, |
| 11543 | TxbSet::Luma32Inter, fctx, |
| 11544 | ); |
| 11545 | let u = mc_trial( |
| 11546 | &chroma[0], |
| 11547 | x / 2, |
| 11548 | y / 2, |
| 11549 | BLOCK / 2, |
| 11550 | mv, |
| 11551 | false, |
| 11552 | ref_u.0, |
| 11553 | ref_u.1, |
| 11554 | ref_u.2, |
| 11555 | ref_u.3, |
| 11556 | false, |
| 11557 | search.base_q_idx, |
| 11558 | search.deadzone, |
| 11559 | chroma_set, fctx, |
| 11560 | ); |
| 11561 | let v = mc_trial( |
| 11562 | &chroma[1], |
| 11563 | x / 2, |
| 11564 | y / 2, |
| 11565 | BLOCK / 2, |
| 11566 | mv, |
| 11567 | false, |
| 11568 | ref_v.0, |
| 11569 | ref_v.1, |
| 11570 | ref_v.2, |
| 11571 | ref_v.3, |
| 11572 | false, |
| 11573 | search.base_q_idx, |
| 11574 | search.deadzone, |
| 11575 | chroma_set, fctx, |
| 11576 | ); |
| 11577 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 11578 | && u.levels.iter().all(|&l| l == 0) |
| 11579 | && v.levels.iter().all(|&l| l == 0); |
| 11580 | let cost = luma_trial.sse |
| 11581 | + u.sse |
| 11582 | + v.sse |
| 11583 | + search.lambda |
| 11584 | * (skip_bits(skip) |
| 11585 | + intra_inter_bits(true) |
| 11586 | + mode_bits_inter |
| 11587 | + if skip { |
| 11588 | 0.0 |
| 11589 | } else { |
| 11590 | luma_trial.bits + u.bits + v.bits |
| 11591 | }); |
| 11592 | consider(Candidate { |
| 11593 | cost, |
| 11594 | luma: luma_trial, |
| 11595 | u, |
| 11596 | v, |
| 11597 | mode: DC_PRED, |
| 11598 | skip, |
| 11599 | mode_bits: mode_bits_inter, |
| 11600 | inter: Some(info), |
| 11601 | }); |
| 11602 | if newmv_census_on() { |
| 11603 | if info.mode == InterMode::NewMv |
| 11604 | && info.ref1.is_none() |
| 11605 | && info.ref_frame == crate::mvstack::LAST_FRAME |
| 11606 | { |
| 11607 | new_cost = cost; |
| 11608 | } else { |
| 11609 | other_cost = other_cost.min(cost); |
| 11610 | } |
| 11611 | } |
| 11612 | } |
| 11613 | } |
| 11614 | if let Some((new_mv, bits)) = newmv_syntax { |
| 11615 | newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits); |
| 11616 | } else { |
| 11617 | newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0); |
| 11618 | } |
| 11619 | |
| 11620 | let best = best.expect("the search offers at least the intra modes"); |
| 11621 | // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`), |
| 11622 | // offered to the SINGLE-REFERENCE winner only -- libaom's |
| 11623 | // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a |
| 11624 | // compound block, so the writer codes no symbol for one. The prediction |
| 11625 | // is built by the DECODER's own plan and blend |
| 11626 | // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`], |
| 11627 | // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs |
| 11628 | // this search's `grid` already carries, so what is priced here is what a |
| 11629 | // decoder reconstructs -- never a second implementation of the blend. |
| 11630 | // |
| 11631 | // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it |
| 11632 | // on). Native crop BD, the standing recipe, with it on against the same |
| 11633 | // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p |
| 11634 | // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against |
| 11635 | // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and |
| 11636 | // one UP -- the keep rule wants two down and one flat, so it stays off. |
| 11637 | // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and |
| 11638 | // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two |
| 11639 | // things bound it and are the upgrade path: only the 32x32 winner is |
| 11640 | // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and |
| 11641 | // that is where libaom cashes most of its OBMC gain), and the symbol/ |
| 11642 | // residual price here is the static-CDF estimate. |
| 11643 | let mut best = best; |
| 11644 | let mut motion_won = 0u8; |
| 11645 | if let Some(info) = best.inter.filter(|i| { |
| 11646 | i.ref1.is_none() |
| 11647 | && (crate::envflags::env_flag!("EC_AV1_OBMC") |
| 11648 | || warp_on()) |
| 11649 | }) { |
| 11650 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 11651 | refs[LAST_FRAME as usize] = Some(reference); |
| 11652 | for &(r, p, _) in extra { |
| 11653 | refs[r as usize] = Some(p); |
| 11654 | } |
| 11655 | // This block's OWN reference planes: the single-reference winner may |
| 11656 | // be one of the extra references, not LAST. |
| 11657 | let planes: [(&[u16], usize, usize, usize); 3] = |
| 11658 | match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { |
| 11659 | Some(&(_, g, _)) => [ |
| 11660 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 11661 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 11662 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 11663 | ], |
| 11664 | None => [ |
| 11665 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 11666 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 11667 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 11668 | ], |
| 11669 | }; |
| 11670 | // The alphabet `tile::write_motion_mode` will code this block's |
| 11671 | // symbol against, mirrored term for term (libaom |
| 11672 | // `motion_mode_allowed`). |
| 11673 | let warp_alphabet = warp_on() |
| 11674 | && crate::decode::num_proj_ref( |
| 11675 | grid, |
| 11676 | mi_row, |
| 11677 | mi_col, |
| 11678 | 8, |
| 11679 | 8, |
| 11680 | mi_cols, |
| 11681 | mi_rows, |
| 11682 | info.ref_frame, |
| 11683 | fctx, |
| 11684 | ) >= 1; |
| 11685 | let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet); |
| 11686 | let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new(); |
| 11687 | if crate::envflags::env_flag!("EC_AV1_OBMC") { |
| 11688 | if let Some(pred) = obmc_prediction( |
| 11689 | grid, |
| 11690 | (mi_row, mi_col), |
| 11691 | (mi_rows, mi_cols), |
| 11692 | (x, y), |
| 11693 | BLOCK, |
| 11694 | info.mv, |
| 11695 | &refs, |
| 11696 | planes, |
| 11697 | reference.width, |
| 11698 | fctx, |
| 11699 | ) { |
| 11700 | candidates.push((1, pred)); |
| 11701 | } |
| 11702 | } |
| 11703 | if warp_alphabet { |
| 11704 | if let Some(pred) = warp_prediction( |
| 11705 | grid, |
| 11706 | (mi_row, mi_col), |
| 11707 | (mi_rows, mi_cols), |
| 11708 | (x, y), |
| 11709 | BLOCK, |
| 11710 | info.mv, |
| 11711 | info.ref_frame, |
| 11712 | planes, |
| 11713 | fctx, |
| 11714 | ) { |
| 11715 | candidates.push((2, pred)); |
| 11716 | } |
| 11717 | } |
| 11718 | for (motion, pred) in candidates { |
| 11719 | let luma_trial = luma.code_from_prediction( |
| 11720 | x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone, |
| 11721 | TxbSet::Luma32Inter, |
| 11722 | ); |
| 11723 | let u = chroma[0].code_from_prediction( |
| 11724 | x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone, |
| 11725 | chroma_set, |
| 11726 | ); |
| 11727 | let v = chroma[1].code_from_prediction( |
| 11728 | x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone, |
| 11729 | chroma_set, |
| 11730 | ); |
| 11731 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 11732 | && u.levels.iter().all(|&l| l == 0) |
| 11733 | && v.levels.iter().all(|&l| l == 0); |
| 11734 | let cost = luma_trial.sse |
| 11735 | + u.sse |
| 11736 | + v.sse |
| 11737 | + search.lambda |
| 11738 | * (skip_bits(skip) |
| 11739 | + intra_inter_bits(true) |
| 11740 | + best.mode_bits |
| 11741 | + mm(motion) |
| 11742 | + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); |
| 11743 | if cost < best.cost + search.lambda * mm(motion_won) { |
| 11744 | motion_won = motion; |
| 11745 | best = Candidate { |
| 11746 | cost, |
| 11747 | luma: luma_trial, |
| 11748 | u, |
| 11749 | v, |
| 11750 | mode: DC_PRED, |
| 11751 | skip, |
| 11752 | mode_bits: best.mode_bits, |
| 11753 | inter: best.inter, |
| 11754 | }; |
| 11755 | } |
| 11756 | } |
| 11757 | } |
| 11758 | // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`, |
| 11759 | // default OFF): the four 16x16 units of `commit_inter_luma` against the |
| 11760 | // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured |
| 11761 | // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and |
| 11762 | // RE-MEASURED it at 0.05, where the rate weight is half of what rejected |
| 11763 | // it, and it is worse again on the deciding native table: film 1080p |
| 11764 | // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the |
| 11765 | // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off -- |
| 11766 | // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1 |
| 11767 | // up against rav1e. (640x384 reads it slightly the other way, +70.0/ |
| 11768 | // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and |
| 11769 | // +28.4/+47.4/-4.0 -- the native table decides.) |
| 11770 | // |
| 11771 | // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks, |
| 11772 | // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing |
| 11773 | // either, and the census names the row: the split units' own set |
| 11774 | // `Luma16Inter` is priced within 1.4% of what it is written at in every |
| 11775 | // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced |
| 11776 | // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting, |
| 11777 | // so a perfect pricer would split even more, and more splitting is what |
| 11778 | // measured worse. The four extra txb_skip/eob symbols simply cost more |
| 11779 | // ladder bytes than the local RD saves. The flat 32x32 transform stays. |
| 11780 | // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection |
| 11781 | // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the |
| 11782 | // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp |
| 11783 | // winner still commits flat: `commit_inter_luma` re-predicts each unit by |
| 11784 | // plain translation, which is not the prediction it was priced from. |
| 11785 | let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) { |
| 11786 | Some(info) => { |
| 11787 | let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { |
| 11788 | Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 11789 | None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 11790 | }; |
| 11791 | let second = info.ref1.and_then(|r| { |
| 11792 | compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| { |
| 11793 | ( |
| 11794 | info.mv1, |
| 11795 | (g.y.as_slice(), g.width, luma.true_width, luma.true_height), |
| 11796 | ) |
| 11797 | }) |
| 11798 | }); |
| 11799 | match info.ref1.is_some() && second.is_none() { |
| 11800 | true => { |
| 11801 | luma.commit(x, y, BLOCK, &best.luma); |
| 11802 | (best.luma.levels.clone(), 0, 0.0, Vec::new()) |
| 11803 | } |
| 11804 | false => commit_inter_luma( |
| 11805 | luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second, |
| 11806 | fctx, |
| 11807 | ), |
| 11808 | } |
| 11809 | } |
| 11810 | None => { |
| 11811 | luma.commit(x, y, BLOCK, &best.luma); |
| 11812 | (best.luma.levels.clone(), 0, 0.0, Vec::new()) |
| 11813 | } |
| 11814 | }; |
| 11815 | // lane-txrd: chroma follows the luma type the var-tx/type search chose. |
| 11816 | let [bu, bv] = match (best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied()) { |
| 11817 | (Some(info), Some(t)) => { |
| 11818 | let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) { |
| 11819 | Some(&(_, g, _)) => ( |
| 11820 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 11821 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 11822 | ), |
| 11823 | None => ( |
| 11824 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), |
| 11825 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), |
| 11826 | ), |
| 11827 | }; |
| 11828 | let sec = info.ref1.and_then(|r| { |
| 11829 | compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| { |
| 11830 | ( |
| 11831 | info.mv1, |
| 11832 | [ |
| 11833 | (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 11834 | (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 11835 | ], |
| 11836 | ) |
| 11837 | }) |
| 11838 | }); |
| 11839 | recode_inter_chroma( |
| 11840 | chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx, |
| 11841 | ) |
| 11842 | .unwrap_or([best.u, best.v]) |
| 11843 | } |
| 11844 | _ => [best.u, best.v], |
| 11845 | }; |
| 11846 | let best = Candidate { u: bu, v: bv, ..best }; |
| 11847 | chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); |
| 11848 | chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); |
| 11849 | ( |
| 11850 | BlockCoeffs { |
| 11851 | luma_tx_types, |
| 11852 | angle_delta_y: 0, |
| 11853 | cfl_alphas: None, |
| 11854 | filter_intra: None, |
| 11855 | luma: coeffs(&levels, BLOCK), |
| 11856 | u: coeffs(&best.u.levels, BLOCK / 2), |
| 11857 | v: coeffs(&best.v.levels, BLOCK / 2), |
| 11858 | mode: best.mode, |
| 11859 | uv_mode: DC_PRED, |
| 11860 | skip: best.skip, |
| 11861 | inter: best.inter, |
| 11862 | motion_mode: motion_won, |
| 11863 | eight: None, |
| 11864 | dv: None, |
| 11865 | palette: None, |
| 11866 | palette_uv: None, |
| 11867 | tx_depth, |
| 11868 | }, |
| 11869 | best.cost + dcost, |
| 11870 | ) |
| 11871 | } |
| 11872 | |
| 11873 | /// lane-av1tpl: the strength `k` of the temporal lambda weighting |
| 11874 | /// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which |
| 11875 | /// is what every measurement before this lane was taken on. Swept by |
| 11876 | /// `EC_AV1_TPL=<k>`. |
| 11877 | /// |
| 11878 | /// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs |
| 11879 | /// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane |
| 11880 | /// baseline exactly, which is the control the rest of the table is read |
| 11881 | /// against: |
| 11882 | /// |
| 11883 | /// | k | film 1080p | film 2160p | screen | |
| 11884 | /// |---|---|---|---| |
| 11885 | /// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 | |
| 11886 | /// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 | |
| 11887 | /// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** | |
| 11888 | /// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 | |
| 11889 | /// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 | |
| 11890 | /// |
| 11891 | /// 0.5 is the only arm that is at least flat on every row and down on five of |
| 11892 | /// the six columns, so it ships as the default. The lookahead pass that feeds |
| 11893 | /// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%). |
| 11894 | const TPL_STRENGTH: f64 = 0.5; |
| 11895 | |
| 11896 | /// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec |
| 11897 | /// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then |
| 11898 | /// byte-identical to the pre-lane one); anything else is the `delta_q_res` |
| 11899 | /// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off. |
| 11900 | /// |
| 11901 | /// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has |
| 11902 | /// nothing to vary the quantizer BY and codes no delta syntax at all. |
| 11903 | fn deltaq_res_log2() -> Option<u8> { |
| 11904 | match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { |
| 11905 | u8::MAX => {} |
| 11906 | 4 => return None, |
| 11907 | r => return Some(r), |
| 11908 | } |
| 11909 | match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) { |
| 11910 | Some("0") => None, |
| 11911 | Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3), |
| 11912 | None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4), |
| 11913 | } |
| 11914 | } |
| 11915 | |
| 11916 | /// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the |
| 11917 | /// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that |
| 11918 | /// sets it holds [`crate::speed::knob_write`], the same exclusive lock the |
| 11919 | /// speed presets take, because the streams every other test pins move under |
| 11920 | /// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]). |
| 11921 | static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = |
| 11922 | std::sync::atomic::AtomicU8::new(u8::MAX); |
| 11923 | |
| 11924 | /// Sets [`DELTAQ_OVERRIDE`]; `None` clears it. |
| 11925 | #[allow(dead_code)] // set only from the `#[cfg(test)]` gates |
| 11926 | pub(crate) fn set_deltaq_res(res_log2: Option<u8>) { |
| 11927 | DELTAQ_OVERRIDE.store( |
| 11928 | res_log2.unwrap_or(u8::MAX), |
| 11929 | std::sync::atomic::Ordering::Relaxed, |
| 11930 | ); |
| 11931 | } |
| 11932 | |
| 11933 | /// How much of the derived qindex step is actually taken |
| 11934 | /// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation). |
| 11935 | fn deltaq_k() -> f64 { |
| 11936 | crate::envflags::var("EC_AV1_DELTAQ_K") |
| 11937 | .ok() |
| 11938 | .and_then(|v| v.trim().parse::<f64>().ok()) |
| 11939 | .filter(|k| k.is_finite() && *k >= 0.0) |
| 11940 | .unwrap_or(1.0) |
| 11941 | } |
| 11942 | |
| 11943 | /// The largest qindex the map may move a superblock by, either way |
| 11944 | /// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective |
| 11945 | /// deltaq around a quarter of the base qindex). |
| 11946 | fn deltaq_clamp() -> i32 { |
| 11947 | crate::envflags::var("EC_AV1_DELTAQ_CLAMP") |
| 11948 | .ok() |
| 11949 | .and_then(|v| v.trim().parse::<i32>().ok()) |
| 11950 | .filter(|c| (0..=63).contains(c)) |
| 11951 | .unwrap_or(16) |
| 11952 | } |
| 11953 | |
| 11954 | /// The qindex a lambda factor `f` asks for, derived rather than fitted. |
| 11955 | /// |
| 11956 | /// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the |
| 11957 | /// square of the quantizer step (`encode_inter_frame`'s own |
| 11958 | /// `lambda = .. * step * step`), so the step this superblock wants is |
| 11959 | /// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the |
| 11960 | /// step ratio is inverted through the table itself -- the index whose `ac_q` |
| 11961 | /// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted |
| 11962 | /// constant. `k` scales the resulting step (1.0 takes all of it), `clamp` |
| 11963 | /// bounds it, and the answer is snapped onto the `res` grid so that every |
| 11964 | /// superblock's qindex is congruent to `base` and the coded delta is a whole |
| 11965 | /// number of steps. |
| 11966 | fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 { |
| 11967 | let base_ac = f64::from(ac_q(8, i32::from(base))); |
| 11968 | let target = base_ac * f.max(1e-6).sqrt(); |
| 11969 | let exact = (1..=255) |
| 11970 | .min_by(|&a, &b| { |
| 11971 | let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs(); |
| 11972 | d(a).partial_cmp(&d(b)).expect("ac_q is finite") |
| 11973 | }) |
| 11974 | .expect("the qindex range is not empty") |
| 11975 | - i32::from(base); |
| 11976 | let want = (exact as f64 * k).round() as i32; |
| 11977 | // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound |
| 11978 | // and need not be a whole number of steps, and clamping afterwards would |
| 11979 | // hand back a qindex that is not congruent to `base`. |
| 11980 | let max_steps = clamp / res; |
| 11981 | let steps = (want as f64 / f64::from(res)).round() as i32; |
| 11982 | let delta = steps.clamp(-max_steps, max_steps) * res; |
| 11983 | (i32::from(base) + delta).clamp(1, 255) as u8 |
| 11984 | } |
| 11985 | |
| 11986 | /// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1` |
| 11987 | /// objective would, from the SAME tpl dependence ratio our own map already |
| 11988 | /// carries (`EC_AV1_DQ_TPL=1`). |
| 11989 | /// |
| 11990 | /// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a |
| 11991 | /// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the |
| 11992 | /// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very |
| 11993 | /// same expression at frame scope) by it, and asks |
| 11994 | /// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose |
| 11995 | /// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and |
| 11996 | /// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`, |
| 11997 | /// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way |
| 11998 | /// libaom reads `r0`. The offset is clamped to libaom's own |
| 11999 | /// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than |
| 12000 | /// twice the +-16 qindex [`deltaq_for_factor`] allows. |
| 12001 | /// |
| 12002 | /// Two things differ from [`deltaq_for_factor`] and both are the point of the |
| 12003 | /// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw |
| 12004 | /// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed, |
| 12005 | /// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is |
| 12006 | /// much stronger for the same map. `strength` scales the offset. |
| 12007 | fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 { |
| 12008 | let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6); |
| 12009 | let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt(); |
| 12010 | let exact = (1..=255) |
| 12011 | .min_by(|&a, &b| { |
| 12012 | let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs(); |
| 12013 | d(a).partial_cmp(&d(b)).expect("dc_q is finite") |
| 12014 | }) |
| 12015 | .expect("the qindex range is not empty") |
| 12016 | - i32::from(base); |
| 12017 | let want = exact as f64 * strength; |
| 12018 | // Snapped onto the `res` grid first, so the coded delta is a whole number |
| 12019 | // of steps, then bounded by libaom's own `res * 9 - 1`. |
| 12020 | let max_steps = (res * 9 - 1) / res; |
| 12021 | let steps = (want / f64::from(res)).round() as i32; |
| 12022 | let delta = steps.clamp(-max_steps, max_steps) * res; |
| 12023 | (i32::from(base) + delta).clamp(1, 255) as u8 |
| 12024 | } |
| 12025 | |
| 12026 | /// The frame-level `r0` libaom's objective divides by: the log-mean of |
| 12027 | /// `1 + r` over the frame's cells, minus 1. |
| 12028 | fn tpl_frame_ratio(ratio: &[f64]) -> f64 { |
| 12029 | if ratio.is_empty() { |
| 12030 | return 0.0; |
| 12031 | } |
| 12032 | let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64; |
| 12033 | m.exp() - 1.0 |
| 12034 | } |
| 12035 | |
| 12036 | /// The [`deltaq_libaom`] strength, or `None` to keep the shipped |
| 12037 | /// [`deltaq_for_factor`] derivation. |
| 12038 | /// |
| 12039 | /// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K` |
| 12040 | /// the strength (default 1.0 = libaom's own offset when the flag armed it); |
| 12041 | /// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`]. |
| 12042 | fn dq_tpl_strength(level: DqLevel) -> Option<f64> { |
| 12043 | let m = dq_level_k()[level as usize]; |
| 12044 | let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K") |
| 12045 | .ok() |
| 12046 | .and_then(|v| v.trim().parse::<f64>().ok()) |
| 12047 | .filter(|k| k.is_finite() && *k >= 0.0); |
| 12048 | let base = match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) { |
| 12049 | Some("0") => return None, |
| 12050 | Some(_) => Some(env_k.unwrap_or(1.0)), |
| 12051 | None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))), |
| 12052 | }; |
| 12053 | base.map(|k| k * m).filter(|k| *k > 0.0) |
| 12054 | } |
| 12055 | |
| 12056 | /// lane-arfq: which pyramid level the frame asking for a |
| 12057 | /// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it |
| 12058 | /// codes no `delta_q` syntax at all (the whole lever lives in |
| 12059 | /// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the |
| 12060 | /// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job. |
| 12061 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 12062 | pub(crate) enum DqLevel { |
| 12063 | /// The mini-GOP's own hidden `ALTREF`, which every other frame of the |
| 12064 | /// group predicts from (directly or through the mid level). |
| 12065 | TopArf = 0, |
| 12066 | /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it. |
| 12067 | MidArf = 1, |
| 12068 | /// A shown leaf -- and every frame of the flat, non-pyramid path. |
| 12069 | Leaf = 2, |
| 12070 | } |
| 12071 | |
| 12072 | /// The per-level multiplier on the [`dq_tpl_strength`] the preset carries: |
| 12073 | /// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else |
| 12074 | /// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes |
| 12075 | /// no `delta_q` (see [`DqLevel`]). |
| 12076 | fn dq_level_k() -> [f64; 3] { |
| 12077 | dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref()) |
| 12078 | } |
| 12079 | |
| 12080 | /// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an |
| 12081 | /// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry. |
| 12082 | fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] { |
| 12083 | let mut k = crate::speed::DQ_LEVEL_K; |
| 12084 | if let Some(spec) = spec { |
| 12085 | for (slot, field) in k.iter_mut().zip(spec.split(':')) { |
| 12086 | if let Some(v) = |
| 12087 | field.trim().parse::<f64>().ok().filter(|v: &f64| v.is_finite() && *v >= 0.0) |
| 12088 | { |
| 12089 | *slot = v; |
| 12090 | } |
| 12091 | } |
| 12092 | } |
| 12093 | k |
| 12094 | } |
| 12095 | |
| 12096 | /// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the |
| 12097 | /// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones |
| 12098 | /// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and |
| 12099 | /// the same tpl map -- and which of the two the frame actually coded. |
| 12100 | fn dq_census() -> bool { |
| 12101 | crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1") |
| 12102 | } |
| 12103 | |
| 12104 | /// The histogram/extent summary [`dq_census`] prints for one set of offsets. |
| 12105 | fn dq_summary(offsets: &[i32]) -> String { |
| 12106 | let n = offsets.len().max(1); |
| 12107 | let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o))); |
| 12108 | let nz = offsets.iter().filter(|&&o| o != 0).count(); |
| 12109 | let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64; |
| 12110 | let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64; |
| 12111 | let mut levels: Vec<i32> = offsets.to_vec(); |
| 12112 | levels.sort_unstable(); |
| 12113 | levels.dedup(); |
| 12114 | format!( |
| 12115 | "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}", |
| 12116 | offsets.len(), |
| 12117 | levels.len() |
| 12118 | ) |
| 12119 | } |
| 12120 | |
| 12121 | /// How many DISTINCT per-superblock quantizer levels the last inter frame's |
| 12122 | /// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter |
| 12123 | /// (class `gate-blind-to-feature`: every exactness assert below passes on a |
| 12124 | /// grid that is one flat value, i.e. on no delta_q at all). Process-global |
| 12125 | /// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which |
| 12126 | /// keeps the LARGEST count seen since the last read. |
| 12127 | static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 12128 | |
| 12129 | /// [`DELTAQ_LEVELS`], reset to 0. |
| 12130 | #[allow(dead_code)] // read only from the `#[cfg(test)]` gates |
| 12131 | pub(crate) fn take_deltaq_levels() -> usize { |
| 12132 | DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 12133 | } |
| 12134 | |
| 12135 | /// This superblock's search state: the quantizer it is coded at, and the |
| 12136 | /// lambda that quantizer implies. RD lambda goes as the square of the step, |
| 12137 | /// which is exactly the relation [`deltaq_for_factor`] inverted, so with no |
| 12138 | /// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour |
| 12139 | /// before lane-deltaq). |
| 12140 | fn sb_q_search<'m>( |
| 12141 | sb_q: &[u8], |
| 12142 | sb_cols: usize, |
| 12143 | base_q_idx: u8, |
| 12144 | (sb_r, sb_c): (usize, usize), |
| 12145 | base: Search<'m>, |
| 12146 | ) -> Search<'m> { |
| 12147 | let q = sb_q[sb_r * sb_cols + sb_c]; |
| 12148 | let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx))); |
| 12149 | Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base } |
| 12150 | } |
| 12151 | |
| 12152 | fn tpl_strength() -> f64 { |
| 12153 | std::env::var("EC_AV1_TPL") |
| 12154 | .ok() |
| 12155 | .and_then(|v| v.parse::<f64>().ok()) |
| 12156 | .filter(|k| k.is_finite() && *k >= 0.0) |
| 12157 | .unwrap_or(TPL_STRENGTH) |
| 12158 | } |
| 12159 | |
| 12160 | /// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting |
| 12161 | /// the frame being coded. 1 turns the weighting off; 2 is the shipped |
| 12162 | /// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under |
| 12163 | /// [`tpl_propagating`], which is the map that can actually use them and is |
| 12164 | /// the default since lane-av1tpl3, so the default window is 8. Swept by |
| 12165 | /// `EC_AV1_TPL_D=<d>`. |
| 12166 | /// |
| 12167 | /// The streaming facade holds `depth - 1` pictures back so it feeds |
| 12168 | /// `encode_inter_frame` the same window `encode_sequence` does; both read |
| 12169 | /// THIS function, so the two paths cannot disagree about the window. |
| 12170 | pub(crate) const TPL_DEPTH: usize = 8; |
| 12171 | |
| 12172 | /// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]). |
| 12173 | /// 0.5 is libaom's own square-root compression of its dependence ratio. |
| 12174 | const TPL_POWER: f64 = 0.5; |
| 12175 | |
| 12176 | /// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the |
| 12177 | /// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`. |
| 12178 | /// |
| 12179 | /// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom |
| 12180 | /// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map |
| 12181 | /// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]: |
| 12182 | /// |
| 12183 | /// | k | D | p | film 1080p | film 2160p | screen | |
| 12184 | /// |---|---|---|---|---|---| |
| 12185 | /// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 | |
| 12186 | /// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 | |
| 12187 | /// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 | |
| 12188 | /// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 | |
| 12189 | /// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 | |
| 12190 | /// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 | |
| 12191 | /// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 | |
| 12192 | /// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 | |
| 12193 | /// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 | |
| 12194 | /// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** | |
| 12195 | /// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 | |
| 12196 | /// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 | |
| 12197 | /// |
| 12198 | /// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of |
| 12199 | /// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside |
| 12200 | /// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p |
| 12201 | /// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was |
| 12202 | /// 0.1..0.4 UP on film 2160p, so it shipped off. |
| 12203 | /// |
| 12204 | /// lane-av1tpl3 found why and turned it on. The denominator is the cell's own |
| 12205 | /// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour |
| 12206 | /// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of |
| 12207 | /// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1 |
| 12208 | /// wherever the window leans on a flat bar, which is exactly where coding is |
| 12209 | /// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio |
| 12210 | /// (libaom's own granularity) puts a busy cell's denominator next to the flat |
| 12211 | /// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed |
| 12212 | /// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on |
| 12213 | /// the same native gate (baseline = the shipped one-frame map): |
| 12214 | /// |
| 12215 | /// | arm | film 1080p | film 2160p | screen | |
| 12216 | /// |---|---|---|---| |
| 12217 | /// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 | |
| 12218 | /// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 | |
| 12219 | /// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 | |
| 12220 | /// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 | |
| 12221 | /// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 | |
| 12222 | /// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 | |
| 12223 | /// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 | |
| 12224 | /// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 | |
| 12225 | /// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 | |
| 12226 | /// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** | |
| 12227 | /// |
| 12228 | /// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4, |
| 12229 | /// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships |
| 12230 | /// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The |
| 12231 | /// floor is a real effect on the ratio and never a win once the aggregation |
| 12232 | /// is in -- the aggregation is the same fix, done where libaom does it. |
| 12233 | fn tpl_propagating() -> bool { |
| 12234 | std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0") |
| 12235 | } |
| 12236 | |
| 12237 | pub(crate) fn tpl_depth() -> usize { |
| 12238 | std::env::var("EC_AV1_TPL_D") |
| 12239 | .ok() |
| 12240 | .and_then(|v| v.parse::<usize>().ok()) |
| 12241 | .filter(|d| *d >= 1) |
| 12242 | .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH)) |
| 12243 | .max(1) |
| 12244 | } |
| 12245 | |
| 12246 | /// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this |
| 12247 | /// process, so the gate can price it against the encode it rides on. |
| 12248 | static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 12249 | |
| 12250 | /// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell, |
| 12251 | /// the winning displacement and its SAD. |
| 12252 | /// |
| 12253 | /// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at |
| 12254 | /// the left/above winners, first-best tie-break. Built once on the frame's |
| 12255 | /// own thread and read-only afterwards, so it cannot make a tile's bytes |
| 12256 | /// depend on the thread count. |
| 12257 | fn tpl_coarse_pass( |
| 12258 | cur: &[u8], |
| 12259 | next: &[u8], |
| 12260 | width: usize, |
| 12261 | height: usize, |
| 12262 | ) -> Vec<((i32, i32), u32)> { |
| 12263 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 12264 | let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 { |
| 12265 | let (sx, sy) = (bx as i32 + mx, by as i32 + my); |
| 12266 | if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height { |
| 12267 | return u32::MAX; |
| 12268 | } |
| 12269 | let (sx, sy) = (sx as usize, sy as usize); |
| 12270 | let mut sum = 0u32; |
| 12271 | for r in 0..16 { |
| 12272 | let a = &next[(by + r) * width + bx..][..16]; |
| 12273 | let b = &cur[(sy + r) * width + sx..][..16]; |
| 12274 | sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>(); |
| 12275 | } |
| 12276 | sum |
| 12277 | }; |
| 12278 | let mut out = Vec::with_capacity(cells_x * cells_y); |
| 12279 | let mut above = vec![(0i32, 0i32); cells_x]; |
| 12280 | for cy in 0..cells_y { |
| 12281 | let mut left = (0i32, 0i32); |
| 12282 | for cx in 0..cells_x { |
| 12283 | let (bx, by) = (cx * 16, cy * 16); |
| 12284 | let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32)); |
| 12285 | for cand in [left, above[cx]] { |
| 12286 | if cand != (0, 0) { |
| 12287 | let s = sad(bx, by, cand); |
| 12288 | if s < best.0 { |
| 12289 | best = (s, cand); |
| 12290 | } |
| 12291 | } |
| 12292 | } |
| 12293 | for step in [8i32, 4, 2, 1] { |
| 12294 | let centre = best.1; |
| 12295 | for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] { |
| 12296 | let mv = (centre.0 + dx, centre.1 + dy); |
| 12297 | if mv.0.abs() > 32 || mv.1.abs() > 32 { |
| 12298 | continue; |
| 12299 | } |
| 12300 | let s = sad(bx, by, mv); |
| 12301 | if s < best.0 { |
| 12302 | best = (s, mv); |
| 12303 | } |
| 12304 | } |
| 12305 | } |
| 12306 | left = best.1; |
| 12307 | above[cx] = best.1; |
| 12308 | out.push((best.1, best.0)); |
| 12309 | } |
| 12310 | } |
| 12311 | out |
| 12312 | } |
| 12313 | |
| 12314 | /// The intra-cost proxy libaom's tpl gets from a DC prediction plus a |
| 12315 | /// transform: here, the mean absolute deviation of the cell from its own DC. |
| 12316 | /// It is the denominator every propagated cost is read against, so only its |
| 12317 | /// SHAPE across the frame matters, not its scale. |
| 12318 | fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> { |
| 12319 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 12320 | let mut out = Vec::with_capacity(cells_x * cells_y); |
| 12321 | for cy in 0..cells_y { |
| 12322 | for cx in 0..cells_x { |
| 12323 | let (bx, by) = (cx * 16, cy * 16); |
| 12324 | let mut sum = 0u32; |
| 12325 | for r in 0..16 { |
| 12326 | sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>(); |
| 12327 | } |
| 12328 | let dc = ((sum + 128) / 256) as u8; |
| 12329 | let mut cost = 0u32; |
| 12330 | for r in 0..16 { |
| 12331 | cost += frame[(by + r) * width + bx..][..16] |
| 12332 | .iter() |
| 12333 | .map(|&p| u32::from(p.abs_diff(dc))) |
| 12334 | .sum::<u32>(); |
| 12335 | } |
| 12336 | out.push(cost); |
| 12337 | } |
| 12338 | } |
| 12339 | out |
| 12340 | } |
| 12341 | |
| 12342 | /// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS |
| 12343 | /// frame the next one predicts from, per 16x16 cell -- each cell of `next` |
| 12344 | /// splats its own area, at its winning displacement, onto the (at most four) |
| 12345 | /// cells of `cur` it lands on. 1.0 is "referenced exactly once". |
| 12346 | fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> { |
| 12347 | let start = std::time::Instant::now(); |
| 12348 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 12349 | let pass = tpl_coarse_pass(cur, next, width, height); |
| 12350 | let mut area = vec![0.0f64; cells_x * cells_y]; |
| 12351 | for cy in 0..cells_y { |
| 12352 | for cx in 0..cells_x { |
| 12353 | let (mv, _) = pass[cy * cells_x + cx]; |
| 12354 | let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); |
| 12355 | let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); |
| 12356 | for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) { |
| 12357 | let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16); |
| 12358 | for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) { |
| 12359 | let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16); |
| 12360 | area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0; |
| 12361 | } |
| 12362 | } |
| 12363 | } |
| 12364 | } |
| 12365 | TPL_NANOS.fetch_add( |
| 12366 | start.elapsed().as_nanos() as u64, |
| 12367 | std::sync::atomic::Ordering::Relaxed, |
| 12368 | ); |
| 12369 | area |
| 12370 | } |
| 12371 | |
| 12372 | /// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda |
| 12373 | /// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where |
| 12374 | /// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean. |
| 12375 | /// Decreasing in referenced-ness (a block the next frame leans on is coded |
| 12376 | /// more distortion-averse) and 1.0 at the frame's own mean, so the frame's |
| 12377 | /// total lambda scale is only redistributed, never moved -- a global move is |
| 12378 | /// the thing lane-av1lambda already measured inert. |
| 12379 | fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> { |
| 12380 | let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4); |
| 12381 | let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6); |
| 12382 | let mut out = Vec::with_capacity(sb_cols * sb_rows); |
| 12383 | for sr in 0..sb_rows { |
| 12384 | for sc in 0..sb_cols { |
| 12385 | let mut sum = 0.0; |
| 12386 | for r in 0..4 { |
| 12387 | for c in 0..4 { |
| 12388 | sum += map[(sr * 4 + r) * cells_x + sc * 4 + c]; |
| 12389 | } |
| 12390 | } |
| 12391 | let w_rel = sum / 16.0 / mean; |
| 12392 | out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0)); |
| 12393 | } |
| 12394 | } |
| 12395 | if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { |
| 12396 | let mut hist = [0usize; 8]; |
| 12397 | for w in map { |
| 12398 | hist[((w / mean * 2.0) as usize).min(7)] += 1; |
| 12399 | } |
| 12400 | let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); |
| 12401 | eprintln!( |
| 12402 | "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \ |
| 12403 | sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative", |
| 12404 | map.len(), |
| 12405 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 12406 | ); |
| 12407 | } |
| 12408 | out |
| 12409 | } |
| 12410 | |
| 12411 | /// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda |
| 12412 | /// factor per 16x16 cell of `frames[0]` (the frame being coded), from how |
| 12413 | /// much of the WHOLE lookahead window leans on that cell. |
| 12414 | /// |
| 12415 | /// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the |
| 12416 | /// coarse pass gives a displacement and an inter cost; a cell's own |
| 12417 | /// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that |
| 12418 | /// cell well saves the frames that predict from it -- and it is splatted, |
| 12419 | /// area-weighted, onto the (at most four) cells of `frames[f-1]` its |
| 12420 | /// displacement lands on. Walking `f` from the far end of the window back to |
| 12421 | /// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame |
| 12422 | /// area map could not do at all. |
| 12423 | /// |
| 12424 | /// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean |
| 12425 | /// factor over the frame is exactly 1: a cell the window leans on is coded |
| 12426 | /// more distortion-averse (smaller lambda), and the frame's TOTAL lambda |
| 12427 | /// scale only moves around, never up or down -- a global move is what |
| 12428 | /// lane-av1lambda already measured inert. |
| 12429 | /// Returns the per-cell lambda factors AND the per-cell dependence ratio |
| 12430 | /// `mc_dep / intra` they were derived from -- the second half is what |
| 12431 | /// [`deltaq_libaom`] needs, since the factor alone has been through a |
| 12432 | /// mean normalisation the raw ratio cannot be recovered across. |
| 12433 | fn tpl_lambda_factors( |
| 12434 | frames: &[&[u8]], |
| 12435 | width: usize, |
| 12436 | height: usize, |
| 12437 | k: f64, |
| 12438 | ) -> (Vec<f64>, Vec<f64>) { |
| 12439 | let start = std::time::Instant::now(); |
| 12440 | let (cells_x, cells_y) = (width / 16, height / 16); |
| 12441 | let cells = cells_x * cells_y; |
| 12442 | let levels = frames.len(); |
| 12443 | let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect(); |
| 12444 | let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels) |
| 12445 | .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height)) |
| 12446 | .collect(); |
| 12447 | let mut mc_dep = vec![vec![0.0f64; cells]; levels]; |
| 12448 | for f in (1..levels).rev() { |
| 12449 | for cy in 0..cells_y { |
| 12450 | for cx in 0..cells_x { |
| 12451 | let ci = cy * cells_x + cx; |
| 12452 | let (mv, inter) = passes[f - 1][ci]; |
| 12453 | let saved = f64::from(intra[f][ci].saturating_sub(inter)); |
| 12454 | let propagate = saved + mc_dep[f][ci]; |
| 12455 | if propagate <= 0.0 { |
| 12456 | continue; |
| 12457 | } |
| 12458 | // The 16x16 window of the PREVIOUS frame this cell predicted |
| 12459 | // from, spread over the cells it overlaps. |
| 12460 | let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1); |
| 12461 | let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); |
| 12462 | for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) { |
| 12463 | let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16); |
| 12464 | for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) { |
| 12465 | let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16); |
| 12466 | mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0; |
| 12467 | } |
| 12468 | } |
| 12469 | } |
| 12470 | } |
| 12471 | } |
| 12472 | // The tail compression `p`: `mc_dep/intra` is a ratio with a very long |
| 12473 | // tail (a nearly flat cell the window leans on has a tiny denominator), |
| 12474 | // and at p = 1 that tail slams into the clamp. libaom reads its own |
| 12475 | // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P` |
| 12476 | // sweeps the exponent, 1 being the raw ratio. |
| 12477 | let power = std::env::var("EC_AV1_TPL_P") |
| 12478 | .ok() |
| 12479 | .and_then(|v| v.parse::<f64>().ok()) |
| 12480 | .filter(|p| p.is_finite() && *p > 0.0) |
| 12481 | .unwrap_or(TPL_POWER); |
| 12482 | // lane-av1tpl3, the three shape fixes, each its own knob so the gate can |
| 12483 | // read them apart. `SB` and `LOG` are the shipped shape (set the knob to |
| 12484 | // `0` to take either back out); `FLOOR` defaults to off. |
| 12485 | // |
| 12486 | // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the |
| 12487 | // frame's own mean intra cost. A cell of flat content has a near-zero |
| 12488 | // MAD, so its ratio explodes exactly where coding is cheap. |
| 12489 | // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra |
| 12490 | // and mc_dep are summed over the 64x64 superblock first -- libaom's |
| 12491 | // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not |
| 12492 | // per-16x16 numbers), which is also what makes the ratio survive one |
| 12493 | // flat cell next to a busy one. |
| 12494 | // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through |
| 12495 | // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail |
| 12496 | // harder than the `p` exponent alone can. |
| 12497 | let floor_frac = std::env::var("EC_AV1_TPL_FLOOR") |
| 12498 | .ok() |
| 12499 | .and_then(|v| v.parse::<f64>().ok()) |
| 12500 | .filter(|f| f.is_finite() && *f >= 0.0) |
| 12501 | .unwrap_or(0.0); |
| 12502 | let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0"); |
| 12503 | let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0"); |
| 12504 | let intra_mean = |
| 12505 | intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64; |
| 12506 | let floor = floor_frac * intra_mean; |
| 12507 | let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0); |
| 12508 | // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by |
| 12509 | // every cell under it. The edge groups are partial and summed as they are. |
| 12510 | let ratio: Vec<f64> = if sb_agg { |
| 12511 | let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4)); |
| 12512 | let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows]; |
| 12513 | for cy in 0..cells_y { |
| 12514 | for cx in 0..cells_x { |
| 12515 | let e = &mut sb[(cy / 4) * sb_cols + cx / 4]; |
| 12516 | e.0 += mc_dep[0][cy * cells_x + cx]; |
| 12517 | e.1 += denom(cy * cells_x + cx); |
| 12518 | } |
| 12519 | } |
| 12520 | (0..cells) |
| 12521 | .map(|c| { |
| 12522 | let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4]; |
| 12523 | dep / den.max(1.0) |
| 12524 | }) |
| 12525 | .collect() |
| 12526 | } else { |
| 12527 | (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect() |
| 12528 | }; |
| 12529 | let mut out: Vec<f64> = ratio |
| 12530 | .iter() |
| 12531 | .map(|&r| { |
| 12532 | let r = if log_beta { (1.0 + r).log2() } else { r }; |
| 12533 | (1.0 + k * r).powf(-power) |
| 12534 | }) |
| 12535 | .collect(); |
| 12536 | let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9); |
| 12537 | for f in &mut out { |
| 12538 | *f = (*f / mean).clamp(0.25, 4.0); |
| 12539 | } |
| 12540 | TPL_NANOS.fetch_add( |
| 12541 | start.elapsed().as_nanos() as u64, |
| 12542 | std::sync::atomic::Ordering::Relaxed, |
| 12543 | ); |
| 12544 | if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") { |
| 12545 | let mut hist = [0usize; 8]; |
| 12546 | for &f in &out { |
| 12547 | hist[((f * 4.0) as usize).min(7)] += 1; |
| 12548 | } |
| 12549 | let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f))); |
| 12550 | let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count(); |
| 12551 | eprintln!( |
| 12552 | "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \ |
| 12553 | range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative", |
| 12554 | TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6, |
| 12555 | ); |
| 12556 | } |
| 12557 | (out, ratio) |
| 12558 | } |
| 12559 | |
| 12560 | /// Where one inter frame sits in a coding-order pyramid: which DPB slots its |
| 12561 | /// references name, which slot it refreshes, whether it is shown when it is |
| 12562 | /// coded, and the `ref_frame_sign_bias` that follows from all of it. `None` |
| 12563 | /// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot |
| 12564 | /// 0/2 alternation, every frame shown, every reference in the past). |
| 12565 | /// |
| 12566 | /// The sign bias is carried rather than derived here because only the caller |
| 12567 | /// knows what order hint each slot holds; it is armed onto the tile writer |
| 12568 | /// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so |
| 12569 | /// the writer scans the same stacks the decoder will. |
| 12570 | #[derive(Debug, Clone, Copy)] |
| 12571 | pub(crate) struct PyramidFrame { |
| 12572 | /// The slot `LAST_FRAME` (and every reference this encoder does not name |
| 12573 | /// apart) reads. |
| 12574 | pub last_slot: u8, |
| 12575 | /// The single slot `refresh_frame_flags` sets. |
| 12576 | pub self_slot: u8, |
| 12577 | /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a |
| 12578 | /// pyramid, which is what makes `sign_bias`'s last entry true. |
| 12579 | pub altref_slot: u8, |
| 12580 | /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past |
| 12581 | /// picture (the leaf chain alternates its refresh between two slots, so |
| 12582 | /// the frame before `LAST` is still intact). `None` leaves |
| 12583 | /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder |
| 12584 | /// wrote before, and the caller then passes no `last2` picture either. |
| 12585 | pub last2_slot: Option<u8>, |
| 12586 | /// `show_frame`: false for a hidden frame, output later by a |
| 12587 | /// `show_existing_frame` header. |
| 12588 | pub show_frame: bool, |
| 12589 | /// lane-arfq: which level's `delta_q` strength this frame reads |
| 12590 | /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid |
| 12591 | /// one share `Level::Arf` and differ only by their q offset. |
| 12592 | pub dq_level: DqLevel, |
| 12593 | /// This frame's `ref_frame_sign_bias` (spec 5.9.2). |
| 12594 | pub sign_bias: crate::mvstack::SignBiasTable, |
| 12595 | } |
| 12596 | |
| 12597 | /// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's |
| 12598 | /// `temporal_filter` in the small: every 16x16 luma block of `src` is |
| 12599 | /// motion-compensated from each picture of `window` (the group's own display |
| 12600 | /// neighbours, nearest first) and averaged in with weight |
| 12601 | /// `exp(-mse / strength)`, so a neighbour that matches badly contributes |
| 12602 | /// nothing and one that matches well cancels the grain the block's residual |
| 12603 | /// would otherwise have to code. |
| 12604 | /// |
| 12605 | /// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma |
| 12606 | /// rides the luma block's own vector (halved), which is what libaom does at |
| 12607 | /// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16 |
| 12608 | /// grid tiles it exactly. |
| 12609 | /// |
| 12610 | /// Priced before it was built by `encode::tests::arf_pred_census`: on film B |
| 12611 | /// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered |
| 12612 | /// one's (film A 5.9%) with the two past neighbours at strength 30, and the |
| 12613 | /// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the |
| 12614 | /// quality the ARF is coded at, so the substitution itself costs little. |
| 12615 | // lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and |
| 12616 | // `ARF_TF_WIN_FUT` future ones); this takes every picture in it. |
| 12617 | pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture { |
| 12618 | const SIDE: usize = 16; |
| 12619 | let neighbours: Vec<&Picture> = window |
| 12620 | .iter() |
| 12621 | .filter(|p| p.width == src.width && p.height == src.height) |
| 12622 | .collect(); |
| 12623 | if neighbours.is_empty() || strength <= 0.0 { |
| 12624 | return src.clone(); |
| 12625 | } |
| 12626 | let mut out = src.clone(); |
| 12627 | // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or |
| 12628 | // `None` when the displaced block leaves the picture. |
| 12629 | let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { |
| 12630 | let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); |
| 12631 | if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width { |
| 12632 | return None; |
| 12633 | } |
| 12634 | let (sy, sx) = (sy as usize, sx as usize); |
| 12635 | let mut acc = 0u64; |
| 12636 | for row in 0..SIDE { |
| 12637 | let c = &src.y[(by + row) * src.width + bx..][..SIDE]; |
| 12638 | let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; |
| 12639 | acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>(); |
| 12640 | } |
| 12641 | Some((acc, (sy, sx))) |
| 12642 | }; |
| 12643 | // The log-step diamond `arf_pred_census` priced this with. |
| 12644 | let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> { |
| 12645 | let mut best = sad(r, bx, by, (0, 0))?; |
| 12646 | let mut centre = (0isize, 0isize); |
| 12647 | let mut step = 16isize; |
| 12648 | while step >= 1 { |
| 12649 | let from = centre; |
| 12650 | for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] { |
| 12651 | let mv = (from.0 + dy * step, from.1 + dx * step); |
| 12652 | if let Some(s) = sad(r, bx, by, mv) { |
| 12653 | if s.0 < best.0 { |
| 12654 | best = s; |
| 12655 | centre = mv; |
| 12656 | } |
| 12657 | } |
| 12658 | } |
| 12659 | step /= 2; |
| 12660 | } |
| 12661 | Some(best.1) |
| 12662 | }; |
| 12663 | let (cw, ch) = (src.width / 2, src.height / 2); |
| 12664 | for by in (0..src.height).step_by(SIDE) { |
| 12665 | for bx in (0..src.width).step_by(SIDE) { |
| 12666 | if by + SIDE > src.height || bx + SIDE > src.width { |
| 12667 | continue; |
| 12668 | } |
| 12669 | let mut y_acc = vec![0f64; SIDE * SIDE]; |
| 12670 | let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]]; |
| 12671 | let mut wsum = 1.0f64; |
| 12672 | // Chroma keeps its OWN weight sum: an edge block whose halved |
| 12673 | // vector leaves the chroma plane contributes to luma only, and |
| 12674 | // dividing chroma by the luma sum would darken it (class |
| 12675 | // `metric blind to a plane`, on the encoder side). |
| 12676 | let mut cwsum = 1.0f64; |
| 12677 | for row in 0..SIDE { |
| 12678 | for col in 0..SIDE { |
| 12679 | y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]); |
| 12680 | } |
| 12681 | } |
| 12682 | for row in 0..SIDE / 2 { |
| 12683 | for col in 0..SIDE / 2 { |
| 12684 | let i = (by / 2 + row) * cw + bx / 2 + col; |
| 12685 | c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]); |
| 12686 | c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]); |
| 12687 | } |
| 12688 | } |
| 12689 | for r in &neighbours { |
| 12690 | let Some((sy, sx)) = search(r, bx, by) else { continue }; |
| 12691 | let mut sse = 0f64; |
| 12692 | for row in 0..SIDE { |
| 12693 | for col in 0..SIDE { |
| 12694 | let d = f64::from(src.y[(by + row) * src.width + bx + col]) |
| 12695 | - f64::from(r.y[(sy + row) * r.width + sx + col]); |
| 12696 | sse += d * d; |
| 12697 | } |
| 12698 | } |
| 12699 | let w = (-sse / (SIDE * SIDE) as f64 / strength).exp(); |
| 12700 | for row in 0..SIDE { |
| 12701 | for col in 0..SIDE { |
| 12702 | y_acc[row * SIDE + col] += |
| 12703 | w * f64::from(r.y[(sy + row) * r.width + sx + col]); |
| 12704 | } |
| 12705 | } |
| 12706 | // Chroma reads the luma vector halved; a block on the picture |
| 12707 | // edge whose halved vector would leave the chroma plane is |
| 12708 | // left to luma alone rather than clamped to a different |
| 12709 | // displacement than the luma it must stay registered with. |
| 12710 | let (cy, cx) = (sy / 2, sx / 2); |
| 12711 | if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw { |
| 12712 | for row in 0..SIDE / 2 { |
| 12713 | for col in 0..SIDE / 2 { |
| 12714 | let i = (cy + row) * cw + cx + col; |
| 12715 | c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]); |
| 12716 | c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]); |
| 12717 | } |
| 12718 | } |
| 12719 | cwsum += w; |
| 12720 | } |
| 12721 | wsum += w; |
| 12722 | } |
| 12723 | for row in 0..SIDE { |
| 12724 | for col in 0..SIDE { |
| 12725 | out.y[(by + row) * src.width + bx + col] = |
| 12726 | (y_acc[row * SIDE + col] / wsum).round() as u16; |
| 12727 | } |
| 12728 | } |
| 12729 | for row in 0..SIDE / 2 { |
| 12730 | for col in 0..SIDE / 2 { |
| 12731 | let i = (by / 2 + row) * cw + bx / 2 + col; |
| 12732 | out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16; |
| 12733 | out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16; |
| 12734 | } |
| 12735 | } |
| 12736 | } |
| 12737 | } |
| 12738 | out |
| 12739 | } |
| 12740 | |
| 12741 | /// Encodes one picture as an inter frame predicting from `reference`'s |
| 12742 | /// reconstruction, which the caller decoded (or, for the frame right after |
| 12743 | /// the key frame, is the key frame's own reconstruction). |
| 12744 | pub(crate) fn encode_inter_frame( |
| 12745 | picture: &Picture, |
| 12746 | reference: &Picture, |
| 12747 | base_q_idx: u8, |
| 12748 | deadzone: f64, |
| 12749 | order_hint: u32, |
| 12750 | // The order hint each of the seven `ref_frame_idx` entries names, which a |
| 12751 | // decoder reads out of its own reference state -- only spec 5.9.22's |
| 12752 | // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only |
| 12753 | // on a `reference_select` frame. [`flat_order_hints`] builds it for the |
| 12754 | // callers that follow this crate's own flat slot plan. |
| 12755 | order_hints: [u32; 7], |
| 12756 | render: (usize, usize), |
| 12757 | // The tables this frame's writer starts from: what the previous frame |
| 12758 | // stored into the slot this one's `primary_ref_frame` names. `None` |
| 12759 | // starts from the defaults, which is right only for the frame straight |
| 12760 | // after a key frame. |
| 12761 | start_cdfs: Option<&crate::cdf_state::Cdfs>, |
| 12762 | // The key frame's own (padded) reconstruction, which every frame of the |
| 12763 | // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame |
| 12764 | // with `LAST_FRAME` alone, exactly as before. |
| 12765 | golden: Option<&Picture>, |
| 12766 | // The frame two back, held in the slot this frame is about to refresh |
| 12767 | // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two |
| 12768 | // inter frames of a GOP, where the frame two back IS the key frame. |
| 12769 | altref: Option<&Picture>, |
| 12770 | // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown |
| 12771 | // frame BEFORE `reference` on the leaf chain, offered to the 32x32 |
| 12772 | // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF` |
| 12773 | // take. `None` (every caller but the pyramid leaves) codes the frame |
| 12774 | // with the reference set unchanged. |
| 12775 | last2: Option<&Picture>, |
| 12776 | fctx: &crate::decode::FrameCtx, |
| 12777 | // Where this frame sits in the coding-order pyramid; `None` is the flat |
| 12778 | // one-shown-frame-per-picture stream this encoder wrote before. |
| 12779 | pyramid: Option<PyramidFrame>, |
| 12780 | // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of |
| 12781 | // them), padded like this one -- the lookahead window the per-block |
| 12782 | // lambda weighting propagates back through ([`tpl_lambda_factors`]). An |
| 12783 | // EMPTY slice codes the frame at one lambda, as before. |
| 12784 | lookahead: &[Picture], |
| 12785 | ) -> Result<Encoded> { |
| 12786 | picture.check()?; |
| 12787 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 12788 | return Err(Error::unsupported( |
| 12789 | "AV1 encode", |
| 12790 | "an inter frame is coded only for a picture that is a whole number \ |
| 12791 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 12792 | superblock's partition below that", |
| 12793 | )); |
| 12794 | } |
| 12795 | if reference.width != picture.width || reference.height != picture.height { |
| 12796 | return Err(Error::unsupported( |
| 12797 | "AV1 encode", |
| 12798 | "the reference picture must be the same size as the one being coded", |
| 12799 | )); |
| 12800 | } |
| 12801 | |
| 12802 | // The single slot this crate's inter frames ever predict from or |
| 12803 | // refresh (`inter_frame_headers`'s contract): every frame both reads and |
| 12804 | // overwrites slot 0, so the frame just coded is always what the next one |
| 12805 | // predicts against. |
| 12806 | const LAST_SLOT: u8 = 0; |
| 12807 | // Slot 0 and slot 2 alternate so the frame two back survives one more |
| 12808 | // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2) |
| 12809 | // and the picture this frame names as `ALTREF_FRAME` is the one sitting |
| 12810 | // in the very slot it will overwrite. |
| 12811 | let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot); |
| 12812 | let last_slot = pyramid.map_or( |
| 12813 | if order_hint <= 1 { |
| 12814 | LAST_SLOT |
| 12815 | } else if (order_hint - 1) % 2 == 1 { |
| 12816 | 0 |
| 12817 | } else { |
| 12818 | 2 |
| 12819 | }, |
| 12820 | |p| p.last_slot, |
| 12821 | ); |
| 12822 | // `render`, not `picture.width`/`picture.height`: `picture` here is |
| 12823 | // already padded to a whole number of superblocks (`encode_sequence`'s |
| 12824 | // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so |
| 12825 | // every true-edge clamp downstream) must come from the frame's real, |
| 12826 | // unpadded size, same as `key_frame_headers_colour` takes `render` and |
| 12827 | // not the padded picture in `encode_key_frame_inner`. |
| 12828 | let (seq, mut header) = inter_frame_headers_slots( |
| 12829 | render.0, |
| 12830 | render.1, |
| 12831 | base_q_idx, |
| 12832 | order_hint, |
| 12833 | last_slot, |
| 12834 | self_slot, |
| 12835 | match pyramid { |
| 12836 | Some(p) => p.altref_slot, |
| 12837 | None if altref.is_some() => self_slot, |
| 12838 | None => GOLDEN_SLOT, |
| 12839 | }, |
| 12840 | )?; |
| 12841 | header.render_width = render.0 as u32; |
| 12842 | header.render_height = render.1 as u32; |
| 12843 | // lane-refs: this frame's motion-compensation kernel, written into the |
| 12844 | // header AND armed on the context every prediction reads, in one place so |
| 12845 | // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched |
| 12846 | // tile decodes to different pixels than the encoder scored). |
| 12847 | header.interpolation_filter = frame_interp_filter(); |
| 12848 | fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter)); |
| 12849 | let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); |
| 12850 | // The order hint behind each `ref_frame_idx` entry. The flat path's own |
| 12851 | // slot plan (`inter_frame_headers_slots`) is: every reference but |
| 12852 | // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except |
| 12853 | // `ALTREF_FRAME`, which reads the frame two back when there is one; |
| 12854 | // `GOLDEN_FRAME` is the key frame, order hint 0. Only |
| 12855 | // `frame::write_frame_header`'s `skipModeAllowed` reads this. |
| 12856 | header.order_hints = order_hints; |
| 12857 | // lane-last2: `inter_frame_headers_slots` points every un-named |
| 12858 | // reference at `last_slot`; the pyramid's leaf chain retains a second, |
| 12859 | // older picture and names it here. The caller's `sign_bias` / |
| 12860 | // `order_hints` entry 1 is derived from this same slot, so the stack |
| 12861 | // scans and `skipModeAllowed` read what the decoder will. |
| 12862 | if let Some(slot) = pyramid.and_then(|p| p.last2_slot) { |
| 12863 | header.ref_frame_idx[1] = slot; |
| 12864 | } |
| 12865 | header.reference_select = reference_select(); |
| 12866 | // Armed HERE, not only beside the tile write below: `ref_distance`'s own |
| 12867 | // per-reference order-hint distance is read by the block SEARCH, which |
| 12868 | // runs long before the writer arms these (the distance-scaled search step |
| 12869 | // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob |
| 12870 | // never reached the tool). |
| 12871 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 12872 | // lane-hpmv: armed here for the same reason the order hints are -- the |
| 12873 | // block SEARCH reads it (its eighth-pel stage) long before the writer. |
| 12874 | let hp_mv = header.allow_high_precision_mv; |
| 12875 | crate::tile::arm_high_precision_mv(hp_mv); |
| 12876 | if let Some(p) = pyramid { |
| 12877 | header.show_frame = p.show_frame; |
| 12878 | header.showable_frame = !p.show_frame; |
| 12879 | header.ref_frame_sign_bias = p.sign_bias; |
| 12880 | } |
| 12881 | // `TxMode::Select` here too: an inter block then codes one `txfm_split` |
| 12882 | // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA |
| 12883 | // block inside this frame codes and searches its own `tx_depth`, the same |
| 12884 | // as in a key frame (`crate::tile::write_tx_syntax_inter`). |
| 12885 | let tx_select = tx_select() && tx_select_inter(); |
| 12886 | if tx_select { |
| 12887 | header.tx_mode = TxMode::Select; |
| 12888 | } |
| 12889 | |
| 12890 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 12891 | // lane-palw: the encoder's own in-process reconstruct reads its palette |
| 12892 | // colour-index maps back through `decode::palette_onscreen`, which takes |
| 12893 | // the frame's mi dims off the `FrameCtx` -- a real decode gets them from |
| 12894 | // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish |
| 12895 | // them here so the reconstruct clamps a block cut by the frame edge |
| 12896 | // exactly as the writer now does. |
| 12897 | let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize); |
| 12898 | fctx.seg_mi_dims.set(frame_mi_dims); |
| 12899 | // lane-hbd r4: encoder stays 8-bit by design; narrow the source once |
| 12900 | // here (see `encode_key_frame_inner`). |
| 12901 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 12902 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 12903 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 12904 | // This frame's own `allow_screen_content_tools`. It can only be set when |
| 12905 | // the SEQUENCE offers the bit at all, which is the key frame's decision |
| 12906 | // ([`SEQ_SCREEN`]): a frame header that contradicts |
| 12907 | // `seq_force_screen_content_tools` is a corrupt stream, not a tighter |
| 12908 | // encode. |
| 12909 | let screen = seq_screen() |
| 12910 | && screen_content(&picture_y8, picture.width, true_width, true_height); |
| 12911 | header.allow_screen_content_tools = screen; |
| 12912 | // lane-txi, as on the key frame: the header bit the writer's own |
| 12913 | // `Cdfs` then reads for every luma `tx_type` symbol. |
| 12914 | header.reduced_tx_set = !wide_tx_set(screen); |
| 12915 | // lane-intertx, desync (a): the frame context this value is read back |
| 12916 | // through ([`decode::reduce_inherited_chroma_tx_type`] inside |
| 12917 | // `recode_inter_chroma`, and every inter decode helper the search's own |
| 12918 | // trial decode shares) must carry THIS frame's bit, not whatever the |
| 12919 | // previous frame's trial decode last left in the shared cell -- a stale |
| 12920 | // `true` here narrows the chroma allowance the search reconstructs |
| 12921 | // against under the one the header's bit actually allows. |
| 12922 | fctx.reduced_tx_set_inter.set(header.reduced_tx_set); |
| 12923 | // The search prices coefficients against the tables this frame's writer |
| 12924 | // starts from, not against the defaults (lane-av1txbits) -- but only on a |
| 12925 | // frame the screen detector said no to (lane-av1price2): armed HERE, after |
| 12926 | // `screen` exists, and again on every search/tile worker below. |
| 12927 | crate::tile::arm_pricing_cdfs(start_cdfs, screen); |
| 12928 | let mut luma = Plane { |
| 12929 | source: &picture_y8, |
| 12930 | reconstruction: vec![128; picture_y8.len()], |
| 12931 | width: picture.width, |
| 12932 | height: picture.height, |
| 12933 | true_width, |
| 12934 | true_height, |
| 12935 | tile_x0: 0, |
| 12936 | tile_y0: 0, |
| 12937 | tile_x1: picture.width, |
| 12938 | tile_y1: picture.height, |
| 12939 | ctx: CoefCtxMap::default(), |
| 12940 | }; |
| 12941 | let mut chroma = [ |
| 12942 | Plane { |
| 12943 | source: &picture_u8, |
| 12944 | reconstruction: vec![128; picture_u8.len()], |
| 12945 | width: picture.width / 2, |
| 12946 | height: picture.height / 2, |
| 12947 | true_width: true_width / 2, |
| 12948 | true_height: true_height / 2, |
| 12949 | tile_x0: 0, |
| 12950 | tile_y0: 0, |
| 12951 | tile_x1: picture.width / 2, |
| 12952 | tile_y1: picture.height / 2, |
| 12953 | ctx: CoefCtxMap::default(), |
| 12954 | }, |
| 12955 | Plane { |
| 12956 | source: &picture_v8, |
| 12957 | reconstruction: vec![128; picture_v8.len()], |
| 12958 | width: picture.width / 2, |
| 12959 | height: picture.height / 2, |
| 12960 | true_width: true_width / 2, |
| 12961 | true_height: true_height / 2, |
| 12962 | tile_x0: 0, |
| 12963 | tile_y0: 0, |
| 12964 | tile_x1: picture.width / 2, |
| 12965 | tile_y1: picture.height / 2, |
| 12966 | ctx: CoefCtxMap::default(), |
| 12967 | }, |
| 12968 | ]; |
| 12969 | |
| 12970 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 12971 | let top_arf = matches!( |
| 12972 | pyramid, |
| 12973 | Some(p) if p.dq_level == DqLevel::TopArf |
| 12974 | ); |
| 12975 | let arfmode_v = arfmode(); |
| 12976 | let search = Search { |
| 12977 | base_q_idx, |
| 12978 | deadzone, |
| 12979 | lambda: lambda_scale() |
| 12980 | * match pyramid { |
| 12981 | Some(p) if !p.show_frame => hidden_lambda_factor(), |
| 12982 | _ => 1.0, |
| 12983 | } |
| 12984 | * step |
| 12985 | * step, |
| 12986 | modes: &KEY_FRAME_MODES, |
| 12987 | top_k: prune_top_k_inter(), |
| 12988 | screen, |
| 12989 | // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose |
| 12990 | // offset is the pyramid's own `arf_q_offset`) reads its leaf offer |
| 12991 | // set from [`crate::speed::ARFMODE`]; every other frame -- the mid |
| 12992 | // and quarter hidden frames, the leaves, the flat path -- keeps the |
| 12993 | // full set. |
| 12994 | arf_leaf_intra: !top_arf || arfmode_v & 1 == 0, |
| 12995 | arf_leaf8: !top_arf || arfmode_v & 2 == 0, |
| 12996 | arf_leaf_compound: !top_arf || arfmode_v & 4 == 0, |
| 12997 | }; |
| 12998 | let mode_bits_table = inter_mode_bits(); |
| 12999 | // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of |
| 13000 | // this frame the NEXT one predicts from. Off (`None`) without a |
| 13001 | // lookahead picture or at strength 0. |
| 13002 | let tpl_k = tpl_strength(); |
| 13003 | let window: Vec<&Picture> = lookahead |
| 13004 | .iter() |
| 13005 | .take_while(|n| n.width == picture.width && n.height == picture.height) |
| 13006 | .collect(); |
| 13007 | let tpl_sources: Vec<Vec<u8>> = |
| 13008 | window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect(); |
| 13009 | let tpl_cells_x = picture.width / 16; |
| 13010 | // `.1` is the propagating map's raw per-cell dependence ratio, which only |
| 13011 | // [`deltaq_libaom`] reads; the one-frame area map has no such ratio. |
| 13012 | let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> = |
| 13013 | (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| { |
| 13014 | if tpl_propagating() { |
| 13015 | let mut frames: Vec<&[u8]> = vec![&picture_y8]; |
| 13016 | frames.extend(tpl_sources.iter().map(Vec::as_slice)); |
| 13017 | let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k); |
| 13018 | (f, Some(r)) |
| 13019 | } else { |
| 13020 | // The shipped map is one factor per 64x64; it is spread over that |
| 13021 | // superblock's own 16 cells so the application site below (which |
| 13022 | // averages the four cells of a 32x32 block) reads exactly the |
| 13023 | // superblock factor, whichever map fed it. |
| 13024 | let map = |
| 13025 | tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height); |
| 13026 | let cells_y = picture.height / 16; |
| 13027 | let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k); |
| 13028 | let f: Vec<f64> = (0..tpl_cells_x * cells_y) |
| 13029 | .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4]) |
| 13030 | .collect(); |
| 13031 | (f, None) |
| 13032 | } |
| 13033 | }); |
| 13034 | let (tpl_factors, tpl_ratio) = match tpl_both { |
| 13035 | Some((f, r)) => (Some(f), r), |
| 13036 | None => (None, None), |
| 13037 | }; |
| 13038 | |
| 13039 | // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded |
| 13040 | // coding surface's: `blocks` carries one entry per 32x32 block the tile |
| 13041 | // writer will actually visit, same count it checks `blocks.len()` |
| 13042 | // against, which is fewer than the padded surface's own block count |
| 13043 | // whenever the true size is not a 64x64 multiple. |
| 13044 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 13045 | let (cols, rows) = (cols as usize, rows as usize); |
| 13046 | let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 13047 | // lane-deltaq: one absolute qindex per 64x64 superblock, from the same |
| 13048 | // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present |
| 13049 | // only when the map is, and `delta_q_res` follows straight into the frame |
| 13050 | // header (`write_delta_q_params`) and into the tile writer's own plan. |
| 13051 | // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3 |
| 13052 | // measured the per-superblock quantizer as a win on both films and a |
| 13053 | // 0.5 loss vs libaom on the desktop capture, so a frame that set |
| 13054 | // `allow_screen_content_tools` codes no delta syntax at all and stays |
| 13055 | // byte-identical to the pre-lane encoder. |
| 13056 | // lane-arfq: the level whose `delta_q` strength this frame reads; the |
| 13057 | // flat path (no pyramid) is a leaf. |
| 13058 | let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level); |
| 13059 | let deltaq_res: Option<i32> = tpl_factors |
| 13060 | .as_ref() |
| 13061 | .filter(|_| !screen) |
| 13062 | .and(deltaq_res_log2().map(|r| 1i32 << r)); |
| 13063 | // The same 16-cell mean the superblock's own lambda takes, clamped to the |
| 13064 | // map the frame actually has -- read over the factors or over the raw |
| 13065 | // dependence ratios, whichever mapping is asking. |
| 13066 | let sb_mean = |m: &[f64], sb: usize| { |
| 13067 | let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols); |
| 13068 | (0..16) |
| 13069 | .map(|i| { |
| 13070 | let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4); |
| 13071 | m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)] |
| 13072 | }) |
| 13073 | .sum::<f64>() |
| 13074 | / 16.0 |
| 13075 | }; |
| 13076 | // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the |
| 13077 | // raw dependence ratio; without it (and always without a ratio map, i.e. |
| 13078 | // on the one-frame area map) the shipped derivation stands. |
| 13079 | let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio); |
| 13080 | let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 { |
| 13081 | match (libaom, tpl_ratio.as_deref(), r_frame) { |
| 13082 | (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res), |
| 13083 | _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res), |
| 13084 | } |
| 13085 | }; |
| 13086 | let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) { |
| 13087 | (Some(f), Some(res)) => { |
| 13088 | let libaom = dq_tpl_strength(dq_level); |
| 13089 | let mut g: Vec<u8> = |
| 13090 | (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect(); |
| 13091 | // lane-b128m: under 128 superblocks the delta_q syntax is coded |
| 13092 | // ONCE per 128 root (the reader's own unit), so all four 64x64 |
| 13093 | // cells of a root have to be searched -- and quantized -- at the |
| 13094 | // one qindex the root's top-left cell codes. |
| 13095 | if sb128_on() { |
| 13096 | for sb_r in 0.._sb_rows { |
| 13097 | for sb_c in 0..sb_cols { |
| 13098 | let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)]; |
| 13099 | g[sb_r * sb_cols + sb_c] = q; |
| 13100 | } |
| 13101 | } |
| 13102 | } |
| 13103 | Some(g) |
| 13104 | } |
| 13105 | _ => None, |
| 13106 | }; |
| 13107 | // lane-dq census: both mappings on the SAME superblocks, whether or not |
| 13108 | // the frame codes any delta syntax (`deltaq_res` is `None` with the lever |
| 13109 | // off, and the census then prices the default `res = 4` grid). |
| 13110 | if dq_census() { |
| 13111 | if let Some(f) = &tpl_factors { |
| 13112 | let res = deltaq_res.unwrap_or(4); |
| 13113 | let off = |libaom: Option<f64>| -> Vec<i32> { |
| 13114 | (0..sb_cols * _sb_rows) |
| 13115 | .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx)) |
| 13116 | .collect() |
| 13117 | }; |
| 13118 | let strength = dq_tpl_strength(dq_level); |
| 13119 | let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0)))); |
| 13120 | let coded = match (deltaq_res.is_some(), strength) { |
| 13121 | (false, _) => "none".to_string(), |
| 13122 | (true, None) => "ours".to_string(), |
| 13123 | (true, Some(k)) => format!("libaom k={k}"), |
| 13124 | }; |
| 13125 | eprintln!( |
| 13126 | "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}", |
| 13127 | sb_cols * _sb_rows, |
| 13128 | r_frame.unwrap_or(f64::NAN), |
| 13129 | dq_summary(&ours), |
| 13130 | dq_summary(&aom), |
| 13131 | ); |
| 13132 | } |
| 13133 | } |
| 13134 | if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) { |
| 13135 | header.delta.q_present = true; |
| 13136 | header.delta.q_res = res.trailing_zeros() as u8; |
| 13137 | } |
| 13138 | // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with |
| 13139 | // below, so the root search prices the group the writer really codes. |
| 13140 | let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0); |
| 13141 | if let Some(g) = &sb_q { |
| 13142 | let mut levels: Vec<u8> = g.clone(); |
| 13143 | levels.sort_unstable(); |
| 13144 | levels.dedup(); |
| 13145 | DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed); |
| 13146 | } |
| 13147 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 13148 | // This frame's tile grid, as in `encode_key_frame_inner`. |
| 13149 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 13150 | let layout = |
| 13151 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 13152 | header.tile_info = tile_info_of(&layout, 1); |
| 13153 | let header_tile_info = header.tile_info.clone(); |
| 13154 | // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is |
| 13155 | // integer-`u8`-scale), so the DPB reference plane is narrowed for it -- |
| 13156 | // once per frame (lane-av1rd2), not once per block, which is a whole |
| 13157 | // plane's map per 32x32 block and now per leaf too. |
| 13158 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 13159 | // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour |
| 13160 | // availability -- intra edges and the MV stack's scans alike -- already |
| 13161 | // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`, |
| 13162 | // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote; |
| 13163 | // giving each job its own planes and its own `MiGrid` therefore leaves |
| 13164 | // every decision, and so every coded bit, exactly where the whole-frame |
| 13165 | // loop left it, at any tile count and any thread count. |
| 13166 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 13167 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 13168 | let [cb, cr] = &mut chroma; |
| 13169 | let chroma_out = [ |
| 13170 | crate::par::Shared::new(&mut cb.reconstruction), |
| 13171 | crate::par::Shared::new(&mut cr.reconstruction), |
| 13172 | ]; |
| 13173 | let search_tile = |index: usize, |
| 13174 | fctx: &crate::decode::FrameCtx| |
| 13175 | -> Result<Vec<(usize, Quadrant)>> { |
| 13176 | // Thread-local, and this job may be running on a `search_tiles` |
| 13177 | // worker: `ref_distance`'s order-hint distance (the scaled motion |
| 13178 | // search step) is read by the SEARCH, so every worker arms it or the |
| 13179 | // tile's bits depend on the thread count. |
| 13180 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 13181 | crate::tile::arm_high_precision_mv(hp_mv); |
| 13182 | crate::tile::arm_pricing_cdfs(start_cdfs, screen); |
| 13183 | let rect = layout.rect(index); |
| 13184 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 13185 | let mut chroma = [ |
| 13186 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 13187 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 13188 | ]; |
| 13189 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 13190 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 13191 | grid.set_sign_bias(sign_bias); |
| 13192 | // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name, |
| 13193 | // built once per tile job (`obmc_prediction`). |
| 13194 | let mut obmc_refs: [Option<&Picture>; 8] = [None; 8]; |
| 13195 | obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference); |
| 13196 | obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2; |
| 13197 | obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden; |
| 13198 | obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref; |
| 13199 | grid.set_tile_bounds( |
| 13200 | rect.mi_row0 as usize, |
| 13201 | rect.mi_col0 as usize, |
| 13202 | rect.mi_row1 as usize, |
| 13203 | rect.mi_col1 as usize, |
| 13204 | ); |
| 13205 | let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); |
| 13206 | // lane-b128: under a 128x128 superblock the search walks the roots the |
| 13207 | // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root), |
| 13208 | // not plain raster -- a search that visits BL before TR builds every mv |
| 13209 | // stack and neighbour context off blocks the writer has not coded yet, |
| 13210 | // which is what made the write-time drl clamp fire at all (lane-sb128b). |
| 13211 | // At a 64 superblock the two orders are identical and this is the same |
| 13212 | // raster loop as before. |
| 13213 | let sb128_search = sb128_on(); |
| 13214 | let root_step = if sb128_search { 2 } else { 1 }; |
| 13215 | let mut roots: Vec<(usize, usize)> = Vec::new(); |
| 13216 | { |
| 13217 | let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize); |
| 13218 | let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize); |
| 13219 | let mut r = r0; |
| 13220 | while r < r1 { |
| 13221 | let mut c = c0; |
| 13222 | while c < c1 { |
| 13223 | roots.push((r, c)); |
| 13224 | c += root_step; |
| 13225 | } |
| 13226 | r += root_step; |
| 13227 | } |
| 13228 | } |
| 13229 | for (root_r, root_c) in roots { |
| 13230 | // The 64x64 cells of this root, in the writer's own order. |
| 13231 | let cells: Vec<(usize, usize)> = if sb128_search { |
| 13232 | [(0, 0), (0, 1), (1, 0), (1, 1)] |
| 13233 | .into_iter() |
| 13234 | .map(|(dr, dc)| (root_r + dr, root_c + dc)) |
| 13235 | .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize) |
| 13236 | .collect() |
| 13237 | } else { |
| 13238 | vec![(root_r, root_c)] |
| 13239 | }; |
| 13240 | // What the four cells below really cost, against which the whole |
| 13241 | // 128x128 candidate is weighed. |
| 13242 | let mark128 = blocks.len(); |
| 13243 | let mut root_cost = 0.0f64; |
| 13244 | // The 128 root's own compound pairs, at its 32x32-mi window (the 64 |
| 13245 | // root builds the same list one size down, per superblock). |
| 13246 | let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 13247 | if header.reference_select && b128_compound() && !screen && sb128_search { |
| 13248 | [ |
| 13249 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 13250 | (crate::mvstack::ALTREF_FRAME, altref), |
| 13251 | ] |
| 13252 | .into_iter() |
| 13253 | .filter_map(|(r, pic)| { |
| 13254 | pic.map(|p| { |
| 13255 | ( |
| 13256 | r, |
| 13257 | p, |
| 13258 | crate::mvstack::find_mv_stack_compound( |
| 13259 | &grid, |
| 13260 | root_r * 16, |
| 13261 | root_c * 16, |
| 13262 | 32, |
| 13263 | 32, |
| 13264 | (crate::mvstack::LAST_FRAME, r), |
| 13265 | mi_cols, |
| 13266 | mi_rows, |
| 13267 | grid.sign_bias_table(), |
| 13268 | &[(0, 0); 7], |
| 13269 | None, |
| 13270 | ), |
| 13271 | ) |
| 13272 | }) |
| 13273 | }) |
| 13274 | .collect() |
| 13275 | } else { |
| 13276 | Vec::new() |
| 13277 | }; |
| 13278 | let root128 = (sb128_search && b128_root() && cells.len() == 4) |
| 13279 | .then(|| search_root_128( |
| 13280 | &mut luma, |
| 13281 | &mut chroma, |
| 13282 | &grid, |
| 13283 | (root_r, root_c), |
| 13284 | (rows, cols), |
| 13285 | (header.mi_cols, header.mi_rows), |
| 13286 | search, |
| 13287 | &tpl_factors, |
| 13288 | sb_q.as_ref(), |
| 13289 | sb_cols, |
| 13290 | tpl_cells_x, |
| 13291 | base_q_idx, |
| 13292 | dq_res, |
| 13293 | reference, |
| 13294 | &root_compound, |
| 13295 | fctx, |
| 13296 | )) |
| 13297 | .flatten(); |
| 13298 | // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts |
| 13299 | // are priced; the cheaper one competes with the NONE block and with |
| 13300 | // the four superblocks below. |
| 13301 | let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed); |
| 13302 | let root_rect = (sb128_search && b128_rect() && cells.len() == 4) |
| 13303 | .then(|| { |
| 13304 | let mut best: Option<(bool, _)> = None; |
| 13305 | for horz in [true, false] { |
| 13306 | if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 { |
| 13307 | continue; |
| 13308 | } |
| 13309 | let Some(found) = search_root_128_rect( |
| 13310 | &mut luma, |
| 13311 | &mut chroma, |
| 13312 | &mut grid, |
| 13313 | (root_r, root_c), |
| 13314 | (rows, cols), |
| 13315 | (header.mi_cols, header.mi_rows), |
| 13316 | search, |
| 13317 | &tpl_factors, |
| 13318 | sb_q.as_ref(), |
| 13319 | sb_cols, |
| 13320 | tpl_cells_x, |
| 13321 | base_q_idx, |
| 13322 | dq_res, |
| 13323 | reference, |
| 13324 | &root_compound, |
| 13325 | horz, |
| 13326 | fctx, |
| 13327 | ) else { |
| 13328 | continue; |
| 13329 | }; |
| 13330 | if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) { |
| 13331 | best = Some((horz, found)); |
| 13332 | } |
| 13333 | } |
| 13334 | best |
| 13335 | }) |
| 13336 | .flatten(); |
| 13337 | // lane-ab128: and the same root as one of the four AB shapes -- two |
| 13338 | // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced; |
| 13339 | // the cheapest joins the candidate list below. |
| 13340 | let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed); |
| 13341 | let root_ab = (sb128_search |
| 13342 | && (b128_ab() || forced_ab != 0) |
| 13343 | && cells.len() == 4 |
| 13344 | && forced_rect == 0) |
| 13345 | .then(|| { |
| 13346 | let mut best: Option<(usize, _)> = None; |
| 13347 | for symbol in 4..=7usize { |
| 13348 | if forced_ab != 0 && usize::from(forced_ab) != symbol { |
| 13349 | continue; |
| 13350 | } |
| 13351 | let Some(found) = search_root_128_ab( |
| 13352 | &mut luma, |
| 13353 | &mut chroma, |
| 13354 | &mut grid, |
| 13355 | (root_r, root_c), |
| 13356 | (rows, cols), |
| 13357 | (header.mi_cols, header.mi_rows), |
| 13358 | search, |
| 13359 | &tpl_factors, |
| 13360 | sb_q.as_ref(), |
| 13361 | sb_cols, |
| 13362 | tpl_cells_x, |
| 13363 | base_q_idx, |
| 13364 | reference, |
| 13365 | &root_compound, |
| 13366 | symbol, |
| 13367 | fctx, |
| 13368 | ) else { |
| 13369 | continue; |
| 13370 | }; |
| 13371 | if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) { |
| 13372 | best = Some((symbol, found)); |
| 13373 | } |
| 13374 | } |
| 13375 | best |
| 13376 | }) |
| 13377 | .flatten(); |
| 13378 | for (sb_r, sb_c) in cells { |
| 13379 | // lane-b64: the whole superblock as ONE 64x64 block, tried before |
| 13380 | // its quadrants are (`search_skip_64`) and compared against the |
| 13381 | // four of them below. Only a superblock wholly inside the true |
| 13382 | // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the |
| 13383 | // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask |
| 13384 | // only that the block's half is inside, and the trial is ranked |
| 13385 | // over the inside part alone ([`Plane::block_sse`]). |
| 13386 | let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK); |
| 13387 | let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols |
| 13388 | && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows |
| 13389 | && x64 + SUPERBLOCK <= luma.true_width |
| 13390 | && y64 + SUPERBLOCK <= luma.true_height; |
| 13391 | let edge_inside = b64_edge() |
| 13392 | && crate::tile::has_half( |
| 13393 | sb_c as u32 * crate::tile::SB_MI, |
| 13394 | crate::tile::SB_MI, |
| 13395 | header.mi_cols, |
| 13396 | ) |
| 13397 | && crate::tile::has_half( |
| 13398 | sb_r as u32 * crate::tile::SB_MI, |
| 13399 | crate::tile::SB_MI, |
| 13400 | header.mi_rows, |
| 13401 | ); |
| 13402 | let sb64_legal = b64_root() |
| 13403 | && sb_r * 2 + 1 < rows |
| 13404 | && sb_c * 2 + 1 < cols |
| 13405 | && (whole_inside || edge_inside); |
| 13406 | // One lambda for the whole superblock, the same mean the 32x32 |
| 13407 | // level takes over its own four tpl cells: the 64-vs-four-32 |
| 13408 | // comparison below weighs one cost against four, so both sides |
| 13409 | // have to be priced at the same lambda. |
| 13410 | let sb_search = match &tpl_factors { |
| 13411 | // lane-deltaq: with a per-superblock quantizer the lambda |
| 13412 | // comes from that quantizer, not from the raw map factor -- |
| 13413 | // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped. |
| 13414 | Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search), |
| 13415 | Some(f) if sb64_legal => { |
| 13416 | let mean = (0..16) |
| 13417 | .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) |
| 13418 | .sum::<f64>() |
| 13419 | / 16.0; |
| 13420 | Search { lambda: search.lambda * mean, ..search } |
| 13421 | } |
| 13422 | _ => search, |
| 13423 | }; |
| 13424 | let mark = blocks.len(); |
| 13425 | let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None; |
| 13426 | let mut sb_cost = 0.0f64; |
| 13427 | if sb64_legal { |
| 13428 | let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 13429 | let (mi_row, mi_col) = (sb_r * 16, sb_c * 16); |
| 13430 | let stack = |
| 13431 | find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows); |
| 13432 | // lane-b64b: the `LAST` + extra-reference pairs at this |
| 13433 | // superblock's own 16x16-mi window, the same stacks the tile |
| 13434 | // writer's `Whole64` arm rebuilds. Empty unless the frame |
| 13435 | // codes `reference_select`, which is what gates the syntax. |
| 13436 | // `!screen` for the same reason the residual arm is gated |
| 13437 | // there ([`b64_residual`]): a desktop capture's superblocks |
| 13438 | // are flat runs the skip arm already codes for nothing, and |
| 13439 | // MEASURED, compound at the root cost it +33.4/-23.8 -> |
| 13440 | // +33.7/-23.6 while both film rows gained (step 1's table). |
| 13441 | let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 13442 | if header.reference_select && b64_compound() && !screen { |
| 13443 | [ |
| 13444 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 13445 | (crate::mvstack::ALTREF_FRAME, altref), |
| 13446 | ] |
| 13447 | .into_iter() |
| 13448 | .filter_map(|(r, pic)| { |
| 13449 | pic.map(|p| { |
| 13450 | ( |
| 13451 | r, |
| 13452 | p, |
| 13453 | crate::mvstack::find_mv_stack_compound( |
| 13454 | &grid, |
| 13455 | mi_row, |
| 13456 | mi_col, |
| 13457 | 16, |
| 13458 | 16, |
| 13459 | (crate::mvstack::LAST_FRAME, r), |
| 13460 | mi_cols, |
| 13461 | mi_rows, |
| 13462 | grid.sign_bias_table(), |
| 13463 | &[(0, 0); 7], |
| 13464 | None, |
| 13465 | ), |
| 13466 | ) |
| 13467 | }) |
| 13468 | }) |
| 13469 | .collect() |
| 13470 | } else { |
| 13471 | Vec::new() |
| 13472 | }; |
| 13473 | if let Some((cost, block)) = search_skip_64( |
| 13474 | &mut luma, |
| 13475 | &mut chroma, |
| 13476 | (x64, y64), |
| 13477 | (SUPERBLOCK, SUPERBLOCK), |
| 13478 | &sb_search, |
| 13479 | b64_residual() && !screen, |
| 13480 | reference, |
| 13481 | &stack, |
| 13482 | &sb_compound, |
| 13483 | fctx, |
| 13484 | ) { |
| 13485 | let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK); |
| 13486 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base); |
| 13487 | let cost = cost |
| 13488 | + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false); |
| 13489 | sb64 = Some((cost, block, after)); |
| 13490 | } |
| 13491 | } |
| 13492 | // A superblock whose 64x64 trial already codes almost nothing per |
| 13493 | // pixel is taken outright and its quadrants are never searched -- |
| 13494 | // the same `split_rd_breakout` shape the 32x32 level uses one |
| 13495 | // size up, and where this lever BUYS wall instead of spending it. |
| 13496 | let early64 = sb64.as_ref().is_some_and(|(c, _, _)| { |
| 13497 | split_rd_breakout_at( |
| 13498 | b64_breakout_threshold(), |
| 13499 | *c, |
| 13500 | SUPERBLOCK, |
| 13501 | sb_search.lambda, |
| 13502 | ) |
| 13503 | }); |
| 13504 | for quadrant in 0..if early64 { 0 } else { 4 } { |
| 13505 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 13506 | // lane-av1tpl2: this 32x32 block's own lambda -- every RD |
| 13507 | // decision under it (partition, mode, tx, motion) reads |
| 13508 | // `search.lambda`, so scaling the one field here scales all |
| 13509 | // of them. 32x32 and not the 16x16 the map is built at |
| 13510 | // because the whole-vs-split comparison right below weighs |
| 13511 | // one 32x32 cost against four 16x16 ones: a per-leaf lambda |
| 13512 | // would make those two numbers incomparable. |
| 13513 | let search = match &tpl_factors { |
| 13514 | // lane-deltaq: the quantizer is a SUPERBLOCK-level |
| 13515 | // symbol, so all four quadrants take their superblock's |
| 13516 | // own qindex and the lambda it implies. No granularity is |
| 13517 | // lost: the shipped map (`EC_AV1_TPL_SB`) is already one |
| 13518 | // factor per superblock, shared by its sixteen cells. |
| 13519 | Some(_) if sb_q.is_some() => sb_q_search(sb_q.as_ref().expect("armed"), sb_cols, base_q_idx, (sb_r, sb_c), search), |
| 13520 | Some(f) => { |
| 13521 | let mean = (0..4) |
| 13522 | .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2]) |
| 13523 | .sum::<f64>() |
| 13524 | / 4.0; |
| 13525 | Search { lambda: search.lambda * mean, ..search } |
| 13526 | } |
| 13527 | None => search, |
| 13528 | }; |
| 13529 | // Same filter as the tile writer's: a quadrant whose own mi |
| 13530 | // origin is not inside the true frame is never coded. |
| 13531 | if r32 >= rows || c32 >= cols { |
| 13532 | continue; |
| 13533 | } |
| 13534 | // spec `decode_partition`'s hasRows/hasCols recomputed at this |
| 13535 | // 32x32 block's own half (`crate::tile::has_half`), same as |
| 13536 | // the key frame search: the true frame edge can fall inside a |
| 13537 | // quadrant a superblock-level check already let through, and |
| 13538 | // such a quadrant cannot be left whole -- it must split into |
| 13539 | // the 16x16 leaves that are actually inside the true frame |
| 13540 | // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split` |
| 13541 | // arm). |
| 13542 | let (has_cols32, has_rows32) = ( |
| 13543 | crate::tile::has_half( |
| 13544 | c32 as u32 * crate::tile::BLOCK_MI, |
| 13545 | crate::tile::BLOCK_MI, |
| 13546 | header.mi_cols, |
| 13547 | ), |
| 13548 | crate::tile::has_half( |
| 13549 | r32 as u32 * crate::tile::BLOCK_MI, |
| 13550 | crate::tile::BLOCK_MI, |
| 13551 | header.mi_rows, |
| 13552 | ), |
| 13553 | ); |
| 13554 | if has_cols32 && has_rows32 { |
| 13555 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 13556 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 13557 | let stack = |
| 13558 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 13559 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ |
| 13560 | (crate::mvstack::LAST2_FRAME, last2), |
| 13561 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 13562 | (crate::mvstack::ALTREF_FRAME, altref), |
| 13563 | ] |
| 13564 | .into_iter() |
| 13565 | .filter_map(|(r, pic)| { |
| 13566 | pic.map(|p| { |
| 13567 | ( |
| 13568 | r, |
| 13569 | p, |
| 13570 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), |
| 13571 | ) |
| 13572 | }) |
| 13573 | }) |
| 13574 | .collect(); |
| 13575 | let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks |
| 13576 | .iter() |
| 13577 | .map(|(r, p, st)| (*r, *p, st)) |
| 13578 | .collect(); |
| 13579 | // The COMPOUND stack of each `LAST` + extra pair, off the |
| 13580 | // same grid (and the same armed sign bias) the tile writer |
| 13581 | // rebuilds it from. Empty unless this frame codes |
| 13582 | // `reference_select`, which is what gates the syntax. |
| 13583 | let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 13584 | if header.reference_select { |
| 13585 | extra_stacks |
| 13586 | .iter() |
| 13587 | .map(|&(r, p, _)| { |
| 13588 | ( |
| 13589 | r, |
| 13590 | p, |
| 13591 | crate::mvstack::find_mv_stack_compound( |
| 13592 | &grid, |
| 13593 | mi_row, |
| 13594 | mi_col, |
| 13595 | 8, |
| 13596 | 8, |
| 13597 | (crate::mvstack::LAST_FRAME, r), |
| 13598 | mi_cols, |
| 13599 | mi_rows, |
| 13600 | grid.sign_bias_table(), |
| 13601 | &[(0, 0); 7], |
| 13602 | None, |
| 13603 | ), |
| 13604 | ) |
| 13605 | }) |
| 13606 | .collect() |
| 13607 | } else { |
| 13608 | Vec::new() |
| 13609 | }; |
| 13610 | |
| 13611 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 13612 | let (block, mut cost_whole) = search_inter_block( |
| 13613 | &mut luma, |
| 13614 | &mut chroma, |
| 13615 | (x, y), |
| 13616 | &search, |
| 13617 | &mode_bits_table, |
| 13618 | reference, |
| 13619 | &stack, |
| 13620 | &extra, |
| 13621 | &compound, |
| 13622 | &grid, |
| 13623 | (mi_row, mi_col), |
| 13624 | (mi_rows, mi_cols), |
| 13625 | fctx, |
| 13626 | ); |
| 13627 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 13628 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 13629 | |
| 13630 | // What four 16x16 leaves cost instead (spec |
| 13631 | // PARTITION_SPLIT at BLOCK_32X32, which |
| 13632 | // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm |
| 13633 | // already writes for a straddling quadrant). Each leaf is |
| 13634 | // searched against the reconstruction -- and the `mi` |
| 13635 | // grid -- the ones before it left, exactly as the writer |
| 13636 | // and the decoder will read them. |
| 13637 | // |
| 13638 | // A block the whole-32 search left skipped (no residual |
| 13639 | // at all) is not offered the split: libaom prunes the |
| 13640 | // same way at cpu-used 6, and it is where the wall would |
| 13641 | // otherwise go on static content. |
| 13642 | let leaf_positions: Vec<(usize, usize)> = (0..4) |
| 13643 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 13644 | .collect(); |
| 13645 | let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| { |
| 13646 | crate::tile::has_half( |
| 13647 | sc as u32 * crate::tile::SUB_MI, |
| 13648 | crate::tile::SUB_MI, |
| 13649 | header.mi_cols, |
| 13650 | ) && crate::tile::has_half( |
| 13651 | sr as u32 * crate::tile::SUB_MI, |
| 13652 | crate::tile::SUB_MI, |
| 13653 | header.mi_rows, |
| 13654 | ) |
| 13655 | }); |
| 13656 | // The breakout above: a 32x32 block that codes almost |
| 13657 | // nothing is not offered the split at all. |
| 13658 | let breakout = split_breakout_coeffs(); |
| 13659 | let split = (!block.skip |
| 13660 | && !split_rd_breakout(cost_whole, BLOCK, search.lambda) |
| 13661 | && (breakout == 0 || block.luma.len() > 4 * breakout) |
| 13662 | && leaves_legal |
| 13663 | && split_inter_blocks()) |
| 13664 | .then(|| { |
| 13665 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 13666 | let mut cost = search.lambda * partition_bits(BLOCK, true); |
| 13667 | let mut leaves = Vec::with_capacity(4); |
| 13668 | for &(sr, sc) in &leaf_positions { |
| 13669 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 13670 | let (lx, ly) = (sc * SUB, sr * SUB); |
| 13671 | let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 13672 | let stack = find_mv_stack( |
| 13673 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 13674 | ); |
| 13675 | let cstacks = leaf_compound_stacks( |
| 13676 | &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows, |
| 13677 | header.reference_select, golden, altref, |
| 13678 | ); |
| 13679 | let (leaf, leaf_cost) = code_square_inter( |
| 13680 | &mut luma, |
| 13681 | &mut chroma, |
| 13682 | (lx, ly), |
| 13683 | SUB, |
| 13684 | &search, |
| 13685 | &mode_bits_table, |
| 13686 | reference, |
| 13687 | &stack, |
| 13688 | &cstacks, |
| 13689 | &grid, |
| 13690 | (mi_row, mi_col), |
| 13691 | (mi_rows, mi_cols), |
| 13692 | &obmc_refs, |
| 13693 | fctx, |
| 13694 | ); |
| 13695 | let leaf_cost = leaf_cost |
| 13696 | + search.lambda * partition_bits(SUB, false); |
| 13697 | let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 13698 | |
| 13699 | // And what four 8x8 leaves cost instead -- |
| 13700 | // the same tree one step further down, which |
| 13701 | // the writer codes as a real PARTITION_SPLIT |
| 13702 | // at BLOCK_16X16 (lane-av1rd2). Same |
| 13703 | // skipped-block prune as the level above. |
| 13704 | let eight = (!leaf.skip |
| 13705 | && !split_rd_breakout(leaf_cost, SUB, search.lambda) |
| 13706 | && (breakout == 0 || leaf.luma.len() > breakout) |
| 13707 | && split_inter_8() |
| 13708 | // lane-arfmode: arm 2 makes 16x16 the top |
| 13709 | // ARF's leaf floor -- the RD-optional 8x8 |
| 13710 | // comparison is not offered. Counted only |
| 13711 | // when every other prune let it through, |
| 13712 | // so the counter means "refused", not |
| 13713 | // "never considered". The spec-forced 8x8s |
| 13714 | // at a straddling 16x16 (the |
| 13715 | // `sub_positions` path below) are a |
| 13716 | // different site and stay. |
| 13717 | && (search.arf_leaf8 || arfmode_hit_and_no())) |
| 13718 | .then(|| { |
| 13719 | restore( |
| 13720 | &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base, |
| 13721 | ); |
| 13722 | let mut cost8 = search.lambda |
| 13723 | * (partition_bits(SUB, true) |
| 13724 | + 4.0 * partition_bits(8, false)); |
| 13725 | let mut eight = Vec::with_capacity(4); |
| 13726 | for i in 0..4 { |
| 13727 | let (mr, mc) = |
| 13728 | (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2); |
| 13729 | let stack8 = find_mv_stack( |
| 13730 | &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 13731 | ); |
| 13732 | let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 13733 | if header.reference_select && leaf_compound() { |
| 13734 | [ |
| 13735 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 13736 | (crate::mvstack::ALTREF_FRAME, altref), |
| 13737 | ] |
| 13738 | .into_iter() |
| 13739 | .filter_map(|(r, pic)| { |
| 13740 | pic.map(|p| { |
| 13741 | ( |
| 13742 | r, |
| 13743 | p, |
| 13744 | crate::mvstack::find_mv_stack_compound( |
| 13745 | &grid, mr, mc, 2, 2, |
| 13746 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 13747 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 13748 | ), |
| 13749 | ) |
| 13750 | }) |
| 13751 | }) |
| 13752 | .collect() |
| 13753 | } else { |
| 13754 | Vec::new() |
| 13755 | }; |
| 13756 | let (leaf8, cost) = code_square_inter( |
| 13757 | &mut luma, |
| 13758 | &mut chroma, |
| 13759 | (lx + (i % 2) * 8, ly + (i / 2) * 8), |
| 13760 | 8, |
| 13761 | &search, |
| 13762 | &mode_bits_table, |
| 13763 | reference, |
| 13764 | &stack8, |
| 13765 | &cstacks8, |
| 13766 | &grid, |
| 13767 | (mr, mc), |
| 13768 | (mi_rows, mi_cols), |
| 13769 | &obmc_refs, |
| 13770 | fctx, |
| 13771 | ); |
| 13772 | cost8 += cost; |
| 13773 | record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip); |
| 13774 | eight.push(leaf8); |
| 13775 | } |
| 13776 | (eight, cost8) |
| 13777 | }); |
| 13778 | match eight { |
| 13779 | Some((eight, cost8)) if cost8 < leaf_cost => { |
| 13780 | partition_hit(3); |
| 13781 | cost += cost8; |
| 13782 | leaves.push(BlockCoeffs { |
| 13783 | eight: Some(eight), |
| 13784 | ..BlockCoeffs::default() |
| 13785 | }); |
| 13786 | continue; |
| 13787 | } |
| 13788 | Some(_) => restore( |
| 13789 | &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf, |
| 13790 | ), |
| 13791 | None => {} |
| 13792 | } |
| 13793 | partition_hit(2); |
| 13794 | cost += leaf_cost; |
| 13795 | record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip); |
| 13796 | leaves.push(leaf); |
| 13797 | } |
| 13798 | (leaves, cost) |
| 13799 | }); |
| 13800 | if let Some((leaves, cost)) = split { |
| 13801 | if cost < cost_whole { |
| 13802 | // The leaves' own `mi` cells are already in the |
| 13803 | // grid, and their reconstruction is what the |
| 13804 | // planes hold. |
| 13805 | partition_hit(1); |
| 13806 | sb_cost += cost; |
| 13807 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 13808 | continue; |
| 13809 | } |
| 13810 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 13811 | } |
| 13812 | partition_hit(0); |
| 13813 | sb_cost += cost_whole; |
| 13814 | record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip); |
| 13815 | blocks.push((r32 * cols + c32, Quadrant::Whole(block))); |
| 13816 | } else { |
| 13817 | // The sub-positions actually inside the true frame, same |
| 13818 | // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`. |
| 13819 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 13820 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 13821 | .filter(|&(sr, sc)| { |
| 13822 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 13823 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 13824 | }) |
| 13825 | .collect(); |
| 13826 | // Each leaf searches intra against its own `NEARESTMV` |
| 13827 | // candidate (`code_square_inter`), same real-inter choice |
| 13828 | // `search_inter_block` makes for a whole 32x32 block, at |
| 13829 | // this leaf's own 4x4-mi mv-stack window -- unless the |
| 13830 | // leaf's own half itself straddles the true edge, which |
| 13831 | // it codes as two (or one, at a true corner) 8x8 leaves |
| 13832 | // (`crate::tile::write_leaf8`'s inter counterpart), |
| 13833 | // mirroring the key frame search's straddling-16x16 |
| 13834 | // handling above (lane-av1inter8). |
| 13835 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 13836 | for (sr, sc) in sub_positions { |
| 13837 | let (has_cols16, has_rows16) = ( |
| 13838 | crate::tile::has_half( |
| 13839 | sc as u32 * crate::tile::SUB_MI, |
| 13840 | crate::tile::SUB_MI, |
| 13841 | header.mi_cols, |
| 13842 | ), |
| 13843 | crate::tile::has_half( |
| 13844 | sr as u32 * crate::tile::SUB_MI, |
| 13845 | crate::tile::SUB_MI, |
| 13846 | header.mi_rows, |
| 13847 | ), |
| 13848 | ); |
| 13849 | if has_cols16 && has_rows16 { |
| 13850 | let (x, y) = (sc * SUB, sr * SUB); |
| 13851 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 13852 | let stack = find_mv_stack( |
| 13853 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 13854 | ); |
| 13855 | let cstacks = leaf_compound_stacks( |
| 13856 | &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows, |
| 13857 | header.reference_select, golden, altref, |
| 13858 | ); |
| 13859 | let (block, _) = code_square_inter( |
| 13860 | &mut luma, |
| 13861 | &mut chroma, |
| 13862 | (x, y), |
| 13863 | SUB, |
| 13864 | &search, |
| 13865 | &mode_bits_table, |
| 13866 | reference, |
| 13867 | &stack, |
| 13868 | &cstacks, |
| 13869 | &grid, |
| 13870 | (mi_row, mi_col), |
| 13871 | (mi_rows, mi_cols), |
| 13872 | &obmc_refs, |
| 13873 | fctx, |
| 13874 | ); |
| 13875 | // One publication point for every coded leaf |
| 13876 | // (`record_mi`): this site used to spell the vote |
| 13877 | // out with `ref_frame` pinned to LAST and `mv1` |
| 13878 | // to (0,0), which is the encoder-grid-drift class |
| 13879 | // -- correct only for as long as a leaf can never |
| 13880 | // be compound. |
| 13881 | record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip); |
| 13882 | leaves.push(block); |
| 13883 | } else { |
| 13884 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 13885 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 13886 | let mut eight = Vec::with_capacity(2); |
| 13887 | for i in 0..4 { |
| 13888 | let leaf_x = x_sub + (i % 2) * 8; |
| 13889 | let leaf_y = y_sub + (i / 2) * 8; |
| 13890 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 13891 | continue; |
| 13892 | } |
| 13893 | let (mi_row, mi_col) = |
| 13894 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 13895 | let stack = find_mv_stack( |
| 13896 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 13897 | ); |
| 13898 | let cstacks = leaf_compound_stacks( |
| 13899 | &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows, |
| 13900 | header.reference_select, golden, altref, |
| 13901 | ); |
| 13902 | let (leaf, _) = code_square_inter( |
| 13903 | &mut luma, |
| 13904 | &mut chroma, |
| 13905 | (leaf_x, leaf_y), |
| 13906 | 8, |
| 13907 | &search, |
| 13908 | &mode_bits_table, |
| 13909 | reference, |
| 13910 | &stack, |
| 13911 | &cstacks, |
| 13912 | &grid, |
| 13913 | (mi_row, mi_col), |
| 13914 | (mi_rows, mi_cols), |
| 13915 | &obmc_refs, |
| 13916 | fctx, |
| 13917 | ); |
| 13918 | // Same publication point as the 16x16 |
| 13919 | // straddling leaf above (`record_mi`). |
| 13920 | record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip); |
| 13921 | eight.push(leaf); |
| 13922 | } |
| 13923 | leaves.push(BlockCoeffs { |
| 13924 | eight: Some(eight), |
| 13925 | ..BlockCoeffs::default() |
| 13926 | }); |
| 13927 | } |
| 13928 | } |
| 13929 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 13930 | } |
| 13931 | } |
| 13932 | // The 64x64 root against what its four quadrants really cost. |
| 13933 | if let Some((cost64, block, after)) = sb64 |
| 13934 | && (early64 |
| 13935 | || cost64 |
| 13936 | < sb_cost |
| 13937 | + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true)) |
| 13938 | { |
| 13939 | B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 13940 | if block.inter.is_some_and(|i| i.ref1.is_some()) { |
| 13941 | B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 13942 | } |
| 13943 | if !whole_inside { |
| 13944 | B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 13945 | } |
| 13946 | blocks.truncate(mark); |
| 13947 | restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after); |
| 13948 | // Overwrites every 16x16 mi cell the quadrant searches |
| 13949 | // published under this superblock, so the next block's stack |
| 13950 | // is built off the block that was really coded. |
| 13951 | record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip); |
| 13952 | blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block))); |
| 13953 | for q in 1..4 { |
| 13954 | let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2); |
| 13955 | blocks.push((r32 * cols + c32, Quadrant::Covered)); |
| 13956 | } |
| 13957 | root_cost += cost64; |
| 13958 | } else { |
| 13959 | root_cost += sb_cost; |
| 13960 | } |
| 13961 | } |
| 13962 | // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's |
| 13963 | // `partition_w128` symbol) against what its four superblocks really |
| 13964 | // cost, the same weighing the 64 root does one size down. Both sides |
| 13965 | // carry their own partition symbol, so the comparison is complete. |
| 13966 | // The root candidates, each tagged with the PARTITION symbol its |
| 13967 | // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB |
| 13968 | // shapes (lane-ab128). |
| 13969 | let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new(); |
| 13970 | if let Some((c, l, b, a)) = root128 { |
| 13971 | cands.push((c, l, 0, vec![b], a)); |
| 13972 | } |
| 13973 | if let Some((horz, (c, l, halves, a))) = root_rect { |
| 13974 | cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a)); |
| 13975 | } |
| 13976 | if let Some((symbol, (c, l, pieces, a))) = root_ab { |
| 13977 | cands.push((c, l, symbol, pieces.to_vec(), a)); |
| 13978 | } |
| 13979 | // The witness knobs drop every other arm outright: on synthetic |
| 13980 | // content the whole block always wins its own comparison. |
| 13981 | if forced_rect != 0 { |
| 13982 | cands.retain(|c| c.2 == 1 || c.2 == 2); |
| 13983 | } |
| 13984 | if forced_ab != 0 { |
| 13985 | cands.retain(|c| c.2 == usize::from(forced_ab)); |
| 13986 | } |
| 13987 | cands.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 13988 | // lane-rectdq class sweep: under a 128 superblock grid the FOUR- |
| 13989 | // superblock arm codes the delta_q group too -- the Whole64 writer |
| 13990 | // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call |
| 13991 | // with `!sb128_armed()`) and every smaller shape below it pass |
| 13992 | // `is_whole_sb = false` under a 128 grid, so the arm's first |
| 13993 | // (root-origin) superblock codes the group even when skipped. Only the skipped 128 |
| 13994 | // NONE root escapes it, so the split side is charged here at the same |
| 13995 | // root lambda the candidates are priced with. |
| 13996 | let split_dq = |
| 13997 | delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c)); |
| 13998 | if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next() |
| 13999 | && (cost128 |
| 14000 | < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq) |
| 14001 | // The witness knobs take the root whatever it costs, so the |
| 14002 | // forced block really reaches the writer. |
| 14003 | || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed) |
| 14004 | || forced_rect != 0 |
| 14005 | || forced_ab != 0) |
| 14006 | { |
| 14007 | let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); |
| 14008 | blocks.truncate(mark128); |
| 14009 | restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after); |
| 14010 | let at = (root_r * 2) * cols + root_c * 2; |
| 14011 | match shape { |
| 14012 | 0 => { |
| 14013 | B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 14014 | let block = halves.into_iter().next().expect("the NONE arm's block"); |
| 14015 | record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip); |
| 14016 | blocks.push((at, Quadrant::Whole128(block))); |
| 14017 | } |
| 14018 | // lane-ab128: three pieces, published at their own footprints |
| 14019 | // in the writer's own order ([`ab128_pieces`]). |
| 14020 | symbol @ 4..=7 => { |
| 14021 | B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 14022 | for (((mr, mc), (w, h)), piece) in |
| 14023 | ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves) |
| 14024 | { |
| 14025 | record_mi_rect( |
| 14026 | &mut grid, |
| 14027 | *mr, |
| 14028 | *mc, |
| 14029 | (w / 4, h / 4), |
| 14030 | piece.inter, |
| 14031 | piece.skip, |
| 14032 | ); |
| 14033 | } |
| 14034 | blocks.push((at, Quadrant::Ab128(symbol as u8, halves))); |
| 14035 | } |
| 14036 | symbol => { |
| 14037 | let horz = symbol == 1; |
| 14038 | if horz { |
| 14039 | B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 14040 | } else { |
| 14041 | B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 14042 | } |
| 14043 | let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) }; |
| 14044 | for (i, half) in halves.iter().enumerate() { |
| 14045 | let (mr, mc) = if horz { |
| 14046 | (root_r * 16 + i * 16, root_c * 16) |
| 14047 | } else { |
| 14048 | (root_r * 16, root_c * 16 + i * 16) |
| 14049 | }; |
| 14050 | record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip); |
| 14051 | } |
| 14052 | blocks.push((at, Quadrant::Rect128(horz, halves))); |
| 14053 | } |
| 14054 | } |
| 14055 | for q in 1..16 { |
| 14056 | let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4); |
| 14057 | blocks.push((r32 * cols + c32, Quadrant::Covered)); |
| 14058 | } |
| 14059 | } |
| 14060 | } |
| 14061 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 14062 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 14063 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 14064 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 14065 | copy_rect( |
| 14066 | out, |
| 14067 | &tile.reconstruction, |
| 14068 | frame_width / 2, |
| 14069 | x0 / 2, |
| 14070 | y0 / 2, |
| 14071 | x1.div_ceil(2), |
| 14072 | y1.div_ceil(2), |
| 14073 | ); |
| 14074 | } |
| 14075 | Ok(blocks) |
| 14076 | }; |
| 14077 | for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)? |
| 14078 | .into_iter() |
| 14079 | .flatten() |
| 14080 | { |
| 14081 | blocks[at] = quadrant; |
| 14082 | } |
| 14083 | |
| 14084 | // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128 |
| 14085 | // superblock roots the search left whole, so a flat BD result is |
| 14086 | // attributable (class `gate-blind-to-feature`). A key frame codes none: |
| 14087 | // only the inter writer has a 128x128 block. |
| 14088 | if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") { |
| 14089 | let whole = blocks |
| 14090 | .iter() |
| 14091 | .filter(|q| matches!(q, Quadrant::Whole128(_))) |
| 14092 | .count(); |
| 14093 | let roots = blocks |
| 14094 | .iter() |
| 14095 | .filter(|q| !matches!(q, Quadrant::Covered)) |
| 14096 | .count(); |
| 14097 | // lane-b128r: of those roots, how many code a REAL residual rather |
| 14098 | // than the skip-only block lane-b128 shipped -- the fire count this |
| 14099 | // arm's own gate row is read against. |
| 14100 | let residual = blocks |
| 14101 | .iter() |
| 14102 | .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip)) |
| 14103 | .count(); |
| 14104 | // lane-b128r: and how many named a second reference (the compound |
| 14105 | // arm at the 128 root). |
| 14106 | let compound = blocks |
| 14107 | .iter() |
| 14108 | .filter(|q| { |
| 14109 | matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())) |
| 14110 | }) |
| 14111 | .count(); |
| 14112 | // lane-b128hv: and how many roots took a rect cut instead, per shape |
| 14113 | // -- the HORZ/VERT fire count the gate rows are read against. |
| 14114 | let horz = blocks |
| 14115 | .iter() |
| 14116 | .filter(|q| matches!(q, Quadrant::Rect128(true, _))) |
| 14117 | .count(); |
| 14118 | let vert = blocks |
| 14119 | .iter() |
| 14120 | .filter(|q| matches!(q, Quadrant::Rect128(false, _))) |
| 14121 | .count(); |
| 14122 | let rect_compound = blocks |
| 14123 | .iter() |
| 14124 | .filter(|q| { |
| 14125 | matches!(q, Quadrant::Rect128(_, hs) |
| 14126 | if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some()))) |
| 14127 | }) |
| 14128 | .count(); |
| 14129 | // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A |
| 14130 | // .. _VERT_B order -- the per-shape fire count its gate rows are read |
| 14131 | // against. |
| 14132 | let ab: [usize; 4] = std::array::from_fn(|i| { |
| 14133 | blocks |
| 14134 | .iter() |
| 14135 | .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4)) |
| 14136 | .count() |
| 14137 | }); |
| 14138 | eprintln!( |
| 14139 | "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \ |
| 14140 | {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \ |
| 14141 | compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \ |
| 14142 | {roots} coded blocks ({:.1}% of the frame's area at 128)", |
| 14143 | ab[0], |
| 14144 | ab[1], |
| 14145 | ab[2], |
| 14146 | ab[3], |
| 14147 | 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64 |
| 14148 | / blocks.len().max(1) as f64, |
| 14149 | ); |
| 14150 | } |
| 14151 | let modes = blocks |
| 14152 | .iter() |
| 14153 | .flat_map(Quadrant::blocks) |
| 14154 | .map(|b| b.mode) |
| 14155 | .collect::<Vec<_>>(); |
| 14156 | let inter_block_share = blocks |
| 14157 | .iter() |
| 14158 | .flat_map(Quadrant::blocks) |
| 14159 | .filter(|b| b.inter.is_some()) |
| 14160 | .count() as f64 |
| 14161 | / modes.len() as f64; |
| 14162 | for block in blocks.iter().flat_map(Quadrant::blocks) { |
| 14163 | if let Some(info) = block.inter { |
| 14164 | let r = (info.ref_frame as usize).min(7); |
| 14165 | REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 14166 | } |
| 14167 | } |
| 14168 | #[cfg(test)] |
| 14169 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 14170 | // This frame's header leaves `disable_frame_end_update_cdf` off, so it |
| 14171 | // stores its end-of-tile tables with the counts reset (spec 7.20) and the |
| 14172 | // next frame's writer starts from them -- exactly what |
| 14173 | // `crate::stream::stored_cdfs_for` hands the decoder. |
| 14174 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 14175 | let mut cdfs = start_cdfs |
| 14176 | .cloned() |
| 14177 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); |
| 14178 | // lane-txi: set per frame, never inherited from the snapshot the |
| 14179 | // previous frame stored -- the content gate can flip the bit between |
| 14180 | // frames (class `per-tile-state-not-reset`). |
| 14181 | cdfs.reduced_tx_set = header.reduced_tx_set; |
| 14182 | let start_cdfs = CdfSnapshot(cdfs); |
| 14183 | let reference_select_bit = header.reference_select; |
| 14184 | let switchable_motion_mode = header.is_motion_mode_switchable; |
| 14185 | let warped_motion = header.allow_warped_motion; |
| 14186 | let order_hint_bits = seq.order_hint_bits; |
| 14187 | let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32; |
| 14188 | let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32; |
| 14189 | // What this frame stores is the LARGEST tile's end-of-tile tables -- |
| 14190 | // its own header's `context_update_tile_id` (spec 7.20), which |
| 14191 | // `tile_info_of` set to exactly that tile. |
| 14192 | let store_tile = layout.largest_tile(); |
| 14193 | let end_cdfs = std::cell::RefCell::new(None); |
| 14194 | // As in `encode_key_frame_inner`: every tile starts from this frame's |
| 14195 | // own tables, so no tile depends on any other. |
| 14196 | let code_tiles = |bits: u8, |
| 14197 | sb_cols: usize, |
| 14198 | cdef_grid: &[u8], |
| 14199 | units: &[Option<crate::restoration::WienerInfo>]| |
| 14200 | -> Result<Vec<Vec<u8>>> { |
| 14201 | let (out, stored) = write_tiles(layout.count(), store_tile, |index| { |
| 14202 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); |
| 14203 | crate::tile::arm_delta_q( |
| 14204 | deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0), |
| 14205 | sb_cols, |
| 14206 | sb_q.clone().unwrap_or_default(), |
| 14207 | base_q_idx, |
| 14208 | ); |
| 14209 | crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec()); |
| 14210 | crate::tile::arm_sb128(sb128_on()); |
| 14211 | crate::tile::arm_sign_bias(sign_bias); |
| 14212 | // Thread-locals: every tile job arms its own worker. |
| 14213 | crate::tile::arm_reference_select(reference_select_bit); |
| 14214 | crate::tile::arm_motion_mode(switchable_motion_mode); |
| 14215 | crate::tile::arm_warped_motion(warped_motion); |
| 14216 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 14217 | crate::tile::arm_high_precision_mv(hp_mv); |
| 14218 | crate::tile::arm_screen(screen); |
| 14219 | crate::tile::arm_frame_mi_dims(frame_mi_dims); |
| 14220 | crate::tile::arm_filter_intra(filter_intra_on()); |
| 14221 | let mut cdfs = start_cdfs.0.clone(); |
| 14222 | crate::tile::arm_pricing_cdfs(Some(&cdfs), screen); |
| 14223 | // Each tile's own MV grid: a candidate scan never reaches past |
| 14224 | // the tile's bounds, so a grid holding only this tile's own |
| 14225 | // blocks reads exactly as the decoder's frame-wide one does |
| 14226 | // under `MiGrid::set_tile_bounds`. |
| 14227 | let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 14228 | mv_grid.set_sign_bias(sign_bias); |
| 14229 | let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 14230 | mi_cols, |
| 14231 | mi_rows, |
| 14232 | base_q_idx, |
| 14233 | &blocks, |
| 14234 | tx_select, |
| 14235 | &mut cdfs, |
| 14236 | layout.rect(index), |
| 14237 | &mut mv_grid, |
| 14238 | )?; |
| 14239 | Ok((bytes, Some(cdfs))) |
| 14240 | })?; |
| 14241 | if let Some(cdfs) = stored { |
| 14242 | *end_cdfs.borrow_mut() = Some(cdfs); |
| 14243 | } |
| 14244 | Ok(out) |
| 14245 | }; |
| 14246 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 14247 | // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs |
| 14248 | // this tile against the same single-slot reference this encoder predicted |
| 14249 | // from, under each candidate level. |
| 14250 | // The reference a DECODER holds is this frame's cropped size, not the |
| 14251 | // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a |
| 14252 | // reference whose height is not the header's own `frame_height` (spec |
| 14253 | // 7.9's compatible-size rule), and the chained-decode round trips prove |
| 14254 | // the two predict identically. |
| 14255 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 14256 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { |
| 14257 | reference.clone() |
| 14258 | } else { |
| 14259 | Picture { |
| 14260 | width: fw, |
| 14261 | height: fh, |
| 14262 | y: crop_plane(&reference.y, reference.width, fw, fh), |
| 14263 | u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), |
| 14264 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), |
| 14265 | } |
| 14266 | }; |
| 14267 | // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1, |
| 14268 | // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose |
| 14269 | // blocks may name GOLDEN needs that plane too, cropped the same way. |
| 14270 | let trial_golden = golden.map(|g| { |
| 14271 | if (g.width, g.height) == (fw, fh) { |
| 14272 | g.clone() |
| 14273 | } else { |
| 14274 | Picture { |
| 14275 | width: fw, |
| 14276 | height: fh, |
| 14277 | y: crop_plane(&g.y, g.width, fw, fh), |
| 14278 | u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), |
| 14279 | v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), |
| 14280 | } |
| 14281 | } |
| 14282 | }); |
| 14283 | let trial_altref = altref.map(|a| { |
| 14284 | if (a.width, a.height) == (fw, fh) { |
| 14285 | a.clone() |
| 14286 | } else { |
| 14287 | Picture { |
| 14288 | width: fw, |
| 14289 | height: fh, |
| 14290 | y: crop_plane(&a.y, a.width, fw, fh), |
| 14291 | u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), |
| 14292 | v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), |
| 14293 | } |
| 14294 | } |
| 14295 | }); |
| 14296 | let trial_last2 = last2.map(|l| { |
| 14297 | if (l.width, l.height) == (fw, fh) { |
| 14298 | l.clone() |
| 14299 | } else { |
| 14300 | Picture { |
| 14301 | width: fw, |
| 14302 | height: fh, |
| 14303 | y: crop_plane(&l.y, l.width, fw, fh), |
| 14304 | u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2), |
| 14305 | v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2), |
| 14306 | } |
| 14307 | } |
| 14308 | }); |
| 14309 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 14310 | refs[1] = Some(&trial_ref); |
| 14311 | refs[2] = trial_last2.as_ref(); |
| 14312 | refs[4] = trial_golden.as_ref(); |
| 14313 | refs[7] = trial_altref.as_ref(); |
| 14314 | let refpix = crate::decode::RefPix::ready(refs); |
| 14315 | // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the |
| 14316 | // sum the block search believed it was minimising. Against the |
| 14317 | // post-filter per-frame PSNR the gate prints, this separates a trial |
| 14318 | // whose reconstruction is a lie from a filter stage that undoes the win. |
| 14319 | if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { |
| 14320 | let sse: u64 = luma |
| 14321 | .reconstruction |
| 14322 | .chunks(luma.width) |
| 14323 | .take(luma.true_height) |
| 14324 | .zip(picture_y8.chunks(luma.width)) |
| 14325 | .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width])) |
| 14326 | .map(|(&r, &s)| { |
| 14327 | let d = i64::from(r) - i64::from(s); |
| 14328 | (d * d) as u64 |
| 14329 | }) |
| 14330 | .sum(); |
| 14331 | eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}"); |
| 14332 | } |
| 14333 | let post = |luma: &Plane<'_>, tag: &str| { |
| 14334 | if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { |
| 14335 | return; |
| 14336 | } |
| 14337 | let sse: u64 = luma |
| 14338 | .reconstruction |
| 14339 | .chunks(luma.width) |
| 14340 | .take(luma.true_height) |
| 14341 | .zip(picture_y8.chunks(luma.width)) |
| 14342 | .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width])) |
| 14343 | .map(|(&r, &s)| { |
| 14344 | let d = i64::from(r) - i64::from(s); |
| 14345 | (d * d) as u64 |
| 14346 | }) |
| 14347 | .sum(); |
| 14348 | eprintln!("{tag} q={base_q_idx} luma sse={sse}"); |
| 14349 | }; |
| 14350 | pick_and_apply_filters( |
| 14351 | &mut header, |
| 14352 | &mut luma, |
| 14353 | &mut chroma, |
| 14354 | [&picture_y8, &picture_u8, &picture_v8], |
| 14355 | // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes |
| 14356 | // this frame's own `tx_select`, so the search runs under inter |
| 14357 | // `TxMode::Select` too (it used to skip and leave every inter frame |
| 14358 | // unfiltered once Select became the default). |
| 14359 | true, |
| 14360 | &mut tiles, |
| 14361 | search.lambda, |
| 14362 | fctx, |
| 14363 | &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows), |
| 14364 | // As in `encode_key_frame_inner`, but this frame's end-of-tile tables |
| 14365 | // are what the NEXT frame writes from, so the winning re-code |
| 14366 | // publishes its own into `end_cdfs` -- the first write's are stale |
| 14367 | // the moment a second tile is coded. |
| 14368 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 14369 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 14370 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 14371 | crate::decode::decode_inter_frame_tiles_lr( |
| 14372 | &payloads, |
| 14373 | &header_tile_info, |
| 14374 | h.mi_cols, |
| 14375 | h.mi_rows, |
| 14376 | base_q_idx, |
| 14377 | h.frame_width, |
| 14378 | h.frame_height, |
| 14379 | &refpix, |
| 14380 | cdef, |
| 14381 | lf, |
| 14382 | h.allow_high_precision_mv, |
| 14383 | h.force_integer_mv, |
| 14384 | Some(fctx.interp_filter.get()), |
| 14385 | seq.enable_dual_filter, |
| 14386 | h.reference_select, |
| 14387 | // lane-txi: this frame's own bit, not the hardcoded `true` |
| 14388 | // the wrapper used to pass. |
| 14389 | h.reduced_tx_set, |
| 14390 | tx_select, |
| 14391 | lr, |
| 14392 | // The trial decode re-reads the tile the writer just wrote, |
| 14393 | // so it starts from the same tables the writer did (this |
| 14394 | // frame's `start_cdfs`), not from the defaults. |
| 14395 | Some(start_cdfs.0.clone()), |
| 14396 | sign_bias, |
| 14397 | h.allow_screen_content_tools, |
| 14398 | switchable_motion_mode, |
| 14399 | h.allow_warped_motion, |
| 14400 | seq.enable_filter_intra, |
| 14401 | // lane-deltaq: this frame's own delta_q/delta_lf params, so |
| 14402 | // the trial decode reads the per-superblock `delta_qindex` |
| 14403 | // syntax the writer just wrote. |
| 14404 | h.delta.clone(), |
| 14405 | fctx, |
| 14406 | ) |
| 14407 | }, |
| 14408 | )?; |
| 14409 | post(&luma, "EC_POSTFILTER"); |
| 14410 | let mut cdfs = end_cdfs |
| 14411 | .into_inner() |
| 14412 | .unwrap_or_else(|| start_cdfs.0.clone()); |
| 14413 | cdfs.reset_counts(); |
| 14414 | let next_cdfs = CdfSnapshot(cdfs); |
| 14415 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 14416 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 14417 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 14418 | let mut stream = temporal_delimiter(); |
| 14419 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 14420 | |
| 14421 | let [u, v] = chroma; |
| 14422 | Ok(Encoded { |
| 14423 | stream, |
| 14424 | modes, |
| 14425 | inter_block_share, |
| 14426 | reconstruction: Picture { |
| 14427 | width: luma.width, |
| 14428 | height: luma.height, |
| 14429 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 14430 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 14431 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 14432 | }, |
| 14433 | tile, |
| 14434 | mi_cols: header.mi_cols, |
| 14435 | mi_rows: header.mi_rows, |
| 14436 | base_q_idx, |
| 14437 | tx_select, |
| 14438 | switchable_motion_mode, |
| 14439 | screen, |
| 14440 | reduced_tx_set: header.reduced_tx_set, |
| 14441 | start_cdfs, |
| 14442 | next_cdfs, |
| 14443 | loop_filter: header.loop_filter, |
| 14444 | cdef: header.cdef, |
| 14445 | loop_restoration: header.loop_restoration, |
| 14446 | // An inter frame never allows intrabc (spec 5.9.2 codes the bit on |
| 14447 | // intra frames only). |
| 14448 | allow_intrabc: false, |
| 14449 | delta: header.delta.clone(), |
| 14450 | }) |
| 14451 | } |
| 14452 | |
| 14453 | /// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key |
| 14454 | /// frame's temporal unit followed by one inter frame's temporal unit per |
| 14455 | /// remaining picture, all sharing the key frame's sequence header -- and |
| 14456 | /// each frame's own [`Encoded`], in coding order. |
| 14457 | #[derive(Clone, Debug)] |
| 14458 | pub struct EncodedSequence { |
| 14459 | /// The whole stream: `frames[0].stream` (a temporal delimiter, the |
| 14460 | /// sequence header and the key frame) followed by each later frame's |
| 14461 | /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses |
| 14462 | /// the sequence header the key frame carried). |
| 14463 | pub stream: Vec<u8>, |
| 14464 | /// One entry per picture, in DISPLAY order — the order a decoder outputs |
| 14465 | /// them and the order `pictures` came in. Without a pyramid that is also |
| 14466 | /// the coding order; with one the two differ, and `coding_order` is the |
| 14467 | /// map between them. |
| 14468 | pub frames: Vec<Encoded>, |
| 14469 | /// The index into `frames` of each coded frame, in CODING order — what a |
| 14470 | /// per-coded-frame census (`take_predicted_bits`) must be zipped against. |
| 14471 | /// `0..frames.len()` on the flat path. |
| 14472 | pub coding_order: Vec<usize>, |
| 14473 | } |
| 14474 | |
| 14475 | /// Encodes a sequence of pictures as a key frame followed by one inter frame |
| 14476 | /// per remaining picture, each predicting from the previous frame's own |
| 14477 | /// decoded reconstruction — never from the source, which is what a decoder |
| 14478 | /// cannot see. Every picture must be the same even size (any even width and |
| 14479 | /// height — each is padded to a whole number of 64x64 superblocks |
| 14480 | /// internally, which is what lets an inter frame's reference always match |
| 14481 | /// the frame being coded against it), and `pictures` must be non-empty. |
| 14482 | /// |
| 14483 | /// # Errors |
| 14484 | /// Returns an error when `pictures` is empty, when any picture besides the |
| 14485 | /// first is not the same size as the first, or under the same conditions |
| 14486 | /// [`encode_key_frame`] and the inter frame path do. |
| 14487 | pub(crate) fn encode_sequence_with_ctx( |
| 14488 | pictures: &[Picture], |
| 14489 | base_q_idx: u8, |
| 14490 | deadzone: f64, fctx: &crate::decode::FrameCtx, |
| 14491 | ) -> Result<EncodedSequence> { |
| 14492 | let Some((first, rest)) = pictures.split_first() else { |
| 14493 | return Err(Error::unsupported( |
| 14494 | "AV1 encode", |
| 14495 | "a sequence needs at least one picture", |
| 14496 | )); |
| 14497 | }; |
| 14498 | first.check_even()?; |
| 14499 | let render = (first.width, first.height); |
| 14500 | // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is |
| 14501 | // coded as mini-GOPs -- a hidden ALTREF ahead of its display position, |
| 14502 | // the leaves that predict backward off it, and a `show_existing_frame` |
| 14503 | // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for |
| 14504 | // an A/B. Screen content stays flat (the content gate in |
| 14505 | // `Av1Encoder::encode_frames`, whose detector this asks first so the |
| 14506 | // whole sequence path is decided in one place), and so does a run that |
| 14507 | // asks for a quantizer rounding offset the facade does not carry: the |
| 14508 | // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone -- |
| 14509 | // the ablations' -- must keep the flat path rather than be silently |
| 14510 | // ignored. |
| 14511 | // |
| 14512 | // The reordering itself is NOT reimplemented here: it is the facade's |
| 14513 | // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]), |
| 14514 | // called with this sequence's shape, so the two paths cannot drift. |
| 14515 | let pyramid = crate::encoder::Pyramid::from_env() |
| 14516 | .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON) |
| 14517 | .filter(|_| !picture_is_screen(first)); |
| 14518 | LAST_SEQ_PYRAMID.with(|c| c.set(pyramid)); |
| 14519 | if let Some(pyramid) = pyramid { |
| 14520 | for picture in rest { |
| 14521 | picture.check_even()?; |
| 14522 | if (picture.width, picture.height) != render { |
| 14523 | return Err(Error::unsupported( |
| 14524 | "AV1 encode", |
| 14525 | "every picture in a sequence must be the same size as the first", |
| 14526 | )); |
| 14527 | } |
| 14528 | } |
| 14529 | return crate::encoder::Av1Encoder::encode_sequence_pyramid( |
| 14530 | pictures, |
| 14531 | base_q_idx, |
| 14532 | pyramid, |
| 14533 | armed_tiles(), |
| 14534 | ); |
| 14535 | } |
| 14536 | // The key frame and every inter frame after it are coded at the same |
| 14537 | // padded size, so the reference each inter frame predicts from -- the |
| 14538 | // previous frame's own uncropped reconstruction, at the size a decoder's |
| 14539 | // reference buffer actually holds -- always matches the frame being |
| 14540 | // coded against it. |
| 14541 | let key = encode_key_frame_inner( |
| 14542 | &first.padded_to(SUPERBLOCK), |
| 14543 | base_q_idx, |
| 14544 | deadzone, |
| 14545 | &KEY_FRAME_MODES, |
| 14546 | split_blocks(), |
| 14547 | render, |
| 14548 | unspecified_color_config(), fctx, |
| 14549 | )?; |
| 14550 | let mut stream = key.stream.clone(); |
| 14551 | // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the |
| 14552 | // key frame refreshes every slot, each inter frame only slot 0), which is |
| 14553 | // what `GOLDEN_FRAME` names. |
| 14554 | let golden = key.reconstruction.clone(); |
| 14555 | // The frame two back, once there is one that is not the key frame |
| 14556 | // itself (which `GOLDEN_FRAME` already names). |
| 14557 | let mut prev2: Option<Picture> = None; |
| 14558 | let mut carried = key.next_cdfs.clone(); |
| 14559 | let mut reference = key.reconstruction.clone(); |
| 14560 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 14561 | for (i, picture) in rest.iter().enumerate() { |
| 14562 | picture.check_even()?; |
| 14563 | // lane-av1tpl2: the lookahead window the per-block lambda weighting |
| 14564 | // propagates back through -- the next [`tpl_depth`] - 1 pictures' |
| 14565 | // sources at this frame's coded (padded) size. The tail of the |
| 14566 | // sequence gets a shorter window, and the last frame none at all. |
| 14567 | let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..] |
| 14568 | .iter() |
| 14569 | .take(tpl_depth() - 1) |
| 14570 | .map(|n| n.padded_to(SUPERBLOCK)) |
| 14571 | .collect(); |
| 14572 | if (picture.width, picture.height) != render { |
| 14573 | return Err(Error::unsupported( |
| 14574 | "AV1 encode", |
| 14575 | "every picture in a sequence must be the same size as the first", |
| 14576 | )); |
| 14577 | } |
| 14578 | let order_hint = (i + 1) as u32; |
| 14579 | let inter = encode_inter_frame( |
| 14580 | &picture.padded_to(SUPERBLOCK), |
| 14581 | &reference, |
| 14582 | base_q_idx, |
| 14583 | deadzone, |
| 14584 | order_hint, |
| 14585 | flat_order_hints(order_hint, 0, prev2.is_some()), |
| 14586 | render, |
| 14587 | Some(&carried.0), |
| 14588 | Some(&golden), |
| 14589 | prev2.as_ref(), |
| 14590 | None, |
| 14591 | fctx, |
| 14592 | None, |
| 14593 | &lookahead, |
| 14594 | )?; |
| 14595 | stream.extend_from_slice(&inter.stream); |
| 14596 | carried = inter.next_cdfs.clone(); |
| 14597 | prev2 = Some(std::mem::replace( |
| 14598 | &mut reference, |
| 14599 | inter.reconstruction.clone(), |
| 14600 | )); |
| 14601 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 14602 | } |
| 14603 | Ok(EncodedSequence { |
| 14604 | stream, |
| 14605 | coding_order: (0..frames.len()).collect(), |
| 14606 | frames, |
| 14607 | }) |
| 14608 | } |
| 14609 | |
| 14610 | #[cfg(test)] |
| 14611 | mod tests { |
| 14612 | |
| 14613 | /// Every (site, frame type, block side) the census can be called with |
| 14614 | /// lands in its own ten-counter bucket, inside the array (class |
| 14615 | /// `enumerate-table-domain`: an off-by-one here would silently add two |
| 14616 | /// sites' trials together). |
| 14617 | #[test] |
| 14618 | fn the_split_census_buckets_are_distinct_and_in_bounds() { |
| 14619 | let mut seen = std::collections::BTreeSet::new(); |
| 14620 | for site in 0..2 { |
| 14621 | for key in [true, false] { |
| 14622 | for side in [8usize, 16, 32, 64] { |
| 14623 | let base = super::split_census_base(site, key, side); |
| 14624 | assert!(base + 10 <= super::SPLIT_CENSUS.len(), "{site} {key} {side}"); |
| 14625 | assert!(seen.insert(base), "{site} {key} {side} collides"); |
| 14626 | } |
| 14627 | } |
| 14628 | } |
| 14629 | assert_eq!(seen.len(), 16); |
| 14630 | } |
| 14631 | |
| 14632 | /// An [`crate::mvstack::MvStack`] with every context at zero and no |
| 14633 | /// neighbours, for the pricer tests below to fill the one band each of |
| 14634 | /// them is about. |
| 14635 | /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer |
| 14636 | /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL |
| 14637 | /// against the same stack -- an offer the writer clamps prices the |
| 14638 | /// residual against a predictor the decoder never derives, which is the |
| 14639 | /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER |
| 14640 | /// side, so the stream stays legal; here the pricer's own offer set is |
| 14641 | /// enumerated, class `enumerate-table-domain`). |
| 14642 | /// |
| 14643 | /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer |
| 14644 | #[test] |
| 14645 | fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() { |
| 14646 | for n in 0..=4usize { |
| 14647 | let mut stack = bare_stack(); |
| 14648 | for i in 0..n { |
| 14649 | stack.entries.push(crate::mvstack::StackEntry { |
| 14650 | mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)), |
| 14651 | weight: 1, |
| 14652 | }); |
| 14653 | stack.drl_ctx.push(0); |
| 14654 | } |
| 14655 | stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv); |
| 14656 | stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv); |
| 14657 | stack.pred_mv = stack.nearest_mv; |
| 14658 | // Aim the vector at each entry in turn, so every index the offer |
| 14659 | // set holds is the one that wins at least once. |
| 14660 | for target in 0..n.max(1) { |
| 14661 | let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv); |
| 14662 | let (_, idx) = best_new_mv_syntax(&stack, mv) |
| 14663 | .expect("a zero residual is always codable"); |
| 14664 | let idx = usize::from(idx); |
| 14665 | assert_eq!( |
| 14666 | crate::tile::signalled_drl_idx(n, 0, idx), |
| 14667 | idx, |
| 14668 | "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}", |
| 14669 | ); |
| 14670 | } |
| 14671 | // The NEARMV arm's own offer set (`search_inter_block`, |
| 14672 | // `search_skip_64`): indices 1 and 2, offered only when the stack |
| 14673 | // really holds that entry. |
| 14674 | for idx in 1..=2usize { |
| 14675 | if stack.entries.get(idx).is_some() { |
| 14676 | assert_eq!( |
| 14677 | crate::tile::signalled_drl_idx(n, 1, idx), |
| 14678 | idx, |
| 14679 | "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}", |
| 14680 | ); |
| 14681 | } |
| 14682 | } |
| 14683 | } |
| 14684 | } |
| 14685 | |
| 14686 | fn bare_stack() -> crate::mvstack::MvStack { |
| 14687 | crate::mvstack::MvStack { |
| 14688 | entries: Default::default(), |
| 14689 | nearest_mv: (0, 0), |
| 14690 | near_mv: (0, 0), |
| 14691 | pred_mv: (0, 0), |
| 14692 | new_mv_ctx: 0, |
| 14693 | ref_mv_ctx: 0, |
| 14694 | zero_mv_ctx: 0, |
| 14695 | drl_ctx: Default::default(), |
| 14696 | above_refs: (None, None), |
| 14697 | left_refs: (None, None), |
| 14698 | above_nbr: None, |
| 14699 | left_nbr: None, |
| 14700 | above_skip: false, |
| 14701 | left_skip: false, |
| 14702 | } |
| 14703 | } |
| 14704 | |
| 14705 | /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs' |
| 14706 | /// `write_compound_ref_frames` codes for a pair, each at that symbol's |
| 14707 | /// own neighbour-derived context. Red before lane-ctx, where the pricer |
| 14708 | /// spent four constants at CDF row 0 that assumed the pair was |
| 14709 | /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as |
| 14710 | /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely. |
| 14711 | #[test] |
| 14712 | fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() { |
| 14713 | use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF}; |
| 14714 | use crate::encode::symbol_bits as b; |
| 14715 | use crate::mvstack::{ |
| 14716 | ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 14717 | LAST_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx, |
| 14718 | single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, |
| 14719 | single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx, |
| 14720 | }; |
| 14721 | // (pair, unidirectional?, the tree's symbols as (table, p index, |
| 14722 | // context selector, value)) -- transcribed from the writer. |
| 14723 | // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`. |
| 14724 | type Sym = (char, usize, usize, usize); |
| 14725 | let cases: [((i8, i8), bool, &[Sym]); 7] = [ |
| 14726 | ((LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)]), |
| 14727 | ( |
| 14728 | (LAST_FRAME, LAST3_FRAME), |
| 14729 | true, |
| 14730 | &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)], |
| 14731 | ), |
| 14732 | ( |
| 14733 | (LAST_FRAME, GOLDEN_FRAME), |
| 14734 | true, |
| 14735 | &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)], |
| 14736 | ), |
| 14737 | ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]), |
| 14738 | ( |
| 14739 | (LAST_FRAME, ALTREF_FRAME), |
| 14740 | false, |
| 14741 | &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)], |
| 14742 | ), |
| 14743 | ( |
| 14744 | (LAST_FRAME, BWDREF_FRAME), |
| 14745 | false, |
| 14746 | &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0)], |
| 14747 | ), |
| 14748 | ( |
| 14749 | (LAST_FRAME, ALTREF2_FRAME), |
| 14750 | false, |
| 14751 | &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1)], |
| 14752 | ), |
| 14753 | ]; |
| 14754 | let nbr = |ref0, ref1: Option<i8>| { |
| 14755 | Some(NeighbourRef { |
| 14756 | is_inter: true, |
| 14757 | ref0, |
| 14758 | ref1, |
| 14759 | uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)), |
| 14760 | }) |
| 14761 | }; |
| 14762 | // No neighbours (every context zero), then a mixed pair that puts the |
| 14763 | // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0. |
| 14764 | for (above_nbr, left_nbr, above_refs, left_refs) in [ |
| 14765 | (None, None, (None, None), (None, None)), |
| 14766 | ( |
| 14767 | nbr(LAST_FRAME, None), |
| 14768 | nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)), |
| 14769 | (Some(LAST_FRAME), None), |
| 14770 | (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)), |
| 14771 | ), |
| 14772 | ] { |
| 14773 | let stack = crate::mvstack::MvStack { |
| 14774 | above_nbr, |
| 14775 | left_nbr, |
| 14776 | above_refs, |
| 14777 | left_refs, |
| 14778 | ..bare_stack() |
| 14779 | }; |
| 14780 | let (a, a1) = above_refs; |
| 14781 | let (l, l1) = left_refs; |
| 14782 | let ctx_of = |sel: usize| match sel { |
| 14783 | 1 => single_ref_p1_ctx(a, a1, l, l1), |
| 14784 | 2 => single_ref_p2_ctx(a, a1, l, l1), |
| 14785 | 3 => single_ref_p3_ctx(a, a1, l, l1), |
| 14786 | 4 => single_ref_p4_ctx(a, a1, l, l1), |
| 14787 | 5 => single_ref_p5_ctx(a, a1, l, l1), |
| 14788 | 6 => single_ref_p6_ctx(a, a1, l, l1), |
| 14789 | _ => uni_comp_ref_p1_ctx(a, a1, l, l1), |
| 14790 | }; |
| 14791 | for (pair, unidir, symbols) in cases { |
| 14792 | let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1) |
| 14793 | + b( |
| 14794 | &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)], |
| 14795 | usize::from(!unidir), |
| 14796 | ); |
| 14797 | for &(table, p, sel, v) in symbols { |
| 14798 | let row = ctx_of(sel); |
| 14799 | want += match table { |
| 14800 | 'u' => b(&UNI_COMP_REF[row][p], v), |
| 14801 | 'c' => b(&COMP_REF[row][p], v), |
| 14802 | _ => b(&COMP_BWDREF[row][p], v), |
| 14803 | }; |
| 14804 | } |
| 14805 | let got = super::compound_ref_bits(pair, &stack); |
| 14806 | assert!( |
| 14807 | (got - want).abs() < 1e-9, |
| 14808 | "pair {pair:?} above {above_refs:?} left {left_refs:?}: \ |
| 14809 | priced {got} bits, writer codes {want}" |
| 14810 | ); |
| 14811 | } |
| 14812 | } |
| 14813 | } |
| 14814 | |
| 14815 | /// The `skip` and `is_inter` symbols are priced at the SAME context |
| 14816 | /// tile.rs codes them with -- `above_skip + left_skip` for the first and |
| 14817 | /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx |
| 14818 | /// on every neighbour configuration whose context is not zero (class |
| 14819 | /// pricer-context-zero). |
| 14820 | #[test] |
| 14821 | fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() { |
| 14822 | use crate::cdf::{INTRA_INTER, SKIP}; |
| 14823 | use crate::encode::symbol_bits as b; |
| 14824 | use crate::mvstack::NeighbourRef; |
| 14825 | let nbr = |is_inter| NeighbourRef { |
| 14826 | is_inter, |
| 14827 | ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 }, |
| 14828 | ref1: None, |
| 14829 | uni: false, |
| 14830 | }; |
| 14831 | for (above, left, above_skip, left_skip) in [ |
| 14832 | (None, None, false, false), |
| 14833 | (Some(nbr(true)), Some(nbr(true)), true, false), |
| 14834 | (Some(nbr(false)), Some(nbr(false)), true, true), |
| 14835 | (Some(nbr(false)), None, false, true), |
| 14836 | (None, Some(nbr(true)), true, true), |
| 14837 | ] { |
| 14838 | let stack = crate::mvstack::MvStack { |
| 14839 | above_nbr: above, |
| 14840 | left_nbr: left, |
| 14841 | above_skip, |
| 14842 | left_skip, |
| 14843 | ..bare_stack() |
| 14844 | }; |
| 14845 | let skip_ctx = usize::from(above_skip) + usize::from(left_skip); |
| 14846 | let ii_ctx = crate::tile::intra_inter_ctx( |
| 14847 | above.is_some(), |
| 14848 | left.is_some(), |
| 14849 | above.is_some_and(|n| n.is_inter), |
| 14850 | left.is_some_and(|n| n.is_inter), |
| 14851 | ); |
| 14852 | for v in [false, true] { |
| 14853 | let (got, want) = ( |
| 14854 | super::skip_bits_at(&stack, v), |
| 14855 | b(&SKIP[skip_ctx], usize::from(v)), |
| 14856 | ); |
| 14857 | assert!( |
| 14858 | (got - want).abs() < 1e-9, |
| 14859 | "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}" |
| 14860 | ); |
| 14861 | let (got, want) = ( |
| 14862 | super::intra_inter_bits_at(&stack, v), |
| 14863 | b(&INTRA_INTER[ii_ctx], usize::from(v)), |
| 14864 | ); |
| 14865 | assert!( |
| 14866 | (got - want).abs() < 1e-9, |
| 14867 | "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}" |
| 14868 | ); |
| 14869 | } |
| 14870 | } |
| 14871 | } |
| 14872 | |
| 14873 | /// [`super::single_ref_bits`] pays exactly what tile.rs' |
| 14874 | /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD |
| 14875 | /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at |
| 14876 | /// the context that symbol's own `single_ref_p*_ctx` derives from the |
| 14877 | /// block's above/left neighbours. Red before lane-pricer, where every |
| 14878 | /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0. |
| 14879 | #[test] |
| 14880 | fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() { |
| 14881 | use crate::cdf::SINGLE_REF as SR; |
| 14882 | use crate::encode::symbol_bits as b; |
| 14883 | use crate::mvstack::{ |
| 14884 | ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, |
| 14885 | LAST_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, |
| 14886 | single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx, |
| 14887 | }; |
| 14888 | let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack { |
| 14889 | above_refs, |
| 14890 | left_refs, |
| 14891 | above_nbr, |
| 14892 | left_nbr, |
| 14893 | ..bare_stack() |
| 14894 | }; |
| 14895 | let nbr = |ref0, ref1| { |
| 14896 | Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false }) |
| 14897 | }; |
| 14898 | // (reference, the symbols `write_single_ref` emits as (p index, value)) |
| 14899 | let cases: [(i8, &[(usize, usize)]); 7] = [ |
| 14900 | (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]), |
| 14901 | (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]), |
| 14902 | (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]), |
| 14903 | (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]), |
| 14904 | (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]), |
| 14905 | (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]), |
| 14906 | (ALTREF_FRAME, &[(0, 1), (1, 1)]), |
| 14907 | ]; |
| 14908 | // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair |
| 14909 | // that puts every p* context on a different row -- the second with a |
| 14910 | // COMPOUND left neighbour, which is what takes `reference_mode_ctx` |
| 14911 | // off row 0. |
| 14912 | for (above_refs, left_refs, above_nbr, left_nbr) in [ |
| 14913 | ((None, None), (None, None), None, None), |
| 14914 | ( |
| 14915 | (Some(LAST_FRAME), None), |
| 14916 | (Some(ALTREF_FRAME), Some(LAST_FRAME)), |
| 14917 | nbr(LAST_FRAME, None), |
| 14918 | nbr(ALTREF_FRAME, Some(LAST_FRAME)), |
| 14919 | ), |
| 14920 | ] { |
| 14921 | let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr); |
| 14922 | let (a, a1) = above_refs; |
| 14923 | let (l, l1) = left_refs; |
| 14924 | let ctx_of = |p: usize| match p { |
| 14925 | 0 => single_ref_p1_ctx(a, a1, l, l1), |
| 14926 | 1 => single_ref_p2_ctx(a, a1, l, l1), |
| 14927 | 2 => single_ref_p3_ctx(a, a1, l, l1), |
| 14928 | 3 => single_ref_p4_ctx(a, a1, l, l1), |
| 14929 | 4 => single_ref_p5_ctx(a, a1, l, l1), |
| 14930 | _ => single_ref_p6_ctx(a, a1, l, l1), |
| 14931 | }; |
| 14932 | for (ref_frame, symbols) in cases { |
| 14933 | // Plus the `comp_mode = 0` symbol the writer codes ahead of |
| 14934 | // the reference syntax on a `reference_select` frame. |
| 14935 | let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum(); |
| 14936 | if super::reference_select() { |
| 14937 | want += b( |
| 14938 | &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx( |
| 14939 | above_nbr, left_nbr, |
| 14940 | )], |
| 14941 | 0, |
| 14942 | ); |
| 14943 | } |
| 14944 | let got = super::single_ref_bits(ref_frame, &stack); |
| 14945 | assert!( |
| 14946 | (got - want).abs() < 1e-9, |
| 14947 | "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \ |
| 14948 | priced {got} bits, writer codes {want}" |
| 14949 | ); |
| 14950 | } |
| 14951 | } |
| 14952 | } |
| 14953 | |
| 14954 | /// lane-av1tpl2's propagated map, on the two properties every decision |
| 14955 | /// under it rests on: a frame the whole lookahead window repeats exactly |
| 14956 | /// (uniform texture) leans on every cell alike, so every factor is 1 and |
| 14957 | /// the weighting is a no-op; and where the window really does save bits |
| 14958 | /// by predicting -- the textured half of a frame whose other half is |
| 14959 | /// flat -- the factor FALLS below 1, i.e. that half is coded more |
| 14960 | /// distortion-averse than the half nothing gains from. |
| 14961 | /// The distortion metric itself (lane-sse): a block the true frame edge |
| 14962 | /// cuts through is scored over its INSIDE part only, so a difference that |
| 14963 | /// lives entirely in the padding costs nothing and a block wholly past |
| 14964 | /// the edge scores zero. Before this, the search ranked modes, |
| 14965 | /// transforms and partition trees on samples the display crop throws |
| 14966 | /// away -- which lane-b64b had fixed for the 64x64 root alone. |
| 14967 | #[test] |
| 14968 | fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() { |
| 14969 | // A 40x40 true frame on a 64x64 padded coding surface. |
| 14970 | let source = vec![10u8; 64 * 64]; |
| 14971 | let plane = fresh_plane(&source, 64, 64, 40, 40); |
| 14972 | let mut reconstruction = vec![10u8; 64 * 64]; |
| 14973 | // Off by 190 at (50, 50) -- past the true edge in both axes. |
| 14974 | reconstruction[50 * 64 + 50] = 200; |
| 14975 | assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored"); |
| 14976 | // Off by 10 at (39, 39) -- the last sample the decoder shows. |
| 14977 | reconstruction[39 * 64 + 39] = 20; |
| 14978 | assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored"); |
| 14979 | // A 16x16 block whose every sample is padding. |
| 14980 | let block = vec![200u8; 16 * 16]; |
| 14981 | assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored"); |
| 14982 | // A 16x16 block the edge cuts: 8 of its columns are inside. |
| 14983 | assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0); |
| 14984 | } |
| 14985 | |
| 14986 | /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must |
| 14987 | /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the |
| 14988 | /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound. |
| 14989 | #[test] |
| 14990 | fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() { |
| 14991 | let (base, res) = (162u8, 4i32); |
| 14992 | let rf = 2.0; |
| 14993 | // A superblock the window leans on more than the frame average is |
| 14994 | // coded FINER (lower qindex); a slack one coarser; the average one |
| 14995 | // exactly at the base. |
| 14996 | assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer"); |
| 14997 | assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser"); |
| 14998 | assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0"); |
| 14999 | // Every offset is a whole number of steps and inside +-(res * 9 - 1). |
| 15000 | let max = ((res * 9 - 1) / res) * res; |
| 15001 | for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] { |
| 15002 | for k in [0.5f64, 1.0, 1.5] { |
| 15003 | let q = i32::from(super::deltaq_libaom(base, r, rf, k, res)); |
| 15004 | let d = q - i32::from(base); |
| 15005 | assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step"); |
| 15006 | assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}"); |
| 15007 | } |
| 15008 | } |
| 15009 | // The clamp is REACHED from both ends, so the bound is a real bound |
| 15010 | // and not a formula that never gets there. |
| 15011 | assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max); |
| 15012 | assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max); |
| 15013 | // A stronger `k` never moves less than a weaker one. |
| 15014 | let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs(); |
| 15015 | assert!(d(0.5) <= d(1.0) && d(1.0) <= d(1.5), "strength must be monotone: {} {} {}", d(0.5), d(1.0), d(1.5)); |
| 15016 | // The frame reference is libaom's log-mean: flat in, the same value out. |
| 15017 | assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9); |
| 15018 | } |
| 15019 | |
| 15020 | /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto |
| 15021 | /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the |
| 15022 | /// shipped default, and the multiplier reaches the strength. |
| 15023 | #[test] |
| 15024 | fn the_per_level_delta_q_strength_indexes_the_levels_it_names() { |
| 15025 | let d = crate::speed::DQ_LEVEL_K; |
| 15026 | assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table"); |
| 15027 | assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]); |
| 15028 | // Short and broken fields fall back per SLOT, not per spec. |
| 15029 | assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]); |
| 15030 | assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]); |
| 15031 | assert_eq!(super::DqLevel::TopArf as usize, 0); |
| 15032 | assert_eq!(super::DqLevel::MidArf as usize, 1); |
| 15033 | assert_eq!(super::DqLevel::Leaf as usize, 2); |
| 15034 | } |
| 15035 | |
| 15036 | #[test] |
| 15037 | fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() { |
| 15038 | // Four 64x64 superblocks across: the shipped map forms its ratio per |
| 15039 | // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could |
| 15040 | // only ever produce one ratio -- and one ratio, mean-normalised, is |
| 15041 | // the flat map, whatever the content underneath it. |
| 15042 | let (w, h) = (256usize, 64usize); |
| 15043 | let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect(); |
| 15044 | let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform]; |
| 15045 | let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0); |
| 15046 | assert_eq!(f.len(), 64, "16x4 cells of 16x16"); |
| 15047 | for (i, &v) in f.iter().enumerate() { |
| 15048 | assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda"); |
| 15049 | } |
| 15050 | |
| 15051 | // Left half textured, right half constant: the window saves bits |
| 15052 | // predicting the left half and nothing at all on the right. |
| 15053 | let split: Vec<u8> = (0..w * h) |
| 15054 | .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 }) |
| 15055 | .collect(); |
| 15056 | let frames: Vec<&[u8]> = vec![&split, &split, &split]; |
| 15057 | let cells_x = w / 16; |
| 15058 | for k in [0.25f64, 0.5, 1.0, 2.0] { |
| 15059 | let (f, _) = super::tpl_lambda_factors(&frames, w, h, k); |
| 15060 | for r in 0..h / 16 { |
| 15061 | let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]); |
| 15062 | assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1"); |
| 15063 | assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1"); |
| 15064 | } |
| 15065 | } |
| 15066 | } |
| 15067 | |
| 15068 | /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a |
| 15069 | /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a |
| 15070 | /// row holds `32 >> bw_in_mi_log2` bits and the table holds |
| 15071 | /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that |
| 15072 | /// superblock must therefore hit every bit of the table EXACTLY ONCE. |
| 15073 | /// r4's `4 - bw_log2` index halved the row stride: the walk then covered |
| 15074 | /// only a quarter of the 16x8 table and read the wrong byte for every |
| 15075 | /// block row but the first (silently wrong above-right/below-left |
| 15076 | /// availability -- wrong pixels, no error). |
| 15077 | #[test] |
| 15078 | fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { |
| 15079 | for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 15080 | let (bw_log2, bh_log2) = |
| 15081 | ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); |
| 15082 | let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); |
| 15083 | for (name, table) in |
| 15084 | [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] |
| 15085 | { |
| 15086 | assert_eq!( |
| 15087 | table.len() * 8, |
| 15088 | rows * cols, |
| 15089 | "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" |
| 15090 | ); |
| 15091 | let mut seen = vec![0u32; table.len() * 8]; |
| 15092 | for blk_row in 0..rows { |
| 15093 | for blk_col in 0..cols { |
| 15094 | let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); |
| 15095 | assert!( |
| 15096 | idx < seen.len(), |
| 15097 | "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" |
| 15098 | ); |
| 15099 | seen[idx] += 1; |
| 15100 | } |
| 15101 | } |
| 15102 | assert!( |
| 15103 | seen.iter().all(|&n| n == 1), |
| 15104 | "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ |
| 15105 | (row stride is not {cols})" |
| 15106 | ); |
| 15107 | } |
| 15108 | } |
| 15109 | } |
| 15110 | use super::*; |
| 15111 | use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; |
| 15112 | use crate::probe::run_with_stdin; |
| 15113 | use std::process::{Command, Stdio}; |
| 15114 | |
| 15115 | /// Every rectangular shape this decoder codes, at every position a block |
| 15116 | /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`] |
| 15117 | /// must answer exactly what libaom's `has_top_right`/`has_bottom_left` |
| 15118 | /// (`reconintra.c`) answer, whose bodies are ported below. |
| 15119 | /// |
| 15120 | /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]): |
| 15121 | /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the |
| 15122 | /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right) |
| 15123 | /// and 7 (below-left) of the 21 reachable positions with no gate seeing |
| 15124 | /// it. The per-shape `(len, byte sum)` fingerprints below come from the |
| 15125 | /// oracle's own arrays, so a re-routed or truncated table fails here even |
| 15126 | /// where the two rows happen to agree. |
| 15127 | /// |
| 15128 | /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/ |
| 15129 | /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the |
| 15130 | /// callers handle by predicting each transform unit as its own block. |
| 15131 | /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's |
| 15132 | /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is |
| 15133 | /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL |
| 15134 | /// (the horizontal shapes, which those partitions never produce). |
| 15135 | #[test] |
| 15136 | fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { |
| 15137 | // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so |
| 15138 | // it pins the 64 reach explicitly instead of following the process's |
| 15139 | // own superblock knob (`for_encoder`), which made it red under |
| 15140 | // `EC_AV1_SB128=1` for no defect of the code under test. |
| 15141 | let fctx = &crate::decode::FrameCtx::new(); |
| 15142 | // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum). |
| 15143 | const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ |
| 15144 | (4, 8, 64, 9280, 64, 550), |
| 15145 | (8, 4, 64, 3712, 64, 9630), |
| 15146 | (8, 16, 16, 2352, 16, 134), |
| 15147 | (16, 8, 16, 960, 16, 2400), |
| 15148 | (16, 32, 4, 620, 4, 32), |
| 15149 | (32, 16, 4, 32, 4, 184), |
| 15150 | (32, 64, 1, 127, 1, 0), |
| 15151 | (64, 32, 1, 19, 1, 34), |
| 15152 | (4, 16, 32, 5472, 32, 14), |
| 15153 | (16, 4, 32, 960, 32, 6464), |
| 15154 | (8, 32, 8, 1400, 8, 2), |
| 15155 | (32, 8, 8, 32, 8, 1136), |
| 15156 | (16, 64, 2, 382, 2, 0), |
| 15157 | (64, 16, 2, 4, 2, 84), |
| 15158 | ]; |
| 15159 | /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for |
| 15160 | /// a block whose transform covers it whole (`row_off == col_off == 0`, |
| 15161 | /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel |
| 15162 | /// superblock (`sb_mi_size == 16`). |
| 15163 | fn libaom_reach( |
| 15164 | bw: usize, |
| 15165 | bh: usize, |
| 15166 | x: usize, |
| 15167 | y: usize, |
| 15168 | width: usize, |
| 15169 | height: usize, _fctx: &crate::decode::FrameCtx, |
| 15170 | ) -> (bool, bool) { |
| 15171 | let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); |
| 15172 | let (_bw_unit, bh_unit) = (bw / 4, bh / 4); |
| 15173 | let sb_mi_size = 16usize; |
| 15174 | let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; |
| 15175 | let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; |
| 15176 | let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; |
| 15177 | let (tr_table, bl_table) = rect_reach_tables(bw, bh); |
| 15178 | let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; |
| 15179 | // has_top_right: top_available && right_available, then row_off == 0. |
| 15180 | let top_right = if y == 0 || x + bw >= width { |
| 15181 | false |
| 15182 | } else if blk_row_in_sb == 0 { |
| 15183 | // (`col_off + tx_wide_unit < plane_bw_unit` above this is |
| 15184 | // `bw_unit < bw_unit`, false for a whole-block transform.) |
| 15185 | true |
| 15186 | } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { |
| 15187 | false |
| 15188 | } else { |
| 15189 | bit(tr_table) |
| 15190 | }; |
| 15191 | // has_bottom_left: bottom_available && left_available, col_off == 0. |
| 15192 | let bottom_left = if x == 0 || y + bh >= height { |
| 15193 | false |
| 15194 | } else if blk_col_in_sb == 0 { |
| 15195 | // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.) |
| 15196 | (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size |
| 15197 | } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { |
| 15198 | false |
| 15199 | } else { |
| 15200 | bit(bl_table) |
| 15201 | }; |
| 15202 | (top_right, bottom_left) |
| 15203 | } |
| 15204 | for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { |
| 15205 | let (tr, bl) = rect_reach_tables(bw, bh); |
| 15206 | let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>(); |
| 15207 | assert_eq!( |
| 15208 | (tr.len(), sum(tr), bl.len(), sum(bl)), |
| 15209 | (tr_len, tr_sum, bl_len, bl_sum), |
| 15210 | "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" |
| 15211 | ); |
| 15212 | // Two superblocks across and down, so the superblock-relative |
| 15213 | // position (and not the frame position) is what decides. |
| 15214 | for sb_y in [0usize, 64] { |
| 15215 | for sb_x in [0usize, 64] { |
| 15216 | for y in (sb_y..sb_y + 64).step_by(bh) { |
| 15217 | for x in (sb_x..sb_x + 64).step_by(bw) { |
| 15218 | let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); |
| 15219 | let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); |
| 15220 | assert_eq!( |
| 15221 | (got.above_right, got.below_left), |
| 15222 | want, |
| 15223 | "{bw}x{bh} at ({x}, {y})" |
| 15224 | ); |
| 15225 | } |
| 15226 | } |
| 15227 | } |
| 15228 | } |
| 15229 | } |
| 15230 | } |
| 15231 | |
| 15232 | /// Whether ffmpeg is on PATH. Absence normally SKIPs, but |
| 15233 | /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every |
| 15234 | /// aomenc gate decodes its stream through ffmpeg and is meaningless |
| 15235 | /// without it -- turns it into a hard failure. Without this the require |
| 15236 | /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first |
| 15237 | /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg |
| 15238 | /// printed SKIP and reported green (class gate-skips-on-its-own-failure). |
| 15239 | fn have_ffmpeg() -> bool { |
| 15240 | let present = Command::new("ffmpeg") |
| 15241 | .arg("-version") |
| 15242 | .stdout(Stdio::null()) |
| 15243 | .stderr(Stdio::null()) |
| 15244 | .status() |
| 15245 | .is_ok_and(|s| s.success()); |
| 15246 | assert!( |
| 15247 | present |
| 15248 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 15249 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 15250 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 15251 | ); |
| 15252 | present |
| 15253 | } |
| 15254 | |
| 15255 | /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the |
| 15256 | /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it). |
| 15257 | fn have_encoder(encoder: &str) -> bool { |
| 15258 | Command::new("ffmpeg") |
| 15259 | .args(["-hide_banner", "-encoders"]) |
| 15260 | .stderr(Stdio::null()) |
| 15261 | .output() |
| 15262 | .is_ok_and(|o| { |
| 15263 | String::from_utf8_lossy(&o.stdout) |
| 15264 | .lines() |
| 15265 | .any(|l| l.split_whitespace().nth(1) == Some(encoder)) |
| 15266 | }) |
| 15267 | } |
| 15268 | |
| 15269 | /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes. |
| 15270 | fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { |
| 15271 | let out = run_with_stdin( |
| 15272 | Command::new("ffmpeg").args([ |
| 15273 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 15274 | ]), |
| 15275 | stream, |
| 15276 | ); |
| 15277 | assert!( |
| 15278 | out.status.success(), |
| 15279 | "ffmpeg refused the stream: {}", |
| 15280 | String::from_utf8_lossy(&out.stderr) |
| 15281 | ); |
| 15282 | let (luma, chroma) = (width * height, width * height / 4); |
| 15283 | assert_eq!( |
| 15284 | out.stdout.len(), |
| 15285 | luma + 2 * chroma, |
| 15286 | "expected one 4:2:0 frame" |
| 15287 | ); |
| 15288 | Picture { |
| 15289 | width, |
| 15290 | height, |
| 15291 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 15292 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 15293 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 15294 | } |
| 15295 | } |
| 15296 | |
| 15297 | /// A picture with something of everything in it: a gradient, an edge, a |
| 15298 | /// ripple and a block of flat colour, none of them aligned to the block |
| 15299 | /// grid. |
| 15300 | /// The in-loop filters actually FIRE and the stream still decodes to |
| 15301 | /// exactly what the encoder kept as its reconstruction |
| 15302 | /// (gate-blind-to-feature: a filter search that always answered "off" |
| 15303 | /// would leave every other test just as green, and the BD gate that |
| 15304 | /// would notice is `#[ignore]`d). |
| 15305 | /// |
| 15306 | /// Run: |
| 15307 | /// cargo test -p ec-av1 --release --lib -- \ |
| 15308 | /// encode::tests::the_filter_search_picks_real_filters |
| 15309 | #[test] |
| 15310 | fn the_filter_search_picks_real_filters() { |
| 15311 | let _knobs = crate::speed::knob_read(); |
| 15312 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15313 | let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); |
| 15314 | let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); |
| 15315 | let fired = encoded |
| 15316 | .frames |
| 15317 | .iter() |
| 15318 | .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) |
| 15319 | .count(); |
| 15320 | assert!( |
| 15321 | fired > 0, |
| 15322 | "no frame of this sequence chose any in-loop filtering: {:?}", |
| 15323 | encoded |
| 15324 | .frames |
| 15325 | .iter() |
| 15326 | .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) |
| 15327 | .collect::<Vec<_>>() |
| 15328 | ); |
| 15329 | // The reconstruction the encoder predicts from is the FILTERED one, |
| 15330 | // and it is what a decoder of the stream produces -- byte for byte, |
| 15331 | // frame for frame. |
| 15332 | let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 15333 | assert_eq!(decoded.len(), encoded.frames.len()); |
| 15334 | for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 15335 | assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); |
| 15336 | assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); |
| 15337 | assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); |
| 15338 | } |
| 15339 | } |
| 15340 | |
| 15341 | fn test_card(width: usize, height: usize) -> Picture { |
| 15342 | let mut picture = Picture::grey(width, height); |
| 15343 | for y in 0..height { |
| 15344 | for x in 0..width { |
| 15345 | let gradient = x as f64 * 200.0 / width as f64; |
| 15346 | let ripple = 30.0 |
| 15347 | * (x as f64 * std::f64::consts::PI / 23.0).sin() |
| 15348 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 15349 | let edge = if x > width * 3 / 7 && y > height / 3 { |
| 15350 | 40.0 |
| 15351 | } else { |
| 15352 | 0.0 |
| 15353 | }; |
| 15354 | picture.y[y * width + x] = |
| 15355 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 15356 | } |
| 15357 | } |
| 15358 | for y in 0..height / 2 { |
| 15359 | for x in 0..width / 2 { |
| 15360 | let i = y * width / 2 + x; |
| 15361 | picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; |
| 15362 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 15363 | } |
| 15364 | } |
| 15365 | picture |
| 15366 | } |
| 15367 | |
| 15368 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 15369 | let squared: f64 = a |
| 15370 | .iter() |
| 15371 | .zip(b) |
| 15372 | .map(|(&x, &y)| { |
| 15373 | let d = f64::from(x) - f64::from(y); |
| 15374 | d * d |
| 15375 | }) |
| 15376 | .sum(); |
| 15377 | if squared == 0.0 { |
| 15378 | return f64::INFINITY; |
| 15379 | } |
| 15380 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 15381 | } |
| 15382 | |
| 15383 | /// lane-i64's witness: a smooth gradient is exactly the picture a whole |
| 15384 | /// 64x64 intra block predicts as well as four 32x32 ones, so the key |
| 15385 | /// frame's new root fires on most superblocks -- and what BOTH decoders |
| 15386 | /// produce is the encoder's own reconstruction, sample for sample. |
| 15387 | /// |
| 15388 | /// The fire count is the `gate-blind-to-feature` guard: without it every |
| 15389 | /// assert below passes on a stream that codes no whole superblock at all. |
| 15390 | #[test] |
| 15391 | fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() { |
| 15392 | let _knobs = crate::speed::knob_read(); |
| 15393 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15394 | // 4 x 3 superblocks, all of them wholly inside the frame. |
| 15395 | let (width, height) = (256usize, 192usize); |
| 15396 | let mut picture = Picture::grey(width, height); |
| 15397 | for y in 0..height { |
| 15398 | for x in 0..width { |
| 15399 | picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16; |
| 15400 | } |
| 15401 | } |
| 15402 | for y in 0..height / 2 { |
| 15403 | for x in 0..width / 2 { |
| 15404 | picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16; |
| 15405 | picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16; |
| 15406 | } |
| 15407 | } |
| 15408 | let _ = take_i64_root_hits(); |
| 15409 | let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap(); |
| 15410 | let [roots, _offered, _edge] = take_i64_root_hits(); |
| 15411 | // The counters are process-global, so another test encoding in |
| 15412 | // parallel can only ADD to them -- the per-FRAME fact is the mode |
| 15413 | // list, which carries one entry per coded block and so exactly 12 |
| 15414 | // when every superblock was coded as one 64x64 intra block. |
| 15415 | assert_eq!( |
| 15416 | encoded.modes.len(), |
| 15417 | 12, |
| 15418 | "not every superblock was coded as one 64x64 intra block" |
| 15419 | ); |
| 15420 | assert!( |
| 15421 | roots >= 8, |
| 15422 | "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12" |
| 15423 | ); |
| 15424 | eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12"); |
| 15425 | |
| 15426 | let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 15427 | assert_eq!(ours.len(), 1, "our decoder's frames"); |
| 15428 | assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 15429 | assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 15430 | assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 15431 | |
| 15432 | if !have_ffmpeg() { |
| 15433 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 15434 | return; |
| 15435 | } |
| 15436 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15437 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 15438 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 15439 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 15440 | } |
| 15441 | |
| 15442 | /// The claim the whole encoder rests on: what a decoder produces is what |
| 15443 | /// the encoder said it would, sample for sample, on every plane. |
| 15444 | /// |
| 15445 | /// Prediction reads the reconstruction, so a single sample of drift |
| 15446 | /// anywhere would spread into every block below and to the right of it — |
| 15447 | /// which is why this is an equality and not a tolerance. |
| 15448 | #[test] |
| 15449 | fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { |
| 15450 | let _knobs = crate::speed::knob_read(); |
| 15451 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15452 | if !have_ffmpeg() { |
| 15453 | eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); |
| 15454 | return; |
| 15455 | } |
| 15456 | for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] { |
| 15457 | let picture = test_card(width, height); |
| 15458 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15459 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15460 | assert_eq!( |
| 15461 | decoded.y, encoded.reconstruction.y, |
| 15462 | "{width}x{height}: luma" |
| 15463 | ); |
| 15464 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 15465 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 15466 | } |
| 15467 | // One q index from each of the four coefficient-CDF contexts |
| 15468 | // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size. |
| 15469 | let (width, height) = (64usize, 64usize); |
| 15470 | let picture = test_card(width, height); |
| 15471 | let _ = take_tx_depth_hits(); |
| 15472 | for &q in &[15u8, 45, 100, 200] { |
| 15473 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 15474 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15475 | assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); |
| 15476 | assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); |
| 15477 | assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); |
| 15478 | } |
| 15479 | // lane-av1tx: the exactness above is only a claim about SPLIT |
| 15480 | // transforms if some block actually split one (`gate-blind-to-feature` |
| 15481 | // -- with `tx_depth` stuck at 0 every assert here passes on the |
| 15482 | // pre-lane stream). The test card's edges split at these four |
| 15483 | // quantizers; the counter is per-process (another test encoding in |
| 15484 | // parallel can only ADD to it, so this can be masked, never falsely |
| 15485 | // failed), so it is read once for the whole q ladder. |
| 15486 | let depths = take_tx_depth_hits(); |
| 15487 | assert!( |
| 15488 | depths[1] + depths[2] > 0, |
| 15489 | "no block split its transform: depths {depths:?}" |
| 15490 | ); |
| 15491 | } |
| 15492 | |
| 15493 | /// A synthetic screen-content picture -- a few flat colours in a grid of |
| 15494 | /// boxes with hard edges and text-like bars, the shape a desktop capture |
| 15495 | /// has -- so the palette path is exercised on content it is for. |
| 15496 | #[cfg(test)] |
| 15497 | fn screen_card(width: usize, height: usize) -> Picture { |
| 15498 | const INK: [u16; 4] = [16, 90, 180, 235]; |
| 15499 | let mut picture = Picture::grey(width, height); |
| 15500 | for y in 0..height { |
| 15501 | for x in 0..width { |
| 15502 | let cell = (x / 24 + y / 24) % 2; |
| 15503 | let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); |
| 15504 | picture.y[y * width + x] = INK[cell * 2 + bar]; |
| 15505 | } |
| 15506 | } |
| 15507 | // Four chroma colours, not two: a two-colour chroma block only ever |
| 15508 | // codes a `PaletteSizeUV` of 2, which leaves |
| 15509 | // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking |
| 15510 | // deltas and the neighbour cache flags, exercised only when |
| 15511 | // neighbouring blocks share colours) unproven by the ffmpeg oracle. |
| 15512 | const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; |
| 15513 | const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; |
| 15514 | for y in 0..height / 2 { |
| 15515 | for x in 0..width / 2 { |
| 15516 | let cell = (x / 12 + 2 * (y / 12)) % 4; |
| 15517 | picture.u[y * (width / 2) + x] = CHROMA_U[cell]; |
| 15518 | picture.v[y * (width / 2) + x] = CHROMA_V[cell]; |
| 15519 | } |
| 15520 | } |
| 15521 | picture |
| 15522 | } |
| 15523 | |
| 15524 | /// The lane's own end-to-end check: on screen content the detector fires, |
| 15525 | /// blocks really take a palette (fire count, class |
| 15526 | /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every |
| 15527 | /// symbol this lane writes -- reconstructs exactly what the encoder did. |
| 15528 | /// The film-shaped `test_card` must NOT trip the detector, which is what |
| 15529 | /// keeps every non-screen stream byte-identical. |
| 15530 | #[test] |
| 15531 | fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { |
| 15532 | let _knobs = crate::speed::knob_read(); |
| 15533 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15534 | let (width, height) = (192usize, 96usize); |
| 15535 | let _ = crate::tile::take_palette_hits(); |
| 15536 | let picture = screen_card(width, height); |
| 15537 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15538 | assert!( |
| 15539 | encoded.screen, |
| 15540 | "the detector did not fire on screen content -- no palette syntax was coded at all" |
| 15541 | ); |
| 15542 | let hits = crate::tile::take_palette_hits(); |
| 15543 | assert!(hits[0] > 0, "no block took a palette: {hits:?}"); |
| 15544 | eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); |
| 15545 | // The chroma half is a claim about the plane-1 syntax only if some |
| 15546 | // block really took a chroma palette (`gate-blind-to-feature`): every |
| 15547 | // exactness assert below passes on a stream that codes |
| 15548 | // `palette_uv_mode == 0` everywhere. |
| 15549 | let uv_hits = crate::tile::take_palette_uv_hits(); |
| 15550 | assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}"); |
| 15551 | let uv_cached = crate::tile::take_palette_uv_cache_hits(); |
| 15552 | eprintln!( |
| 15553 | "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", |
| 15554 | uv_hits[0], |
| 15555 | &uv_hits[2..] |
| 15556 | ); |
| 15557 | assert!( |
| 15558 | uv_cached > 0, |
| 15559 | "no chroma base colour came out of the neighbour cache -- \ |
| 15560 | `write_palette_colors_uv`'s cache half is unproven by the oracle below" |
| 15561 | ); |
| 15562 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 15563 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 15564 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 15565 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 15566 | if !have_ffmpeg() { |
| 15567 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 15568 | return; |
| 15569 | } |
| 15570 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15571 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 15572 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 15573 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 15574 | // A whole GOP: the inter frames' own intra blocks carry the palette |
| 15575 | // syntax too (the three intra arms of the inter writers), which only |
| 15576 | // ffmpeg reading the frames back can prove. |
| 15577 | let moved: Vec<Picture> = (0..4) |
| 15578 | .map(|f| { |
| 15579 | let base = screen_card(width, height); |
| 15580 | let mut out = Picture::grey(width, height); |
| 15581 | for y in 0..height { |
| 15582 | for x in 0..width { |
| 15583 | let sx = (x + f * 7) % width; |
| 15584 | out.y[y * width + x] = base.y[y * width + sx]; |
| 15585 | } |
| 15586 | } |
| 15587 | for y in 0..height / 2 { |
| 15588 | for x in 0..width / 2 { |
| 15589 | let sx = (x + f * 3) % (width / 2); |
| 15590 | out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; |
| 15591 | out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; |
| 15592 | } |
| 15593 | } |
| 15594 | out |
| 15595 | }) |
| 15596 | .collect(); |
| 15597 | let _ = crate::tile::take_palette_hits(); |
| 15598 | let _ = crate::tile::take_palette_uv_hits(); |
| 15599 | let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); |
| 15600 | let gop_hits = crate::tile::take_palette_hits(); |
| 15601 | let gop_uv_hits = crate::tile::take_palette_uv_hits(); |
| 15602 | let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); |
| 15603 | eprintln!( |
| 15604 | "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ |
| 15605 | {} chroma palette blocks", |
| 15606 | inter_screen, gop_hits[0], gop_uv_hits[0] |
| 15607 | ); |
| 15608 | assert!( |
| 15609 | gop_uv_hits[0] > 0, |
| 15610 | "no block of the GOP took a chroma palette: {gop_uv_hits:?}" |
| 15611 | ); |
| 15612 | assert!( |
| 15613 | inter_screen > 0, |
| 15614 | "no inter frame set allow_screen_content_tools" |
| 15615 | ); |
| 15616 | let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); |
| 15617 | for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { |
| 15618 | assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma"); |
| 15619 | } |
| 15620 | if have_ffmpeg() { |
| 15621 | let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); |
| 15622 | for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { |
| 15623 | assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma"); |
| 15624 | assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); |
| 15625 | assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); |
| 15626 | } |
| 15627 | } |
| 15628 | |
| 15629 | // The other half of the keep rule: film-shaped content leaves the |
| 15630 | // detector (and so the whole sequence header) alone. |
| 15631 | let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); |
| 15632 | assert!(!film.screen, "the detector fired on the film-shaped test card"); |
| 15633 | } |
| 15634 | |
| 15635 | /// The lane's keep-rule measurement: the gate's own screen capture, one |
| 15636 | /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers. |
| 15637 | /// Setting the bit forces deblocking, CDEF and loop restoration off for |
| 15638 | /// that frame, so the table is exactly the filter loss against the bytes |
| 15639 | /// the copied blocks save. |
| 15640 | #[test] |
| 15641 | #[ignore = "needs the real-library manifest and ffmpeg"] |
| 15642 | fn probe_intrabc_key_frame() { |
| 15643 | let _knobs = crate::speed::knob_write(); |
| 15644 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15645 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 15646 | .join("../../fixtures"); |
| 15647 | let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else { |
| 15648 | eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest"); |
| 15649 | return; |
| 15650 | }; |
| 15651 | let Some(clip) = manifest |
| 15652 | .lines() |
| 15653 | .skip(1) |
| 15654 | .filter_map(|l| l.split('\t').next()) |
| 15655 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 15656 | else { |
| 15657 | eprintln!("SKIP probe_intrabc_key_frame: no OBS recording"); |
| 15658 | return; |
| 15659 | }; |
| 15660 | let (width, height) = (1280usize, 768usize); |
| 15661 | let picture = clip_frame(clip, "0", width, height); |
| 15662 | eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |"); |
| 15663 | for q in [5u8, 20, 35, 45] { |
| 15664 | for on in [false, true] { |
| 15665 | force_intrabc(Some(on)); |
| 15666 | let _ = crate::tile::take_intrabc_hits(); |
| 15667 | let _ = take_intrabc_search(); |
| 15668 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 15669 | let hits = crate::tile::take_intrabc_hits(); |
| 15670 | let search = take_intrabc_search(); |
| 15671 | eprintln!( |
| 15672 | "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |", |
| 15673 | if encoded.allow_intrabc { "on" } else { "off" }, |
| 15674 | encoded.stream.len(), |
| 15675 | psnr_all(&encoded.reconstruction, &picture), |
| 15676 | hits[0], |
| 15677 | &hits[1..], |
| 15678 | search[0], search[1], search[2], |
| 15679 | ); |
| 15680 | } |
| 15681 | } |
| 15682 | force_intrabc(None); |
| 15683 | } |
| 15684 | |
| 15685 | /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card |
| 15686 | /// sets `allow_intrabc` (so every in-loop filter is off), blocks really |
| 15687 | /// take a block vector (fire count + DV histogram, class |
| 15688 | /// `gate-blind-to-feature`), and both our own decoder and ffmpeg -- |
| 15689 | /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct |
| 15690 | /// exactly what the encoder did. |
| 15691 | #[test] |
| 15692 | fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() { |
| 15693 | let _knobs = crate::speed::knob_write(); |
| 15694 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15695 | // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4 |
| 15696 | // superblocks of 64) and tall enough for a source superblock row |
| 15697 | // above the blocks that copy from it. |
| 15698 | let (width, height) = (512usize, 256usize); |
| 15699 | let picture = screen_card(width, height); |
| 15700 | let _ = crate::tile::take_intrabc_hits(); |
| 15701 | // The default is OFF (it measured worse on the real screen capture -- |
| 15702 | // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns |
| 15703 | // the arm on for its own encode and puts it back straight after. |
| 15704 | force_intrabc(Some(true)); |
| 15705 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15706 | force_intrabc(None); |
| 15707 | assert!( |
| 15708 | encoded.allow_intrabc, |
| 15709 | "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)", |
| 15710 | intrabc_source_share() * 100.0 |
| 15711 | ); |
| 15712 | let hits = crate::tile::take_intrabc_hits(); |
| 15713 | eprintln!( |
| 15714 | "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%", |
| 15715 | hits[0], |
| 15716 | &hits[1..], |
| 15717 | intrabc_source_share() * 100.0 |
| 15718 | ); |
| 15719 | let search = take_intrabc_search(); |
| 15720 | eprintln!( |
| 15721 | "intrabc searches {} found-valid {} won-RD {}", |
| 15722 | search[0], search[1], search[2] |
| 15723 | ); |
| 15724 | assert!( |
| 15725 | hits[0] > 0, |
| 15726 | "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}" |
| 15727 | ); |
| 15728 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 15729 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 15730 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 15731 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 15732 | if !have_ffmpeg() { |
| 15733 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 15734 | return; |
| 15735 | } |
| 15736 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15737 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 15738 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 15739 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 15740 | } |
| 15741 | |
| 15742 | /// The minimal repro that isolated the inter-residual desync: a key frame |
| 15743 | /// followed by one inter frame whose single superblock carries one |
| 15744 | /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma |
| 15745 | /// coefficient, its three sibling blocks all `skip: true`. Before the |
| 15746 | /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data |
| 15747 | /// found when processing input") even though every symbol either block |
| 15748 | /// codes is otherwise proven (all-skip inter blocks decode clean, and the |
| 15749 | /// same coefficient syntax decodes clean on every intra key-frame gate). |
| 15750 | #[test] |
| 15751 | fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { |
| 15752 | let _knobs = crate::speed::knob_write(); |
| 15753 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15754 | if !have_ffmpeg() { |
| 15755 | eprintln!( |
| 15756 | "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg" |
| 15757 | ); |
| 15758 | return; |
| 15759 | } |
| 15760 | let (width, height) = (64usize, 64usize); |
| 15761 | let picture = Picture::grey(width, height); |
| 15762 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15763 | |
| 15764 | let (seq, _) = key_frame_headers(width, height, 100).unwrap(); |
| 15765 | let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); |
| 15766 | |
| 15767 | let residual_block = BlockCoeffs { |
| 15768 | luma_tx_types: Vec::new(), |
| 15769 | angle_delta_y: 0, |
| 15770 | cfl_alphas: None, |
| 15771 | filter_intra: None, |
| 15772 | luma: vec![Coeff { |
| 15773 | row: 0, |
| 15774 | col: 0, |
| 15775 | level: 4, |
| 15776 | }], |
| 15777 | u: Vec::new(), |
| 15778 | v: Vec::new(), |
| 15779 | mode: 0, |
| 15780 | uv_mode: 0, |
| 15781 | skip: false, |
| 15782 | eight: None, |
| 15783 | dv: None, |
| 15784 | palette: None, |
| 15785 | palette_uv: None, |
| 15786 | tx_depth: 0, |
| 15787 | inter: Some(InterInfo { |
| 15788 | ref1: None, |
| 15789 | mv1: (0, 0), |
| 15790 | ref_frame: crate::mvstack::LAST_FRAME, |
| 15791 | mode: InterMode::NearestMv, |
| 15792 | mv: (0, 0), |
| 15793 | ref_mv_idx: 0, |
| 15794 | }), |
| 15795 | motion_mode: 0, |
| 15796 | }; |
| 15797 | let skipped_block = BlockCoeffs { |
| 15798 | skip: true, |
| 15799 | inter: Some(InterInfo { |
| 15800 | ref1: None, |
| 15801 | mv1: (0, 0), |
| 15802 | ref_frame: crate::mvstack::LAST_FRAME, |
| 15803 | mode: InterMode::NearestMv, |
| 15804 | mv: (0, 0), |
| 15805 | ref_mv_idx: 0, |
| 15806 | }), |
| 15807 | ..BlockCoeffs::default() |
| 15808 | }; |
| 15809 | let blocks = vec![ |
| 15810 | Quadrant::Whole(residual_block), |
| 15811 | Quadrant::Whole(skipped_block.clone()), |
| 15812 | Quadrant::Whole(skipped_block.clone()), |
| 15813 | Quadrant::Whole(skipped_block), |
| 15814 | ]; |
| 15815 | // lane-av1obmc: the header this tile is decoded under carries |
| 15816 | // `is_motion_mode_switchable`, so the writer must be armed with it |
| 15817 | // too or the decoder reads a `motion_mode` symbol nobody wrote. |
| 15818 | crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable); |
| 15819 | crate::tile::arm_warped_motion(inter_header.allow_warped_motion); |
| 15820 | let tile = |
| 15821 | crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) |
| 15822 | .unwrap(); |
| 15823 | |
| 15824 | // `key.stream` is already a temporal delimiter, the sequence header |
| 15825 | // and the key frame's own OBU (`encode_key_frame` built it from the |
| 15826 | // same `key_frame_headers(width, height, 100)` this test calls), so |
| 15827 | // the inter frame's OBU is appended straight onto it rather than |
| 15828 | // re-deriving the key frame's tile bytes. |
| 15829 | let mut stream = key.stream.clone(); |
| 15830 | stream.extend_from_slice(&temporal_delimiter()); |
| 15831 | stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); |
| 15832 | |
| 15833 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 15834 | } |
| 15835 | |
| 15836 | /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded |
| 15837 | /// frame size an AV1 decoder allocates, not necessarily the render size |
| 15838 | /// (see [`a_frame_round_trips_at_its_own_size`]). |
| 15839 | fn ffprobe_size(stream: &[u8]) -> (u32, u32) { |
| 15840 | // Distinct per call, not per process: the test binary runs callers on |
| 15841 | // parallel threads, and a shared name lets one test's cleanup delete |
| 15842 | // the stream another test's ffprobe is still reading. |
| 15843 | static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 15844 | let path = std::env::temp_dir().join(format!( |
| 15845 | "ec-av1-probe-{}-{}.obu", |
| 15846 | std::process::id(), |
| 15847 | PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 15848 | )); |
| 15849 | let _ = std::fs::remove_file(&path); |
| 15850 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 15851 | let out = Command::new("ffprobe") |
| 15852 | .args([ |
| 15853 | "-v", |
| 15854 | "error", |
| 15855 | "-f", |
| 15856 | "obu", |
| 15857 | "-select_streams", |
| 15858 | "v:0", |
| 15859 | "-show_entries", |
| 15860 | "stream=width,height", |
| 15861 | "-of", |
| 15862 | "csv=p=0", |
| 15863 | ]) |
| 15864 | .arg(&path) |
| 15865 | .output() |
| 15866 | .expect("ffprobe failed to run"); |
| 15867 | let _ = std::fs::remove_file(&path); |
| 15868 | assert!( |
| 15869 | out.status.success(), |
| 15870 | "ffprobe refused the stream: {}", |
| 15871 | String::from_utf8_lossy(&out.stderr) |
| 15872 | ); |
| 15873 | let text = String::from_utf8_lossy(&out.stdout); |
| 15874 | let mut fields = text.trim().split(','); |
| 15875 | let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); |
| 15876 | let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); |
| 15877 | (width, height) |
| 15878 | } |
| 15879 | |
| 15880 | /// lane-av1cap: the final filter replay against the capture decode it |
| 15881 | /// replaced, at the block-padded and straddling sizes the whole-frame |
| 15882 | /// tests cover -- `set_verify_final_replay` makes |
| 15883 | /// [`pick_and_apply_filters`] run both on every frame and assert, per |
| 15884 | /// frame, that the spliced picture and the two filter stages the |
| 15885 | /// restoration search reads are bit-identical over the frame's own crop. |
| 15886 | #[test] |
| 15887 | fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() { |
| 15888 | let _knobs = crate::speed::knob_write(); |
| 15889 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15890 | crate::decode::set_verify_final_replay(true); |
| 15891 | for &(width, height) in |
| 15892 | &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)] |
| 15893 | { |
| 15894 | eprintln!("--- {width}x{height}"); |
| 15895 | let picture = test_card(width, height); |
| 15896 | let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15897 | } |
| 15898 | crate::decode::set_verify_final_replay(false); |
| 15899 | } |
| 15900 | |
| 15901 | /// A key frame at an arbitrary even size round-trips through ffmpeg over |
| 15902 | /// its own render rectangle: [`Encoded::reconstruction`] is exactly the |
| 15903 | /// picture's own size, and what ffmpeg decodes over that same top-left |
| 15904 | /// region equals it sample for sample. |
| 15905 | /// |
| 15906 | /// This does not check that `ffprobe` reports the picture's own size, |
| 15907 | /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded |
| 15908 | /// (block-padded) frame size, the same one libaom itself would code for |
| 15909 | /// a non-block-aligned picture. `render_width`/`render_height` (which |
| 15910 | /// this crate sets correctly, spec 5.9.6) is a display hint no AV1 |
| 15911 | /// decoder is required to crop pixels by, and ffmpeg's does not -- |
| 15912 | /// checked empirically against ffprobe here and against a real libaom |
| 15913 | /// encode separately. So the coded size, not the render size, is what |
| 15914 | /// `ffprobe` is asserted to report below. |
| 15915 | #[test] |
| 15916 | fn a_frame_round_trips_at_its_own_size() { |
| 15917 | let _knobs = crate::speed::knob_read(); |
| 15918 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15919 | if !have_ffmpeg() { |
| 15920 | eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); |
| 15921 | return; |
| 15922 | } |
| 15923 | // 854x480 is covered separately by |
| 15924 | // `an_854x480_picture_round_trips_through_its_padding`, which its own |
| 15925 | // doc comment explains was worth keeping as its own test. |
| 15926 | for &(width, height) in &[ |
| 15927 | (1920usize, 1080usize), |
| 15928 | (640, 352), |
| 15929 | (1280, 720), |
| 15930 | (64, 56), |
| 15931 | (854, 480), |
| 15932 | (216, 96), |
| 15933 | (192, 120), |
| 15934 | ] { |
| 15935 | let picture = test_card(width, height); |
| 15936 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15937 | assert_eq!( |
| 15938 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 15939 | (width, height), |
| 15940 | "{width}x{height}: reconstruction is cropped to the picture's own size" |
| 15941 | ); |
| 15942 | assert_eq!( |
| 15943 | ffprobe_size(&encoded.stream), |
| 15944 | (width as u32, height as u32), |
| 15945 | "{width}x{height}: ffprobe reports the true (display) size, not the padded one" |
| 15946 | ); |
| 15947 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15948 | assert_eq!( |
| 15949 | decoded.y, encoded.reconstruction.y, |
| 15950 | "{width}x{height}: luma" |
| 15951 | ); |
| 15952 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 15953 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 15954 | } |
| 15955 | } |
| 15956 | |
| 15957 | /// 854x480 (padded to 864x480, an edge-replication padded key frame) used |
| 15958 | /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug |
| 15959 | /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact |
| 15960 | /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned |
| 15961 | /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while |
| 15962 | /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 + |
| 15963 | /// col`) -- different bits of an 8-byte table, one true, one false. The |
| 15964 | /// stride libaom indexes by is fixed at its compile-time maximum |
| 15965 | /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock |
| 15966 | /// size a stream uses, so the right stride for a 16x16 or 32x32 block is |
| 15967 | /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s |
| 15968 | /// row/col position within the (correctly 64-relative) superblock stayed |
| 15969 | /// right, only the table's own row stride was wrong. Fixed in |
| 15970 | /// `Reach::table_stride`; not an arithmetic-coder desync (an |
| 15971 | /// EC_RNG-per-symbol trace against the same debug decoder found the |
| 15972 | /// bitstream byte-for-byte identical to libaom's across all 51188 |
| 15973 | /// symbols of this frame before this bug was found). |
| 15974 | /// |
| 15975 | /// Since the frame header started writing the true (unpadded) display |
| 15976 | /// size into `frame_width`/`frame_height` rather than the padded coded |
| 15977 | /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded |
| 15978 | /// 864x480 and cropping ourselves now reads past what ffmpeg actually |
| 15979 | /// emits (`av1_common_int.h`'s render/upscale path, mirrored by |
| 15980 | /// `av1_frame_size` on the decode side, crops the loop-filtered picture to |
| 15981 | /// the header's own size before output). |
| 15982 | #[test] |
| 15983 | fn an_854x480_picture_round_trips_through_its_padding() { |
| 15984 | let _knobs = crate::speed::knob_read(); |
| 15985 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 15986 | if !have_ffmpeg() { |
| 15987 | return; |
| 15988 | } |
| 15989 | let (width, height) = (854usize, 480usize); |
| 15990 | let picture = test_card(width, height); |
| 15991 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 15992 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 15993 | assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); |
| 15994 | assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); |
| 15995 | assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); |
| 15996 | } |
| 15997 | |
| 15998 | /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left` |
| 15999 | /// transform-unit path, for every 4x4 unit of every 8x8 block of a |
| 16000 | /// superblock, both partition tables: |
| 16001 | /// |
| 16002 | /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the |
| 16003 | /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so |
| 16004 | /// wiring the TU sites onto it changes no existing stream; |
| 16005 | /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is |
| 16006 | /// NULL in libaom because that lookup never happens, and reading a |
| 16007 | /// 4x4 row out of the three-row vert tables is what crashed a real |
| 16008 | /// `--enable-tx-size-search=1` stream (r2); |
| 16009 | /// 3. and it must be the BLOCK's vert answer where the two tables |
| 16010 | /// disagree: the top-right 4x4 unit of the 8x8 block at superblock |
| 16011 | /// row 1, column 0 reads its above-right samples from the 8x8 to its |
| 16012 | /// upper right, which a vertical AB partition codes AFTER it |
| 16013 | /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1). |
| 16014 | #[test] |
| 16015 | fn of_tu_follows_the_block_row_including_under_vert_ab() { |
| 16016 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16017 | // The 8x8 square at superblock row 1, column 0, and the TX4 unit in |
| 16018 | // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's |
| 16019 | // above-right answer is the BLOCK's, which is the whole reason a unit |
| 16020 | // asks the block instead of looking itself up (the |
| 16021 | // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2). |
| 16022 | let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 16023 | assert_eq!( |
| 16024 | Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, |
| 16025 | plain.above_right, |
| 16026 | "ordinary table: the top-right TX4 unit takes the block's row" |
| 16027 | ); |
| 16028 | let guard = Reach::vert_ab_partition(); |
| 16029 | let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 16030 | assert_eq!( |
| 16031 | Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, |
| 16032 | vert.above_right, |
| 16033 | "vert AB: the unit follows the vert row the block just picked" |
| 16034 | ); |
| 16035 | assert_ne!( |
| 16036 | plain.above_right, vert.above_right, |
| 16037 | "this position is the cell where the vert tables disagree; pick another if libaom's tables change" |
| 16038 | ); |
| 16039 | drop(guard); |
| 16040 | } |
| 16041 | |
| 16042 | /// `Reach::top_right`/`bottom_left` against a from-scratch transcription |
| 16043 | /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/ |
| 16044 | /// reconintra.c`), for every 16x16 and 32x32 block position across three |
| 16045 | /// superblocks square -- interior and every superblock edge (top row, |
| 16046 | /// left column, right column, bottom row) both sizes reach. Written to |
| 16047 | /// catch the class the `table_stride` bug was: an index stride silently |
| 16048 | /// wrong for one block size while looking plausible for the other. |
| 16049 | #[test] |
| 16050 | fn reach_matches_libaom_has_top_right_and_has_bottom_left() { |
| 16051 | // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so |
| 16052 | // it pins the 64 reach explicitly instead of following the process's |
| 16053 | // own superblock knob (`for_encoder`), which made it red under |
| 16054 | // `EC_AV1_SB128=1` for no defect of the code under test. |
| 16055 | let fctx = &crate::decode::FrameCtx::new(); |
| 16056 | // Transcribed from has_top_right/has_bottom_left's row_off==0, |
| 16057 | // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a |
| 16058 | // 128px reference grid) pinned as libaom pins it, independent of the |
| 16059 | // 64px superblock this crate actually codes. |
| 16060 | fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { |
| 16061 | if y == 0 || x + side >= width { |
| 16062 | return false; |
| 16063 | } |
| 16064 | let (row, col, per_side) = ( |
| 16065 | (y % SUPERBLOCK) / side, |
| 16066 | (x % SUPERBLOCK) / side, |
| 16067 | SUPERBLOCK / side, |
| 16068 | ); |
| 16069 | if row == 0 { |
| 16070 | return true; |
| 16071 | } |
| 16072 | if col + 1 == per_side { |
| 16073 | return false; |
| 16074 | } |
| 16075 | let stride = 128 / side; |
| 16076 | let index = row * stride + col; |
| 16077 | let table = if side == BLOCK { |
| 16078 | [95u8, 87].to_vec() |
| 16079 | } else { |
| 16080 | vec![255, 85, 119, 85, 127, 85, 119, 85] |
| 16081 | }; |
| 16082 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 16083 | } |
| 16084 | |
| 16085 | fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool { |
| 16086 | if x == 0 || y + side >= height { |
| 16087 | return false; |
| 16088 | } |
| 16089 | let (row, col, per_side) = ( |
| 16090 | (y % SUPERBLOCK) / side, |
| 16091 | (x % SUPERBLOCK) / side, |
| 16092 | SUPERBLOCK / side, |
| 16093 | ); |
| 16094 | if col == 0 { |
| 16095 | return row * side + side < SUPERBLOCK; |
| 16096 | } |
| 16097 | if row + 1 == per_side { |
| 16098 | return false; |
| 16099 | } |
| 16100 | let stride = 128 / side; |
| 16101 | let index = row * stride + col; |
| 16102 | let table = if side == BLOCK { |
| 16103 | [4u8, 4].to_vec() |
| 16104 | } else { |
| 16105 | vec![84, 16, 84, 0, 84, 16, 84, 0] |
| 16106 | }; |
| 16107 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 16108 | } |
| 16109 | |
| 16110 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 16111 | for side in [16usize, BLOCK] { |
| 16112 | for y in (0..height).step_by(side) { |
| 16113 | for x in (0..width).step_by(side) { |
| 16114 | let reach = Reach::of(side, x, y, width, height, fctx); |
| 16115 | assert_eq!( |
| 16116 | reach.above_right, |
| 16117 | libaom_top_right(side, x, y, width, height), |
| 16118 | "side={side} x={x} y={y}: above_right" |
| 16119 | ); |
| 16120 | assert_eq!( |
| 16121 | reach.below_left, |
| 16122 | libaom_bottom_left(side, x, y, height, fctx), |
| 16123 | "side={side} x={x} y={y}: below_left" |
| 16124 | ); |
| 16125 | } |
| 16126 | } |
| 16127 | } |
| 16128 | } |
| 16129 | |
| 16130 | /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are |
| 16131 | /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8 |
| 16132 | /// column inside the superblock) may read the below-left samples the |
| 16133 | /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots |
| 16134 | /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe |
| 16135 | /// swept in r6 produced a decodable 16x16-level VERT_B stream (every |
| 16136 | /// stream that partitions that small first hits the still-refused |
| 16137 | /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms). |
| 16138 | /// [`Reach::of_tu`] against a from-scratch transcription of libaom's |
| 16139 | /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma, |
| 16140 | /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in |
| 16141 | /// pixels -- lane-palette2 r12: the square multi-TU path used the |
| 16142 | /// standalone-block tables instead of this rule and granted a 16x16 |
| 16143 | /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses. |
| 16144 | #[test] |
| 16145 | fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { |
| 16146 | // libaom, in MI units: bw_unit/bh_unit = block size / 4, |
| 16147 | // *_count_unit = tx size / 4. |
| 16148 | fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 16149 | let (plane_bw_unit, count) = (bw / 4, tx / 4); |
| 16150 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 16151 | let _ = bh; |
| 16152 | if row_off_u > 0 { |
| 16153 | col_off_u + count < plane_bw_unit |
| 16154 | } else if col_off_u + count < plane_bw_unit { |
| 16155 | true |
| 16156 | } else { |
| 16157 | blk |
| 16158 | } |
| 16159 | } |
| 16160 | fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 16161 | let (plane_bh_unit, count) = (bh / 4, tx / 4); |
| 16162 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 16163 | let _ = bw; |
| 16164 | if col_off_u > 0 { |
| 16165 | false |
| 16166 | } else if row_off_u + count < plane_bh_unit { |
| 16167 | true |
| 16168 | } else { |
| 16169 | blk |
| 16170 | } |
| 16171 | } |
| 16172 | for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 16173 | for &tx in &[4usize, 8, 16, 32] { |
| 16174 | if tx > bw.min(bh) { |
| 16175 | continue; |
| 16176 | } |
| 16177 | for row_off in (0..bh).step_by(tx) { |
| 16178 | for col_off in (0..bw).step_by(tx) { |
| 16179 | for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { |
| 16180 | let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); |
| 16181 | assert_eq!( |
| 16182 | got.above_right, |
| 16183 | libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), |
| 16184 | "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 16185 | ); |
| 16186 | assert_eq!( |
| 16187 | got.below_left, |
| 16188 | libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), |
| 16189 | "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 16190 | ); |
| 16191 | } |
| 16192 | } |
| 16193 | } |
| 16194 | } |
| 16195 | } |
| 16196 | } |
| 16197 | |
| 16198 | #[test] |
| 16199 | fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { |
| 16200 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16201 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 16202 | // Interior superblock, so neither the frame edge nor the col == 0 / |
| 16203 | // last-row early returns answer instead of the table. |
| 16204 | let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); |
| 16205 | let mut flipped = 0; |
| 16206 | for row in 0..8 { |
| 16207 | for col in 1..8 { |
| 16208 | let (x, y) = (sb_x + col * 8, sb_y + row * 8); |
| 16209 | let raster = Reach::of(8, x, y, width, height, fctx).below_left; |
| 16210 | let vert = { |
| 16211 | let _guard = Reach::vert_ab_partition(); |
| 16212 | Reach::of(8, x, y, width, height, fctx).below_left |
| 16213 | }; |
| 16214 | // The TR square of a VERT_A/_B sits at an even row, odd |
| 16215 | // column; every other slot must be untouched by the guard. |
| 16216 | if row % 2 == 0 && col % 2 == 1 { |
| 16217 | assert!(!raster, "raster below_left at row={row} col={col}"); |
| 16218 | assert!(vert, "vert below_left at row={row} col={col}"); |
| 16219 | flipped += 1; |
| 16220 | } else { |
| 16221 | assert_eq!(raster, vert, "guard moved row={row} col={col}"); |
| 16222 | } |
| 16223 | } |
| 16224 | } |
| 16225 | assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); |
| 16226 | // The guard is scoped: it must not leak past its own block. |
| 16227 | assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); |
| 16228 | } |
| 16229 | |
| 16230 | /// An odd width or height is refused by name, not by however the padder |
| 16231 | /// or the block coder would happen to fail on it. |
| 16232 | #[test] |
| 16233 | fn odd_dimensions_are_refused() { |
| 16234 | let _knobs = crate::speed::knob_read(); |
| 16235 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16236 | for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { |
| 16237 | let picture = Picture::grey(width, height); |
| 16238 | let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) |
| 16239 | .expect_err(&format!("{width}x{height} is odd and must be refused")); |
| 16240 | assert!( |
| 16241 | err.to_string().contains("even"), |
| 16242 | "{width}x{height}: error was {err}" |
| 16243 | ); |
| 16244 | } |
| 16245 | } |
| 16246 | |
| 16247 | /// A sequence at a size that is not a multiple of the block grid decodes |
| 16248 | /// to the right frame count and the right size for every frame, |
| 16249 | /// including the inter frames whose reference is the previous frame's |
| 16250 | /// own (padded) reconstruction. |
| 16251 | #[test] |
| 16252 | fn sequence_round_trips_at_a_non_multiple_size() { |
| 16253 | let _knobs = crate::speed::knob_read(); |
| 16254 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16255 | if !have_ffmpeg() { |
| 16256 | eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); |
| 16257 | return; |
| 16258 | } |
| 16259 | let (width, height) = (160usize, 96usize); |
| 16260 | let pictures: Vec<Picture> = (0..3) |
| 16261 | .map(|i| panned_test_card(width, height, i * 3)) |
| 16262 | .collect(); |
| 16263 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 16264 | assert_eq!(encoded.frames.len(), 3); |
| 16265 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 16266 | assert_eq!( |
| 16267 | (frame.reconstruction.width, frame.reconstruction.height), |
| 16268 | (width, height), |
| 16269 | "frame {i}: reconstruction size" |
| 16270 | ); |
| 16271 | } |
| 16272 | // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the |
| 16273 | // true (display) size a sequence's frames share, not the padded one. |
| 16274 | assert_eq!( |
| 16275 | ffprobe_size(&encoded.stream), |
| 16276 | (width as u32, height as u32), |
| 16277 | "sequence: ffprobe reports the true (display) size" |
| 16278 | ); |
| 16279 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 16280 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 16281 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 16282 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 16283 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 16284 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 16285 | } |
| 16286 | } |
| 16287 | |
| 16288 | /// 1280x720 -- the export size a real edith timeline hits -- is exactly |
| 16289 | /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge |
| 16290 | /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s |
| 16291 | /// `pos + side_mi / 2 < bound` boundary), which is the case |
| 16292 | /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than |
| 16293 | /// refusing. A key frame alone already covered this size; this proves the |
| 16294 | /// inter tile writer's parity with it across a real multi-frame export. |
| 16295 | #[test] |
| 16296 | fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { |
| 16297 | let _knobs = crate::speed::knob_read(); |
| 16298 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16299 | if !have_ffmpeg() { |
| 16300 | eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg"); |
| 16301 | return; |
| 16302 | } |
| 16303 | let (width, height) = (1280usize, 720usize); |
| 16304 | let pictures: Vec<Picture> = (0..3) |
| 16305 | .map(|i| panned_test_card(width, height, i * 3)) |
| 16306 | .collect(); |
| 16307 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 16308 | assert_eq!(encoded.frames.len(), 3); |
| 16309 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 16310 | assert_eq!( |
| 16311 | (frame.reconstruction.width, frame.reconstruction.height), |
| 16312 | (width, height), |
| 16313 | "frame {i}: reconstruction size" |
| 16314 | ); |
| 16315 | } |
| 16316 | assert_eq!( |
| 16317 | ffprobe_size(&encoded.stream), |
| 16318 | (width as u32, height as u32), |
| 16319 | "ffprobe reports the true (display) 1280x720 size" |
| 16320 | ); |
| 16321 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 16322 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 16323 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 16324 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 16325 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 16326 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 16327 | } |
| 16328 | } |
| 16329 | |
| 16330 | /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16 |
| 16331 | /// leaf's own half (`has_half` at the SUB level) itself straddles the |
| 16332 | /// true edge on one axis only. lane-av1-rect r7 wired the key frame |
| 16333 | /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly |
| 16334 | /// this case; lane-av1inter8 extends the same leaf-8 path to inter |
| 16335 | /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s |
| 16336 | /// straddling-16x16 branch), so an inter frame no longer refuses this |
| 16337 | /// size either. This only proves the encoder does not error out -- see |
| 16338 | /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the |
| 16339 | /// decoder-clean proof (a 3-frame sequence, so the inter path is |
| 16340 | /// actually exercised). |
| 16341 | #[test] |
| 16342 | fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { |
| 16343 | let _knobs = crate::speed::knob_read(); |
| 16344 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16345 | let (width, height) = (640usize, 360usize); |
| 16346 | let picture = Picture::grey(width, height); |
| 16347 | encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle"); |
| 16348 | |
| 16349 | // `encode_sequence`'s second frame is the inter path: same size, now |
| 16350 | // wired the same way. |
| 16351 | let pictures = vec![picture.clone(), picture]; |
| 16352 | encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) |
| 16353 | .expect("inter frame now codes the mod-32==8 straddle too"); |
| 16354 | } |
| 16355 | |
| 16356 | /// The r15 fix at production size: three 640x360 key frames (inter is |
| 16357 | /// still refused at this size, per the test above, so this stands in for |
| 16358 | /// the charter's "3-frame sequence" using three independent key frames of |
| 16359 | /// shifted content), each proven decoder-clean through ffmpeg rather than |
| 16360 | /// only encoder-clean. |
| 16361 | #[test] |
| 16362 | fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { |
| 16363 | let _knobs = crate::speed::knob_read(); |
| 16364 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16365 | if !have_ffmpeg() { |
| 16366 | eprintln!( |
| 16367 | "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \ |
| 16368 | no ffmpeg" |
| 16369 | ); |
| 16370 | return; |
| 16371 | } |
| 16372 | let (width, height) = (640usize, 360usize); |
| 16373 | for shift in [0i64, 7, 19] { |
| 16374 | let picture = panned_test_card(width, height, shift); |
| 16375 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 16376 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 16377 | assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); |
| 16378 | assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); |
| 16379 | assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); |
| 16380 | } |
| 16381 | } |
| 16382 | |
| 16383 | /// The 640x360 straddle class, but through the inter path an actual |
| 16384 | /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)): |
| 16385 | /// proves the leaf-8 inter stream this round wires up is not just |
| 16386 | /// encoder-clean (the test above) but decoder-clean against ffmpeg too. |
| 16387 | #[test] |
| 16388 | fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { |
| 16389 | let _knobs = crate::speed::knob_read(); |
| 16390 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16391 | if !have_ffmpeg() { |
| 16392 | eprintln!( |
| 16393 | "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" |
| 16394 | ); |
| 16395 | return; |
| 16396 | } |
| 16397 | let (width, height) = (640usize, 360usize); |
| 16398 | let pictures: Vec<Picture> = (0..4) |
| 16399 | .map(|i| panned_test_card(width, height, i * 3)) |
| 16400 | .collect(); |
| 16401 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 16402 | assert_eq!(encoded.frames.len(), 4); |
| 16403 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 16404 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 16405 | } |
| 16406 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); |
| 16407 | assert_eq!(decoded.len(), 4, "decoded frame count"); |
| 16408 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 16409 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 16410 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 16411 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 16412 | } |
| 16413 | } |
| 16414 | |
| 16415 | /// One frame of a real clip, scaled to a whole number of 32x32 blocks. |
| 16416 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 16417 | let out = Command::new("ffmpeg") |
| 16418 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) |
| 16419 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 16420 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 16421 | .output() |
| 16422 | .expect("ffmpeg failed to run"); |
| 16423 | assert!( |
| 16424 | out.status.success(), |
| 16425 | "ffmpeg: {}", |
| 16426 | String::from_utf8_lossy(&out.stderr) |
| 16427 | ); |
| 16428 | let (luma, chroma) = (width * height, width * height / 4); |
| 16429 | assert_eq!( |
| 16430 | out.stdout.len(), |
| 16431 | luma + 2 * chroma, |
| 16432 | "expected one 4:2:0 frame" |
| 16433 | ); |
| 16434 | Picture { |
| 16435 | width, |
| 16436 | height, |
| 16437 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 16438 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 16439 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 16440 | } |
| 16441 | } |
| 16442 | |
| 16443 | /// Prints what the mode search saves over DC prediction alone, for the |
| 16444 | /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the |
| 16445 | /// weight the search puts on rate can be swept. |
| 16446 | #[test] |
| 16447 | #[ignore = "a sweep, not a gate"] |
| 16448 | fn probe_lambda() { |
| 16449 | let _knobs = crate::speed::knob_read(); |
| 16450 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16451 | let mut pictures = vec![ |
| 16452 | ("test card".to_string(), test_card(160, 96)), |
| 16453 | ("stripes".to_string(), stripes(160, 96, true)), |
| 16454 | ]; |
| 16455 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 16456 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 16457 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 16458 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 16459 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 16460 | } |
| 16461 | } |
| 16462 | for (name, picture) in pictures { |
| 16463 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 16464 | let searched = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 16465 | println!( |
| 16466 | "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", |
| 16467 | bd_rate(&dc, &searched) * 100.0, |
| 16468 | 10f64.powf(searched[1].1), |
| 16469 | searched[1].0, |
| 16470 | 10f64.powf(dc[1].1), |
| 16471 | dc[1].0, |
| 16472 | ); |
| 16473 | } |
| 16474 | } |
| 16475 | |
| 16476 | /// Prints the whole mode-search ladder, so two builds of the search can be |
| 16477 | /// compared against each other rather than each against its own baseline. |
| 16478 | #[test] |
| 16479 | #[ignore = "a sweep, not a gate"] |
| 16480 | fn probe_ladder() { |
| 16481 | let _knobs = crate::speed::knob_read(); |
| 16482 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16483 | for (name, picture) in sweep_pictures() { |
| 16484 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 16485 | let points = all |
| 16486 | .iter() |
| 16487 | .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) |
| 16488 | .collect::<Vec<_>>() |
| 16489 | .join(" "); |
| 16490 | println!("ladder {name}: {points}"); |
| 16491 | } |
| 16492 | } |
| 16493 | |
| 16494 | /// Splitting a 32x32 block into four 16x16 ones, measured both ways over |
| 16495 | /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what |
| 16496 | /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report. |
| 16497 | #[test] |
| 16498 | #[ignore = "a sweep, not a gate"] |
| 16499 | fn probe_split() { |
| 16500 | let _knobs = crate::speed::knob_read(); |
| 16501 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16502 | for (name, picture) in sweep_pictures() { |
| 16503 | let ladder = |split: bool| { |
| 16504 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 16505 | .iter() |
| 16506 | .map(|&q| { |
| 16507 | let encoded = encode_key_frame_inner( |
| 16508 | &picture, |
| 16509 | q, |
| 16510 | 0.5, |
| 16511 | &KEY_FRAME_MODES, |
| 16512 | split, |
| 16513 | (picture.width, picture.height), |
| 16514 | unspecified_color_config(), fctx, |
| 16515 | ) |
| 16516 | .unwrap(); |
| 16517 | ( |
| 16518 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 16519 | (encoded.stream.len() as f64).log10(), |
| 16520 | ) |
| 16521 | }) |
| 16522 | .collect(); |
| 16523 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 16524 | points |
| 16525 | }; |
| 16526 | let (whole, split) = (ladder(false), ladder(true)); |
| 16527 | let blocks = encode_key_frame_inner( |
| 16528 | &picture, |
| 16529 | 90, |
| 16530 | 0.5, |
| 16531 | &KEY_FRAME_MODES, |
| 16532 | true, |
| 16533 | (picture.width, picture.height), |
| 16534 | unspecified_color_config(), fctx, |
| 16535 | ) |
| 16536 | .unwrap() |
| 16537 | .modes |
| 16538 | .len(); |
| 16539 | let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); |
| 16540 | println!( |
| 16541 | "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", |
| 16542 | bd_rate(&whole, &split) * 100.0 |
| 16543 | ); |
| 16544 | } |
| 16545 | } |
| 16546 | |
| 16547 | /// A striped picture, running one way or the other. The stripes are what |
| 16548 | /// separates a vertical predictor from a horizontal one: a mode search |
| 16549 | /// reading a transposed edge would pick the wrong one of the pair, which no |
| 16550 | /// symmetric picture would show. |
| 16551 | fn stripes(width: usize, height: usize, vertical: bool) -> Picture { |
| 16552 | let mut picture = Picture::grey(width, height); |
| 16553 | for y in 0..height { |
| 16554 | for x in 0..width { |
| 16555 | let along = if vertical { x } else { y }; |
| 16556 | picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; |
| 16557 | } |
| 16558 | } |
| 16559 | picture |
| 16560 | } |
| 16561 | |
| 16562 | /// Where two planes first disagree, and by how much: a mismatch reported as |
| 16563 | /// a position says which block and which sample of it went wrong, which a |
| 16564 | /// pair of thousand-sample arrays does not. |
| 16565 | fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> { |
| 16566 | let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?; |
| 16567 | let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); |
| 16568 | Some(format!( |
| 16569 | "{differ} samples differ, first at ({}, {}): ours {} theirs {}", |
| 16570 | i % width, |
| 16571 | i / width, |
| 16572 | ours[i], |
| 16573 | theirs[i] |
| 16574 | )) |
| 16575 | } |
| 16576 | |
| 16577 | /// Every mode the encoder offers has to predict what the decoder predicts, |
| 16578 | /// not just the ones a particular picture happens to choose: each is forced |
| 16579 | /// over a whole picture and the reconstruction gated against ffmpeg. |
| 16580 | #[test] |
| 16581 | fn every_mode_decodes_to_what_the_encoder_predicted() { |
| 16582 | let _knobs = crate::speed::knob_write(); |
| 16583 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16584 | if !have_ffmpeg() { |
| 16585 | eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); |
| 16586 | return; |
| 16587 | } |
| 16588 | // A mode ablation measures the MODE search: a filter-intra block is |
| 16589 | // coded `DC_PRED` whatever mode the arm forces, so it would fail the |
| 16590 | // "the encoder coded something else" check for a reason that is not |
| 16591 | // about the mode search at all. |
| 16592 | force_filter_intra(Some(false)); |
| 16593 | // 128 wide is a whole number of superblocks and 160 is not: the last |
| 16594 | // superblock of a 160-wide row is half a one, whose blocks have no |
| 16595 | // above-right samples inside the frame at all. |
| 16596 | for (width, height) in [(128, 96), (160, 96)] { |
| 16597 | let picture = test_card(width, height); |
| 16598 | for mode in KEY_FRAME_MODES { |
| 16599 | let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap(); |
| 16600 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 16601 | for (plane, ours, theirs, stride) in [ |
| 16602 | ("luma", &encoded.reconstruction.y, &decoded.y, width), |
| 16603 | ("U", &encoded.reconstruction.u, &decoded.u, width / 2), |
| 16604 | ("V", &encoded.reconstruction.v, &decoded.v, width / 2), |
| 16605 | ] { |
| 16606 | assert!( |
| 16607 | first_difference(ours, theirs, stride).is_none(), |
| 16608 | "{width}x{height} mode {mode}, {plane}: {}", |
| 16609 | first_difference(ours, theirs, stride).unwrap() |
| 16610 | ); |
| 16611 | } |
| 16612 | assert!( |
| 16613 | encoded.modes.iter().all(|&m| m == mode), |
| 16614 | "mode {mode}: the encoder coded something else" |
| 16615 | ); |
| 16616 | } |
| 16617 | } |
| 16618 | } |
| 16619 | |
| 16620 | /// The search has to follow the picture: vertical stripes are cheapest |
| 16621 | /// predicted from the row above, horizontal ones from the column to the |
| 16622 | /// left. Reading the edges the other way round would swap the two answers |
| 16623 | /// while leaving every fidelity gate intact. |
| 16624 | #[test] |
| 16625 | fn the_search_picks_the_direction_the_picture_runs() { |
| 16626 | let _knobs = crate::speed::knob_write(); |
| 16627 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16628 | // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]: |
| 16629 | // a filter-intra block is coded `DC_PRED` whatever mode the arm |
| 16630 | // offers, and these stripes are SCREEN content, where the filter arm |
| 16631 | // now searches its own transform depth (lane-fitu) and wins outright |
| 16632 | // -- which says nothing about the mode search this gate measures. |
| 16633 | force_filter_intra(Some(false)); |
| 16634 | for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { |
| 16635 | let picture = stripes(128, 96, vertical); |
| 16636 | // Only the pair, because on stripes a third mode predicts exactly |
| 16637 | // what the right one of the pair does -- PAETH reads the corner and |
| 16638 | // the left column, which a striped picture makes equal -- and the |
| 16639 | // tie then goes to whichever is cheaper to name, which is not what |
| 16640 | // this gate is about. |
| 16641 | let encoded = |
| 16642 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap(); |
| 16643 | // The first block of the picture has neither neighbour, so it |
| 16644 | // cannot tell the modes apart; every other one can. |
| 16645 | let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); |
| 16646 | assert!( |
| 16647 | picked * 2 > encoded.modes.len() - 1, |
| 16648 | "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", |
| 16649 | encoded.modes.len() - 1, |
| 16650 | encoded.modes |
| 16651 | ); |
| 16652 | } |
| 16653 | } |
| 16654 | |
| 16655 | /// What the search is for: the same picture, at the same quantizer, coded |
| 16656 | /// smaller and more faithfully than DC alone can manage. |
| 16657 | /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid |
| 16658 | /// between the two rate-distortion curves in log-rate against PSNR, as a |
| 16659 | /// fraction of the reference's rate. Negative means the second curve costs |
| 16660 | /// less for the same picture. |
| 16661 | fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { |
| 16662 | let low = reference[0].0.max(other[0].0); |
| 16663 | let high = reference[reference.len() - 1] |
| 16664 | .0 |
| 16665 | .min(other[other.len() - 1].0); |
| 16666 | // lane-av1tx: `TxMode::Select` moved the directional ladder clear of |
| 16667 | // the non-directional one on the synthetic diagonals -- every point |
| 16668 | // both higher in PSNR *and* lower in rate -- so there is no PSNR band |
| 16669 | // to integrate over any more. A curve that dominates that way has |
| 16670 | // saved everything the measure can express (the |
| 16671 | // `instrument-at-bound` class: the answer is at the instrument's own |
| 16672 | // edge, not undefined), so name it rather than panicking; anything |
| 16673 | // less clean than strict dominance still is. |
| 16674 | if high <= low { |
| 16675 | let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); |
| 16676 | let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); |
| 16677 | let dominates = other[0].0 > reference[reference.len() - 1].0 |
| 16678 | && other_hi_rate <= ref_lo_rate; |
| 16679 | assert!( |
| 16680 | dominates, |
| 16681 | "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" |
| 16682 | ); |
| 16683 | return -1.0; |
| 16684 | } |
| 16685 | let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { |
| 16686 | let i = curve |
| 16687 | .windows(2) |
| 16688 | .position(|w| psnr >= w[0].0 && psnr <= w[1].0) |
| 16689 | .unwrap_or(0); |
| 16690 | let (x0, y0) = curve[i]; |
| 16691 | let (x1, y1) = curve[i + 1]; |
| 16692 | y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) |
| 16693 | }; |
| 16694 | let steps = 64; |
| 16695 | let mut area = 0.0; |
| 16696 | for step in 0..steps { |
| 16697 | let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); |
| 16698 | area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); |
| 16699 | } |
| 16700 | 10f64.powf(area / f64::from(steps)) - 1.0 |
| 16701 | } |
| 16702 | |
| 16703 | /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by |
| 16704 | /// fidelity. |
| 16705 | fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { |
| 16706 | // A mode ablation measures the MODE search: the palette would code |
| 16707 | // these synthetic two-colour pictures losslessly under every arm and |
| 16708 | // leave nothing to compare (see [`force_screen`]). |
| 16709 | force_screen(Some(false)); |
| 16710 | // Same reason, for the filter-intra candidate: it wins blocks under |
| 16711 | // BOTH arms of a mode ablation and so cancels the difference the |
| 16712 | // ablation measures (class `gate-recipe-confound`). |
| 16713 | force_filter_intra(Some(false)); |
| 16714 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 16715 | .iter() |
| 16716 | .map(|&q| { |
| 16717 | let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap(); |
| 16718 | ( |
| 16719 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 16720 | (encoded.stream.len() as f64).log10(), |
| 16721 | ) |
| 16722 | }) |
| 16723 | .collect(); |
| 16724 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 16725 | points |
| 16726 | } |
| 16727 | |
| 16728 | /// What the search is for: the same pictures cost less to code at the same |
| 16729 | /// fidelity than DC prediction alone can manage. A picture that runs one |
| 16730 | /// way saves far more than a busy one, which is the shape a working |
| 16731 | /// directional pair has. |
| 16732 | #[test] |
| 16733 | fn the_search_beats_dc_alone() { |
| 16734 | let _knobs = crate::speed::knob_read(); |
| 16735 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16736 | for (name, picture, want) in [ |
| 16737 | ("test card", test_card(160, 96), -0.05), |
| 16738 | ("stripes", stripes(160, 96, true), -0.40), |
| 16739 | ] { |
| 16740 | let saved = bd_rate( |
| 16741 | &ladder(&picture, &[DC_PRED], fctx), |
| 16742 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 16743 | ); |
| 16744 | assert!( |
| 16745 | saved < want, |
| 16746 | "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", |
| 16747 | saved * 100.0, |
| 16748 | -want * 100.0 |
| 16749 | ); |
| 16750 | } |
| 16751 | } |
| 16752 | |
| 16753 | /// The pictures a sweep is measured over: two synthetic ones, plus a frame |
| 16754 | /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated. |
| 16755 | fn sweep_pictures() -> Vec<(String, Picture)> { |
| 16756 | let mut pictures = vec![ |
| 16757 | ("test card".to_string(), test_card(160, 96)), |
| 16758 | ("stripes".to_string(), stripes(160, 96, true)), |
| 16759 | ("diagonal".to_string(), diagonal(160, 96, true)), |
| 16760 | ]; |
| 16761 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 16762 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 16763 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 16764 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 16765 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 16766 | } |
| 16767 | } |
| 16768 | pictures |
| 16769 | } |
| 16770 | |
| 16771 | /// What the six directional modes are worth, per picture, at whatever |
| 16772 | /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read |
| 16773 | /// no further, and how often the search picks one. |
| 16774 | #[test] |
| 16775 | #[ignore = "a sweep, not a gate"] |
| 16776 | fn probe_directional() { |
| 16777 | let _knobs = crate::speed::knob_write(); |
| 16778 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16779 | for (name, picture) in sweep_pictures() { |
| 16780 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 16781 | let flat = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 16782 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 16783 | let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap(); |
| 16784 | let directional = encoded |
| 16785 | .modes |
| 16786 | .iter() |
| 16787 | .filter(|&&m| (3..=8).contains(&m)) |
| 16788 | .count(); |
| 16789 | // A picture whose ladders sit at different fidelities altogether |
| 16790 | // has no BD-rate to report -- see the flat-sample-window class. |
| 16791 | let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 16792 | a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) |
| 16793 | }; |
| 16794 | let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 16795 | if overlap(a, b) { |
| 16796 | format!("{:+.2}%", bd_rate(a, b) * 100.0) |
| 16797 | } else { |
| 16798 | "no overlap".to_string() |
| 16799 | } |
| 16800 | }; |
| 16801 | println!( |
| 16802 | "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", |
| 16803 | against(&flat, &all), |
| 16804 | against(&dc, &all), |
| 16805 | encoded.modes.len(), |
| 16806 | ); |
| 16807 | } |
| 16808 | } |
| 16809 | |
| 16810 | /// A picture whose stripes run along a diagonal, one way or the other. |
| 16811 | /// This is to the directional modes what [`stripes`] is to the vertical and |
| 16812 | /// horizontal pair: a predictor that walked the edge in the wrong direction |
| 16813 | /// would answer the two pictures the same way round. |
| 16814 | fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { |
| 16815 | let mut picture = Picture::grey(width, height); |
| 16816 | for y in 0..height { |
| 16817 | for x in 0..width { |
| 16818 | let along = if down_right { x + height - y } else { x + y }; |
| 16819 | picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; |
| 16820 | } |
| 16821 | } |
| 16822 | picture |
| 16823 | } |
| 16824 | |
| 16825 | /// The mode picked by the most blocks of a picture, ignoring the first |
| 16826 | /// block, which has no neighbours to tell the modes apart with. |
| 16827 | fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { |
| 16828 | // A mode ablation measures the MODE search: the palette would code |
| 16829 | // these synthetic two-colour pictures losslessly under every arm and |
| 16830 | // leave nothing to compare (see [`force_screen`]). |
| 16831 | force_screen(Some(false)); |
| 16832 | let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); |
| 16833 | let blocks = &encoded.modes[1..]; |
| 16834 | let mut counts = [0usize; 13]; |
| 16835 | for &mode in blocks { |
| 16836 | counts[usize::from(mode)] += 1; |
| 16837 | } |
| 16838 | let (mode, count) = counts |
| 16839 | .iter() |
| 16840 | .enumerate() |
| 16841 | .max_by_key(|&(_, count)| *count) |
| 16842 | .expect("thirteen modes"); |
| 16843 | (mode as u8, *count, blocks.len()) |
| 16844 | } |
| 16845 | |
| 16846 | /// The search has to follow a diagonal the way it runs: stripes down and to |
| 16847 | /// the right are cheapest predicted at 135 degrees, stripes down and to the |
| 16848 | /// left at 45. A walk that stepped the wrong way along the edge, or read |
| 16849 | /// the above row where it should read the left column, would swap these. |
| 16850 | #[test] |
| 16851 | fn the_search_picks_the_diagonal_the_picture_runs() { |
| 16852 | let _knobs = crate::speed::knob_write(); |
| 16853 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16854 | for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { |
| 16855 | let picture = diagonal(160, 96, down_right); |
| 16856 | let (mode, count, blocks) = favourite_mode(&picture, fctx); |
| 16857 | assert_eq!( |
| 16858 | mode, want, |
| 16859 | "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" |
| 16860 | ); |
| 16861 | } |
| 16862 | } |
| 16863 | |
| 16864 | /// What the directional modes are for: a picture that runs along a diagonal |
| 16865 | /// costs far less to code with them than the seven that read only their own |
| 16866 | /// edges can manage, and a picture that runs no particular way costs no |
| 16867 | /// more. The second half is the one that bites: a mode set the search |
| 16868 | /// cannot price is a mode set that loses rate on content that does not want |
| 16869 | /// it, which is what costing the mode symbol is for. |
| 16870 | #[test] |
| 16871 | fn the_diagonals_beat_the_modes_that_read_no_further() { |
| 16872 | let _knobs = crate::speed::knob_read(); |
| 16873 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16874 | for (name, picture, want) in [ |
| 16875 | ("down-right", diagonal(160, 96, true), -0.20), |
| 16876 | ("down-left", diagonal(160, 96, false), -0.20), |
| 16877 | ("test card", test_card(160, 96), 0.01), |
| 16878 | ] { |
| 16879 | let saved = bd_rate( |
| 16880 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 16881 | &ladder(&picture, &KEY_FRAME_MODES, fctx), |
| 16882 | ); |
| 16883 | assert!( |
| 16884 | saved < want, |
| 16885 | "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", |
| 16886 | saved * 100.0, |
| 16887 | -want * 100.0 |
| 16888 | ); |
| 16889 | } |
| 16890 | } |
| 16891 | |
| 16892 | /// A mode the encoder cannot predict must be refused rather than coded as |
| 16893 | /// something else, and a search with nothing to choose from likewise. |
| 16894 | #[test] |
| 16895 | fn a_mode_the_encoder_cannot_predict_is_refused() { |
| 16896 | let _knobs = crate::speed::knob_read(); |
| 16897 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16898 | let picture = test_card(64, 64); |
| 16899 | let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) |
| 16900 | .unwrap_err() |
| 16901 | .to_string(); |
| 16902 | assert!( |
| 16903 | message.contains("intra mode 13"), |
| 16904 | "the refusal must name the mode, got {message}" |
| 16905 | ); |
| 16906 | assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); |
| 16907 | } |
| 16908 | |
| 16909 | /// The picture that comes back is the picture that went in, to within the |
| 16910 | /// quantizer. A prediction that read the wrong neighbours, or a block |
| 16911 | /// written into the wrong place, would still decode to what the encoder |
| 16912 | /// reconstructed — it is this gate that says the reconstruction is of the |
| 16913 | /// right picture. |
| 16914 | #[test] |
| 16915 | fn the_encoded_picture_is_the_one_that_went_in() { |
| 16916 | let _knobs = crate::speed::knob_read(); |
| 16917 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16918 | let picture = test_card(160, 96); |
| 16919 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 16920 | let luma = psnr(&encoded.reconstruction.y, &picture.y); |
| 16921 | assert!(luma > 36.0, "luma PSNR {luma} at q 100"); |
| 16922 | for (plane, (got, want)) in [ |
| 16923 | (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), |
| 16924 | (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), |
| 16925 | ] |
| 16926 | .iter() |
| 16927 | .enumerate() |
| 16928 | { |
| 16929 | let chroma = psnr(got, want); |
| 16930 | assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); |
| 16931 | } |
| 16932 | } |
| 16933 | |
| 16934 | /// A finer quantizer costs bits and buys fidelity, and a wider deadzone |
| 16935 | /// does the opposite. Both are monotone, which is what a rate-distortion |
| 16936 | /// loop above this will assume. |
| 16937 | #[test] |
| 16938 | fn fidelity_and_rate_move_with_the_quantizer() { |
| 16939 | let _knobs = crate::speed::knob_read(); |
| 16940 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 16941 | let picture = test_card(128, 128); |
| 16942 | let mut previous: Option<(usize, f64)> = None; |
| 16943 | for &q in &[70u8, 90, 110] { |
| 16944 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 16945 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 16946 | if let Some((bytes, better)) = previous { |
| 16947 | assert!( |
| 16948 | encoded.stream.len() < bytes, |
| 16949 | "q {q}: {} bytes", |
| 16950 | encoded.stream.len() |
| 16951 | ); |
| 16952 | assert!(quality < better, "q {q}: PSNR {quality}"); |
| 16953 | } |
| 16954 | previous = Some((encoded.stream.len(), quality)); |
| 16955 | } |
| 16956 | |
| 16957 | // The deadzone half of this claim lives in |
| 16958 | // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now: |
| 16959 | // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding |
| 16960 | // every zeroing, the deadzone no longer moves a coded stream |
| 16961 | // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against |
| 16962 | // fewer at 0.5 on this 128x128 card), and that is the pass doing its |
| 16963 | // job, not a quantiser defect. |
| 16964 | |
| 16965 | // Bytes must not jump up across a q-context boundary: a wrong CDF |
| 16966 | // table for the far side would show up as a rate discontinuity here, |
| 16967 | // even though a coarser quantizer always codes no more than a finer |
| 16968 | // one on the same picture. |
| 16969 | // |
| 16970 | // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since |
| 16971 | // chroma searches its own mode, a coarser quantizer can pick a |
| 16972 | // *different* uv_mode on a block whose modes now cost nearly the |
| 16973 | // same, and the search prices that symbol against the static default |
| 16974 | // CDF while the writer codes it against an adapted one -- 311 -> 319 |
| 16975 | // bytes at q 120->121 on this picture. The table this gate is really |
| 16976 | // watching would move the rate by far more than the mode churn does. |
| 16977 | // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the |
| 16978 | // same block can also change transform DEPTH between two neighbouring |
| 16979 | // quantizers (297 -> 315 bytes at q 120->121 here), and the depth |
| 16980 | // symbol is priced off the static CDF row 0 for the same reason the |
| 16981 | // uv_mode one is. |
| 16982 | // Ceiling: a q-context table wrong by under 10% would pass. Upgrade |
| 16983 | // path is pricing through the adapting CDF state (what |
| 16984 | // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the |
| 16985 | // drift of), after which the exact bound comes back. |
| 16986 | for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { |
| 16987 | let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len(); |
| 16988 | let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len(); |
| 16989 | assert!( |
| 16990 | hi_bytes as f64 <= lo_bytes as f64 * 1.10, |
| 16991 | "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" |
| 16992 | ); |
| 16993 | } |
| 16994 | } |
| 16995 | |
| 16996 | /// A flat picture is a flat stream: every block predicts its neighbours' |
| 16997 | /// average, which is the picture's own value, and codes nothing. |
| 16998 | #[test] |
| 16999 | fn a_flat_picture_costs_almost_nothing() { |
| 17000 | let _knobs = crate::speed::knob_read(); |
| 17001 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 17002 | let mut picture = Picture::grey(128, 128); |
| 17003 | picture.y.fill(97); |
| 17004 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 17005 | // The first block has no neighbour and predicts 128, so it carries a |
| 17006 | // DC; every block after it predicts 97 and carries nothing. |
| 17007 | assert!( |
| 17008 | encoded.stream.len() < 100, |
| 17009 | "{} bytes for a flat picture", |
| 17010 | encoded.stream.len() |
| 17011 | ); |
| 17012 | for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { |
| 17013 | assert_eq!(s, 97, "sample {i} of a flat picture"); |
| 17014 | } |
| 17015 | } |
| 17016 | |
| 17017 | /// The sizes the encoder refuses, refused for a reason rather than by |
| 17018 | /// panicking somewhere below. Sizes off the 32x32 block grid encode fine |
| 17019 | /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge |
| 17020 | /// lands past the halfway point of whichever block it falls in, so |
| 17021 | /// `PARTITION_NONE` or a single gathered split flag still says everything |
| 17022 | /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16 |
| 17023 | /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the |
| 17024 | /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4 |
| 17025 | /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred, |
| 17026 | /// down to the in-frame 8x8s, no rectangular transform anywhere (the old |
| 17027 | /// refusal here claimed otherwise and was wrong; see |
| 17028 | /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_ |
| 17029 | /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never |
| 17030 | /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec |
| 17031 | /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the |
| 17032 | /// true edge always lands on an 8-luma-sample boundary in mi terms and a |
| 17033 | /// 4x4 leaf -- which neither writer has -- is never asked for. What is |
| 17034 | /// still refused is a malformed picture. |
| 17035 | #[test] |
| 17036 | fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() { |
| 17037 | let _knobs = crate::speed::knob_read(); |
| 17038 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 17039 | encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) |
| 17040 | .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split"); |
| 17041 | encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx) |
| 17042 | .expect("36 luma columns still round up to an even MiCols"); |
| 17043 | |
| 17044 | let mut short = Picture::grey(64, 64); |
| 17045 | short.u.truncate(10); |
| 17046 | assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); |
| 17047 | } |
| 17048 | |
| 17049 | /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own |
| 17050 | /// column half only (`has_half` false on cols, true on rows) -- exactly |
| 17051 | /// the single-axis straddle lane-av1-rect r7 wires through |
| 17052 | /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean: |
| 17053 | /// dav1d rejects the stream ("Invalid data found"). r7's falsification |
| 17054 | /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is |
| 17055 | /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own |
| 17056 | /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every |
| 17057 | /// `partition_context_lookup` entry this writer ever produces (no 4x4 |
| 17058 | /// splits exist) has bit 0 clear, so the ctx is provably 0 for every |
| 17059 | /// leaf regardless of neighbour state -- our writer already agreed with |
| 17060 | /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise |
| 17061 | /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a |
| 17062 | /// spec-accurate fix in its own right (it matters once 4x4 exists), and |
| 17063 | /// it does not regress the gate. r11 tell-for-tell traced two further, |
| 17064 | /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read |
| 17065 | /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both |
| 17066 | /// leaves, when the second leaf's true above (or left) neighbour is the |
| 17067 | /// first leaf itself -- fixed by threading the first leaf's mode into the |
| 17068 | /// second leaf's context, mi-precise, like `record_mi` already does for |
| 17069 | /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was |
| 17070 | /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when |
| 17071 | /// `reduced_tx_set` is false), but this crate's key frames set |
| 17072 | /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts |
| 17073 | /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2` |
| 17074 | /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE` |
| 17075 | /// symbol bits to desync everything after it. Fixed with a new |
| 17076 | /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact |
| 17077 | /// eset/size slot). Both fixes are provably correct against libaom |
| 17078 | /// source and each closed part of the gap (leaf0's `eob` went from a |
| 17079 | /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual |
| 17080 | /// divergence remained in the `EOB_PT` symbol's decoded value despite an |
| 17081 | /// aligned bit cost. r12 traced that residual with a fresh dual-trace |
| 17082 | /// (do not reuse r11's committed logs, which predate its own fixes) and |
| 17083 | /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded |
| 17084 | /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but |
| 17085 | /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` -- |
| 17086 | /// every other `write_block` caller at 16x16 and up already passes |
| 17087 | /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of |
| 17088 | /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a |
| 17089 | /// different amount of arithmetic range and derailed everything after |
| 17090 | /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an |
| 17091 | /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and |
| 17092 | /// `write_leaf8` called only `record_mi` (the coefficient-context half), |
| 17093 | /// never updating those coarse arrays itself -- so a *second* straddling |
| 17094 | /// 16x16 quadrant stacked above or left of the first (never covered by |
| 17095 | /// r11's same-call `prev_leaf` override, which only threads state |
| 17096 | /// between the two leaves of one shared quadrant) read whatever stale |
| 17097 | /// mode sat in that slot before either leaf ran. Fixed by writing the |
| 17098 | /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing |
| 17099 | /// (3) alone shrank the tell drift after leaf(0,8) from a decoder |
| 17100 | /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell` |
| 17101 | /// offset of a single unit; fixing (3)+(4) together still leaves a |
| 17102 | /// residual divergence one leaf further in -- the decoder now reads |
| 17103 | /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample |
| 17104 | /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning |
| 17105 | /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still |
| 17106 | /// desyncs the stream by exactly the width of one earlier symbol -- not |
| 17107 | /// yet isolated to a single named symbol. r15 found the last bug: the |
| 17108 | /// header fix from r14 explained the rng skew fully, and the remaining |
| 17109 | /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself -- |
| 17110 | /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf |
| 17111 | /// loop, once per leaf, so the first leaf's write clobbered the true |
| 17112 | /// external neighbour mode the second leaf of the *same* straddling |
| 17113 | /// quadrant still needed for its non-adjacency axis (a column-straddle |
| 17114 | /// case: two leaves share one `outer_at` column index, so leaf 1's |
| 17115 | /// write to `left_mode[r]` overwrote the real western neighbour before |
| 17116 | /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and |
| 17117 | /// doing it once, after the whole leaf loop, from the last (bottom/ |
| 17118 | /// right-most) leaf's mode. The stream now round-trips through ffmpeg. |
| 17119 | #[test] |
| 17120 | fn a_single_axis_straddle_round_trips_through_ffmpeg() { |
| 17121 | let _knobs = crate::speed::knob_read(); |
| 17122 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 17123 | if !have_ffmpeg() { |
| 17124 | eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg"); |
| 17125 | return; |
| 17126 | } |
| 17127 | let (width, height) = (40usize, 32usize); |
| 17128 | let picture = test_card(width, height); |
| 17129 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 17130 | assert_eq!( |
| 17131 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 17132 | (width, height) |
| 17133 | ); |
| 17134 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 17135 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 17136 | } |
| 17137 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 17138 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 17139 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 17140 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 17141 | } |
| 17142 | |
| 17143 | /// A frame of real video, rather than a picture built to be easy. |
| 17144 | /// |
| 17145 | /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to |
| 17146 | /// seek; ffmpeg decodes one frame, crops it to the block grid, and the |
| 17147 | /// encoder's reconstruction has to survive the same equality gate as the |
| 17148 | /// synthetic pictures — real video reaches contexts a test card does not. |
| 17149 | #[test] |
| 17150 | fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() { |
| 17151 | let _knobs = crate::speed::knob_read(); |
| 17152 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 17153 | let Ok(clip) = std::env::var("EC_AV1_CLIP") else { |
| 17154 | eprintln!( |
| 17155 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \ |
| 17156 | set EC_AV1_CLIP to a clip" |
| 17157 | ); |
| 17158 | return; |
| 17159 | }; |
| 17160 | if !have_ffmpeg() { |
| 17161 | eprintln!( |
| 17162 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 17163 | ); |
| 17164 | return; |
| 17165 | } |
| 17166 | let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into()); |
| 17167 | // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the |
| 17168 | // test quick while still spanning many superblocks. |
| 17169 | let (width, height) = (640usize, 352usize); |
| 17170 | let picture = clip_frame(&clip, &skip, width, height); |
| 17171 | |
| 17172 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 17173 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 17174 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 17175 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 17176 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 17177 | eprintln!( |
| 17178 | "{} bytes, luma PSNR {:.2} dB", |
| 17179 | encoded.stream.len(), |
| 17180 | psnr(&decoded.y, &picture.y) |
| 17181 | ); |
| 17182 | } |
| 17183 | |
| 17184 | /// [`test_card`], panned `shift` samples to the right (wrapping), so a |
| 17185 | /// sequence of these is a translation a motion search can actually find |
| 17186 | /// — the content [`test_card`] itself draws, not a fresh pattern, so an |
| 17187 | /// inter frame's rate against the key frame's is measuring the same |
| 17188 | /// picture moving, not two different pictures. |
| 17189 | fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { |
| 17190 | let mut picture = Picture::grey(width, height); |
| 17191 | for y in 0..height { |
| 17192 | for x in 0..width { |
| 17193 | let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; |
| 17194 | let gradient = sx * 200.0 / width as f64; |
| 17195 | let ripple = 30.0 |
| 17196 | * (sx * std::f64::consts::PI / 23.0).sin() |
| 17197 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 17198 | let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { |
| 17199 | 40.0 |
| 17200 | } else { |
| 17201 | 0.0 |
| 17202 | }; |
| 17203 | picture.y[y * width + x] = |
| 17204 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 17205 | } |
| 17206 | } |
| 17207 | for y in 0..height / 2 { |
| 17208 | for x in 0..width / 2 { |
| 17209 | let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; |
| 17210 | let i = y * width / 2 + x; |
| 17211 | picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; |
| 17212 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 17213 | } |
| 17214 | } |
| 17215 | picture |
| 17216 | } |
| 17217 | |
| 17218 | /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream. |
| 17219 | fn ffmpeg_decode_sequence( |
| 17220 | stream: &[u8], |
| 17221 | width: usize, |
| 17222 | height: usize, |
| 17223 | frames: usize, |
| 17224 | ) -> Vec<Picture> { |
| 17225 | let out = run_with_stdin( |
| 17226 | Command::new("ffmpeg").args([ |
| 17227 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 17228 | ]), |
| 17229 | stream, |
| 17230 | ); |
| 17231 | assert!( |
| 17232 | out.status.success(), |
| 17233 | "ffmpeg refused the stream: {}", |
| 17234 | String::from_utf8_lossy(&out.stderr) |
| 17235 | ); |
| 17236 | let (luma, chroma) = (width * height, width * height / 4); |
| 17237 | let frame_bytes = luma + 2 * chroma; |
| 17238 | assert_eq!( |
| 17239 | out.stdout.len(), |
| 17240 | frame_bytes * frames, |
| 17241 | "expected {frames} 4:2:0 frames, ffmpeg said: {}", |
| 17242 | String::from_utf8_lossy(&out.stderr) |
| 17243 | ); |
| 17244 | (0..frames) |
| 17245 | .map(|i| { |
| 17246 | let base = i * frame_bytes; |
| 17247 | Picture { |
| 17248 | width, |
| 17249 | height, |
| 17250 | y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), |
| 17251 | u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 17252 | v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), |
| 17253 | } |
| 17254 | }) |
| 17255 | .collect() |
| 17256 | } |
| 17257 | |
| 17258 | /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`] |
| 17259 | /// makes for a key frame, extended down the reference chain: each inter |
| 17260 | /// frame's reconstruction predicts from the previous frame's own decoded |
| 17261 | /// reconstruction, so a single sample of drift anywhere would propagate |
| 17262 | /// into every frame after it -- which is why every frame is checked, not |
| 17263 | /// just the last one, and why this is an equality and not a tolerance. |
| 17264 | #[test] |
| 17265 | fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { |
| 17266 | let _knobs = crate::speed::knob_read(); |
| 17267 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 17268 | if !have_ffmpeg() { |
| 17269 | eprintln!( |
| 17270 | "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 17271 | ); |
| 17272 | return; |
| 17273 | } |
| 17274 | let (width, height) = (128usize, 64usize); |
| 17275 | let pictures: Vec<Picture> = (0..5) |
| 17276 | .map(|i| panned_test_card(width, height, i * 3)) |
| 17277 | .collect(); |
| 17278 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 17279 | assert_eq!(encoded.frames.len(), 5); |
| 17280 | |
| 17281 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); |
| 17282 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17283 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); |
| 17284 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); |
| 17285 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); |
| 17286 | } |
| 17287 | |
| 17288 | eprintln!("frame bytes luma PSNR (dB) inter share"); |
| 17289 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 17290 | eprintln!( |
| 17291 | "{i:5} {:5} {:14.2} {:11.2}", |
| 17292 | frame.stream.len(), |
| 17293 | psnr(&frame.reconstruction.y, &pictures[i].y), |
| 17294 | frame.inter_block_share |
| 17295 | ); |
| 17296 | } |
| 17297 | } |
| 17298 | |
| 17299 | /// The same sequence through OUR OWN decoder, sample-exact against the |
| 17300 | /// encoder's reconstruction. ffmpeg stays the bitstream oracle |
| 17301 | /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no |
| 17302 | /// divergence point at all, while our decoder can be traced symbol by |
| 17303 | /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is |
| 17304 | /// the instrument the inter `TxMode::Select` hunt lacked; on failure it |
| 17305 | /// names the first differing frame, plane and position. |
| 17306 | /// lane-sb128b: the writer used to price a `NEWMV` residual against |
| 17307 | /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the |
| 17308 | /// write-time stack could not carry, while the drl symbols signalled the |
| 17309 | /// clamped index -- so the decoder derived a DIFFERENT motion vector with |
| 17310 | /// the entropy stream still in sync, and the drift only surfaced frames |
| 17311 | /// later as a drl desync (on film B, as the encoder's own trial decode |
| 17312 | /// refusing a reference slot). |
| 17313 | /// |
| 17314 | /// The clamp needs a stack that shrinks between search and write, which |
| 17315 | /// is what a 128x128 superblock's visit order does; the counter is the |
| 17316 | /// point (class `gate-blind-to-feature`): a green round trip on a clip |
| 17317 | /// that never clamps proves nothing. |
| 17318 | /// |
| 17319 | /// `#[ignore]`: [`force_sb128`] moves a process-global. |
| 17320 | /// |
| 17321 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17322 | /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture |
| 17323 | /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode |
| 17324 | /// and one motion vector where the four 64x64 roots below spend four of |
| 17325 | /// each (cen3's L1). The counter is the gate on the fixture (class |
| 17326 | /// `gate-blind-to-feature`): a green round trip on a clip that never |
| 17327 | /// codes a 128x128 block proves nothing. RED before the search existed |
| 17328 | /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every |
| 17329 | /// root by construction). |
| 17330 | /// |
| 17331 | /// Both readers: our own decoder sample-exact against the encoder's |
| 17332 | /// reconstruction (a writer/reader desync surfaces as a pixel miss or a |
| 17333 | /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle. |
| 17334 | /// |
| 17335 | /// `#[ignore]`: [`force_sb128`] moves a process-global. |
| 17336 | /// |
| 17337 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17338 | /// a_128_superblock_clip_whose_root_search --nocapture |
| 17339 | #[test] |
| 17340 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17341 | fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() { |
| 17342 | let _knobs = crate::speed::knob_write(); |
| 17343 | if !have_ffmpeg() { |
| 17344 | eprintln!("SKIP: no ffmpeg"); |
| 17345 | return; |
| 17346 | } |
| 17347 | force_sb128(true); |
| 17348 | let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id())); |
| 17349 | std::fs::create_dir_all(&dir).unwrap(); |
| 17350 | let clip = dir.join("smpte-1280x768.y4m"); |
| 17351 | // A slow horizontal pan over a still pattern: whole 128x128 regions |
| 17352 | // share one motion vector, which is exactly what a 128 root can code |
| 17353 | // as one block and four 64 roots cannot. |
| 17354 | let ok = Command::new("ffmpeg") |
| 17355 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17356 | .args(["-i", "smptebars=size=1600x768:rate=24"]) |
| 17357 | .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) |
| 17358 | .args(["-pix_fmt", "yuv420p"]) |
| 17359 | .arg(&clip) |
| 17360 | .status() |
| 17361 | .expect("ffmpeg failed to run") |
| 17362 | .success(); |
| 17363 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17364 | let (width, height) = (1280usize, 768usize); |
| 17365 | let pictures = |
| 17366 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); |
| 17367 | let _ = take_b128_none_hits(); |
| 17368 | let _ = crate::tile::take_sb128_none_hits(); |
| 17369 | let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); |
| 17370 | let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits()); |
| 17371 | eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}"); |
| 17372 | assert!( |
| 17373 | coded > 0, |
| 17374 | "no 128x128 block was coded on this clip, so it cannot witness the root search", |
| 17375 | ); |
| 17376 | assert_eq!(won, coded, "every 128x128 root the search took must be coded as one"); |
| 17377 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17378 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17379 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17380 | let recon = &frame.reconstruction; |
| 17381 | for (plane, got, want) in [ |
| 17382 | ("luma", &dec.y, &recon.y), |
| 17383 | ("U", &dec.u, &recon.u), |
| 17384 | ("V", &dec.v, &recon.v), |
| 17385 | ] { |
| 17386 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17387 | assert_eq!( |
| 17388 | differ, 0, |
| 17389 | "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ |
| 17390 | own reconstruction", |
| 17391 | got.len() |
| 17392 | ); |
| 17393 | } |
| 17394 | } |
| 17395 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17396 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17397 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17398 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17399 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17400 | } |
| 17401 | } |
| 17402 | |
| 17403 | /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma |
| 17404 | /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The |
| 17405 | /// same pan the skip-only witness above uses, with the arm FORCED |
| 17406 | /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual |
| 17407 | /// about once per frame, which witnesses the shape but not every context |
| 17408 | /// it reads, and forcing codes all 420 roots of the clip through it. RED |
| 17409 | /// before this lane by construction (`write_inter_block_128` refused |
| 17410 | /// every non-skip 128 block, so no such block existed to decode), and RED |
| 17411 | /// again on the first draft of the writer, whose neighbour band recorded |
| 17412 | /// `skip = true` for a block that carries a residual -- the next root's |
| 17413 | /// `skip` symbol then took CDF row 1 where the reader takes row 0. |
| 17414 | /// |
| 17415 | /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces |
| 17416 | /// the skip arm's cost unconditionally (that is what makes the writer see |
| 17417 | /// the residual), and the cost model moved under it since lane-b128r -- |
| 17418 | /// lane-rectdq made every non-skipped root pay its delta_q group and the |
| 17419 | /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root |
| 17420 | /// lost its partition at ALL 420 roots and the writer coded none. q=60 |
| 17421 | /// puts 52 written blocks back on this clip; the `coded > 0` assert below |
| 17422 | /// is the guard that catches the next such drift. |
| 17423 | /// |
| 17424 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17425 | /// a_128_root_block_with_a_real_residual --nocapture |
| 17426 | #[test] |
| 17427 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17428 | fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() { |
| 17429 | let _knobs = crate::speed::knob_write(); |
| 17430 | if !have_ffmpeg() { |
| 17431 | eprintln!("SKIP: no ffmpeg"); |
| 17432 | return; |
| 17433 | } |
| 17434 | force_sb128(true); |
| 17435 | let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id())); |
| 17436 | std::fs::create_dir_all(&dir).unwrap(); |
| 17437 | let clip = dir.join("smpte-pan-1280x768.y4m"); |
| 17438 | let ok = Command::new("ffmpeg") |
| 17439 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17440 | .args(["-i", "smptebars=size=1600x768:rate=24"]) |
| 17441 | .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) |
| 17442 | .args(["-pix_fmt", "yuv420p"]) |
| 17443 | .arg(&clip) |
| 17444 | .status() |
| 17445 | .expect("ffmpeg failed to run") |
| 17446 | .success(); |
| 17447 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17448 | let (width, height) = (1280usize, 768usize); |
| 17449 | let pictures = |
| 17450 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); |
| 17451 | let _ = take_b128_residual_hits(); |
| 17452 | let _ = crate::tile::take_sb128_residual_hits(); |
| 17453 | force_b128_residual(true); |
| 17454 | let encoded = encode_sequence(&pictures, 60, 0.5).unwrap(); |
| 17455 | let (won, coded) = |
| 17456 | (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits()); |
| 17457 | eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}"); |
| 17458 | assert!( |
| 17459 | coded > 0, |
| 17460 | "no 128x128 block carried a residual on this clip, so it cannot witness the arm", |
| 17461 | ); |
| 17462 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17463 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17464 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17465 | let recon = &frame.reconstruction; |
| 17466 | for (plane, got, want) in [ |
| 17467 | ("luma", &dec.y, &recon.y), |
| 17468 | ("U", &dec.u, &recon.u), |
| 17469 | ("V", &dec.v, &recon.v), |
| 17470 | ] { |
| 17471 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17472 | assert_eq!( |
| 17473 | differ, 0, |
| 17474 | "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ |
| 17475 | own reconstruction", |
| 17476 | got.len() |
| 17477 | ); |
| 17478 | } |
| 17479 | } |
| 17480 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17481 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17482 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17483 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17484 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17485 | } |
| 17486 | } |
| 17487 | |
| 17488 | /// lane-edge128: a 128x128 root block WITH a residual on a clip whose |
| 17489 | /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec |
| 17490 | /// 5.11.56) codes ONE literal for the block that first reaches a unit and |
| 17491 | /// copies it over every unit the block SPANS, so the four units of a 128 |
| 17492 | /// root share one index -- while the encoder's CDEF search prices a |
| 17493 | /// preset per unit and its filter replay applied all four. Only the first |
| 17494 | /// reached the stream, so every decoder filtered the other three with the |
| 17495 | /// origin's strengths and the encoder's reconstruction (the picture the |
| 17496 | /// next frame predicts from) was a filter apart from what a decoder |
| 17497 | /// produces. RED before this lane on the native BD gate's bars 2160p row |
| 17498 | /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples, |
| 17499 | /// the rows above the 128 superblock's own edge); the stream itself was |
| 17500 | /// always right -- ffmpeg and our own decoder agreed with each other and |
| 17501 | /// disagreed with the encoder. |
| 17502 | /// |
| 17503 | /// `take_cdef_covered_units` is the gate on the fixture (class |
| 17504 | /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair |
| 17505 | /// for the whole frame codes no literal at all and witnesses nothing. |
| 17506 | /// |
| 17507 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17508 | /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture |
| 17509 | #[test] |
| 17510 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17511 | fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() { |
| 17512 | let _knobs = crate::speed::knob_write(); |
| 17513 | if !have_ffmpeg() { |
| 17514 | eprintln!("SKIP: no ffmpeg"); |
| 17515 | return; |
| 17516 | } |
| 17517 | force_sb128(true); |
| 17518 | let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id())); |
| 17519 | std::fs::create_dir_all(&dir).unwrap(); |
| 17520 | let clip = dir.join("testsrc2-1280x768.y4m"); |
| 17521 | // Detailed synthetic content: its CDEF search spends more than one |
| 17522 | // strength pair, which is what puts a `cdef_idx` literal in the tile. |
| 17523 | let ok = Command::new("ffmpeg") |
| 17524 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17525 | .args(["-i", "testsrc2=size=1280x768:rate=24"]) |
| 17526 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 17527 | .arg(&clip) |
| 17528 | .status() |
| 17529 | .expect("ffmpeg failed to run") |
| 17530 | .success(); |
| 17531 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17532 | let (width, height) = (1280usize, 768usize); |
| 17533 | let pictures = |
| 17534 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); |
| 17535 | force_b128_root(true); |
| 17536 | force_b128_residual(true); |
| 17537 | let _ = crate::tile::take_sb128_residual_hits(); |
| 17538 | let _ = crate::filter_search::take_cdef_covered_units(); |
| 17539 | let encoded = encode_sequence(&pictures, 90, 0.5).unwrap(); |
| 17540 | let coded = crate::tile::take_sb128_residual_hits(); |
| 17541 | let covered = crate::filter_search::take_cdef_covered_units(); |
| 17542 | eprintln!( |
| 17543 | "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \ |
| 17544 | another unit's literal: {covered}" |
| 17545 | ); |
| 17546 | assert!(coded > 0, "no 128x128 block carried a residual on this clip"); |
| 17547 | assert!( |
| 17548 | covered > 0, |
| 17549 | "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \ |
| 17550 | cannot witness the rule", |
| 17551 | ); |
| 17552 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17553 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17554 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17555 | for (plane, got, want) in [ |
| 17556 | ("luma", &dec.y, &frame.reconstruction.y), |
| 17557 | ("U", &dec.u, &frame.reconstruction.u), |
| 17558 | ("V", &dec.v, &frame.reconstruction.v), |
| 17559 | ] { |
| 17560 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17561 | assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); |
| 17562 | } |
| 17563 | } |
| 17564 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17565 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17566 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17567 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17568 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17569 | } |
| 17570 | } |
| 17571 | |
| 17572 | /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves |
| 17573 | /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a |
| 17574 | /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now |
| 17575 | /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own |
| 17576 | /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the |
| 17577 | /// rect partition with [`force_b128_rect`]) so every inter root of the |
| 17578 | /// clip goes through it; the `coded > 0` assert is the guard that catches |
| 17579 | /// the next fixture drift (the whole-128 twin of this witness went RED |
| 17580 | /// twice that way). |
| 17581 | /// |
| 17582 | /// cargo test -p ec-av1 --release --lib -- --ignored --exact \ |
| 17583 | /// encode::tests::a_rect128_half_with_a_real_residual --nocapture |
| 17584 | #[test] |
| 17585 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17586 | fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() { |
| 17587 | let _knobs = crate::speed::knob_write(); |
| 17588 | if !have_ffmpeg() { |
| 17589 | eprintln!("SKIP: no ffmpeg"); |
| 17590 | return; |
| 17591 | } |
| 17592 | force_sb128(true); |
| 17593 | let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id())); |
| 17594 | std::fs::create_dir_all(&dir).unwrap(); |
| 17595 | let clip = dir.join("smpte-pan-1280x768.y4m"); |
| 17596 | let ok = Command::new("ffmpeg") |
| 17597 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17598 | .args(["-i", "smptebars=size=1600x768:rate=24"]) |
| 17599 | .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) |
| 17600 | .args(["-pix_fmt", "yuv420p"]) |
| 17601 | .arg(&clip) |
| 17602 | .status() |
| 17603 | .expect("ffmpeg failed to run") |
| 17604 | .success(); |
| 17605 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17606 | let (width, height) = (1280usize, 768usize); |
| 17607 | let pictures = |
| 17608 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); |
| 17609 | force_b128_rect(1); |
| 17610 | force_b128_rectres(true); |
| 17611 | let _ = take_b128_rectres_hits(); |
| 17612 | let _ = crate::tile::take_sb128_rectres_hits(); |
| 17613 | let encoded = encode_sequence(&pictures, 60, 0.5).unwrap(); |
| 17614 | let (won, coded) = |
| 17615 | (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits()); |
| 17616 | eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}"); |
| 17617 | assert!( |
| 17618 | coded > 0, |
| 17619 | "no 128x64 half carried a residual on this clip, so it cannot witness the arm", |
| 17620 | ); |
| 17621 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17622 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17623 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17624 | let recon = &frame.reconstruction; |
| 17625 | for (plane, got, want) in [ |
| 17626 | ("luma", &dec.y, &recon.y), |
| 17627 | ("U", &dec.u, &recon.u), |
| 17628 | ("V", &dec.v, &recon.v), |
| 17629 | ] { |
| 17630 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17631 | assert_eq!( |
| 17632 | differ, 0, |
| 17633 | "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ |
| 17634 | own reconstruction", |
| 17635 | got.len() |
| 17636 | ); |
| 17637 | } |
| 17638 | } |
| 17639 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17640 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17641 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17642 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17643 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17644 | } |
| 17645 | } |
| 17646 | |
| 17647 | /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE |
| 17648 | /// pieces carry residuals -- the 128x64 half through the two-chunk arm, |
| 17649 | /// the two 64x64 squares through the one-chunk arm (the shape libaom's |
| 17650 | /// own AB partitions earn their keep with). testsrc2 at 12 frames, the |
| 17651 | /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose |
| 17652 | /// reference picture the GOP has not produced yet, which refuses before |
| 17653 | /// any AB root is coded. |
| 17654 | /// |
| 17655 | /// cargo test -p ec-av1 --release --lib -- --ignored --exact \ |
| 17656 | /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture |
| 17657 | #[test] |
| 17658 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17659 | fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() { |
| 17660 | let _knobs = crate::speed::knob_write(); |
| 17661 | if !have_ffmpeg() { |
| 17662 | eprintln!("SKIP: no ffmpeg"); |
| 17663 | return; |
| 17664 | } |
| 17665 | force_sb128(true); |
| 17666 | let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id())); |
| 17667 | std::fs::create_dir_all(&dir).unwrap(); |
| 17668 | let clip = dir.join("testsrc2-1280x768.y4m"); |
| 17669 | let ok = Command::new("ffmpeg") |
| 17670 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17671 | .args(["-i", "testsrc2=size=1280x768:rate=24"]) |
| 17672 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 17673 | .arg(&clip) |
| 17674 | .status() |
| 17675 | .expect("ffmpeg failed to run") |
| 17676 | .success(); |
| 17677 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17678 | let (width, height) = (1280usize, 768usize); |
| 17679 | let pictures = |
| 17680 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); |
| 17681 | force_b128_ab(4); |
| 17682 | force_b128_rectres(true); |
| 17683 | let _ = take_b128_rectres_hits(); |
| 17684 | let _ = crate::tile::take_sb128_rectres_hits(); |
| 17685 | let encoded = encode_sequence(&pictures, 60, 0.5).unwrap(); |
| 17686 | let (won, coded) = |
| 17687 | (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits()); |
| 17688 | eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}"); |
| 17689 | assert!( |
| 17690 | coded > 0, |
| 17691 | "no AB piece carried a residual on this clip, so it cannot witness the arm", |
| 17692 | ); |
| 17693 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17694 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17695 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17696 | let recon = &frame.reconstruction; |
| 17697 | for (plane, got, want) in [ |
| 17698 | ("luma", &dec.y, &recon.y), |
| 17699 | ("U", &dec.u, &recon.u), |
| 17700 | ("V", &dec.v, &recon.v), |
| 17701 | ] { |
| 17702 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17703 | assert_eq!( |
| 17704 | differ, 0, |
| 17705 | "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ |
| 17706 | own reconstruction", |
| 17707 | got.len() |
| 17708 | ); |
| 17709 | } |
| 17710 | } |
| 17711 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17712 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17713 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17714 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17715 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17716 | } |
| 17717 | } |
| 17718 | |
| 17719 | /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ |
| 17720 | /// half WITH a residual under a clip whose CDEF search codes a |
| 17721 | /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin |
| 17722 | /// and the decoder stamps BOTH units it spans with it, so the owner map |
| 17723 | /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to |
| 17724 | /// collapse the pair -- exactly the bug class that broke bars 2160p at |
| 17725 | /// the whole-128 root. RED before this lane by construction: no rect |
| 17726 | /// piece could carry a residual, so no such literal existed. |
| 17727 | /// |
| 17728 | /// cargo test -p ec-av1 --release --lib -- --ignored --exact \ |
| 17729 | /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture |
| 17730 | #[test] |
| 17731 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17732 | fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() { |
| 17733 | let _knobs = crate::speed::knob_write(); |
| 17734 | if !have_ffmpeg() { |
| 17735 | eprintln!("SKIP: no ffmpeg"); |
| 17736 | return; |
| 17737 | } |
| 17738 | force_sb128(true); |
| 17739 | let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id())); |
| 17740 | std::fs::create_dir_all(&dir).unwrap(); |
| 17741 | let clip = dir.join("testsrc2-1280x768.y4m"); |
| 17742 | // Detailed synthetic content: its CDEF search spends more than one |
| 17743 | // strength pair, which is what puts a `cdef_idx` literal in the tile. |
| 17744 | let ok = Command::new("ffmpeg") |
| 17745 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17746 | .args(["-i", "testsrc2=size=1280x768:rate=24"]) |
| 17747 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 17748 | .arg(&clip) |
| 17749 | .status() |
| 17750 | .expect("ffmpeg failed to run") |
| 17751 | .success(); |
| 17752 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17753 | let (width, height) = (1280usize, 768usize); |
| 17754 | let pictures = |
| 17755 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); |
| 17756 | force_b128_rect(1); |
| 17757 | force_b128_rectres(true); |
| 17758 | let _ = crate::tile::take_sb128_rectres_hits(); |
| 17759 | let _ = crate::filter_search::take_cdef_covered_units(); |
| 17760 | let encoded = encode_sequence(&pictures, 90, 0.5).unwrap(); |
| 17761 | let coded = crate::tile::take_sb128_rectres_hits(); |
| 17762 | let covered = crate::filter_search::take_cdef_covered_units(); |
| 17763 | eprintln!( |
| 17764 | "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \ |
| 17765 | another unit's literal: {covered}" |
| 17766 | ); |
| 17767 | assert!(coded > 0, "no 128x64 half carried a residual on this clip"); |
| 17768 | assert!( |
| 17769 | covered > 0, |
| 17770 | "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \ |
| 17771 | cannot witness the rule", |
| 17772 | ); |
| 17773 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17774 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17775 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17776 | for (plane, got, want) in [ |
| 17777 | ("luma", &dec.y, &frame.reconstruction.y), |
| 17778 | ("U", &dec.u, &frame.reconstruction.u), |
| 17779 | ("V", &dec.v, &frame.reconstruction.v), |
| 17780 | ] { |
| 17781 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17782 | assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); |
| 17783 | } |
| 17784 | } |
| 17785 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17786 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17787 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17788 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17789 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17790 | } |
| 17791 | } |
| 17792 | |
| 17793 | /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block |
| 17794 | /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same |
| 17795 | /// `write_compound_block` chain every smaller compound block takes, at a |
| 17796 | /// window it had never been exercised at. RED before this lane: the |
| 17797 | /// search passed an empty compound list at the 128 root, so the count was |
| 17798 | /// 0 and no such block existed to decode. |
| 17799 | /// |
| 17800 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17801 | /// a_128_root_compound_block --nocapture |
| 17802 | #[test] |
| 17803 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17804 | fn a_128_root_compound_block_decodes_exact_through_both_decoders() { |
| 17805 | let _knobs = crate::speed::knob_write(); |
| 17806 | if !have_ffmpeg() { |
| 17807 | eprintln!("SKIP: no ffmpeg"); |
| 17808 | return; |
| 17809 | } |
| 17810 | force_sb128(true); |
| 17811 | let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id())); |
| 17812 | std::fs::create_dir_all(&dir).unwrap(); |
| 17813 | let clip = dir.join("testsrc2-1280x768.y4m"); |
| 17814 | // Moving objects that occlude each other: a pan is coded by one |
| 17815 | // reference outright, and a compound pair only pays where the two |
| 17816 | // references disagree. |
| 17817 | let ok = Command::new("ffmpeg") |
| 17818 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17819 | .args(["-i", "testsrc2=size=1280x768:rate=24"]) |
| 17820 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 17821 | .arg(&clip) |
| 17822 | .status() |
| 17823 | .expect("ffmpeg failed to run") |
| 17824 | .success(); |
| 17825 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17826 | let (width, height) = (1280usize, 768usize); |
| 17827 | let pictures = |
| 17828 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); |
| 17829 | // The compound candidate wins the 128 block's own search on this pan |
| 17830 | // but the root then loses to its four cells, so the root is forced |
| 17831 | // (the residual arm is left at its default, off). |
| 17832 | force_b128_root(true); |
| 17833 | let _ = take_b128_compound_hits(); |
| 17834 | let _ = crate::tile::take_sb128_compound_hits(); |
| 17835 | let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); |
| 17836 | let (won, coded) = |
| 17837 | (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits()); |
| 17838 | eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}"); |
| 17839 | assert!(coded > 0, "no compound 128x128 block was coded on this clip"); |
| 17840 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17841 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 17842 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17843 | for (plane, got, want) in [ |
| 17844 | ("luma", &dec.y, &frame.reconstruction.y), |
| 17845 | ("U", &dec.u, &frame.reconstruction.u), |
| 17846 | ("V", &dec.v, &frame.reconstruction.v), |
| 17847 | ] { |
| 17848 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17849 | assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); |
| 17850 | } |
| 17851 | } |
| 17852 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17853 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17854 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); |
| 17855 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); |
| 17856 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); |
| 17857 | } |
| 17858 | } |
| 17859 | |
| 17860 | /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT` |
| 17861 | /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one |
| 17862 | /// square. Three passes over one `testsrc2` clip: |
| 17863 | /// |
| 17864 | /// * HORZ forced at every root ([`force_b128_rect`]), so every context |
| 17865 | /// the 128x64 shape reads is exercised rather than the handful the RD |
| 17866 | /// would pick; |
| 17867 | /// * VERT forced the same way; |
| 17868 | /// * UNFORCED, which is the count the gate rows are read against -- the |
| 17869 | /// same clip with the RD free to choose among NONE / HORZ / VERT / |
| 17870 | /// four superblocks. |
| 17871 | /// |
| 17872 | /// Each pass is sample-exact against the encoder's own reconstruction |
| 17873 | /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch |
| 17874 | /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED |
| 17875 | /// before this lane by construction: `write_sb128_root` could only name |
| 17876 | /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three. |
| 17877 | /// |
| 17878 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17879 | /// a_128_root_horz_and_vert --nocapture |
| 17880 | #[test] |
| 17881 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17882 | fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() { |
| 17883 | let _knobs = crate::speed::knob_write(); |
| 17884 | if !have_ffmpeg() { |
| 17885 | eprintln!("SKIP: no ffmpeg"); |
| 17886 | return; |
| 17887 | } |
| 17888 | force_sb128(true); |
| 17889 | let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id())); |
| 17890 | std::fs::create_dir_all(&dir).unwrap(); |
| 17891 | let clip = dir.join("testsrc2-1280x768.y4m"); |
| 17892 | let ok = Command::new("ffmpeg") |
| 17893 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17894 | .args(["-i", "testsrc2=size=1280x768:rate=24"]) |
| 17895 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 17896 | .arg(&clip) |
| 17897 | .status() |
| 17898 | .expect("ffmpeg failed to run") |
| 17899 | .success(); |
| 17900 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17901 | let (width, height) = (1280usize, 768usize); |
| 17902 | let pictures = |
| 17903 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); |
| 17904 | let mut unforced = (0usize, 0usize); |
| 17905 | for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] { |
| 17906 | force_b128_rect(force); |
| 17907 | let _ = take_b128_horz_hits(); |
| 17908 | let _ = take_b128_vert_hits(); |
| 17909 | let _ = crate::tile::take_sb128_horz_hits(); |
| 17910 | let _ = crate::tile::take_sb128_vert_hits(); |
| 17911 | let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); |
| 17912 | let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits()); |
| 17913 | let (coded_h, coded_v) = ( |
| 17914 | crate::tile::take_sb128_horz_hits(), |
| 17915 | crate::tile::take_sb128_vert_hits(), |
| 17916 | ); |
| 17917 | eprintln!( |
| 17918 | "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \ |
| 17919 | {coded_h} 128x64 + {coded_v} 64x128 halves" |
| 17920 | ); |
| 17921 | match force { |
| 17922 | 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"), |
| 17923 | 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"), |
| 17924 | // The unforced count is REPORTED, not asserted: it is the |
| 17925 | // number the gate is read against, and a zero here would be |
| 17926 | // an RD result, not a defect (the forced passes already prove |
| 17927 | // the writer and the reader agree on the shape). |
| 17928 | _ => unforced = (won_h, won_v), |
| 17929 | } |
| 17930 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 17931 | assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count"); |
| 17932 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 17933 | for (plane, got, want) in [ |
| 17934 | ("luma", &dec.y, &frame.reconstruction.y), |
| 17935 | ("U", &dec.u, &frame.reconstruction.u), |
| 17936 | ("V", &dec.v, &frame.reconstruction.v), |
| 17937 | ] { |
| 17938 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 17939 | assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ"); |
| 17940 | } |
| 17941 | } |
| 17942 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 17943 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 17944 | assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma"); |
| 17945 | assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U"); |
| 17946 | assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V"); |
| 17947 | } |
| 17948 | } |
| 17949 | force_b128_rect(0); |
| 17950 | eprintln!( |
| 17951 | "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames", |
| 17952 | unforced.0, unforced.1 |
| 17953 | ); |
| 17954 | } |
| 17955 | |
| 17956 | /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two |
| 17957 | /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`. |
| 17958 | /// Five passes over the same `testsrc2` clip |
| 17959 | /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders` |
| 17960 | /// uses: each shape forced at every root ([`force_b128_ab`]), so every |
| 17961 | /// context and every visit order the shape reads is exercised rather than |
| 17962 | /// the handful the RD would pick, and then an UNFORCED pass whose |
| 17963 | /// per-shape count is REPORTED (it is the number the gate rows are read |
| 17964 | /// against). |
| 17965 | /// |
| 17966 | /// Each pass is sample-exact against the encoder's own reconstruction |
| 17967 | /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch |
| 17968 | /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED |
| 17969 | /// before this lane by construction: `write_sb128_root` could only name |
| 17970 | /// NONE / HORZ / VERT / SPLIT, so all four counts were 0. |
| 17971 | /// |
| 17972 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 17973 | /// a_128_root_ab_shapes --nocapture |
| 17974 | #[test] |
| 17975 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 17976 | fn a_128_root_ab_shapes_decode_exact_through_both_decoders() { |
| 17977 | let _knobs = crate::speed::knob_write(); |
| 17978 | if !have_ffmpeg() { |
| 17979 | eprintln!("SKIP: no ffmpeg"); |
| 17980 | return; |
| 17981 | } |
| 17982 | force_sb128(true); |
| 17983 | let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id())); |
| 17984 | std::fs::create_dir_all(&dir).unwrap(); |
| 17985 | let clip = dir.join("testsrc2-1280x768.y4m"); |
| 17986 | let ok = Command::new("ffmpeg") |
| 17987 | .args(["-v", "error", "-y", "-f", "lavfi"]) |
| 17988 | .args(["-i", "testsrc2=size=1280x768:rate=24"]) |
| 17989 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 17990 | .arg(&clip) |
| 17991 | .status() |
| 17992 | .expect("ffmpeg failed to run") |
| 17993 | .success(); |
| 17994 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 17995 | let (width, height) = (1280usize, 768usize); |
| 17996 | let pictures = |
| 17997 | crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); |
| 17998 | let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"]; |
| 17999 | let mut unforced = [0usize; 4]; |
| 18000 | for force in [4u8, 5, 6, 7, 0] { |
| 18001 | force_b128_ab(force); |
| 18002 | let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] }; |
| 18003 | let _ = take_b128_ab_hits(); |
| 18004 | let _ = crate::tile::take_sb128_ab_hits(); |
| 18005 | let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); |
| 18006 | let won = take_b128_ab_hits(); |
| 18007 | let coded = crate::tile::take_sb128_ab_hits(); |
| 18008 | eprintln!( |
| 18009 | "{label}: search won {won:?} AB roots, writer coded {coded:?} \ |
| 18010 | (HORZ_A/HORZ_B/VERT_A/VERT_B)" |
| 18011 | ); |
| 18012 | if force == 0 { |
| 18013 | // The unforced counts are REPORTED, not asserted: a zero here |
| 18014 | // would be an RD result, not a defect (the four forced passes |
| 18015 | // already prove the writer and the reader agree on the shape). |
| 18016 | unforced = won; |
| 18017 | } else { |
| 18018 | let i = usize::from(force) - 4; |
| 18019 | assert!(coded[i] > 0, "no {label} root was coded with {label} forced"); |
| 18020 | } |
| 18021 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 18022 | assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count"); |
| 18023 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 18024 | for (plane, got, want) in [ |
| 18025 | ("luma", &dec.y, &frame.reconstruction.y), |
| 18026 | ("U", &dec.u, &frame.reconstruction.u), |
| 18027 | ("V", &dec.v, &frame.reconstruction.v), |
| 18028 | ] { |
| 18029 | let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); |
| 18030 | assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ"); |
| 18031 | } |
| 18032 | } |
| 18033 | let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 18034 | for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { |
| 18035 | assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma"); |
| 18036 | assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U"); |
| 18037 | assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V"); |
| 18038 | } |
| 18039 | } |
| 18040 | force_b128_ab(0); |
| 18041 | eprintln!( |
| 18042 | "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B", |
| 18043 | unforced[0], unforced[1], unforced[2], unforced[3], |
| 18044 | ); |
| 18045 | } |
| 18046 | |
| 18047 | #[test] |
| 18048 | #[ignore = "sets the process-global superblock size: run it alone"] |
| 18049 | fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() { |
| 18050 | let _knobs = crate::speed::knob_write(); |
| 18051 | if !have_ffmpeg() { |
| 18052 | eprintln!("SKIP: no ffmpeg"); |
| 18053 | return; |
| 18054 | } |
| 18055 | force_sb128(true); |
| 18056 | let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id())); |
| 18057 | std::fs::create_dir_all(&dir).unwrap(); |
| 18058 | let clip = dir.join("mandelbrot-1280x768.y4m"); |
| 18059 | let ok = Command::new("ffmpeg") |
| 18060 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"]) |
| 18061 | .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) |
| 18062 | .arg(&clip) |
| 18063 | .status() |
| 18064 | .expect("ffmpeg failed to run") |
| 18065 | .success(); |
| 18066 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 18067 | let path = clip.to_str().unwrap(); |
| 18068 | let (width, height) = (1280usize, 768usize); |
| 18069 | let pictures = crate::probe::source(path, "0", "null", width, height, 12); |
| 18070 | |
| 18071 | let _ = crate::tile::take_drl_clamp_hits(); |
| 18072 | let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); |
| 18073 | let clamps = crate::tile::take_drl_clamp_hits(); |
| 18074 | assert!( |
| 18075 | clamps > 0, |
| 18076 | "this clip never asked for a drl index the write-time stack could not carry, \ |
| 18077 | so it cannot witness the defect" |
| 18078 | ); |
| 18079 | eprintln!("clamped drl indices: {clamps}"); |
| 18080 | |
| 18081 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 18082 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 18083 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 18084 | let recon = &frame.reconstruction; |
| 18085 | for (plane, got, want) in [ |
| 18086 | ("luma", &dec.y, &recon.y), |
| 18087 | ("U", &dec.u, &recon.u), |
| 18088 | ("V", &dec.v, &recon.v), |
| 18089 | ] { |
| 18090 | let differ = got.iter().zip(want).filter(|(a, b)| a != b).count(); |
| 18091 | assert_eq!( |
| 18092 | differ, 0, |
| 18093 | "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ |
| 18094 | own reconstruction", |
| 18095 | got.len() |
| 18096 | ); |
| 18097 | } |
| 18098 | } |
| 18099 | } |
| 18100 | |
| 18101 | #[test] |
| 18102 | fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { |
| 18103 | let _knobs = crate::speed::knob_read(); |
| 18104 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18105 | // 256x128, not the 128x64 this started at: once a leaf could search |
| 18106 | // its second reference (lane-av1comp4) the small card's every |
| 18107 | // eligible block went to a compound winner, which commits its flat |
| 18108 | // transform, and the split below stopped firing on content that |
| 18109 | // still splits at every larger size ([[gate-blind-to-feature]] -- |
| 18110 | // the guard is right, the fixture had shrunk under it). |
| 18111 | let (width, height) = (256usize, 128usize); |
| 18112 | let pictures: Vec<Picture> = |
| 18113 | (0..5).map(|i| panned_test_card(width, height, i * 3)).collect(); |
| 18114 | let _ = take_inter_tx_split_hits(); |
| 18115 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 18116 | let raw = take_inter_tx_split_hits(); |
| 18117 | // Summed over the four block classes the census keys on (leaf/32x32 x |
| 18118 | // single/compound): this assert is about the split firing at all. |
| 18119 | let split = [ |
| 18120 | raw.iter().step_by(2).sum::<usize>(), |
| 18121 | raw.iter().skip(1).step_by(2).sum::<usize>(), |
| 18122 | ]; |
| 18123 | eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); |
| 18124 | // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this |
| 18125 | // content splits -- a green round trip in which the split never fires |
| 18126 | // would prove only the flat path. |
| 18127 | if tx_select() && tx_select_inter() { |
| 18128 | assert!(split[1] > 0, "the inter var-tx split never fired"); |
| 18129 | } |
| 18130 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 18131 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 18132 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 18133 | let recon = &frame.reconstruction; |
| 18134 | for (plane, got, want, stride) in [ |
| 18135 | ("luma", &dec.y, &recon.y, width), |
| 18136 | ("U", &dec.u, &recon.u, width / 2), |
| 18137 | ("V", &dec.v, &recon.v, width / 2), |
| 18138 | ] { |
| 18139 | assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); |
| 18140 | if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { |
| 18141 | panic!( |
| 18142 | "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ |
| 18143 | reconstruction {} ({} of {} samples differ)", |
| 18144 | at % stride, |
| 18145 | at / stride, |
| 18146 | got[at], |
| 18147 | want[at], |
| 18148 | got.iter().zip(want).filter(|(a, b)| a != b).count(), |
| 18149 | got.len(), |
| 18150 | ); |
| 18151 | } |
| 18152 | } |
| 18153 | } |
| 18154 | } |
| 18155 | |
| 18156 | /// The rate term the mode search ranks every decision by has to be the |
| 18157 | /// rate the writer then spends. The search prices a block's coefficients |
| 18158 | /// through `tile::coeff_bits` -- the writer's own symbol chain, but |
| 18159 | /// against the default CDFs a tile starts from and the contexts of a |
| 18160 | /// block whose neighbours coded nothing -- while the tile writer codes |
| 18161 | /// them against a state that has been adapting all frame (the |
| 18162 | /// price-the-narrowing class). This measures that drift: the sum of what |
| 18163 | /// the search paid for the coefficients it kept, against the bytes the |
| 18164 | /// writer actually emitted for the whole tile (which also carries the |
| 18165 | /// partition/mode/skip/mv syntax the sum leaves out, so the writer is |
| 18166 | /// expected to be the larger of the two). |
| 18167 | #[test] |
| 18168 | fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { |
| 18169 | let _knobs = crate::speed::knob_read(); |
| 18170 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18171 | let (width, height) = (256usize, 128usize); |
| 18172 | let pictures: Vec<Picture> = (0..5) |
| 18173 | .map(|i| panned_test_card(width, height, i * 2)) |
| 18174 | .collect(); |
| 18175 | let _ = take_predicted_bits(); |
| 18176 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 18177 | let predicted = take_predicted_bits(); |
| 18178 | assert_eq!(predicted.len(), encoded.frames.len()); |
| 18179 | |
| 18180 | eprintln!("frame predicted bits written bits drift"); |
| 18181 | // Split by sign: a NEGATIVE drift is the search OVER-pricing (the |
| 18182 | // defect this gate exists to catch), a positive one is the written |
| 18183 | // side carrying syntax the coefficient sum leaves out -- and since |
| 18184 | // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual |
| 18185 | // on that side, so the two directions no longer share a bound. |
| 18186 | let mut worst_over: f64 = 0.0; |
| 18187 | let mut worst_under: f64 = 0.0; |
| 18188 | // The census is per CODED frame, so it is zipped in coding order -- |
| 18189 | // which is not display order under a pyramid. |
| 18190 | let coded: Vec<&Encoded> = |
| 18191 | encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect(); |
| 18192 | for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() { |
| 18193 | let written = frame.tile.len() as f64 * 8.0; |
| 18194 | let drift = (written - bits) / written; |
| 18195 | worst_over = worst_over.max(-drift); |
| 18196 | // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at |
| 18197 | // all (150-250 bits of tile, nearly all of it partition/mode/mv |
| 18198 | // syntax the coefficient sum never counts), so its ratio measures |
| 18199 | // that floor rather than any drift. Frames under 512 written bits |
| 18200 | // are left out of the under-price bound for that reason; the |
| 18201 | // over-price bound -- the defect direction, where the search pays |
| 18202 | // MORE than the writer -- still covers every frame. |
| 18203 | if written >= 512.0 { |
| 18204 | worst_under = worst_under.max(drift); |
| 18205 | } |
| 18206 | eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); |
| 18207 | } |
| 18208 | // Measured 2026-09-06 on this sequence: -13.5% at the key frame, |
| 18209 | // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search |
| 18210 | // over-prices every frame but the last (its sum EXCLUDES the |
| 18211 | // partition/mode/skip/mv syntax the written side carries, so the true |
| 18212 | // coefficient over-price is larger still): the writer's CDFs adapt to |
| 18213 | // the content while the search's stay at the defaults. The bound is |
| 18214 | // set just above the worst measured point -- a widening drift is the |
| 18215 | // thing this gate exists to catch. |
| 18216 | assert!( |
| 18217 | worst_over <= 0.16, |
| 18218 | "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", |
| 18219 | worst_over * 100.0 |
| 18220 | ); |
| 18221 | // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at |
| 18222 | // the worst inter frame, where nearly every block now codes an MV |
| 18223 | // residual and a reference the coefficient sum never counts. Re-measured |
| 18224 | // at +29.6% once the encoder's grid published compound blocks properly |
| 18225 | // (compound share 8.8% -> 11.5%): a compound block carries a second |
| 18226 | // reference tree, a compound mode symbol and -- for the half-new modes |
| 18227 | // -- an MV residual, none of which the coefficient sum counts. |
| 18228 | // lane-av1txbits: pricing against the tables the frame's writer really |
| 18229 | // starts from collapses the over-price above to nothing, so the whole |
| 18230 | // remaining gap is the syntax the coefficient sum leaves out. That is |
| 18231 | // the default on a non-screen frame since lane-av1price2 (this |
| 18232 | // fixture is one), and it reads +32.6% here. |
| 18233 | // lane-av1obmc: every eligible single-reference inter block now also |
| 18234 | // carries a `motion_mode` symbol the coefficient sum never counts, |
| 18235 | // and an OBMC block carries the more expensive of the two values -- |
| 18236 | // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like |
| 18237 | // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder |
| 18238 | // decisions, so this bound and the byte pins above FAIL BY DESIGN |
| 18239 | // under it; the default path (no motion_mode syntax at all) is the |
| 18240 | // one they are measured on. |
| 18241 | // lane-av1pyrdef: `encode_sequence` codes this fixture under the |
| 18242 | // coding pyramid now, so the five frames are a key frame, a hidden |
| 18243 | // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two |
| 18244 | // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the |
| 18245 | // near-empty leaves below it. Both bounds stand where they were. |
| 18246 | // lane-av1rejudge: local warp is ON by default now, so every eligible |
| 18247 | // single-reference block carries that same `motion_mode` symbol (a |
| 18248 | // 3-value alphabet where a warp sample exists) on the DEFAULT path -- |
| 18249 | // +34.9% here, one point past the OBMC reading above. The bound moves |
| 18250 | // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number. |
| 18251 | // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs` |
| 18252 | // symbol and one or two magnitude symbols, none of which the |
| 18253 | // coefficient sum counts either -- +36.9% here against the same |
| 18254 | // fixture's +34.9% with `EC_AV1_CFL=0`. |
| 18255 | // ... and a directional block whose `angle_delta_y` is no longer |
| 18256 | // always ZERO codes a costlier symbol off the same CDF -- +39.1%. |
| 18257 | assert!( |
| 18258 | worst_under <= 0.40, |
| 18259 | "the writer spent {:.2}% more than the search priced -- more than \ |
| 18260 | the mode/mv syntax outside the coefficient sum explains", |
| 18261 | worst_under * 100.0 |
| 18262 | ); |
| 18263 | } |
| 18264 | |
| 18265 | /// The census behind step (1) of the pricer lane: for every transform |
| 18266 | /// block the writer really codes, what the search priced those levels at |
| 18267 | /// against what the writer spent on them, split by table set and non-zero |
| 18268 | /// count. One average hides the interesting part -- the classes the |
| 18269 | /// estimate is systematically wrong about (all-zero blocks, the |
| 18270 | /// one-coefficient blocks the inter search lives on) -- so the split is |
| 18271 | /// printed and only the total is asserted on. |
| 18272 | #[test] |
| 18273 | fn pricer_error_census_by_block_class() { |
| 18274 | let _knobs = crate::speed::knob_read(); |
| 18275 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18276 | let (width, height) = (256usize, 128usize); |
| 18277 | let pictures: Vec<Picture> = (0..5) |
| 18278 | .map(|i| panned_test_card(width, height, i * 2)) |
| 18279 | .collect(); |
| 18280 | crate::tile::pricer_census_on(); |
| 18281 | let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 18282 | let rows = crate::tile::take_pricer_census(); |
| 18283 | assert!(!rows.is_empty(), "the census saw no transform block"); |
| 18284 | |
| 18285 | println!("| set | nz | blocks | priced bits | written bits | error |"); |
| 18286 | println!("|---|---|---|---|---|---|"); |
| 18287 | let (mut priced_all, mut written_all) = (0.0, 0.0); |
| 18288 | for ((set, bucket), (blocks, priced, written)) in &rows { |
| 18289 | priced_all += priced; |
| 18290 | written_all += written; |
| 18291 | println!( |
| 18292 | "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", |
| 18293 | crate::tile::census_bucket_label(*bucket), |
| 18294 | if *written > 0.0 { |
| 18295 | (priced - written) / written * 100.0 |
| 18296 | } else { |
| 18297 | 0.0 |
| 18298 | } |
| 18299 | ); |
| 18300 | } |
| 18301 | println!( |
| 18302 | "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", |
| 18303 | rows.values().map(|r| r.0).sum::<u64>(), |
| 18304 | (priced_all - written_all) / written_all * 100.0 |
| 18305 | ); |
| 18306 | assert!(written_all > 0.0); |
| 18307 | } |
| 18308 | |
| 18309 | /// Step (2) of the pricer lane: the same census, but on the REAL clips |
| 18310 | /// the BD gate scores -- one film clip and the screen capture -- so the |
| 18311 | /// question the film/screen split raises can be answered from data. Real |
| 18312 | /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and |
| 18313 | /// the screen capture larger, and the census says why: on a screen |
| 18314 | /// capture the frame's own starting tables are the tables of a frame that |
| 18315 | /// coded PALETTE and long runs of zero blocks, so they are far from the |
| 18316 | /// tables the writer ends the frame with; the pricer error does not fall |
| 18317 | /// the way it does on film. |
| 18318 | /// |
| 18319 | /// Not a gate -- it prints. Run it once per mode: |
| 18320 | /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \ |
| 18321 | /// --ignored pricer_error_census_on_clips --nocapture |
| 18322 | #[test] |
| 18323 | #[ignore = "reads the real library, needs ffmpeg"] |
| 18324 | fn pricer_error_census_on_clips() { |
| 18325 | let _knobs = crate::speed::knob_write(); |
| 18326 | if !have_ffmpeg() { |
| 18327 | eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg"); |
| 18328 | return; |
| 18329 | } |
| 18330 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 18331 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 18332 | let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4"); |
| 18333 | if film.exists() { |
| 18334 | clips.push(("film 1080p".to_string(), film)); |
| 18335 | } |
| 18336 | if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) |
| 18337 | && let Some(p) = manifest |
| 18338 | .lines() |
| 18339 | .skip(1) |
| 18340 | .filter_map(|l| l.split('\t').next()) |
| 18341 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 18342 | { |
| 18343 | clips.push(("screen".to_string(), std::path::PathBuf::from(p))); |
| 18344 | } |
| 18345 | assert!(!clips.is_empty(), "no source clip available"); |
| 18346 | let (width, height, frames) = (640usize, 384usize, 6usize); |
| 18347 | for (name, path) in &clips { |
| 18348 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18349 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 18350 | SCREEN_FRAMES.iter().for_each(|c| { |
| 18351 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 18352 | }); |
| 18353 | let _ = crate::tile::take_pricing_hits(); |
| 18354 | crate::tile::pricer_census_on(); |
| 18355 | let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 18356 | let rows = crate::tile::take_pricer_census(); |
| 18357 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 18358 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 18359 | println!( |
| 18360 | "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \ |
| 18361 | {screen_on}, pricer armings default={price_default} real={price_real}" |
| 18362 | ); |
| 18363 | println!("| set | nz | blocks | priced bits | written bits | error |"); |
| 18364 | println!("|---|---|---|---|---|---|"); |
| 18365 | let (mut priced_all, mut written_all) = (0.0, 0.0); |
| 18366 | for ((set, bucket), (blocks, priced, written)) in &rows { |
| 18367 | priced_all += priced; |
| 18368 | written_all += written; |
| 18369 | println!( |
| 18370 | "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", |
| 18371 | crate::tile::census_bucket_label(*bucket), |
| 18372 | if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 } |
| 18373 | ); |
| 18374 | } |
| 18375 | println!( |
| 18376 | "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", |
| 18377 | rows.values().map(|r| r.0).sum::<u64>(), |
| 18378 | (priced_all - written_all) / written_all * 100.0 |
| 18379 | ); |
| 18380 | assert!(written_all > 0.0, "{name}: the census saw no transform block"); |
| 18381 | } |
| 18382 | } |
| 18383 | |
| 18384 | /// Low motion has to actually buy something: at least one inter frame of |
| 18385 | /// a panning sequence has to cost fewer bytes than the key frame that |
| 18386 | /// starts it, and the inter-block share it prints has to be non-zero -- |
| 18387 | /// a search that never picks an inter mode would still pass a rate gate |
| 18388 | /// on a picture with no motion in it (the class this repo calls |
| 18389 | /// gate-blind-to-feature), so the share is printed even though it is not |
| 18390 | /// asserted on beyond being reachable at all. |
| 18391 | #[test] |
| 18392 | fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { |
| 18393 | let _knobs = crate::speed::knob_read(); |
| 18394 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18395 | let (width, height) = (256usize, 128usize); |
| 18396 | let pictures: Vec<Picture> = (0..5) |
| 18397 | .map(|i| panned_test_card(width, height, i * 2)) |
| 18398 | .collect(); |
| 18399 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 18400 | |
| 18401 | let key_bytes = encoded.frames[0].stream.len(); |
| 18402 | eprintln!("frame bytes inter share"); |
| 18403 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 18404 | eprintln!( |
| 18405 | "{i:5} {:5} {:11.2}", |
| 18406 | frame.stream.len(), |
| 18407 | frame.inter_block_share |
| 18408 | ); |
| 18409 | } |
| 18410 | assert!( |
| 18411 | encoded.frames[1..] |
| 18412 | .iter() |
| 18413 | .any(|f| f.stream.len() < key_bytes), |
| 18414 | "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" |
| 18415 | ); |
| 18416 | assert!( |
| 18417 | encoded.frames[1..] |
| 18418 | .iter() |
| 18419 | .any(|f| f.inter_block_share > 0.0), |
| 18420 | "no inter frame coded a single inter block -- the search never fired" |
| 18421 | ); |
| 18422 | } |
| 18423 | |
| 18424 | /// A manual perf probe, not a gate: prints where a key frame's and an |
| 18425 | /// inter frame's time goes, coarse stage by coarse stage, so a perf lane |
| 18426 | /// measures before it optimizes rather than guessing. Run with |
| 18427 | /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`. |
| 18428 | #[test] |
| 18429 | #[ignore = "a perf probe, not a gate"] |
| 18430 | fn stage_timing_breakdown() { |
| 18431 | let _knobs = crate::speed::knob_read(); |
| 18432 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18433 | use std::time::Instant; |
| 18434 | |
| 18435 | for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { |
| 18436 | let picture = test_card(width, height); |
| 18437 | |
| 18438 | let t = Instant::now(); |
| 18439 | let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap(); |
| 18440 | let dc_only_t = t.elapsed(); |
| 18441 | |
| 18442 | let t = Instant::now(); |
| 18443 | let non_directional = |
| 18444 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap(); |
| 18445 | let non_directional_t = t.elapsed(); |
| 18446 | |
| 18447 | let t = Instant::now(); |
| 18448 | let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 18449 | let all_modes_t = t.elapsed(); |
| 18450 | |
| 18451 | eprintln!( |
| 18452 | "\n=== key frame {width}x{height} ===\n\ |
| 18453 | 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ |
| 18454 | 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ |
| 18455 | 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", |
| 18456 | dc_only.stream.len(), |
| 18457 | non_directional.stream.len(), |
| 18458 | all_modes.stream.len(), |
| 18459 | ); |
| 18460 | |
| 18461 | // One inter frame predicting off the key frame's own |
| 18462 | // reconstruction, the (256, 256)-padded surface encode_sequence |
| 18463 | // itself would hand encode_inter_frame. |
| 18464 | let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); |
| 18465 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 18466 | let t = Instant::now(); |
| 18467 | let inter = |
| 18468 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap(); |
| 18469 | let inter_t = t.elapsed(); |
| 18470 | eprintln!( |
| 18471 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| 18472 | {:.2})", |
| 18473 | inter.stream.len(), |
| 18474 | inter.inter_block_share |
| 18475 | ); |
| 18476 | } |
| 18477 | |
| 18478 | // Isolated per-call cost of the trial pipeline's own stages, at both |
| 18479 | // transform sizes the search runs, averaged over enough calls to |
| 18480 | // rise above `Instant::now`'s own noise. |
| 18481 | for side in [16usize, 32] { |
| 18482 | const N: u32 = 20_000; |
| 18483 | let residual: Vec<i32> = (0..side * side) |
| 18484 | .map(|i| ((i * 37 % 61) as i32) - 30) |
| 18485 | .collect(); |
| 18486 | |
| 18487 | let t = Instant::now(); |
| 18488 | let mut levels = Vec::new(); |
| 18489 | for _ in 0..N { |
| 18490 | levels = forward_and_quantize(&residual, side, 8, 100, 0.5); |
| 18491 | } |
| 18492 | let forward_t = t.elapsed() / N; |
| 18493 | |
| 18494 | let t = Instant::now(); |
| 18495 | for _ in 0..N { |
| 18496 | std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100)); |
| 18497 | } |
| 18498 | let inverse_t = t.elapsed() / N; |
| 18499 | |
| 18500 | let set = if side == 32 { |
| 18501 | crate::cdf_state::TxbSet::Luma32 |
| 18502 | } else { |
| 18503 | crate::cdf_state::TxbSet::Luma16 |
| 18504 | }; |
| 18505 | let t = Instant::now(); |
| 18506 | for _ in 0..N { |
| 18507 | std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0)); |
| 18508 | } |
| 18509 | let entropy_t = t.elapsed() / N; |
| 18510 | |
| 18511 | let above = vec![128u8; side * 2]; |
| 18512 | let left = vec![128u8; side * 2]; |
| 18513 | let mut prediction = vec![0u8; side * side]; |
| 18514 | let t = Instant::now(); |
| 18515 | for _ in 0..N { |
| 18516 | intra_predict_u8( |
| 18517 | D45_PRED, |
| 18518 | 0, |
| 18519 | Some(&above), |
| 18520 | Some(&left), |
| 18521 | Some(128), |
| 18522 | side, |
| 18523 | side, |
| 18524 | false, |
| 18525 | false, |
| 18526 | &mut prediction, fctx, |
| 18527 | ); |
| 18528 | } |
| 18529 | let predict_t = t.elapsed() / N; |
| 18530 | |
| 18531 | eprintln!( |
| 18532 | "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ |
| 18533 | predict (1 directional mode): {predict_t:>9.2?}\n\ |
| 18534 | forward_and_quantize: {forward_t:>9.2?}\n\ |
| 18535 | dequant_and_inverse: {inverse_t:>9.2?}\n\ |
| 18536 | coeff_bits: {entropy_t:>9.2?}" |
| 18537 | ); |
| 18538 | } |
| 18539 | } |
| 18540 | |
| 18541 | /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets |
| 18542 | /// (motion search, [`crate::mc::predict`], transform+quantize, |
| 18543 | /// `coeff_bits`), plus what is left over once those are subtracted -- |
| 18544 | /// the thirteen-mode intra-candidate loop `search_inter_block` still |
| 18545 | /// runs on every inter block (its own transform/quant/entropy calls are |
| 18546 | /// already inside buckets 2/3, so "left over" here is everything NOT |
| 18547 | /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping, |
| 18548 | /// symbol-cost lookups outside `coeff_bits`). |
| 18549 | /// |
| 18550 | /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`. |
| 18551 | #[test] |
| 18552 | #[ignore = "a perf probe, not a gate"] |
| 18553 | fn stage_timing_breakdown_inter() { |
| 18554 | let _knobs = crate::speed::knob_read(); |
| 18555 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18556 | use std::time::Instant; |
| 18557 | |
| 18558 | let (width, height) = (1280usize, 720); |
| 18559 | let picture = test_card(width, height); |
| 18560 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 18561 | let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); |
| 18562 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 18563 | |
| 18564 | stage_reset(); |
| 18565 | let t = Instant::now(); |
| 18566 | let inter = |
| 18567 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap(); |
| 18568 | let total_t = t.elapsed(); |
| 18569 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 18570 | let accounted = motion_search + transform_quant + entropy; |
| 18571 | // motion_search already contains interpolation's own time (every |
| 18572 | // candidate the search costs calls crate::mc::predict), so it is not |
| 18573 | // added again here -- interpolation is reported alongside as "of |
| 18574 | // which interpolation", not as a fifth additive bucket. |
| 18575 | let other = total_t.saturating_sub(accounted); |
| 18576 | |
| 18577 | eprintln!( |
| 18578 | "\n=== inter frame {width}x{height}, one frame ===\n\ |
| 18579 | total: {total_t:>9.2?} ({} bytes)\n\ |
| 18580 | motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \ |
| 18581 | {interpolation:>9.2?})\n\ |
| 18582 | transform + quantize: {transform_quant:>9.2?}\n\ |
| 18583 | coeff_bits (entropy pricing): {entropy:>9.2?}\n\ |
| 18584 | everything else (13-mode intra {other:>9.2?}\n\ |
| 18585 | candidate loop's own predict/bookkeeping, NEARESTMV's own \ |
| 18586 | predict, RD glue):", |
| 18587 | inter.stream.len(), |
| 18588 | ); |
| 18589 | } |
| 18590 | |
| 18591 | /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real |
| 18592 | /// frames (a dark/flat one, a detailed one, a normal film one) at two |
| 18593 | /// `base_q_idx` values, encoded with the mode search unpruned (`top_k = |
| 18594 | /// None`, the baseline this same build produces without |
| 18595 | /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes |
| 18596 | /// and luma PSNR compared side by side. Not a gate itself -- the numbers |
| 18597 | /// go in the lane report, which is where "ship as default" is decided -- |
| 18598 | /// so it stays `#[ignore]`, run by hand with real clips on this machine. |
| 18599 | /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`. |
| 18600 | #[test] |
| 18601 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 18602 | fn prune_k_quality_sweep() { |
| 18603 | let _knobs = crate::speed::knob_read(); |
| 18604 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18605 | if !have_ffmpeg() { |
| 18606 | eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); |
| 18607 | return; |
| 18608 | } |
| 18609 | let (width, height) = (640usize, 352usize); |
| 18610 | let frames: &[(&str, &str, &str)] = &[ |
| 18611 | // (label, clip, seek) -- a near-black scene, a busy one, and an |
| 18612 | // ordinary film frame, each from a different real file. |
| 18613 | ( |
| 18614 | "dark/flat", |
| 18615 | "/home/user/Videos/reela.mp4", |
| 18616 | "3", |
| 18617 | ), |
| 18618 | ( |
| 18619 | "detailed", |
| 18620 | "/home/user/Downloads/reelb.mkv", |
| 18621 | "1200", |
| 18622 | ), |
| 18623 | ( |
| 18624 | "film", |
| 18625 | "/home/user/Videos/Films/reelc.mkv", |
| 18626 | "600", |
| 18627 | ), |
| 18628 | ]; |
| 18629 | for &(label, clip, skip) in frames { |
| 18630 | if !std::path::Path::new(clip).exists() { |
| 18631 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 18632 | continue; |
| 18633 | } |
| 18634 | let picture = clip_frame(clip, skip, width, height); |
| 18635 | for &q in &[60u8, 150] { |
| 18636 | // SAFETY (not literally unsafe, just process-global): this is |
| 18637 | // a single-threaded #[ignore] probe, run by hand, never |
| 18638 | // alongside other tests that read Search::top_k. |
| 18639 | set_test_top_k_override(None); |
| 18640 | let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 18641 | let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); |
| 18642 | eprint!( |
| 18643 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 18644 | baseline.stream.len(), |
| 18645 | baseline_psnr |
| 18646 | ); |
| 18647 | for &k in &[3usize, 4, 6] { |
| 18648 | set_test_top_k_override(Some(k)); |
| 18649 | let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 18650 | let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); |
| 18651 | eprint!( |
| 18652 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 18653 | pruned.stream.len(), |
| 18654 | pruned_psnr, |
| 18655 | pruned_psnr - baseline_psnr |
| 18656 | ); |
| 18657 | } |
| 18658 | eprintln!(); |
| 18659 | } |
| 18660 | } |
| 18661 | set_test_top_k_override(None); |
| 18662 | } |
| 18663 | |
| 18664 | /// Two consecutive decoded frames from one clip, for an inter-frame |
| 18665 | /// sweep -- [`clip_frame`] alone only ever gives one. |
| 18666 | fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { |
| 18667 | let out = Command::new("ffmpeg") |
| 18668 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) |
| 18669 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 18670 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 18671 | .output() |
| 18672 | .expect("ffmpeg failed to run"); |
| 18673 | assert!( |
| 18674 | out.status.success(), |
| 18675 | "ffmpeg: {}", |
| 18676 | String::from_utf8_lossy(&out.stderr) |
| 18677 | ); |
| 18678 | let (luma, chroma) = (width * height, width * height / 4); |
| 18679 | let frame_len = luma + 2 * chroma; |
| 18680 | assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); |
| 18681 | std::array::from_fn(|i| { |
| 18682 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 18683 | Picture { |
| 18684 | width, |
| 18685 | height, |
| 18686 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 18687 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 18688 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 18689 | } |
| 18690 | }) |
| 18691 | } |
| 18692 | |
| 18693 | /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same |
| 18694 | /// three real clips as [`prune_k_quality_sweep`], but coding a key frame |
| 18695 | /// then one inter frame off it (`search_inter_block`'s own intra |
| 18696 | /// candidates are what [`prune_by_sad`] prunes here, not the key-frame |
| 18697 | /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no |
| 18698 | /// padding step complicates the comparison. Prints bytes and luma PSNR |
| 18699 | /// for the inter frame alone, unpruned vs each `K`. |
| 18700 | /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`. |
| 18701 | #[test] |
| 18702 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 18703 | fn prune_k_quality_sweep_inter() { |
| 18704 | let _knobs = crate::speed::knob_read(); |
| 18705 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18706 | if !have_ffmpeg() { |
| 18707 | eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); |
| 18708 | return; |
| 18709 | } |
| 18710 | let (width, height) = (1280usize, 704usize); |
| 18711 | let frames: &[(&str, &str, &str)] = &[ |
| 18712 | ( |
| 18713 | "dark/flat", |
| 18714 | "/home/user/Videos/reela.mp4", |
| 18715 | "3", |
| 18716 | ), |
| 18717 | ( |
| 18718 | "detailed", |
| 18719 | "/home/user/Downloads/reelb.mkv", |
| 18720 | "1200", |
| 18721 | ), |
| 18722 | ( |
| 18723 | "film", |
| 18724 | "/home/user/Videos/Films/reelc.mkv", |
| 18725 | "600", |
| 18726 | ), |
| 18727 | ]; |
| 18728 | for &(label, clip, skip) in frames { |
| 18729 | if !std::path::Path::new(clip).exists() { |
| 18730 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 18731 | continue; |
| 18732 | } |
| 18733 | let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); |
| 18734 | for &q in &[60u8, 150] { |
| 18735 | // SAFETY (not literally unsafe, just process-global): a |
| 18736 | // single-threaded #[ignore] probe, run by hand, never |
| 18737 | // alongside other tests that read Search::top_k. |
| 18738 | set_test_top_k_override_inter(None); |
| 18739 | let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap(); |
| 18740 | let baseline = encode_inter_frame( |
| 18741 | &inter_source, |
| 18742 | &key.reconstruction, |
| 18743 | q, |
| 18744 | 0.5, |
| 18745 | 1, |
| 18746 | flat_order_hints(1, 0, false), |
| 18747 | (width, height), None, None, None, None, fctx, None, &[], |
| 18748 | ) |
| 18749 | .unwrap(); |
| 18750 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| 18751 | eprint!( |
| 18752 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 18753 | baseline.stream.len(), |
| 18754 | baseline_psnr |
| 18755 | ); |
| 18756 | for &k in &[3usize, 4, 6] { |
| 18757 | set_test_top_k_override_inter(Some(k)); |
| 18758 | let pruned = encode_inter_frame( |
| 18759 | &inter_source, |
| 18760 | &key.reconstruction, |
| 18761 | q, |
| 18762 | 0.5, |
| 18763 | 1, |
| 18764 | flat_order_hints(1, 0, false), |
| 18765 | (width, height), None, None, None, None, fctx, None, &[], |
| 18766 | ) |
| 18767 | .unwrap(); |
| 18768 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| 18769 | eprint!( |
| 18770 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 18771 | pruned.stream.len(), |
| 18772 | pruned_psnr, |
| 18773 | pruned_psnr - baseline_psnr |
| 18774 | ); |
| 18775 | } |
| 18776 | eprintln!(); |
| 18777 | } |
| 18778 | } |
| 18779 | set_test_top_k_override_inter(None); |
| 18780 | } |
| 18781 | |
| 18782 | /// `frames` consecutive pictures out of a real clip, scaled to a whole |
| 18783 | /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`] |
| 18784 | /// to an arbitrary count for the fixture regression gate below. |
| 18785 | fn clip_frames( |
| 18786 | clip: &str, |
| 18787 | skip: &str, |
| 18788 | width: usize, |
| 18789 | height: usize, |
| 18790 | frames: usize, |
| 18791 | ) -> Vec<Picture> { |
| 18792 | clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames) |
| 18793 | } |
| 18794 | |
| 18795 | /// [`clip_frames`] with the filter chain spelled out, so a caller can ask |
| 18796 | /// for a native-resolution CROP instead of a downscale (the downscale is |
| 18797 | /// what destroys a screen capture's exact repeats -- class |
| 18798 | /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces. |
| 18799 | fn clip_frames_vf( |
| 18800 | clip: &str, |
| 18801 | skip: &str, |
| 18802 | vf: &str, |
| 18803 | width: usize, |
| 18804 | height: usize, |
| 18805 | frames: usize, |
| 18806 | ) -> Vec<Picture> { |
| 18807 | // ONE definition of the gate's loader recipe, shared with |
| 18808 | // `examples/enc_probe` so the instrument cannot arm a different source |
| 18809 | // than the gate it reports on (class `instrument disagrees with the |
| 18810 | // gate`; lane-probe). |
| 18811 | crate::probe::source(clip, skip, vf, width, height, frames) |
| 18812 | } |
| 18813 | |
| 18814 | /// The standing regression gate on real content: 12 frames of a real |
| 18815 | /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to |
| 18816 | /// this crate's own input regardless of its own source codec), encoded |
| 18817 | /// as an AV1 GOP and checked against three numeric floors so a |
| 18818 | /// compatibility or quality regression fails the suite instead of |
| 18819 | /// waiting for a downstream repo's gate to catch it (as happened for a |
| 18820 | /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export |
| 18821 | /// refusal, both caught only that way). |
| 18822 | /// |
| 18823 | /// 640x384 is a whole number of 32x32 blocks (no straddle edge case; |
| 18824 | /// that geometry is already covered elsewhere), chosen only so encode |
| 18825 | /// time and gate numbers are not muddied by an edge-block class this |
| 18826 | /// test is not about. |
| 18827 | /// |
| 18828 | /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR |
| 18829 | /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling |
| 18830 | /// below carry a margin off those measured numbers (PSNR floor = |
| 18831 | /// measured - 0.5 dB; byte ceiling = measured * 1.15). |
| 18832 | #[test] |
| 18833 | fn real_clip_encodes_within_its_quality_and_size_budget() { |
| 18834 | let _knobs = crate::speed::knob_read(); |
| 18835 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18836 | if !have_ffmpeg() { |
| 18837 | eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg"); |
| 18838 | return; |
| 18839 | } |
| 18840 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 18841 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 18842 | if !clip.exists() { |
| 18843 | eprintln!( |
| 18844 | "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing", |
| 18845 | clip.display() |
| 18846 | ); |
| 18847 | return; |
| 18848 | } |
| 18849 | let (width, height, frame_count) = (640usize, 384usize, 12usize); |
| 18850 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 18851 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 18852 | assert_eq!(encoded.frames.len(), frame_count); |
| 18853 | |
| 18854 | // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole |
| 18855 | // stream and hands back every frame -- a stream a downstream |
| 18856 | // decoder refuses is the exact class of regression this gate |
| 18857 | // exists for. |
| 18858 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 18859 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 18860 | |
| 18861 | // Gate 2: quality vs the source did not silently collapse. |
| 18862 | let mean_psnr: f64 = decoded |
| 18863 | .iter() |
| 18864 | .zip(&source) |
| 18865 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 18866 | .sum::<f64>() |
| 18867 | / frame_count as f64; |
| 18868 | assert!( |
| 18869 | mean_psnr >= 44.91, |
| 18870 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor" |
| 18871 | ); |
| 18872 | |
| 18873 | // Gate 3: the stream did not silently bloat. |
| 18874 | assert!( |
| 18875 | encoded.stream.len() <= 80_340, |
| 18876 | "stream grew to {} bytes, over the 80340-byte ceiling", |
| 18877 | encoded.stream.len() |
| 18878 | ); |
| 18879 | } |
| 18880 | |
| 18881 | /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a |
| 18882 | /// straddle size: 640x384 is exact on both axes (32-aligned), so |
| 18883 | /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf |
| 18884 | /// path landed in e19bb47 goes unexercised by real, mixed intra/inter |
| 18885 | /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half |
| 18886 | /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_ |
| 18887 | /// straddle_size`'s 1280x720, but that test is a synthetic panned test |
| 18888 | /// card; this one is the real-clip gate, same three floors. |
| 18889 | /// |
| 18890 | /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average |
| 18891 | /// luma PSNR 45.48 dB across the 8 decoded frames vs the source. |
| 18892 | /// Floor/ceiling below carry the same margin as the sibling test (PSNR |
| 18893 | /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15). |
| 18894 | #[test] |
| 18895 | fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() { |
| 18896 | let _knobs = crate::speed::knob_read(); |
| 18897 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18898 | if !have_ffmpeg() { |
| 18899 | eprintln!( |
| 18900 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 18901 | no ffmpeg" |
| 18902 | ); |
| 18903 | return; |
| 18904 | } |
| 18905 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 18906 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 18907 | if !clip.exists() { |
| 18908 | eprintln!( |
| 18909 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 18910 | {} missing", |
| 18911 | clip.display() |
| 18912 | ); |
| 18913 | return; |
| 18914 | } |
| 18915 | let (width, height, frame_count) = (704usize, 400usize, 8usize); |
| 18916 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 18917 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 18918 | assert_eq!(encoded.frames.len(), frame_count); |
| 18919 | |
| 18920 | // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole |
| 18921 | // stream and hands back every frame. |
| 18922 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 18923 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 18924 | |
| 18925 | // Gate 2: quality vs the source did not silently collapse. |
| 18926 | let mean_psnr: f64 = decoded |
| 18927 | .iter() |
| 18928 | .zip(&source) |
| 18929 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 18930 | .sum::<f64>() |
| 18931 | / frame_count as f64; |
| 18932 | assert!( |
| 18933 | mean_psnr >= 44.98, |
| 18934 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor" |
| 18935 | ); |
| 18936 | |
| 18937 | // Gate 3: the stream did not silently bloat. |
| 18938 | assert!( |
| 18939 | encoded.stream.len() <= 62_703, |
| 18940 | "stream grew to {} bytes, over the 62703-byte ceiling", |
| 18941 | encoded.stream.len() |
| 18942 | ); |
| 18943 | } |
| 18944 | |
| 18945 | /// The replica-shaped path: 24 frames, 1280x720, one key frame followed |
| 18946 | /// by inter frames -- the same GOP shape [`encode_sequence`] gives the |
| 18947 | /// facade -- timed end to end, so the edith export-time projection is a |
| 18948 | /// real number rather than a guess from the isolated key/inter numbers |
| 18949 | /// above. Run with and without `EC_AV1_PRUNE_K` set to compare. |
| 18950 | /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`. |
| 18951 | #[test] |
| 18952 | #[ignore = "a perf probe, not a gate"] |
| 18953 | fn sequence_bench_sanity() { |
| 18954 | let _knobs = crate::speed::knob_read(); |
| 18955 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18956 | use std::time::Instant; |
| 18957 | let (width, height) = (1280usize, 720usize); |
| 18958 | let pictures: Vec<Picture> = (0..24) |
| 18959 | .map(|i| panned_test_card(width, height, i * 3)) |
| 18960 | .collect(); |
| 18961 | let t = Instant::now(); |
| 18962 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 18963 | let elapsed = t.elapsed(); |
| 18964 | let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); |
| 18965 | eprintln!( |
| 18966 | "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", |
| 18967 | elapsed / 24 |
| 18968 | ); |
| 18969 | } |
| 18970 | |
| 18971 | /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the |
| 18972 | /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a |
| 18973 | /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx |
| 18974 | /// -- --ignored --nocapture`. |
| 18975 | #[test] |
| 18976 | #[ignore = "a calibration probe, not a gate"] |
| 18977 | fn calibration_sweep_base_q_idx() { |
| 18978 | let _knobs = crate::speed::knob_read(); |
| 18979 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 18980 | if !have_ffmpeg() { |
| 18981 | eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg"); |
| 18982 | return; |
| 18983 | } |
| 18984 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 18985 | for clip in [ |
| 18986 | "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps |
| 18987 | "h264-1080p-60-8bit.mp4", // higher motion, 60fps |
| 18988 | ] { |
| 18989 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 18990 | .join("../../fixtures/video") |
| 18991 | .join(clip); |
| 18992 | if !path.exists() { |
| 18993 | eprintln!("SKIP {clip}: fixture missing"); |
| 18994 | continue; |
| 18995 | } |
| 18996 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 18997 | eprintln!("--- {clip} ---"); |
| 18998 | for q in [40u8, 70, 100, 130, 160, 190, 220, 240] { |
| 18999 | let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); |
| 19000 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames); |
| 19001 | let mean_psnr: f64 = decoded |
| 19002 | .iter() |
| 19003 | .zip(&source) |
| 19004 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 19005 | .sum::<f64>() |
| 19006 | / frames as f64; |
| 19007 | let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64; |
| 19008 | eprintln!( |
| 19009 | "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB", |
| 19010 | encoded.stream.len() |
| 19011 | ); |
| 19012 | } |
| 19013 | } |
| 19014 | } |
| 19015 | |
| 19016 | // ----------------------------------------------------------------------- |
| 19017 | // The encoder's standing BD-rate baseline against libaom and rav1e. |
| 19018 | // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an |
| 19019 | // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder |
| 19020 | // agreeing with our encoder proves nothing about the bitstream. |
| 19021 | // ----------------------------------------------------------------------- |
| 19022 | |
| 19023 | /// All-plane PSNR of a decoded picture against its source, on the same |
| 19024 | /// 8-bit scale [`psnr`] uses. |
| 19025 | fn psnr_all(decoded: &Picture, source: &Picture) -> f64 { |
| 19026 | let cat = |p: &Picture| { |
| 19027 | let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len()); |
| 19028 | v.extend_from_slice(&p.y); |
| 19029 | v.extend_from_slice(&p.u); |
| 19030 | v.extend_from_slice(&p.v); |
| 19031 | v |
| 19032 | }; |
| 19033 | psnr(&cat(decoded), &cat(source)) |
| 19034 | } |
| 19035 | |
| 19036 | /// The pictures back as the planar 8-bit bytes an encoder reads. |
| 19037 | fn raw_yuv420p(source: &[Picture]) -> Vec<u8> { |
| 19038 | let mut raw = Vec::new(); |
| 19039 | for p in source { |
| 19040 | for plane in [&p.y, &p.u, &p.v] { |
| 19041 | raw.extend(plane.iter().map(|&s| s as u8)); |
| 19042 | } |
| 19043 | } |
| 19044 | raw |
| 19045 | } |
| 19046 | |
| 19047 | /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven |
| 19048 | /// through ffmpeg: one point per entry of `points`, each a quality flag |
| 19049 | /// set. Returns the ladder ordered by fidelity and the total encode wall |
| 19050 | /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`], |
| 19051 | /// so both curves are measured by the same decoder. |
| 19052 | fn external_ladder( |
| 19053 | source: &[Picture], |
| 19054 | width: usize, |
| 19055 | height: usize, |
| 19056 | encoder: &str, |
| 19057 | points: &[Vec<String>], |
| 19058 | ) -> (Vec<(f64, f64)>, f64) { |
| 19059 | // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. |
| 19060 | let dir = std::env::temp_dir(); |
| 19061 | let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id())); |
| 19062 | std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source"); |
| 19063 | let mut ladder = Vec::new(); |
| 19064 | let mut wall = 0.0; |
| 19065 | for (i, params) in points.iter().enumerate() { |
| 19066 | let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id())); |
| 19067 | let start = std::time::Instant::now(); |
| 19068 | let out = Command::new("ffmpeg") |
| 19069 | .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 19070 | .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) |
| 19071 | .arg(&raw_path) |
| 19072 | .args(["-an", "-threads", "1"]) |
| 19073 | .args(["-g", &source.len().to_string(), "-c:v", encoder]) |
| 19074 | .args(params) |
| 19075 | .args(["-f", "obu"]) |
| 19076 | .arg(&obu) |
| 19077 | .output() |
| 19078 | .expect("ffmpeg failed to run"); |
| 19079 | wall += start.elapsed().as_secs_f64(); |
| 19080 | assert!( |
| 19081 | out.status.success(), |
| 19082 | "{encoder} {params:?}: {}", |
| 19083 | String::from_utf8_lossy(&out.stderr) |
| 19084 | ); |
| 19085 | let stream = std::fs::read(&obu).expect("reference stream"); |
| 19086 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 19087 | // lane-dkey: every reference point must also decode through OUR |
| 19088 | // decoder, sample-exact against ffmpeg's decode of the same bytes. |
| 19089 | // A BD table computed off streams we cannot read is a table about |
| 19090 | // an encoder we cannot check; this is the assertion that would |
| 19091 | // have caught the `force_integer_mv` defect (its stream decoded to |
| 19092 | // 25 dB garbage while this gate stayed green) and the crf-5 key |
| 19093 | // frame desync. A failure names the encoder, the point's flags and |
| 19094 | // the first differing frame/plane/sample. |
| 19095 | // lane-dpm1: a failing reference point is COLLECTED, not panicked |
| 19096 | // on, so one run still prints the whole BD table and names every |
| 19097 | // bad point instead of stopping at the first. The collection is |
| 19098 | // asserted empty by [`assert_ladder_decodes`] at the end of each |
| 19099 | // gate. |
| 19100 | match crate::stream::decode_stream(&stream) { |
| 19101 | Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!( |
| 19102 | "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}", |
| 19103 | ours.len(), |
| 19104 | decoded.len(), |
| 19105 | )), |
| 19106 | Ok(ours) => { |
| 19107 | for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() { |
| 19108 | if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) { |
| 19109 | note_ladder_failure(format!( |
| 19110 | "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \ |
| 19111 | decoder decoded {got}, ffmpeg {want}" |
| 19112 | )); |
| 19113 | break; |
| 19114 | } |
| 19115 | } |
| 19116 | } |
| 19117 | Err(e) => note_ladder_failure(format!( |
| 19118 | "{encoder} {params:?}: our decoder refused the stream ({e})" |
| 19119 | )), |
| 19120 | } |
| 19121 | let mean: f64 = decoded |
| 19122 | .iter() |
| 19123 | .zip(source) |
| 19124 | .map(|(d, s)| psnr_all(d, s)) |
| 19125 | .sum::<f64>() |
| 19126 | / source.len() as f64; |
| 19127 | ladder.push((mean, (stream.len() as f64).log10())); |
| 19128 | let _ = std::fs::remove_file(&obu); |
| 19129 | } |
| 19130 | let _ = std::fs::remove_file(&raw_path); |
| 19131 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 19132 | (ladder, wall) |
| 19133 | } |
| 19134 | |
| 19135 | /// Every reference ladder point that did not decode sample-exactly |
| 19136 | /// through our own decoder, collected across a whole gate run so the BD |
| 19137 | /// table still prints and EVERY bad point is named |
| 19138 | /// (`encoder params frame plane sample`) instead of only the first. |
| 19139 | static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); |
| 19140 | |
| 19141 | fn note_ladder_failure(msg: String) { |
| 19142 | eprintln!("LADDER DECODE FAILURE: {msg}"); |
| 19143 | LADDER_FAILURES.lock().expect("ladder failures").push(msg); |
| 19144 | } |
| 19145 | |
| 19146 | /// Fail the gate at its END on everything [`external_ladder`] collected. |
| 19147 | fn assert_ladder_decodes() { |
| 19148 | let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures")); |
| 19149 | assert!( |
| 19150 | failures.is_empty(), |
| 19151 | "{} reference ladder point(s) did not decode exactly through our decoder:\n{}", |
| 19152 | failures.len(), |
| 19153 | failures.join("\n"), |
| 19154 | ); |
| 19155 | } |
| 19156 | |
| 19157 | /// First differing sample between two pictures, as |
| 19158 | /// `(plane, index, left, right)` -- so a gate failure names the plane and |
| 19159 | /// the sample instead of just "differs". A length difference counts as a |
| 19160 | /// mismatch of that plane at the first index past the shorter one. |
| 19161 | fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> { |
| 19162 | for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { |
| 19163 | if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { |
| 19164 | return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); |
| 19165 | } |
| 19166 | if l.len() != r.len() { |
| 19167 | return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); |
| 19168 | } |
| 19169 | } |
| 19170 | None |
| 19171 | } |
| 19172 | |
| 19173 | /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR |
| 19174 | /// comes from ffmpeg's decode of our own stream, and at EVERY point the |
| 19175 | /// stream is decoded twice -- by ffmpeg and by our own |
| 19176 | /// [`crate::stream::decode_stream`] -- and all three pictures (encoder |
| 19177 | /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact |
| 19178 | /// in Y, U and V over every shown frame in display order. That is itself |
| 19179 | /// a gate: it proves the bitstream says what the encoder thinks, in the |
| 19180 | /// only two decoders that read it. |
| 19181 | fn our_ladder( |
| 19182 | name: &str, |
| 19183 | source: &[Picture], |
| 19184 | width: usize, |
| 19185 | height: usize, |
| 19186 | fctx: &crate::decode::FrameCtx, |
| 19187 | ) -> (Vec<(f64, f64)>, f64) { |
| 19188 | let mut ladder = Vec::new(); |
| 19189 | let mut wall = 0.0; |
| 19190 | for &q in &[150u8, 120, 90, 60] { |
| 19191 | let start = std::time::Instant::now(); |
| 19192 | // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so |
| 19193 | // the gate has to be able to re-sweep it. 0.5 is the shipped one |
| 19194 | // (`crate::encoder::DEADZONE`). |
| 19195 | let deadzone = std::env::var("EC_AV1_DEADZONE") |
| 19196 | .ok() |
| 19197 | .and_then(|v| v.parse().ok()) |
| 19198 | .unwrap_or(0.5); |
| 19199 | let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap(); |
| 19200 | wall += start.elapsed().as_secs_f64(); |
| 19201 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len()); |
| 19202 | let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 19203 | assert_eq!( |
| 19204 | ours.len(), |
| 19205 | source.len(), |
| 19206 | "{name} q={q}: our decoder's display-order frame count" |
| 19207 | ); |
| 19208 | for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 19209 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { |
| 19210 | panic!( |
| 19211 | "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ |
| 19212 | {got}, the encoder reconstructed {want}" |
| 19213 | ); |
| 19214 | } |
| 19215 | } |
| 19216 | for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() { |
| 19217 | if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) { |
| 19218 | panic!( |
| 19219 | "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \ |
| 19220 | {got}, the encoder reconstructed {want}" |
| 19221 | ); |
| 19222 | } |
| 19223 | } |
| 19224 | let per_frame: Vec<f64> = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect(); |
| 19225 | // lane-txrd: does a tool's loss start at the FIRST inter frame |
| 19226 | // (a local mispricing) or grow down the GOP (propagation into |
| 19227 | // the reference chain)? One line per q point answers it. |
| 19228 | if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") { |
| 19229 | let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect(); |
| 19230 | eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" ")); |
| 19231 | // lane-txrd: per PLANE, because an all-plane mean hides a |
| 19232 | // collapse in one of them (class `metric blind to a plane`). |
| 19233 | let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String { |
| 19234 | let v: Vec<String> = decoded |
| 19235 | .iter() |
| 19236 | .zip(source) |
| 19237 | .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s)))) |
| 19238 | .collect(); |
| 19239 | v.join(" ") |
| 19240 | }; |
| 19241 | eprintln!("{name}: q={q} Y {}", plane(|p| &p.y)); |
| 19242 | eprintln!("{name}: q={q} U {}", plane(|p| &p.u)); |
| 19243 | eprintln!("{name}: q={q} V {}", plane(|p| &p.v)); |
| 19244 | } |
| 19245 | let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64; |
| 19246 | ladder.push((mean, (encoded.stream.len() as f64).log10())); |
| 19247 | } |
| 19248 | // What this clip asked for and what the content gate left it coding |
| 19249 | // under: a screen clip requests a pyramid and codes flat, and that |
| 19250 | // difference is what keeps its row identical to the flat baseline |
| 19251 | // (class `gate-blind-to-feature`). |
| 19252 | eprintln!( |
| 19253 | "{name}: sequence, pyramid requested {:?} effective {:?}", |
| 19254 | crate::encoder::Pyramid::from_env(), |
| 19255 | last_sequence_pyramid(), |
| 19256 | ); |
| 19257 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 19258 | (ladder, wall) |
| 19259 | } |
| 19260 | |
| 19261 | /// [`our_ladder`] through the streaming facade — the surface the editor's |
| 19262 | /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`] |
| 19263 | /// each stream is also reordered (hidden `ALTREF` first, |
| 19264 | /// `show_existing_frame` last per group) and each level is coded at its |
| 19265 | /// own quantizer offset; without one it is the flat ladder, which |
| 19266 | /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence` |
| 19267 | /// pins byte-identical to [`our_ladder`]'s, so this arm must print the |
| 19268 | /// same BD numbers. Returns the ladder, the wall, per pyramid level over |
| 19269 | /// the whole ladder how many frames and how many bytes it spent, and the |
| 19270 | /// pyramid the streams were EFFECTIVELY coded under — the content gate in |
| 19271 | /// `Av1Encoder::encode_frames` drops a screen-content clip back to the |
| 19272 | /// flat path, so a requested pyramid can come back `None` here. |
| 19273 | fn our_ladder_facade( |
| 19274 | name: &str, |
| 19275 | source: &[Picture], |
| 19276 | width: usize, |
| 19277 | height: usize, |
| 19278 | pyramid: Option<crate::encoder::Pyramid>, |
| 19279 | ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) { |
| 19280 | use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; |
| 19281 | let slot = |l: Level| match l { |
| 19282 | Level::Key => 0, |
| 19283 | Level::Arf => 1, |
| 19284 | Level::Leaf => 2, |
| 19285 | Level::ShowExisting => 3, |
| 19286 | }; |
| 19287 | let mut ladder = Vec::new(); |
| 19288 | let mut wall = 0.0; |
| 19289 | let mut effective = None; |
| 19290 | let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); |
| 19291 | for &q in &[150u8, 120, 90, 60] { |
| 19292 | let config = EncoderConfig { |
| 19293 | width, |
| 19294 | height, |
| 19295 | base_q_idx: q, |
| 19296 | gop: source.len(), |
| 19297 | colour: Colour::Unspecified, |
| 19298 | tile_cols_log2: 0, |
| 19299 | tile_rows_log2: 0, |
| 19300 | }; |
| 19301 | let start = std::time::Instant::now(); |
| 19302 | let mut enc = match pyramid { |
| 19303 | None => Av1Encoder::new(config).unwrap(), |
| 19304 | Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(), |
| 19305 | }; |
| 19306 | let mut packets = Vec::new(); |
| 19307 | for picture in source { |
| 19308 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 19309 | } |
| 19310 | packets.extend(enc.flush().unwrap()); |
| 19311 | wall += start.elapsed().as_secs_f64(); |
| 19312 | effective = enc.pyramid(); |
| 19313 | let mut stream = Vec::new(); |
| 19314 | for p in &packets { |
| 19315 | counts[slot(p.level)] += 1; |
| 19316 | bytes[slot(p.level)] += p.data.len(); |
| 19317 | stream.extend_from_slice(&p.data); |
| 19318 | } |
| 19319 | // [[gate-blind-to-hidden-frames]]: a reordered stream is only |
| 19320 | // correct if the DISPLAY-order output still has one frame per |
| 19321 | // source picture, in the right order -- checked against our own |
| 19322 | // decoder as well as ffmpeg's, both below. |
| 19323 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 19324 | assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count"); |
| 19325 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 19326 | for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { |
| 19327 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) { |
| 19328 | panic!( |
| 19329 | "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \ |
| 19330 | decoded {got}, our decoder decoded {want}" |
| 19331 | ); |
| 19332 | } |
| 19333 | } |
| 19334 | let mean: f64 = decoded |
| 19335 | .iter() |
| 19336 | .zip(source) |
| 19337 | .map(|(d, s)| psnr_all(d, s)) |
| 19338 | .sum::<f64>() |
| 19339 | / source.len() as f64; |
| 19340 | ladder.push((mean, (stream.len() as f64).log10())); |
| 19341 | } |
| 19342 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 19343 | (ladder, wall, counts, bytes, effective) |
| 19344 | } |
| 19345 | |
| 19346 | /// Byte-exactness gate for encoder work that is meant to change only |
| 19347 | /// how long the encoder takes. |
| 19348 | /// |
| 19349 | /// The BD gate above measures quality, which a speed lane can move by a |
| 19350 | /// hair without failing anything; this pins the streams themselves. |
| 19351 | /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 |
| 19352 | /// `cdef_idx` literals and per-unit loop restoration syntax are new bits |
| 19353 | /// in the tile) and again on lane-av1mv's merge of it: an extra |
| 19354 | /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate |
| 19355 | /// above, not by this pin. Re-pinned on lane-av1price2: the search now |
| 19356 | /// prices coefficients against the tables the frame's writer really |
| 19357 | /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a |
| 19358 | /// decision change the BD gate judges. Re-pinned again on |
| 19359 | /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the |
| 19360 | /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which |
| 19361 | /// is the same kind of decision change. Re-pinned on lane-av1lambda: |
| 19362 | /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the |
| 19363 | /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on |
| 19364 | /// by default ([`warp_on`], a sequence/frame header bit and a new |
| 19365 | /// motion_mode symbol on eligible blocks) and |
| 19366 | /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl: |
| 19367 | /// every inter frame's superblocks now code at their own lambda |
| 19368 | /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved. |
| 19369 | /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 |
| 19370 | /// and the two var-tx depth searches ([`tx32_depth_search`], |
| 19371 | /// [`compound_var_tx`]) are on by default, all three re-judged on the |
| 19372 | /// native gate's real film rows. |
| 19373 | /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so |
| 19374 | /// every block whose chroma takes it codes a different mode symbol, two |
| 19375 | /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0` |
| 19376 | /// restores the previous streams. Re-pinned again in the same lane once |
| 19377 | /// directional luma winners searched their `angle_delta_y` |
| 19378 | /// (`EC_AV1_ANGLE=0` restores that half). |
| 19379 | #[test] |
| 19380 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { |
| 19381 | // These are DEFAULT-PRESET pins: a speed preset switches search levers |
| 19382 | // off, so it legitimately moves every byte. Encode at speed 0 whatever |
| 19383 | // `EC_AV1_SPEED` says (write guard: the preset is process-global). |
| 19384 | let _knobs = crate::speed::knob_write(); |
| 19385 | let was = crate::speed::speed(); |
| 19386 | crate::speed::set_speed(0); |
| 19387 | if !have_ffmpeg() { |
| 19388 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); |
| 19389 | return; |
| 19390 | } |
| 19391 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 19392 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 19393 | if !clip.exists() { |
| 19394 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip"); |
| 19395 | return; |
| 19396 | } |
| 19397 | let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4); |
| 19398 | // FNV-1a over the stream: a witness that every coded bit is where it |
| 19399 | // was, which a byte count alone is not. |
| 19400 | let fnv = |b: &[u8]| { |
| 19401 | b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { |
| 19402 | (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) |
| 19403 | }) |
| 19404 | }; |
| 19405 | // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen) |
| 19406 | // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP |
| 19407 | // of 4, its leaves at q+8 and a `show_existing_frame` header per |
| 19408 | // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over |
| 19409 | // four frames; four pictures is one short mini-GOP, which is the |
| 19410 | // shape that pays least (the ARF's own quality has no later group to |
| 19411 | // carry it), so this is not the BD gate's number. |
| 19412 | // Re-taken again on lane-av1cfl: the chroma search offers |
| 19413 | // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`, |
| 19414 | // so every block taking either codes different syntax and different |
| 19415 | // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60. |
| 19416 | // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half. |
| 19417 | // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16 |
| 19418 | // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]), |
| 19419 | // so these four pictures code as one truncated group -- a hidden |
| 19420 | // ALTREF at `q-24` and three leaves at `q+16` -- instead of one |
| 19421 | // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and |
| 19422 | // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these. |
| 19423 | // Re-taken on lane-fintra: the sequence header sets |
| 19424 | // `enable_filter_intra`, so every DC_PRED intra block of at most |
| 19425 | // 32x32 without a luma palette carries a `use_filter_intra` flag and |
| 19426 | // the blocks that take one code a filter-intra mode, a different |
| 19427 | // prediction and different coefficients -- 7321 -> 7373 at q=150 and |
| 19428 | // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these. |
| 19429 | // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge |
| 19430 | // (default pyramid `8:-32:16`, one truncated group of 8 with its |
| 19431 | // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64 |
| 19432 | // root can code a REAL residual now (one TX_64X64 luma transform and |
| 19433 | // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548; |
| 19434 | // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid. |
| 19435 | // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at |
| 19436 | // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and |
| 19437 | // one of these four pictures is the key -- 8590 -> 9778 at q=150 and |
| 19438 | // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these. |
| 19439 | // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above |
| 19440 | // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778 |
| 19441 | // -> 9835 at q=150 and 35450 -> 35798 at q=60. |
| 19442 | // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these. |
| 19443 | // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0` |
| 19444 | // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of |
| 19445 | // these four pictures -- offers every superblock a 64x64 intra root |
| 19446 | // now. `EC_AV1_I64=0` restores 8557 / 33345. |
| 19447 | // Re-taken on lane-pricer: the inter RD search prices a single |
| 19448 | // reference through the tree and the neighbour contexts the writer |
| 19449 | // really codes it with, so every inter picture's reference decisions |
| 19450 | // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60. |
| 19451 | // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts |
| 19452 | // for `skip`/`is_inter` and for the whole compound reference tree, so |
| 19453 | // every inter block's cost -- and with it the skip and reference |
| 19454 | // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087 |
| 19455 | // at q=60. Re-taken on lane-ctx2: a single-reference candidate now |
| 19456 | // pays the `comp_mode = 0` symbol the writer codes ahead of it, so |
| 19457 | // single and compound are priced against the same syntax -- 8311 -> |
| 19458 | // 8325 bytes at q=150 and 33087 -> 33014 at q=60. |
| 19459 | // Re-taken on lane-newmv: the motion search charges its own rate term |
| 19460 | // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`]) |
| 19461 | // and each subpel stage re-runs from its own winner |
| 19462 | // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector |
| 19463 | // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150 |
| 19464 | // and 33014 -> 33090 at q=60. |
| 19465 | // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex` |
| 19466 | // from libaom's objective tpl mapping, so every inter picture's |
| 19467 | // quantizer grid -- and every decision priced against it -- moved |
| 19468 | // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more |
| 19469 | // at the merge of both lanes. |
| 19470 | // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its |
| 19471 | // per-superblock `delta_qindex` at 1.5x the preset's strength |
| 19472 | // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer |
| 19473 | // grids -- and every decision priced against them -- moved: |
| 19474 | // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60. |
| 19475 | // Re-taken on lane-arfpred: the top ARF is coded from a temporally |
| 19476 | // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's |
| 19477 | // pixels -- and the leaves that predict from them -- moved: |
| 19478 | // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60. |
| 19479 | // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so |
| 19480 | // the shipped stream did not move. |
| 19481 | // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every |
| 19482 | // picture is coded in 128x128 superblocks now, the inter ones |
| 19483 | // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at |
| 19484 | // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053. |
| 19485 | // Re-taken at the merge of lane-b128m onto main (128 superblocks on |
| 19486 | // by default, on top of the ARF temporal filter). |
| 19487 | // Re-taken on lane-b128r: the 128 root now offers the COMPOUND |
| 19488 | // candidates the 64 root already did ([`b128_compound`]), so every |
| 19489 | // inter frame that carries `reference_select` codes different blocks |
| 19490 | // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60. |
| 19491 | // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly. |
| 19492 | // Re-taken on lane-arftf: that filter's strength swept on the deciding |
| 19493 | // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered |
| 19494 | // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and |
| 19495 | // 33017 at q=60 (the same LENGTH, different bytes). |
| 19496 | // Re-taken at the merge of lane-arftf (ARF filter strength 2) and |
| 19497 | // lane-rlclamp onto the 128 compound default. |
| 19498 | // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ |
| 19499 | // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks, |
| 19500 | // so every inter frame whose RD takes one codes a different partition |
| 19501 | // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that |
| 19502 | // quantizer the rect cut never wins its own comparison on this clip. |
| 19503 | // `EC_AV1_B128HV=0` restores 8290 exactly. |
| 19504 | let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)]; |
| 19505 | let coded: Vec<(u8, usize, u64)> = pins |
| 19506 | .iter() |
| 19507 | .map(|&(q, _, _)| { |
| 19508 | let e = encode_sequence(&source, q, 0.5).unwrap(); |
| 19509 | (q, e.stream.len(), fnv(&e.stream)) |
| 19510 | }) |
| 19511 | .collect(); |
| 19512 | crate::speed::set_speed(was); |
| 19513 | for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) { |
| 19514 | assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved"); |
| 19515 | } |
| 19516 | } |
| 19517 | |
| 19518 | /// A ladder is only a ladder if both axes rise together. |
| 19519 | fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { |
| 19520 | assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); |
| 19521 | for w in ladder.windows(2) { |
| 19522 | assert!( |
| 19523 | w[1].0 > w[0].0 && w[1].1 > w[0].1, |
| 19524 | "{name}: not monotone, {ladder:?}" |
| 19525 | ); |
| 19526 | } |
| 19527 | } |
| 19528 | |
| 19529 | /// The sweep behind [`screen_content`]'s constants |
| 19530 | /// (`unswept-decision-constants`), on the SAME five clips |
| 19531 | /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the |
| 19532 | /// same native crop: for each colour bound N the share of 16x16 luma |
| 19533 | /// blocks with 2..=N distinct colours, and the share of those whose |
| 19534 | /// per-pixel variance also clears a floor V -- libaom's |
| 19535 | /// `av1_set_screen_content_options` counts the variance-cleared blocks |
| 19536 | /// too (its `counts_2`, which gates intrabc), and without that term a |
| 19537 | /// smooth dark film frame reads as screen content. |
| 19538 | /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture` |
| 19539 | #[test] |
| 19540 | #[ignore = "reads the real library"] |
| 19541 | fn probe_screen_detect() { |
| 19542 | let _knobs = crate::speed::knob_read(); |
| 19543 | if !have_ffmpeg() { |
| 19544 | eprintln!("SKIP probe_screen_detect: no ffmpeg"); |
| 19545 | return; |
| 19546 | } |
| 19547 | let limits = [4usize, 8, 16, 32, 64, 128]; |
| 19548 | let floors = [0u64, 4, 16, 64, 256]; |
| 19549 | // The census of one clip at one size: mean share, over the frames, of |
| 19550 | // 16x16 blocks with 2..=N colours whose per-pixel variance is > V. |
| 19551 | let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| { |
| 19552 | let mut acc = [[0f64; 5]; 6]; |
| 19553 | for picture in frames { |
| 19554 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 19555 | let mut hit = [[0usize; 5]; 6]; |
| 19556 | let mut blocks = 0usize; |
| 19557 | for by in (0..ch).step_by(16) { |
| 19558 | for bx in (0..cw).step_by(16) { |
| 19559 | let mut seen = [false; 256]; |
| 19560 | let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64); |
| 19561 | for row in 0..16 { |
| 19562 | for col in 0..16 { |
| 19563 | let v = y[(by + row) * cw + bx + col]; |
| 19564 | sum += u64::from(v); |
| 19565 | sq += u64::from(v) * u64::from(v); |
| 19566 | if !seen[usize::from(v)] { |
| 19567 | seen[usize::from(v)] = true; |
| 19568 | colors += 1; |
| 19569 | } |
| 19570 | } |
| 19571 | } |
| 19572 | let var = (sq - sum * sum / 256) / 256; |
| 19573 | blocks += 1; |
| 19574 | for (li, &limit) in limits.iter().enumerate() { |
| 19575 | if colors > 1 && colors <= limit { |
| 19576 | for (fi, &floor) in floors.iter().enumerate() { |
| 19577 | hit[li][fi] += usize::from(var > floor); |
| 19578 | } |
| 19579 | } |
| 19580 | } |
| 19581 | } |
| 19582 | } |
| 19583 | for li in 0..6 { |
| 19584 | for fi in 0..5 { |
| 19585 | acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64; |
| 19586 | } |
| 19587 | } |
| 19588 | } |
| 19589 | let n = frames.len().max(1) as f64; |
| 19590 | eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len()); |
| 19591 | eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>()); |
| 19592 | for (li, &limit) in limits.iter().enumerate() { |
| 19593 | eprintln!( |
| 19594 | " {limit:>5} |{}", |
| 19595 | (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>() |
| 19596 | ); |
| 19597 | } |
| 19598 | }; |
| 19599 | for (name, path, seek) in native_gate_clips() { |
| 19600 | let Some((nw, nh)) = probe_dims(&path) else { |
| 19601 | eprintln!("SKIP {name}: ffprobe gave no size"); |
| 19602 | continue; |
| 19603 | }; |
| 19604 | let cw = nw.min(1920) / 128 * 128; |
| 19605 | let ch = nh.min(1024) / 128 * 128; |
| 19606 | let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 19607 | let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12); |
| 19608 | census(&name, &frames, cw, ch); |
| 19609 | // The 640x384 gate scales instead of cropping, and the scaling |
| 19610 | // changes the census (bars smooth out): the constants have to |
| 19611 | // separate at BOTH sizes. |
| 19612 | let small = clip_frames(&path, &seek, 640, 384, 12); |
| 19613 | census(&name, &small, 640, 384); |
| 19614 | } |
| 19615 | } |
| 19616 | |
| 19617 | /// The detector against the WHOLE real library (class |
| 19618 | /// `unswept-decision-constants`, user rule "his data is the gate"): |
| 19619 | /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the |
| 19620 | /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its |
| 19621 | /// duration, four frames each, 8-bit 4:2:0, at native size or a |
| 19622 | /// 1920x1080 centred crop when larger (the crop keeps a capture's exact |
| 19623 | /// repeats, which a downscale destroys -- class `gate-recipe-confound`). |
| 19624 | /// Prints per file and offset the share of qualifying 16x16 blocks, the |
| 19625 | /// [`screen_content`] verdict and a content hint (mean luma, luma |
| 19626 | /// standard deviation, inter MAD), then sweeps the colour bound against |
| 19627 | /// the variance floor over the whole library: for each (N, V) the worst |
| 19628 | /// (highest) share among the camera/film rows against the best (lowest) |
| 19629 | /// among the screen-recording rows, so the rule with the widest gap can |
| 19630 | /// be read off. Rows carry the manifest index, codec and size only -- |
| 19631 | /// no titles, no home paths. |
| 19632 | /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture` |
| 19633 | #[test] |
| 19634 | #[ignore = "reads the real library"] |
| 19635 | fn probe_screen_library() { |
| 19636 | let _knobs = crate::speed::knob_read(); |
| 19637 | if !have_ffmpeg() { |
| 19638 | eprintln!("SKIP probe_screen_library: no ffmpeg"); |
| 19639 | return; |
| 19640 | } |
| 19641 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 19642 | let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else { |
| 19643 | eprintln!("SKIP probe_screen_library: no real-library manifest"); |
| 19644 | return; |
| 19645 | }; |
| 19646 | let limits = [4usize, 8, 16, 32, 64]; |
| 19647 | let floors = [0u64, 4, 8, 16, 32, 64, 128]; |
| 19648 | // Whatever ffmpeg gave us, without the exact-count assertion the |
| 19649 | // gate loaders make: a seek near the end of a clip returns fewer |
| 19650 | // frames, and that is a row to print, not a panic. |
| 19651 | let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> { |
| 19652 | let out = Command::new("ffmpeg") |
| 19653 | .args(["-v", "error", "-ss", seek, "-i", clip]) |
| 19654 | .args(["-frames:v", &n.to_string()]) |
| 19655 | .args(["-vf", vf]) |
| 19656 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 19657 | .output(); |
| 19658 | let Ok(out) = out else { return Vec::new() }; |
| 19659 | if !out.status.success() { |
| 19660 | return Vec::new(); |
| 19661 | } |
| 19662 | let (luma, chroma) = (w * h, w * h / 4); |
| 19663 | let frame_len = luma + 2 * chroma; |
| 19664 | (0..out.stdout.len() / frame_len) |
| 19665 | .map(|i| { |
| 19666 | let b = &out.stdout[i * frame_len..][..frame_len]; |
| 19667 | Picture { |
| 19668 | width: w, |
| 19669 | height: h, |
| 19670 | y: b[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 19671 | u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 19672 | v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 19673 | } |
| 19674 | }) |
| 19675 | .collect() |
| 19676 | }; |
| 19677 | // Share (%) of 16x16 blocks with 2..=N colours and per-pixel |
| 19678 | // variance > V, for every (N, V) of the sweep grid, over one frame. |
| 19679 | let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] { |
| 19680 | let mut hit = [[0usize; 7]; 5]; |
| 19681 | let mut blocks = 0usize; |
| 19682 | for by in (0..h).step_by(16) { |
| 19683 | for bx in (0..w).step_by(16) { |
| 19684 | let (bh, bw) = ((h - by).min(16), (w - bx).min(16)); |
| 19685 | let mut seen = [false; 256]; |
| 19686 | let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64); |
| 19687 | for row in 0..bh { |
| 19688 | for col in 0..bw { |
| 19689 | let v = y[(by + row) * w + bx + col]; |
| 19690 | sum += u64::from(v); |
| 19691 | sq += u64::from(v) * u64::from(v); |
| 19692 | if !seen[usize::from(v)] { |
| 19693 | seen[usize::from(v)] = true; |
| 19694 | colors += 1; |
| 19695 | } |
| 19696 | } |
| 19697 | } |
| 19698 | let n = (bh * bw) as u64; |
| 19699 | let var = (sq - sum * sum / n) / n; |
| 19700 | blocks += 1; |
| 19701 | for (li, &limit) in limits.iter().enumerate() { |
| 19702 | if colors > 1 && colors <= limit { |
| 19703 | for (fi, &floor) in floors.iter().enumerate() { |
| 19704 | hit[li][fi] += usize::from(var > floor); |
| 19705 | } |
| 19706 | } |
| 19707 | } |
| 19708 | } |
| 19709 | } |
| 19710 | let mut out = [[0f64; 7]; 5]; |
| 19711 | for li in 0..5 { |
| 19712 | for fi in 0..7 { |
| 19713 | out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64; |
| 19714 | } |
| 19715 | } |
| 19716 | out |
| 19717 | }; |
| 19718 | // (index, label, path, duration, screen-by-its-own-content). The |
| 19719 | // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS") |
| 19720 | // are desktop recordings; everything else in this library is camera |
| 19721 | // or film material. |
| 19722 | let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new(); |
| 19723 | for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] { |
| 19724 | let path = fixtures.join("video").join(file); |
| 19725 | if path.exists() { |
| 19726 | rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false)); |
| 19727 | } |
| 19728 | } |
| 19729 | for (i, line) in manifest.lines().skip(1).enumerate() { |
| 19730 | let f: Vec<&str> = line.split('\t').collect(); |
| 19731 | if f.len() < 10 { |
| 19732 | continue; |
| 19733 | } |
| 19734 | let (path, codec) = (f[0], f[2]); |
| 19735 | if codec == "-" || codec.is_empty() { |
| 19736 | continue; |
| 19737 | } |
| 19738 | let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else { |
| 19739 | eprintln!("SKIP {}: manifest carries no coded size", i + 1); |
| 19740 | continue; |
| 19741 | }; |
| 19742 | if !std::path::Path::new(path).exists() { |
| 19743 | eprintln!("SKIP {}: file is gone", i + 1); |
| 19744 | continue; |
| 19745 | } |
| 19746 | let name = path.rsplit('/').next().unwrap_or(path); |
| 19747 | let is_capture = path.contains("/OBS/") |
| 19748 | || (name.len() > 19 |
| 19749 | && name.as_bytes()[4] == b'-' |
| 19750 | && name.as_bytes()[7] == b'-' |
| 19751 | && name.as_bytes()[10] == b' ' |
| 19752 | && name.as_bytes()[13] == b'-'); |
| 19753 | rows.push(( |
| 19754 | format!("{}", i + 1), |
| 19755 | format!("{codec} {w}x{h}"), |
| 19756 | path.to_string(), |
| 19757 | f[8].parse::<f64>().unwrap_or(0.0), |
| 19758 | is_capture, |
| 19759 | )); |
| 19760 | } |
| 19761 | // Per (N, V): the worst camera/film row and the best screen row, so |
| 19762 | // the separation of the whole library is one subtraction. |
| 19763 | let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]); |
| 19764 | eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |"); |
| 19765 | for (idx, label, path, dur, is_capture) in &rows { |
| 19766 | let Some((nw, nh)) = probe_dims(path) else { |
| 19767 | eprintln!("SKIP {idx}: ffprobe gave no size"); |
| 19768 | continue; |
| 19769 | }; |
| 19770 | let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1); |
| 19771 | let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 19772 | let vf = format!("crop={cw}:{ch}:{x}:{y0}"); |
| 19773 | let mut file_grid = [[0f64; 7]; 5]; |
| 19774 | let mut file_frames = 0usize; |
| 19775 | for pct in [10u32, 50, 90] { |
| 19776 | let seek = format!("{:.3}", dur * f64::from(pct) / 100.0); |
| 19777 | let frames = decode(path, &seek, &vf, cw, ch, 4); |
| 19778 | if frames.is_empty() { |
| 19779 | eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" }); |
| 19780 | continue; |
| 19781 | } |
| 19782 | let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64); |
| 19783 | let mut prev: Option<Vec<u8>> = None; |
| 19784 | for picture in &frames { |
| 19785 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 19786 | let grid = census(&y, cw, ch); |
| 19787 | for li in 0..5 { |
| 19788 | for fi in 0..7 { |
| 19789 | file_grid[li][fi] += grid[li][fi]; |
| 19790 | } |
| 19791 | } |
| 19792 | file_frames += 1; |
| 19793 | // The shipped rule is (16 colours, var > 16): grid row 2, |
| 19794 | // floor 16 is column 3. |
| 19795 | share += grid[2][3]; |
| 19796 | yes += usize::from(screen_content(&y, cw, cw, ch)); |
| 19797 | let n = y.len() as f64; |
| 19798 | let sum: f64 = y.iter().map(|&v| f64::from(v)).sum(); |
| 19799 | let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum(); |
| 19800 | mean += sum / n; |
| 19801 | sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt(); |
| 19802 | if let Some(p) = &prev { |
| 19803 | mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n; |
| 19804 | } |
| 19805 | prev = Some(y); |
| 19806 | } |
| 19807 | let f = frames.len() as f64; |
| 19808 | eprintln!( |
| 19809 | "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |", |
| 19810 | if *is_capture { "screen" } else { "camera" }, |
| 19811 | share / f, |
| 19812 | if yes * 2 > frames.len() { "SCREEN" } else { "camera" }, |
| 19813 | frames.len(), |
| 19814 | mean / f, |
| 19815 | sd / f, |
| 19816 | mad / (f - 1.0).max(1.0), |
| 19817 | ); |
| 19818 | } |
| 19819 | if file_frames == 0 { |
| 19820 | continue; |
| 19821 | } |
| 19822 | for li in 0..5 { |
| 19823 | for fi in 0..7 { |
| 19824 | let s = file_grid[li][fi] / file_frames as f64; |
| 19825 | match is_capture { |
| 19826 | true => scr_min[li][fi] = scr_min[li][fi].min(s), |
| 19827 | false => cam_max[li][fi] = cam_max[li][fi].max(s), |
| 19828 | } |
| 19829 | } |
| 19830 | } |
| 19831 | } |
| 19832 | eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):"); |
| 19833 | eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>()); |
| 19834 | let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64)); |
| 19835 | for (li, &limit) in limits.iter().enumerate() { |
| 19836 | let mut row = String::new(); |
| 19837 | for fi in 0..7 { |
| 19838 | let (c, s) = (cam_max[li][fi], scr_min[li][fi]); |
| 19839 | row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c))); |
| 19840 | if s - c > best { |
| 19841 | best = s - c; |
| 19842 | best_rule = (limit, floors[fi]); |
| 19843 | } |
| 19844 | } |
| 19845 | eprintln!(" {limit:>5} |{row}"); |
| 19846 | } |
| 19847 | // The threshold sits at the midpoint of the widest gap; the shipped |
| 19848 | // constant is its reciprocal in whole parts of the frame. |
| 19849 | let (li, fi) = ( |
| 19850 | limits.iter().position(|&l| l == best_rule.0).unwrap(), |
| 19851 | floors.iter().position(|&f| f == best_rule.1).unwrap(), |
| 19852 | ); |
| 19853 | let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0; |
| 19854 | eprintln!( |
| 19855 | "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}", |
| 19856 | best_rule.0, |
| 19857 | best_rule.1, |
| 19858 | best, |
| 19859 | cam_max[li][fi], |
| 19860 | scr_min[li][fi], |
| 19861 | mid, |
| 19862 | (100.0 / mid.max(0.1)).round() as usize, |
| 19863 | ); |
| 19864 | } |
| 19865 | |
| 19866 | /// The missing instrument: what this encoder costs against libaom and |
| 19867 | /// rav1e at matched fidelity, and how long it takes to get there. |
| 19868 | /// |
| 19869 | /// Recipe, identical on all three sides: 12 consecutive frames of each |
| 19870 | /// clip scaled to 640x384 (a whole number of superblocks), one key frame |
| 19871 | /// then 11 inter frames (`-g 12`, matching our own sequence shape), one |
| 19872 | /// tile, `-threads 1`, no film grain synthesis (neither reference enables |
| 19873 | /// it by default), 4:2:0 8-bit in and out. Reference points: |
| 19874 | /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}` |
| 19875 | /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}: |
| 19876 | /// tile_cols=1:tile_rows=1:threads=1` |
| 19877 | /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on |
| 19878 | /// ffmpeg-decoded frames of each encoder's own stream. |
| 19879 | /// |
| 19880 | /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame |
| 19881 | /// deblocking levels and CDEF strengths, both chosen by re-decoding the |
| 19882 | /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the |
| 19883 | /// four encodes of that ladder together): |
| 19884 | /// |
| 19885 | /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e | |
| 19886 | /// |---|---|---|---|---| |
| 19887 | /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s | |
| 19888 | /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | |
| 19889 | /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | |
| 19890 | /// |
| 19891 | /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long |
| 19892 | /// the encoder takes -- every stream it writes is byte-identical, so the |
| 19893 | /// BD columns are this box's own re-run of the same recipe rather than a |
| 19894 | /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs |
| 19895 | /// rav1e). What moved is the wall of the four encodes: |
| 19896 | /// |
| 19897 | /// | clip | wall ours before | after | instructions:u before -> after | |
| 19898 | /// |---|---|---|---| |
| 19899 | /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) | |
| 19900 | /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) | |
| 19901 | /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) | |
| 19902 | /// |
| 19903 | /// Three exact steps, none of which touches a coded bit: the coefficient |
| 19904 | /// rate pricer stopped rebuilding every CDF table per candidate |
| 19905 | /// (`tile::coeff_bits`), the filter search stopped re-decoding its own |
| 19906 | /// tile once per candidate (`decode::FilterReplay`), and the forward |
| 19907 | /// transform stopped transforming the all-zero residual that 70% of its |
| 19908 | /// calls carry. |
| 19909 | /// |
| 19910 | /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): |
| 19911 | /// |
| 19912 | /// | step | 1080p | 2160p | screen | |
| 19913 | /// |---|---|---|---| |
| 19914 | /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 | |
| 19915 | /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 | |
| 19916 | /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 | |
| 19917 | /// |
| 19918 | /// Re-measured for the record 2026-09-07 (lane-av1resweep), after |
| 19919 | /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth |
| 19920 | /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults |
| 19921 | /// -- all three decided on the REAL film rows of |
| 19922 | /// [`bd_rate_screen_native`], which this downscaled recipe does not |
| 19923 | /// carry: |
| 19924 | /// |
| 19925 | /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e | |
| 19926 | /// |---|---|---|---| |
| 19927 | /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s | |
| 19928 | /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s | |
| 19929 | /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s | |
| 19930 | /// |
| 19931 | /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the |
| 19932 | /// DEFAULT of the sequence path this gate codes through -- the bars are |
| 19933 | /// non-screen so they take it, the capture is gated flat: |
| 19934 | /// |
| 19935 | /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall | |
| 19936 | /// |---|---|---|---|---| |
| 19937 | /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s | |
| 19938 | /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s | |
| 19939 | /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s | |
| 19940 | /// |
| 19941 | /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the |
| 19942 | /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the |
| 19943 | /// facade arm -- which is what "one mini-GOP driver, two entry points" |
| 19944 | /// means here. This downscaled recipe HATES the pyramid (as it hates |
| 19945 | /// every knob the real film rows of `bd_rate_screen_native` keep, which |
| 19946 | /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows |
| 19947 | /// above. The capture's row is the flat row to the byte in both runs -- |
| 19948 | /// that equality IS the content gate. |
| 19949 | /// |
| 19950 | /// Loop restoration is NOT in yet: it is the one filter whose parameters |
| 19951 | /// are per restoration UNIT inside the tile payload, so it needs both |
| 19952 | /// tile writers to code `lr` syntax and an encoder-visible post-CDEF |
| 19953 | /// buffer to solve against -- neither of which this frame-header-level |
| 19954 | /// search reaches. |
| 19955 | /// |
| 19956 | /// The baseline it replaced, before an inter frame's blocks chose their |
| 19957 | /// own partition, was +501.4/+504.4/+440.9 against libaom and |
| 19958 | /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s. |
| 19959 | /// |
| 19960 | /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched |
| 19961 | /// fidelity, while spending far more time than either (the partition |
| 19962 | /// search's own cost, uncut: see the two intra-pruning variants measured |
| 19963 | /// and rejected in the lane report). No |
| 19964 | /// threshold is asserted yet -- this run sets the baseline; the gate |
| 19965 | /// asserts four monotone points per ladder, and at EVERY ladder point of |
| 19966 | /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own |
| 19967 | /// `crate::stream::decode_stream` -- and asserts the encoder's |
| 19968 | /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U |
| 19969 | /// and V over every shown frame in display order. A failure names the |
| 19970 | /// clip, the q, the frame, the plane and the first differing sample. |
| 19971 | /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade, |
| 19972 | /// which exposes no per-packet reconstruction, so that path asserts the |
| 19973 | /// two decoders against each other on all three planes.) |
| 19974 | /// |
| 19975 | /// Run: |
| 19976 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 19977 | /// bd_rate_vs_libaom_and_rav1e --nocapture |
| 19978 | #[test] |
| 19979 | #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"] |
| 19980 | fn bd_rate_vs_libaom_and_rav1e() { |
| 19981 | let _knobs = crate::speed::knob_write(); |
| 19982 | if !have_ffmpeg() { |
| 19983 | eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg"); |
| 19984 | return; |
| 19985 | } |
| 19986 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 19987 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 19988 | // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these |
| 19989 | // rows for real content (the real rows live in the native gate). |
| 19990 | for (label, name) in [ |
| 19991 | ("bars 1080p", "h264-1080p-23.976-8bit.mp4"), |
| 19992 | ("bars 2160p", "h264-2160p-23.976-8bit.mp4"), |
| 19993 | ] { |
| 19994 | let path = fixtures.join("video").join(name); |
| 19995 | if path.exists() { |
| 19996 | clips.push((label.to_string(), path)); |
| 19997 | } else { |
| 19998 | eprintln!("SKIP clip {name}: missing"); |
| 19999 | } |
| 20000 | } |
| 20001 | // Screen capture: the repo carries no screen-capture fixture, so take |
| 20002 | // the first OBS recording the real-library manifest names. |
| 20003 | match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) { |
| 20004 | Ok(manifest) => { |
| 20005 | let screen = manifest |
| 20006 | .lines() |
| 20007 | .skip(1) |
| 20008 | .filter_map(|l| l.split('\t').next()) |
| 20009 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()); |
| 20010 | match screen { |
| 20011 | Some(p) => clips.push(( |
| 20012 | format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), |
| 20013 | std::path::PathBuf::from(p), |
| 20014 | )), |
| 20015 | None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), |
| 20016 | } |
| 20017 | } |
| 20018 | Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"), |
| 20019 | } |
| 20020 | assert!(!clips.is_empty(), "no source clip available"); |
| 20021 | |
| 20022 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 20023 | let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] |
| 20024 | .iter() |
| 20025 | .map(|q| { |
| 20026 | ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] |
| 20027 | .map(String::from) |
| 20028 | .to_vec() |
| 20029 | }) |
| 20030 | .collect(); |
| 20031 | let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] |
| 20032 | .iter() |
| 20033 | .map(|q| { |
| 20034 | vec![ |
| 20035 | "-rav1e-params".to_string(), |
| 20036 | format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), |
| 20037 | ] |
| 20038 | }) |
| 20039 | .collect(); |
| 20040 | println!( |
| 20041 | "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread" |
| 20042 | ); |
| 20043 | println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"); |
| 20044 | println!("|---|---|---|---|---|"); |
| 20045 | for (name, path) in &clips { |
| 20046 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 20047 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 20048 | let _ = take_partition_hits(); |
| 20049 | let _ = crate::tile::take_palette_hits(); |
| 20050 | SCREEN_FRAMES.iter().for_each(|c| { |
| 20051 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 20052 | }); |
| 20053 | let _ = take_uv_mode_hits(); |
| 20054 | let _ = crate::tile::take_inter_mode_hits(); |
| 20055 | let _ = crate::tile::take_drl_hits(); |
| 20056 | let _ = crate::tile::take_ref_hits(); |
| 20057 | let _ = crate::tile::take_compound_mode_hits(); |
| 20058 | let _ = crate::tile::take_compound_pair_hits(); |
| 20059 | let _ = crate::tile::take_compound_size_hits(); |
| 20060 | let _ = crate::tile::take_compound_leaf_mode_hits(); |
| 20061 | let _ = take_b64_root_hits(); |
| 20062 | let _ = take_b64_residual_hits(); |
| 20063 | let _ = take_b64_compound_hits(); |
| 20064 | let _ = crate::motion::take_census(); |
| 20065 | // The entry-surface arm: run the SAME ladder through the |
| 20066 | // streaming facade the editor's export calls, which must print |
| 20067 | // the same BD numbers as the sequence path -- byte for byte the |
| 20068 | // same stream now that both drive one mini-GOP driver |
| 20069 | // (lane-av1pyrdef). |
| 20070 | let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some(); |
| 20071 | let (ours, ours_wall) = match facade { |
| 20072 | false => our_ladder(name, &source, width, height, fctx), |
| 20073 | true => { |
| 20074 | let pyramid = crate::encoder::Pyramid::from_env(); |
| 20075 | let (ladder, wall, counts, bytes, effective) = |
| 20076 | our_ladder_facade(name, &source, width, height, pyramid); |
| 20077 | eprintln!( |
| 20078 | "{name}: facade, pyramid requested {pyramid:?} effective \ |
| 20079 | {effective:?} -- frames key {} arf {} leaf {} \ |
| 20080 | show_existing {}; bytes key {} arf {} leaf {} show_existing {}", |
| 20081 | counts[0], counts[1], counts[2], counts[3], |
| 20082 | bytes[0], bytes[1], bytes[2], bytes[3], |
| 20083 | ); |
| 20084 | (ladder, wall) |
| 20085 | } |
| 20086 | }; |
| 20087 | // How often the inter split actually fired over this clip's four |
| 20088 | // encodes, against the whole 32x32 that was the only outcome |
| 20089 | // before (gate-blind-to-feature). |
| 20090 | let [whole32, split32, whole16, split16] = take_partition_hits(); |
| 20091 | // Which inter modes actually fired over this clip's four encodes, |
| 20092 | // and at which DRL index -- a mode nobody picks is a mode the BD |
| 20093 | // number cannot be crediting (gate-blind-to-feature). |
| 20094 | let [nearest, near, global, new] = crate::tile::take_inter_mode_hits(); |
| 20095 | let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits(); |
| 20096 | let refs = crate::tile::take_ref_hits(); |
| 20097 | let modes_total = (nearest + near + global + new).max(1); |
| 20098 | eprintln!( |
| 20099 | "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \ |
| 20100 | GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \ |
| 20101 | {drl0}/{drl1}/{drl2}/{drl3}", |
| 20102 | 100.0 * nearest as f64 / modes_total as f64, |
| 20103 | 100.0 * near as f64 / modes_total as f64, |
| 20104 | 100.0 * global as f64 / modes_total as f64, |
| 20105 | 100.0 * new as f64 / modes_total as f64, |
| 20106 | ); |
| 20107 | // The compound census: what share of the coded inter blocks took |
| 20108 | // a compound reference at all, which compound mode they took, and |
| 20109 | // which pair (gate-blind-to-feature -- a compound mode nobody |
| 20110 | // picks cannot be what a BD number credits). |
| 20111 | // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many |
| 20112 | // superblocks were left whole at all, and how many of those coded |
| 20113 | // a residual or took a compound reference. |
| 20114 | let (roots, root_res, root_comp) = ( |
| 20115 | take_b64_root_hits(), |
| 20116 | take_b64_residual_hits(), |
| 20117 | take_b64_compound_hits(), |
| 20118 | ); |
| 20119 | eprintln!( |
| 20120 | "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})" |
| 20121 | ); |
| 20122 | let comp_modes = crate::tile::take_compound_mode_hits(); |
| 20123 | let comp_pairs = crate::tile::take_compound_pair_hits(); |
| 20124 | let comp_sizes = crate::tile::take_compound_size_hits(); |
| 20125 | let comp_leaf = crate::tile::take_compound_leaf_mode_hits(); |
| 20126 | let comp_total: usize = comp_modes.iter().sum(); |
| 20127 | eprintln!( |
| 20128 | "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \ |
| 20129 | NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \ |
| 20130 | GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}", |
| 20131 | modes_total + comp_total, |
| 20132 | 100.0 * comp_total as f64 / (modes_total + comp_total) as f64, |
| 20133 | comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3], |
| 20134 | comp_modes[6], comp_modes[7], |
| 20135 | comp_pairs[3], comp_pairs[6], |
| 20136 | ); |
| 20137 | eprintln!( |
| 20138 | "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \ |
| 20139 | NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}", |
| 20140 | comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6], |
| 20141 | comp_leaf[7], |
| 20142 | ); |
| 20143 | eprintln!( |
| 20144 | "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}", |
| 20145 | comp_sizes[1], comp_sizes[2], comp_sizes[3], |
| 20146 | ); |
| 20147 | // Where the wall-owning stage actually goes: how many candidate |
| 20148 | // evaluations (one `mc::predict` + SAD each) a search spends, how |
| 20149 | // many of them are subpel, and how often the winner is the seed |
| 20150 | // it started from -- the census the seeded search is judged by. |
| 20151 | let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] = |
| 20152 | crate::motion::take_census(); |
| 20153 | let per = |n: u64| n as f64 / calls.max(1) as f64; |
| 20154 | eprintln!( |
| 20155 | "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \ |
| 20156 | {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \ |
| 20157 | +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%", |
| 20158 | per(evals), |
| 20159 | 100.0 * subpel as f64 / evals.max(1) as f64, |
| 20160 | per(rounds), |
| 20161 | 100.0 * near_pred as f64 / calls.max(1) as f64, |
| 20162 | 100.0 * unmoved as f64 / calls.max(1) as f64, |
| 20163 | ); |
| 20164 | // lane-newmv, class `instrument at bound`: how often the winner |
| 20165 | // was walked to at the log stage's own WIDEST step -- a high |
| 20166 | // share means the search stops where its step lets it, not where |
| 20167 | // the content is. |
| 20168 | eprintln!( |
| 20169 | "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)", |
| 20170 | 100.0 * widest as f64 / calls.max(1) as f64, |
| 20171 | per(widest_moves), |
| 20172 | ); |
| 20173 | eprintln!( |
| 20174 | "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", |
| 20175 | refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] |
| 20176 | ); |
| 20177 | eprintln!( |
| 20178 | "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ |
| 20179 | 16x16 leaves split into 8s {split16} of {} ({:.1}%)", |
| 20180 | whole32 + split32, |
| 20181 | 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64, |
| 20182 | whole16 + split16, |
| 20183 | 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 |
| 20184 | ); |
| 20185 | // The deblocking level each of this clip's frames chose |
| 20186 | // (lane-av1filt): 0 everywhere would mean the filter never fires. |
| 20187 | let levels = crate::filter_search::take_chosen_levels(); |
| 20188 | type Chosen = ((u8, u8), (u8, u8), (u8, u8)); |
| 20189 | let mean = |f: fn(&Chosen) -> u8| { |
| 20190 | levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64 |
| 20191 | }; |
| 20192 | eprintln!( |
| 20193 | "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \ |
| 20194 | cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}", |
| 20195 | levels.len(), |
| 20196 | mean(|l| l.0.0), |
| 20197 | mean(|l| l.0.1), |
| 20198 | mean(|l| l.1.0), |
| 20199 | mean(|l| l.1.1), |
| 20200 | mean(|l| l.2.0), |
| 20201 | mean(|l| l.2.1), |
| 20202 | ); |
| 20203 | // How many strength presets each frame's CDEF list carried and |
| 20204 | // how the 64x64 units spread over them (lane-av1lr): `bits 0` |
| 20205 | // everywhere would mean the per-unit choice never fires. |
| 20206 | let presets = crate::filter_search::take_cdef_presets(); |
| 20207 | let mut by_bits = [0usize; 4]; |
| 20208 | for (b, _) in &presets { |
| 20209 | by_bits[usize::from(*b)] += 1; |
| 20210 | } |
| 20211 | let units: usize = presets.iter().flat_map(|(_, c)| c).sum(); |
| 20212 | let on_extra: usize = presets |
| 20213 | .iter() |
| 20214 | .flat_map(|(_, c)| c.iter().skip(1)) |
| 20215 | .sum(); |
| 20216 | eprintln!( |
| 20217 | "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \ |
| 20218 | on a non-default preset ({:.1}%)", |
| 20219 | by_bits[0], |
| 20220 | by_bits[1], |
| 20221 | by_bits[2], |
| 20222 | by_bits[3], |
| 20223 | on_extra, |
| 20224 | units, |
| 20225 | 100.0 * on_extra as f64 / units.max(1) as f64 |
| 20226 | ); |
| 20227 | // How the 64x64 luma restoration units split between |
| 20228 | // RESTORE_NONE and Wiener (lane-av1lr). |
| 20229 | let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram(); |
| 20230 | eprintln!( |
| 20231 | "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)", |
| 20232 | 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64 |
| 20233 | ); |
| 20234 | // Which chroma modes the search actually wins with, against the |
| 20235 | // unconditional DC_PRED that was the only outcome before |
| 20236 | // (gate-blind-to-feature). |
| 20237 | // Screen-content detection and the palette it turns on |
| 20238 | // (gate-blind-to-feature): how many frames set |
| 20239 | // `allow_screen_content_tools`, how many blocks took a palette, |
| 20240 | // and of what size. A film clip must print `screen frames on=0`. |
| 20241 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 20242 | let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); |
| 20243 | // Which tables the SEARCH priced against, per frame arming |
| 20244 | // (`tile::arm_pricing_cdfs`): the default tables or the frame's |
| 20245 | // real starting ones. A film clip must show every inter arming on |
| 20246 | // the real side, a screen clip none of them. |
| 20247 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 20248 | eprintln!("{name}: pricer armings default={price_default} real={price_real}"); |
| 20249 | let palette = crate::tile::take_palette_hits(); |
| 20250 | eprintln!( |
| 20251 | "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", |
| 20252 | palette[0], |
| 20253 | (2..=8) |
| 20254 | .filter(|&n| palette[n] > 0) |
| 20255 | .map(|n| format!("{n}={}", palette[n])) |
| 20256 | .collect::<Vec<_>>() |
| 20257 | .join(" ") |
| 20258 | ); |
| 20259 | // The CfL alpha histogram (lane-av1cfl): one entry per chroma |
| 20260 | // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that |
| 20261 | // only ever fires at one magnitude is a search that never left |
| 20262 | // its first candidate (gate-blind-to-feature). |
| 20263 | // The luma angle-delta histogram (lane-av1cfl): how many |
| 20264 | // directional blocks won at each delta. All-zero would mean the |
| 20265 | // refinement never beat the base angle. |
| 20266 | let deltas = take_angle_delta_hits(); |
| 20267 | if deltas.iter().sum::<usize>() > 0 { |
| 20268 | eprintln!( |
| 20269 | "{name}: angle_delta_y {}", |
| 20270 | deltas |
| 20271 | .iter() |
| 20272 | .enumerate() |
| 20273 | .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3)) |
| 20274 | .collect::<Vec<_>>() |
| 20275 | .join(" ") |
| 20276 | ); |
| 20277 | } |
| 20278 | let alphas = take_cfl_alpha_hits(); |
| 20279 | if alphas.iter().sum::<usize>() > 0 { |
| 20280 | eprintln!( |
| 20281 | "{name}: cfl |alpha| {}", |
| 20282 | alphas |
| 20283 | .iter() |
| 20284 | .enumerate() |
| 20285 | .filter(|&(_, &n)| n > 0) |
| 20286 | .map(|(a, &n)| format!("{a}={n}")) |
| 20287 | .collect::<Vec<_>>() |
| 20288 | .join(" ") |
| 20289 | ); |
| 20290 | } |
| 20291 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 20292 | eprintln!( |
| 20293 | "{name}: chroma palette blocks {} sizes {}", |
| 20294 | palette_uv[0], |
| 20295 | (2..=8) |
| 20296 | .filter(|&n| palette_uv[n] > 0) |
| 20297 | .map(|n| format!("{n}={}", palette_uv[n])) |
| 20298 | .collect::<Vec<_>>() |
| 20299 | .join(" ") |
| 20300 | ); |
| 20301 | let uv = take_uv_mode_hits(); |
| 20302 | let uv_total: usize = uv.iter().sum(); |
| 20303 | eprintln!( |
| 20304 | "{name}: uv modes {}", |
| 20305 | uv.iter() |
| 20306 | .enumerate() |
| 20307 | .filter(|&(_, &n)| n > 0) |
| 20308 | .map(|(m, &n)| format!( |
| 20309 | "{}={n} ({:.1}%)", |
| 20310 | UV_MODE_NAMES[m], |
| 20311 | 100.0 * n as f64 / uv_total.max(1) as f64 |
| 20312 | )) |
| 20313 | .collect::<Vec<_>>() |
| 20314 | .join(" ") |
| 20315 | ); |
| 20316 | // Which transform depth the intra blocks of this clip's key |
| 20317 | // frames resolved to (lane-av1tx): depth 0 is one transform over |
| 20318 | // the whole block, 1 and 2 its halvings. |
| 20319 | let depths = take_tx_depth_hits(); |
| 20320 | let depth_total: usize = depths.iter().sum(); |
| 20321 | eprintln!( |
| 20322 | "{name}: intra tx depths {}", |
| 20323 | depths |
| 20324 | .iter() |
| 20325 | .enumerate() |
| 20326 | .map(|(d, &n)| format!( |
| 20327 | "{d}={n} ({:.1}%)", |
| 20328 | 100.0 * n as f64 / depth_total.max(1) as f64 |
| 20329 | )) |
| 20330 | .collect::<Vec<_>>() |
| 20331 | .join(" ") |
| 20332 | ); |
| 20333 | print_inter_tx_census(name); |
| 20334 | // lane-av1obmc: how many blocks actually CODED a motion_mode |
| 20335 | // symbol and which value they took, by footprint -- "OBMC is on" |
| 20336 | // as a measurement rather than a claim (class |
| 20337 | // `gate-blind-to-feature`). |
| 20338 | let mm = crate::tile::take_motion_mode_hits(); |
| 20339 | eprintln!( |
| 20340 | "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \ |
| 20341 | WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \ |
| 20342 | eligible)", |
| 20343 | mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8], |
| 20344 | 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 20345 | 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 20346 | mm.iter().sum::<usize>(), |
| 20347 | ); |
| 20348 | let (aom, aom_wall) = |
| 20349 | external_ladder(&source, width, height, "libaom-av1", &aom_points); |
| 20350 | let (rav1e, rav1e_wall) = |
| 20351 | external_ladder(&source, width, height, "librav1e", &rav1e_points); |
| 20352 | assert_monotone(&format!("{name}: ours"), &ours); |
| 20353 | assert_monotone(&format!("{name}: libaom"), &aom); |
| 20354 | assert_monotone(&format!("{name}: rav1e"), &rav1e); |
| 20355 | let points = ours |
| 20356 | .iter() |
| 20357 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 20358 | .collect::<Vec<_>>() |
| 20359 | .join(", "); |
| 20360 | println!( |
| 20361 | "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", |
| 20362 | bd_rate(&aom, &ours) * 100.0, |
| 20363 | bd_rate(&rav1e, &ours) * 100.0, |
| 20364 | ); |
| 20365 | println!( |
| 20366 | "| references | libaom {} | rav1e {} | | |", |
| 20367 | aom.iter() |
| 20368 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 20369 | .collect::<Vec<_>>() |
| 20370 | .join(", "), |
| 20371 | rav1e |
| 20372 | .iter() |
| 20373 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 20374 | .collect::<Vec<_>>() |
| 20375 | .join(", "), |
| 20376 | ); |
| 20377 | } |
| 20378 | assert_ladder_decodes(); |
| 20379 | } |
| 20380 | /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2, |
| 20381 | /// split by block class in lane-av1txdepth): depth 0 is one transform over |
| 20382 | /// the whole block, 1 its four halves; the classes are the 16x16/8x8 |
| 20383 | /// leaves and the 32x32 root, each single-reference or compound. A class |
| 20384 | /// with no counts at all never reached `commit_inter_luma` -- which is |
| 20385 | /// what its knob being off looks like (class `gate-blind-to-feature`). |
| 20386 | fn print_inter_tx_census(name: &str) { |
| 20387 | let splits = take_inter_tx_split_hits(); |
| 20388 | let total: usize = splits.iter().sum(); |
| 20389 | let row = |label: &str, base: usize| { |
| 20390 | let (n0, n1) = (splits[base], splits[base + 1]); |
| 20391 | format!( |
| 20392 | "{label} 0={n0} 1={n1} ({:.1}% split)", |
| 20393 | 100.0 * n1 as f64 / (n0 + n1).max(1) as f64 |
| 20394 | ) |
| 20395 | }; |
| 20396 | eprintln!( |
| 20397 | "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}", |
| 20398 | row("leaf single", 0), |
| 20399 | row("leaf compound", 2), |
| 20400 | row("32x32 single", 4), |
| 20401 | row("32x32 compound", 6), |
| 20402 | ); |
| 20403 | // lane-txrd: which types the two searches actually COMMITTED over |
| 20404 | // this row's four encodes -- the gate could not say whether a type |
| 20405 | // search fired at all (class `gate-blind-to-feature`). |
| 20406 | const NAMES: [&str; 16] = [ |
| 20407 | "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT", |
| 20408 | "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST", |
| 20409 | "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST", |
| 20410 | ]; |
| 20411 | let name_of = |t: usize| NAMES[t]; |
| 20412 | for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] { |
| 20413 | let total: usize = hits.iter().sum(); |
| 20414 | let live: Vec<String> = hits |
| 20415 | .iter() |
| 20416 | .enumerate() |
| 20417 | .filter(|&(_, &n)| n > 0) |
| 20418 | .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64)) |
| 20419 | .collect(); |
| 20420 | eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" ")); |
| 20421 | } |
| 20422 | let t = take_txrd_stats(); |
| 20423 | if t[0] > 0 { |
| 20424 | eprintln!( |
| 20425 | "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \ |
| 20426 | bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)", |
| 20427 | t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0, |
| 20428 | 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64, |
| 20429 | 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64, |
| 20430 | ); |
| 20431 | eprintln!( |
| 20432 | "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \ |
| 20433 | flat: dsse {:+.2}%, dbits {:+.2}%)", |
| 20434 | t[5], t[6] as f64 / 64.0, |
| 20435 | 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64, |
| 20436 | 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64, |
| 20437 | ); |
| 20438 | } |
| 20439 | } |
| 20440 | |
| 20441 | /// The video stream's coded size, from ffprobe. |
| 20442 | fn probe_dims(clip: &str) -> Option<(usize, usize)> { |
| 20443 | crate::probe::dims(clip) |
| 20444 | } |
| 20445 | |
| 20446 | /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a |
| 20447 | /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s |
| 20448 | /// superblock-aligned one, still centred and still even for 4:2:0. |
| 20449 | /// |
| 20450 | /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide |
| 20451 | /// superblocks by design, so no default gate row has a block the frame |
| 20452 | /// edge cuts through -- while every arbitrary export size does (3840x1608 |
| 20453 | /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP= |
| 20454 | /// 1920x1080` is the straddling arm the edge-clipped distortion score is |
| 20455 | /// read on. |
| 20456 | fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> { |
| 20457 | let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?; |
| 20458 | let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>"); |
| 20459 | let (cw, ch): (usize, usize) = |
| 20460 | (w.parse().expect("crop width"), h.parse().expect("crop height")); |
| 20461 | let (nw, nh) = crate::probe::dims(clip)?; |
| 20462 | assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}"); |
| 20463 | let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 20464 | Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch)) |
| 20465 | } |
| 20466 | |
| 20467 | /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared |
| 20468 | /// with `probe_screen_detect` so the detector sweep measures exactly the |
| 20469 | /// clips the keep table is read off. Selector env vars as documented on |
| 20470 | /// the gate; a missing clip prints a SKIP and drops its row. |
| 20471 | fn native_gate_clips() -> Vec<(String, String, String)> { |
| 20472 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 20473 | let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1"); |
| 20474 | let (film, film4k, screen) = ( |
| 20475 | on("EC_AV1_NATIVE_FILM"), |
| 20476 | on("EC_AV1_NATIVE_FILM4K"), |
| 20477 | on("EC_AV1_NATIVE_SCREEN"), |
| 20478 | ); |
| 20479 | // No selector at all means every clip; any selector means that subset. |
| 20480 | let all = !(film || film4k || screen); |
| 20481 | // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS, |
| 20482 | // not film -- they print as "bars" so no reader takes them for real |
| 20483 | // content -- and the two rows below them are the real AV1 films. |
| 20484 | let mut clips: Vec<(String, String, String)> = Vec::new(); |
| 20485 | for (want, label, file) in [ |
| 20486 | (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"), |
| 20487 | (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"), |
| 20488 | ] { |
| 20489 | if !want { |
| 20490 | continue; |
| 20491 | } |
| 20492 | let path = fixtures.join("video").join(file); |
| 20493 | match path.exists() { |
| 20494 | true => { |
| 20495 | clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into())) |
| 20496 | } |
| 20497 | false => eprintln!("SKIP {label}: {file} missing"), |
| 20498 | } |
| 20499 | } |
| 20500 | let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")); |
| 20501 | // The real films, taken out of the real-library manifest by codec and |
| 20502 | // coded width so no title and no home path lives in this file. Each |
| 20503 | // seek is PINNED (class `seeded fixture not reproducible`) at a |
| 20504 | // moving, non-black window -- a black leader would make every arm |
| 20505 | // read +0.000 (class `flat sample window`). Both sources are 10-bit |
| 20506 | // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is |
| 20507 | // what all three encoders see, so the comparison stays |
| 20508 | // encoder-vs-encoder. |
| 20509 | let pick = |width: &str| -> Option<String> { |
| 20510 | let m = manifest.as_ref().ok()?; |
| 20511 | m.lines() |
| 20512 | .skip(1) |
| 20513 | .map(|l| l.split('\t').collect::<Vec<_>>()) |
| 20514 | .find(|f| { |
| 20515 | f.len() > 4 |
| 20516 | && f[2] == "av1" |
| 20517 | && f[3] == width |
| 20518 | && std::path::Path::new(f[0]).exists() |
| 20519 | }) |
| 20520 | .map(|f| f[0].to_string()) |
| 20521 | }; |
| 20522 | for (want, label, width, seek) in [ |
| 20523 | (all || film, "film A (1080p source)", "1920", "00:35:00"), |
| 20524 | (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"), |
| 20525 | ] { |
| 20526 | if !want { |
| 20527 | continue; |
| 20528 | } |
| 20529 | match pick(width) { |
| 20530 | Some(path) => clips.push((label.to_string(), path, seek.to_string())), |
| 20531 | None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"), |
| 20532 | } |
| 20533 | } |
| 20534 | if all || screen { |
| 20535 | match &manifest { |
| 20536 | Ok(manifest) => match manifest |
| 20537 | .lines() |
| 20538 | .skip(1) |
| 20539 | .filter_map(|l| l.split('\t').next()) |
| 20540 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 20541 | { |
| 20542 | Some(p) => clips.push(( |
| 20543 | format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), |
| 20544 | p.to_string(), |
| 20545 | "0".into(), |
| 20546 | )), |
| 20547 | None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), |
| 20548 | }, |
| 20549 | Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"), |
| 20550 | } |
| 20551 | } |
| 20552 | clips |
| 20553 | } |
| 20554 | |
| 20555 | /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate |
| 20556 | /// downscales the OBS capture to 640x384, which destroys exactly the |
| 20557 | /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist |
| 20558 | /// for (class `gate-recipe-confound`), so every screen-tool decision taken |
| 20559 | /// on that recipe is taken on content the tool cannot serve. This arm |
| 20560 | /// crops -- never scales -- a superblock-aligned window out of the middle |
| 20561 | /// of the capture at its own resolution (at most 1920x1024, so the wall |
| 20562 | /// stays in the minutes) and runs the same 12-frame, four-quantizer |
| 20563 | /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one |
| 20564 | /// thread, with the same three-way (encoder / ffmpeg / our decoder) |
| 20565 | /// sample-exactness assertion `our_ladder` makes. |
| 20566 | /// |
| 20567 | /// It is its own `--ignored` test so the default gate's wall does not |
| 20568 | /// grow. Every variant is an environment knob, and each of those is a |
| 20569 | /// `OnceLock` read once per process, so a variant is a separate run: |
| 20570 | /// |
| 20571 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 20572 | /// bd_rate_screen_native --nocapture # baseline |
| 20573 | /// EC_AV1_INTRABC=1 ... same command # intra block copy |
| 20574 | /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound |
| 20575 | /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles |
| 20576 | /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid |
| 20577 | /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing |
| 20578 | /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm |
| 20579 | /// |
| 20580 | /// The coding pyramid is the DEFAULT of the sequence path this arm codes |
| 20581 | /// through (lane-av1pyrdef); the run prints the requested and the |
| 20582 | /// effective pyramid per clip, and a screen clip's effective one is |
| 20583 | /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the |
| 20584 | /// streaming facade instead, which prints the per-level frame and byte |
| 20585 | /// census and asserts ffmpeg's decode against our own decoder on all |
| 20586 | /// three planes in display order; both arms code the same bytes |
| 20587 | /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`). |
| 20588 | /// |
| 20589 | /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are |
| 20590 | /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg |
| 20591 | /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra |
| 20592 | /// cost -- so every "film" column in the historical tables of this file |
| 20593 | /// is that generator, not film. The real content is `film A`, `film B` |
| 20594 | /// (native crops out of the two AV1 films the real-library manifest |
| 20595 | /// names, at a pinned seek; added 2026-09-07) and the screen capture. A |
| 20596 | /// decision only the bars rows support is not supported. |
| 20597 | /// |
| 20598 | /// Measured 2026-09-07, the five rows before and after the screen |
| 20599 | /// detector grew libaom's variance term ([`screen_var`]) -- before it, |
| 20600 | /// BOTH real films were classified as screen content on 48/48 frames, so |
| 20601 | /// their coefficients were priced against the DEFAULT CDFs and the |
| 20602 | /// palette search ran over film; after, both are non-screen (0/48) and |
| 20603 | /// the capture is unchanged at 48/48: |
| 20604 | /// |
| 20605 | /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours | |
| 20606 | /// |---|---|---|---| |
| 20607 | /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s | |
| 20608 | /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s | |
| 20609 | /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s | |
| 20610 | /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s | |
| 20611 | /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s | |
| 20612 | /// |
| 20613 | /// Both bars rows and the capture are byte-identical across that change |
| 20614 | /// (their classification never moved); the palette search over film was |
| 20615 | /// costing roughly a tenth of the film rows' wall. |
| 20616 | /// |
| 20617 | /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the |
| 20618 | /// sequence path's default -- the four non-screen rows take `4:-16:8`, |
| 20619 | /// the capture is gated flat and does not move a byte: |
| 20620 | /// |
| 20621 | /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e | |
| 20622 | /// |---|---|---|---|---| |
| 20623 | /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s | |
| 20624 | /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s | |
| 20625 | /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s | |
| 20626 | /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s | |
| 20627 | /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s | |
| 20628 | /// |
| 20629 | /// Every row lands on lane-av1pyrgate's facade-arm number to the digit, |
| 20630 | /// which is the point of the shared driver: the two entry points code one |
| 20631 | /// stream. The bars rows are fixtures (recorded, never a decision); the |
| 20632 | /// two real films are what the pyramid ships for. |
| 20633 | /// |
| 20634 | /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`, |
| 20635 | /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset: |
| 20636 | /// setting any one of them keeps only the selected rows (the two 1080p |
| 20637 | /// rows, the two 2160p rows, the capture row respectively). A missing |
| 20638 | /// real film SKIPs its row; it never fails the gate. |
| 20639 | #[test] |
| 20640 | #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"] |
| 20641 | fn bd_rate_screen_native() { |
| 20642 | let _knobs = crate::speed::knob_read(); |
| 20643 | native_bd_arm("bd_rate_screen_native", 12, false); |
| 20644 | } |
| 20645 | |
| 20646 | /// The LONG-GOP arm of the native BD gate: the same recipe as |
| 20647 | /// [`bd_rate_screen_native`] over the two real film rows only, but 48 |
| 20648 | /// pictures with `gop = 48` (`encode_sequence` sets `gop = |
| 20649 | /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which |
| 20650 | /// reaches libaom as `--kf-max-dist=48` and rav1e as |
| 20651 | /// `key_frame_interval=48`), so every encoder sees one key frame and 47 |
| 20652 | /// inter pictures. |
| 20653 | /// |
| 20654 | /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop = |
| 20655 | /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key |
| 20656 | /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`] |
| 20657 | /// above 12 codes the same stream there -- the shipped `16` was measured |
| 20658 | /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture |
| 20659 | /// group (class `instrument at bound` / `gate blind to feature`). The |
| 20660 | /// user's exports are long GOPs, so the pyramid shape is decided here. |
| 20661 | /// |
| 20662 | /// cargo test -p ec-av1 --release --lib -- --ignored \ |
| 20663 | /// bd_rate_film_long_gop --nocapture |
| 20664 | /// |
| 20665 | /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1` |
| 20666 | /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape. |
| 20667 | /// Read every row off the log's own "pyramid requested/effective" print, |
| 20668 | /// never off the argument order of the runs (lane-pyr3 misattributed |
| 20669 | /// three rows that way). |
| 20670 | /// |
| 20671 | /// Table: `lanes/pyr4.sweep.txt`. |
| 20672 | #[test] |
| 20673 | #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"] |
| 20674 | fn bd_rate_film_long_gop() { |
| 20675 | let _knobs = crate::speed::knob_write(); |
| 20676 | native_bd_arm("bd_rate_film_long_gop", 48, true); |
| 20677 | } |
| 20678 | |
| 20679 | /// The shared driver of the two native BD arms above: `frames` pictures |
| 20680 | /// per row (the sequence's `gop` is the same number, so one key frame), |
| 20681 | /// four quantizers, `films_only` dropping every row but the two real |
| 20682 | /// films. |
| 20683 | fn native_bd_arm(label: &str, frames: usize, films_only: bool) { |
| 20684 | if !have_ffmpeg() { |
| 20685 | eprintln!("SKIP {label}: no ffmpeg"); |
| 20686 | return; |
| 20687 | } |
| 20688 | let mut clips = native_gate_clips(); |
| 20689 | if films_only { |
| 20690 | clips.retain(|(name, _, _)| name.starts_with("film ")); |
| 20691 | } |
| 20692 | if clips.is_empty() { |
| 20693 | eprintln!("SKIP {label}: no clip"); |
| 20694 | return; |
| 20695 | } |
| 20696 | |
| 20697 | let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] |
| 20698 | .iter() |
| 20699 | .map(|q| { |
| 20700 | ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] |
| 20701 | .map(String::from) |
| 20702 | .to_vec() |
| 20703 | }) |
| 20704 | .collect(); |
| 20705 | let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] |
| 20706 | .iter() |
| 20707 | .map(|q| { |
| 20708 | vec![ |
| 20709 | "-rav1e-params".to_string(), |
| 20710 | format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), |
| 20711 | ] |
| 20712 | }) |
| 20713 | .collect(); |
| 20714 | println!( |
| 20715 | "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \ |
| 20716 | intrabc {}, palette maxcolors {}", |
| 20717 | armed_tiles(), |
| 20718 | crate::par::tile_threads(), |
| 20719 | intrabc_enabled(), |
| 20720 | palette_max_colors(), |
| 20721 | ); |
| 20722 | println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |"); |
| 20723 | println!("|---|---|---|---|---|"); |
| 20724 | for (name, path, seek) in &clips { |
| 20725 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 20726 | if probe_dims(path).is_none() { |
| 20727 | eprintln!("SKIP {name}: ffprobe gave no size"); |
| 20728 | continue; |
| 20729 | } |
| 20730 | // A whole number of 128-wide superblocks, at most 1920x1024, out |
| 20731 | // of the middle of the frame; the offsets stay even for 4:2:0. |
| 20732 | // ONE definition, shared with `examples/enc_probe` so the probe |
| 20733 | // cannot measure a different window than this gate (lane-probe). |
| 20734 | let (vf, cw, ch) = match native_crop_override(path) { |
| 20735 | Some(over) => over, |
| 20736 | None => crate::probe::gate_crop(path), |
| 20737 | }; |
| 20738 | let source = clip_frames_vf(path, seek, &vf, cw, ch, frames); |
| 20739 | SCREEN_FRAMES.iter().for_each(|c| { |
| 20740 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 20741 | }); |
| 20742 | let _ = crate::tile::take_palette_hits(); |
| 20743 | let _ = crate::tile::take_palette_uv_hits(); |
| 20744 | let _ = crate::tile::take_intrabc_hits(); |
| 20745 | let _ = take_intrabc_search(); |
| 20746 | let _ = crate::tile::take_filter_intra_hits(); |
| 20747 | let _ = take_edge_census(); |
| 20748 | // The sequence path itself codes the pyramid now |
| 20749 | // (lane-av1pyrdef), and prints what it requested and what the |
| 20750 | // content gate left effective. |
| 20751 | let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx); |
| 20752 | // lane-sse: the blocks the true frame edge cuts through, and how |
| 20753 | // much of their RAW squared error sat in the padding the encoder |
| 20754 | // invented past it -- what the inside-only score stopped ranking |
| 20755 | // on. Empty on a superblock-aligned crop, which is every default |
| 20756 | // gate row (class `gate-blind-to-feature`). |
| 20757 | if edge_census() { |
| 20758 | for (side, n, inside, padding) in take_edge_census() { |
| 20759 | eprintln!( |
| 20760 | "{name}: edge {side}x{side} scores={n} inside_sse={inside} \ |
| 20761 | padding_sse={padding} ({:.1}% of raw)", |
| 20762 | 100.0 * padding as f64 / (inside + padding).max(1) as f64, |
| 20763 | ); |
| 20764 | } |
| 20765 | } |
| 20766 | // gate-blind-to-feature: what the screen tools actually did at |
| 20767 | // native resolution, over this clip's four encodes. |
| 20768 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 20769 | let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); |
| 20770 | // Which tables the SEARCH priced against, per frame arming |
| 20771 | // (`tile::arm_pricing_cdfs`): the default tables or the frame's |
| 20772 | // real starting ones. A film clip must show every inter arming on |
| 20773 | // the real side, a screen clip none of them. |
| 20774 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 20775 | eprintln!("{name}: pricer armings default={price_default} real={price_real}"); |
| 20776 | // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many |
| 20777 | // superblocks stayed whole, and how many of those coded a |
| 20778 | // residual, split that residual's luma, or took a compound |
| 20779 | // reference (class `gate-blind-to-feature`). |
| 20780 | // lane-i64: the KEY frame's own 64x64 intra root -- how many of |
| 20781 | // the superblocks offered the trial were coded whole. |
| 20782 | let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits(); |
| 20783 | eprintln!( |
| 20784 | "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \ |
| 20785 | {i64_edge} on a superblock the frame edge cuts", |
| 20786 | 100.0 * i64_whole as f64 / i64_offered.max(1) as f64, |
| 20787 | ); |
| 20788 | eprintln!( |
| 20789 | "{name}: 128x128 roots {} (search) / {} (writer), with a residual \ |
| 20790 | {} (search) / {} (writer); rect/AB pieces with a residual \ |
| 20791 | {} (search) / {} (writer)", |
| 20792 | take_b128_none_hits(), |
| 20793 | crate::tile::take_sb128_none_hits(), |
| 20794 | take_b128_residual_hits(), |
| 20795 | crate::tile::take_sb128_residual_hits(), |
| 20796 | take_b128_rectres_hits(), |
| 20797 | crate::tile::take_sb128_rectres_hits(), |
| 20798 | ); |
| 20799 | eprintln!( |
| 20800 | "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})", |
| 20801 | take_b64_root_hits(), |
| 20802 | take_b64_residual_hits(), |
| 20803 | take_b64_var_tx_hits(), |
| 20804 | take_b64_compound_hits(), |
| 20805 | ); |
| 20806 | // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan |
| 20807 | // of every priced block): what the deadzone quantiser handed the |
| 20808 | // RDOQ pass and what the pass changed, over every TRIAL block of |
| 20809 | // this row's four encodes -- not over the coded stream, so it is |
| 20810 | // the bits AT STAKE in the search, not in the bitstream. |
| 20811 | let rq = crate::tile::take_rdoq_stats(); |
| 20812 | if rq[0] > 0 { |
| 20813 | eprintln!( |
| 20814 | "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \ |
| 20815 | zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)", |
| 20816 | rq[0], |
| 20817 | rq[1], |
| 20818 | 100.0 * rq[2] as f64 / rq[1].max(1) as f64, |
| 20819 | 100.0 * rq[3] as f64 / rq[1].max(1) as f64, |
| 20820 | rq[4], |
| 20821 | rq[5], |
| 20822 | rq[7] as f64 / 64.0, |
| 20823 | rq[6] as f64 / 64.0, |
| 20824 | 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64, |
| 20825 | ); |
| 20826 | } |
| 20827 | // lane-av1obmc2: the same motion_mode census the 640x384 gate |
| 20828 | // prints (class `gate-blind-to-feature`) -- how many blocks coded |
| 20829 | // the symbol at each footprint and how many took OBMC. Without it |
| 20830 | // the native table, which is the standing keep table, could not |
| 20831 | // say whether the tool fired at all. |
| 20832 | let mm = crate::tile::take_motion_mode_hits(); |
| 20833 | eprintln!( |
| 20834 | "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \ |
| 20835 | WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \ |
| 20836 | eligible)", |
| 20837 | mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8], |
| 20838 | 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 20839 | 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64, |
| 20840 | mm.iter().sum::<usize>(), |
| 20841 | ); |
| 20842 | print_inter_tx_census(name); |
| 20843 | // lane-last2 (class `gate-blind-to-feature`): which reference the |
| 20844 | // 32x32-and-below inter blocks of this clip's four encodes chose. |
| 20845 | // The native table is the standing keep table, so a second past |
| 20846 | // reference that never won a block has to be visible HERE and not |
| 20847 | // only in a synthetic witness. |
| 20848 | let rh = crate::encode::take_ref_frame_hits(); |
| 20849 | let rtot: usize = rh.iter().sum(); |
| 20850 | eprintln!( |
| 20851 | "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \ |
| 20852 | (LAST2 {:.1}%)", |
| 20853 | rh[1], rh[2], rh[4], rh[7], rtot, |
| 20854 | 100.0 * rh[2] as f64 / rtot.max(1) as f64, |
| 20855 | ); |
| 20856 | let palette = crate::tile::take_palette_hits(); |
| 20857 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 20858 | let ibc = crate::tile::take_intrabc_hits(); |
| 20859 | let search = take_intrabc_search(); |
| 20860 | eprintln!( |
| 20861 | "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \ |
| 20862 | palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \ |
| 20863 | won {})", |
| 20864 | 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64, |
| 20865 | palette[0], |
| 20866 | palette_uv[0], |
| 20867 | ibc[0], |
| 20868 | search[0], |
| 20869 | search[1], |
| 20870 | search[2], |
| 20871 | ); |
| 20872 | // gate-blind-to-feature: how often the five recursive filter-intra |
| 20873 | // modes actually won a block over this clip's four encodes -- a |
| 20874 | // tool that never fires is not measured by the row above it. |
| 20875 | let fi = crate::tile::take_filter_intra_hits(); |
| 20876 | eprintln!( |
| 20877 | "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})", |
| 20878 | filter_intra_on(), |
| 20879 | fi[0], |
| 20880 | fi[1], |
| 20881 | fi[2], |
| 20882 | fi[3], |
| 20883 | fi[4], |
| 20884 | fi[5], |
| 20885 | ); |
| 20886 | let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points); |
| 20887 | let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points); |
| 20888 | assert_monotone(&format!("{name}: ours"), &ours); |
| 20889 | assert_monotone(&format!("{name}: libaom"), &aom); |
| 20890 | assert_monotone(&format!("{name}: rav1e"), &rav1e); |
| 20891 | let points = ours |
| 20892 | .iter() |
| 20893 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 20894 | .collect::<Vec<_>>() |
| 20895 | .join(", "); |
| 20896 | println!( |
| 20897 | "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", |
| 20898 | bd_rate(&aom, &ours) * 100.0, |
| 20899 | bd_rate(&rav1e, &ours) * 100.0, |
| 20900 | ); |
| 20901 | // lane-pareto2: the two references at THEIR fast presets, plus |
| 20902 | // SVT-AV1, measured in the SAME arm as the row above -- the only |
| 20903 | // way the wall column of a Pareto table means anything (class: |
| 20904 | // wall tables are comparable only inside one interleaved batch). |
| 20905 | // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm. |
| 20906 | if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") { |
| 20907 | let rav1e_at = |sp: u32| -> Vec<Vec<String>> { |
| 20908 | [50, 100, 150, 200] |
| 20909 | .iter() |
| 20910 | .map(|q| { |
| 20911 | vec![ |
| 20912 | "-rav1e-params".to_string(), |
| 20913 | format!( |
| 20914 | "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1" |
| 20915 | ), |
| 20916 | ] |
| 20917 | }) |
| 20918 | .collect() |
| 20919 | }; |
| 20920 | let aom_at = |cu: u32| -> Vec<Vec<String>> { |
| 20921 | [5, 20, 35, 45] |
| 20922 | .iter() |
| 20923 | .map(|q| { |
| 20924 | vec![ |
| 20925 | "-cpu-used".to_string(), |
| 20926 | cu.to_string(), |
| 20927 | "-b:v".to_string(), |
| 20928 | "0".to_string(), |
| 20929 | "-crf".to_string(), |
| 20930 | q.to_string(), |
| 20931 | ] |
| 20932 | }) |
| 20933 | .collect() |
| 20934 | }; |
| 20935 | let svt_at = |pr: u32| -> Vec<Vec<String>> { |
| 20936 | [20, 35, 45, 55] |
| 20937 | .iter() |
| 20938 | .map(|q| { |
| 20939 | vec![ |
| 20940 | "-preset".to_string(), |
| 20941 | pr.to_string(), |
| 20942 | "-crf".to_string(), |
| 20943 | q.to_string(), |
| 20944 | "-svtav1-params".to_string(), |
| 20945 | "lp=1".to_string(), |
| 20946 | ] |
| 20947 | }) |
| 20948 | .collect() |
| 20949 | }; |
| 20950 | let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![ |
| 20951 | ("rav1e speed 8".into(), "librav1e", rav1e_at(8)), |
| 20952 | ("rav1e speed 10".into(), "librav1e", rav1e_at(10)), |
| 20953 | ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)), |
| 20954 | ]; |
| 20955 | if have_encoder("libsvtav1") { |
| 20956 | arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8))); |
| 20957 | arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10))); |
| 20958 | } else { |
| 20959 | eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1"); |
| 20960 | } |
| 20961 | for (label, encoder, points) in arms { |
| 20962 | let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points); |
| 20963 | // A REFERENCE stream our decoder cannot read is a note in |
| 20964 | // this table, not a gate failure: these rows exist to |
| 20965 | // price the references, and `assert_ladder_decodes` keeps |
| 20966 | // its teeth for the two ladders the keep table is read off. |
| 20967 | let notes = |
| 20968 | std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures")); |
| 20969 | if !notes.is_empty() { |
| 20970 | eprintln!("{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)", notes.len()); |
| 20971 | } |
| 20972 | assert_monotone(&format!("{name}: {label}"), &lad); |
| 20973 | println!( |
| 20974 | "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |", |
| 20975 | bd_rate(&aom, &lad) * 100.0, |
| 20976 | bd_rate(&rav1e, &lad) * 100.0, |
| 20977 | ); |
| 20978 | } |
| 20979 | } |
| 20980 | } |
| 20981 | assert_ladder_decodes(); |
| 20982 | } |
| 20983 | |
| 20984 | /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator |
| 20985 | /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC) |
| 20986 | /// on the two film clips at their native gate crop. The 2160p clip loses |
| 20987 | /// at every arm of the propagating map and the named suspect was that its |
| 20988 | /// heavily filtered flat cells give a tiny denominator, so the dependence |
| 20989 | /// ratio explodes exactly where coding is cheap; this prints the numbers |
| 20990 | /// that confirm or refute it. |
| 20991 | #[test] |
| 20992 | #[ignore = "needs ffmpeg and the film fixtures"] |
| 20993 | fn tpl_intra_denominator_histogram() { |
| 20994 | let _knobs = crate::speed::knob_read(); |
| 20995 | if !have_ffmpeg() { |
| 20996 | eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg"); |
| 20997 | return; |
| 20998 | } |
| 20999 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 21000 | for (label, file) in [ |
| 21001 | ("bars 1080p", "h264-1080p-23.976-8bit.mp4"), |
| 21002 | ("bars 2160p", "h264-2160p-23.976-8bit.mp4"), |
| 21003 | ] { |
| 21004 | let path = fixtures.join("video").join(file); |
| 21005 | if !path.exists() { |
| 21006 | eprintln!("SKIP {label}: {file} missing"); |
| 21007 | continue; |
| 21008 | } |
| 21009 | let path = path.to_str().unwrap(); |
| 21010 | let Some((nw, nh)) = probe_dims(path) else { |
| 21011 | eprintln!("SKIP {label}: ffprobe gave no size"); |
| 21012 | continue; |
| 21013 | }; |
| 21014 | let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128); |
| 21015 | let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); |
| 21016 | let source = |
| 21017 | clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8); |
| 21018 | let mut costs: Vec<f64> = Vec::new(); |
| 21019 | for pic in &source { |
| 21020 | let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect(); |
| 21021 | costs.extend( |
| 21022 | super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)), |
| 21023 | ); |
| 21024 | } |
| 21025 | let mean = costs.iter().sum::<f64>() / costs.len() as f64; |
| 21026 | let mut sorted = costs.clone(); |
| 21027 | sorted.sort_by(f64::total_cmp); |
| 21028 | let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean; |
| 21029 | let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count(); |
| 21030 | eprintln!( |
| 21031 | "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \ |
| 21032 | as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \ |
| 21033 | p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \ |
| 21034 | below 1.0x {} ({:.1}%)", |
| 21035 | costs.len(), |
| 21036 | q(0.0), |
| 21037 | q(0.01), |
| 21038 | q(0.05), |
| 21039 | q(0.25), |
| 21040 | q(0.50), |
| 21041 | q(0.75), |
| 21042 | q(0.99), |
| 21043 | q(1.0), |
| 21044 | below(0.25), |
| 21045 | 100.0 * below(0.25) as f64 / costs.len() as f64, |
| 21046 | below(0.5), |
| 21047 | 100.0 * below(0.5) as f64 / costs.len() as f64, |
| 21048 | below(1.0), |
| 21049 | 100.0 * below(1.0) as f64 / costs.len() as f64, |
| 21050 | ); |
| 21051 | } |
| 21052 | } |
| 21053 | |
| 21054 | /// The probe arms the gate's source (lane-probe, class `instrument |
| 21055 | /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg |
| 21056 | /// command line and had no `-ss`, so it read film B from frame 0 -- a |
| 21057 | /// black leader -- and coded 59 kB where the gate's own ladder point |
| 21058 | /// coded 89 kB of the same title; every census taken through it was |
| 21059 | /// probe-relative. Both now call [`crate::probe::source`]; this pins that |
| 21060 | /// the shared loader honours the seek (arming the probe's way and the |
| 21061 | /// gate's way gives byte-identical streams, and dropping the seek does |
| 21062 | /// not), on a synthetic clip whose content moves over time. |
| 21063 | #[test] |
| 21064 | fn the_probe_arms_the_gates_source() { |
| 21065 | let _knobs = crate::speed::knob_write(); |
| 21066 | if !have_ffmpeg() { |
| 21067 | eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg"); |
| 21068 | return; |
| 21069 | } |
| 21070 | let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id())); |
| 21071 | std::fs::create_dir_all(&dir).unwrap(); |
| 21072 | let clip = dir.join("testsrc2.y4m"); |
| 21073 | // 384x202: neither side is a multiple of 128, so the gate's centre |
| 21074 | // window is a real derivation and not the frame itself -- exactly the |
| 21075 | // shape film B has (3840x1608, never 3840x2160). |
| 21076 | let ok = Command::new("ffmpeg") |
| 21077 | .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"]) |
| 21078 | .args(["-frames:v", "20", "-pix_fmt", "yuv420p"]) |
| 21079 | .arg(&clip) |
| 21080 | .status() |
| 21081 | .expect("ffmpeg failed to run") |
| 21082 | .success(); |
| 21083 | assert!(ok, "ffmpeg could not write the synthetic clip"); |
| 21084 | let path = clip.to_str().unwrap(); |
| 21085 | |
| 21086 | // The window: superblock-aligned, centred, even offsets. |
| 21087 | let (vf, w, h) = crate::probe::gate_crop(path); |
| 21088 | assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128)); |
| 21089 | |
| 21090 | let (seek, q) = ("00:00:01", 150u8); |
| 21091 | let gate = clip_frames_vf(path, seek, &vf, w, h, 6); |
| 21092 | let probe = crate::probe::source(path, seek, &vf, w, h, 6); |
| 21093 | assert!( |
| 21094 | gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v), |
| 21095 | "the probe's source differs from the gate's at the same window" |
| 21096 | ); |
| 21097 | let bytes = |src: &[Picture]| { |
| 21098 | encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder()) |
| 21099 | .unwrap() |
| 21100 | .stream |
| 21101 | }; |
| 21102 | assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes"); |
| 21103 | // The two witnesses that both halves of the arming reach ffmpeg: the |
| 21104 | // seek, and the crop's own offset (the film-B defect in miniature -- |
| 21105 | // the probe was reading `crop=..:568` of a 1608-high frame). |
| 21106 | let unseeked = crate::probe::source(path, "0", &vf, w, h, 6); |
| 21107 | assert_ne!( |
| 21108 | bytes(&gate), |
| 21109 | bytes(&unseeked), |
| 21110 | "seeked and unseeked arming coded the same bytes -- the seek is inert" |
| 21111 | ); |
| 21112 | let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6); |
| 21113 | assert_ne!( |
| 21114 | bytes(&gate), |
| 21115 | bytes(&offset), |
| 21116 | "centred and top-aligned windows coded the same bytes -- the crop is inert" |
| 21117 | ); |
| 21118 | std::fs::remove_dir_all(&dir).ok(); |
| 21119 | } |
| 21120 | |
| 21121 | /// lane-probe diagnostic: the gate's own loader + ladder call for ONE |
| 21122 | /// point inside the test binary, to compare against `examples/enc_probe`. |
| 21123 | #[test] |
| 21124 | #[ignore = "diagnostic: needs ffmpeg and a clip"] |
| 21125 | fn probe_parity_point() { |
| 21126 | let _knobs = crate::speed::knob_write(); |
| 21127 | let g = |k: &str| std::env::var(k).unwrap(); |
| 21128 | let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap(); |
| 21129 | let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap(); |
| 21130 | let q: u8 = g("EC_PARITY_Q").parse().unwrap(); |
| 21131 | let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames); |
| 21132 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 21133 | let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); |
| 21134 | let mut hash: u64 = 0xcbf2_9ce4_8422_2325; |
| 21135 | for &b in &e.stream { |
| 21136 | hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); |
| 21137 | } |
| 21138 | eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}", |
| 21139 | e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid()); |
| 21140 | } |
| 21141 | /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The |
| 21142 | /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`): |
| 21143 | /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in |
| 21144 | /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32 |
| 21145 | /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags |
| 21146 | /// the census's far row measures were already banked by `arf_altref`. |
| 21147 | /// This census stays the PRICING arm (class `gate-blind-to-feature`): its |
| 21148 | /// best-of-two SAD shares are read against the fire share the gate census |
| 21149 | /// prints (`references ... LAST2 n (n%)`) and the refutation in |
| 21150 | /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the |
| 21151 | /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off |
| 21152 | /// `LAST`, the backward `ALTREF`, and the rate term price in. |
| 21153 | /// |
| 21154 | /// The measurement is on the gate's own window and loader (`gate_crop`, |
| 21155 | /// 12 pictures) of the two real films: every 16x16 luma block of every |
| 21156 | /// picture gets one full-pel diamond search against the NEAR reference |
| 21157 | /// and the same search against the FAR one, at the two lags the pyramid |
| 21158 | /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF |
| 21159 | /// level, rav1e's own pair. Reported per lag: the share of blocks the far |
| 21160 | /// reference wins at all and by more than 10%, and -- the number the |
| 21161 | /// decision is taken on -- the total SAD of best-of-{near, far} against |
| 21162 | /// the total SAD of near alone, which is the prediction energy a second |
| 21163 | /// reference could remove before any rate is paid for naming it. |
| 21164 | /// |
| 21165 | /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture |
| 21166 | #[test] |
| 21167 | #[ignore = "reads the real films"] |
| 21168 | fn last2_census() { |
| 21169 | if !have_ffmpeg() { |
| 21170 | eprintln!("SKIP last2_census: no ffmpeg"); |
| 21171 | return; |
| 21172 | } |
| 21173 | const SIDE: usize = 16; |
| 21174 | // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or |
| 21175 | // `None` when the displaced block leaves the picture. |
| 21176 | let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { |
| 21177 | let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); |
| 21178 | if sy < 0 || sx < 0 { |
| 21179 | return None; |
| 21180 | } |
| 21181 | let (sy, sx) = (sy as usize, sx as usize); |
| 21182 | if sy + SIDE > r.height || sx + SIDE > r.width { |
| 21183 | return None; |
| 21184 | } |
| 21185 | let mut acc = 0u64; |
| 21186 | for row in 0..SIDE { |
| 21187 | let c = &cur.y[(by + row) * cur.width + bx..][..SIDE]; |
| 21188 | let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; |
| 21189 | acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>(); |
| 21190 | } |
| 21191 | Some(acc) |
| 21192 | }; |
| 21193 | // A log-step diamond from the zero motion vector: the cheapest search |
| 21194 | // that still finds real pans. Both references get exactly this one, |
| 21195 | // so the comparison is search-fair. |
| 21196 | let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 { |
| 21197 | let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize)); |
| 21198 | let mut step = 16isize; |
| 21199 | while step >= 1 { |
| 21200 | let centre = best.1; |
| 21201 | for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] { |
| 21202 | let mv = (centre.0 + dy * step, centre.1 + dx * step); |
| 21203 | if let Some(s) = sad(cur, r, bx, by, mv) { |
| 21204 | if s < best.0 { |
| 21205 | best = (s, mv); |
| 21206 | } |
| 21207 | } |
| 21208 | } |
| 21209 | step /= 2; |
| 21210 | } |
| 21211 | best.0 |
| 21212 | }; |
| 21213 | println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |"); |
| 21214 | println!("|---|---|---|---|---|---|---|---|"); |
| 21215 | for (name, path, seek) in native_gate_clips() { |
| 21216 | if !name.starts_with("film ") { |
| 21217 | continue; |
| 21218 | } |
| 21219 | let (vf, cw, ch) = crate::probe::gate_crop(&path); |
| 21220 | let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12); |
| 21221 | for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] { |
| 21222 | let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64); |
| 21223 | let (mut near_sad, mut best_sad) = (0u64, 0u64); |
| 21224 | for i in far..pictures.len() { |
| 21225 | let cur = &pictures[i]; |
| 21226 | let (rn, rf) = (&pictures[i - near], &pictures[i - far]); |
| 21227 | for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) { |
| 21228 | for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) { |
| 21229 | let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by)); |
| 21230 | blocks += 1; |
| 21231 | wins += u64::from(f < n); |
| 21232 | big += u64::from(f as f64 * 1.1 < n as f64); |
| 21233 | near_sad += n; |
| 21234 | best_sad += n.min(f); |
| 21235 | } |
| 21236 | } |
| 21237 | } |
| 21238 | let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64; |
| 21239 | println!( |
| 21240 | "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |", |
| 21241 | pct(wins), |
| 21242 | pct(big), |
| 21243 | 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64, |
| 21244 | ); |
| 21245 | } |
| 21246 | } |
| 21247 | } |
| 21248 | |
| 21249 | /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a |
| 21250 | /// temporal filter of its SOURCE would take off it, priced before any |
| 21251 | /// encoder change (class `gate-blind-to-feature`). |
| 21252 | /// |
| 21253 | /// The stream census says our top ARF costs 6992 B a frame against |
| 21254 | /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture |
| 21255 | /// quality, and that 61% of the gap is residual, not syntax. Two |
| 21256 | /// explanations are separable here without an encoder: our anchor |
| 21257 | /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and |
| 21258 | /// the residual it codes at that lag is dominated by film grain, which no |
| 21259 | /// motion search can predict (source noise). So, per ARF position of the |
| 21260 | /// gate's own 48-picture window: |
| 21261 | /// |
| 21262 | /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's), |
| 21263 | /// * the same at lag 8 with the CURRENT picture temporally filtered -- |
| 21264 | /// a libaom-shaped motion-compensated average of the +-2 display |
| 21265 | /// neighbours, weights `exp(-mse / strength)` -- which is the residual |
| 21266 | /// energy an ARF temporal filter would remove, and |
| 21267 | /// * PSNR of that filtered picture against the unfiltered one, the |
| 21268 | /// CEILING the filtered ARF's own PSNR is then measured under (the |
| 21269 | /// BD gate scores against the unfiltered source). |
| 21270 | /// |
| 21271 | /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \ |
| 21272 | /// --ignored arf_pred_census --nocapture |
| 21273 | #[test] |
| 21274 | #[ignore = "reads the real films"] |
| 21275 | fn arf_pred_census() { |
| 21276 | if !have_ffmpeg() { |
| 21277 | eprintln!("SKIP arf_pred_census: no ffmpeg"); |
| 21278 | return; |
| 21279 | } |
| 21280 | const SIDE: usize = 16; |
| 21281 | let strength: f64 = std::env::var("EC_ARF_TF_S") |
| 21282 | .ok() |
| 21283 | .and_then(|v| v.parse().ok()) |
| 21284 | .unwrap_or(30.0); |
| 21285 | let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1"); |
| 21286 | // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None` |
| 21287 | // when the displaced block leaves the picture. |
| 21288 | let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { |
| 21289 | let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); |
| 21290 | if sy < 0 || sx < 0 { |
| 21291 | return None; |
| 21292 | } |
| 21293 | let (sy, sx) = (sy as usize, sx as usize); |
| 21294 | if sy + SIDE > r.height || sx + SIDE > r.width { |
| 21295 | return None; |
| 21296 | } |
| 21297 | let mut acc = 0u64; |
| 21298 | for row in 0..SIDE { |
| 21299 | let c = &cur[row * cw..][..SIDE]; |
| 21300 | let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; |
| 21301 | acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>(); |
| 21302 | } |
| 21303 | Some((acc, (sy, sx))) |
| 21304 | }; |
| 21305 | // The same log-step diamond `last2_census` uses, so the two censuses' |
| 21306 | // SADs are comparable. |
| 21307 | let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| { |
| 21308 | let mut best = match at(cur, cw, r, bx, by, (0, 0)) { |
| 21309 | Some(v) => v, |
| 21310 | None => return (u64::MAX, (by, bx)), |
| 21311 | }; |
| 21312 | let mut centre = (0isize, 0isize); |
| 21313 | let mut step = 16isize; |
| 21314 | while step >= 1 { |
| 21315 | let from = centre; |
| 21316 | for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] { |
| 21317 | let mv = (from.0 + dy * step, from.1 + dx * step); |
| 21318 | if let Some(s) = at(cur, cw, r, bx, by, mv) { |
| 21319 | if s.0 < best.0 { |
| 21320 | best = s; |
| 21321 | centre = mv; |
| 21322 | } |
| 21323 | } |
| 21324 | } |
| 21325 | step /= 2; |
| 21326 | } |
| 21327 | best |
| 21328 | }; |
| 21329 | println!( |
| 21330 | "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |" |
| 21331 | ); |
| 21332 | println!("|---|---|---|---|---|---|---|"); |
| 21333 | for (name, path, seek) in native_gate_clips() { |
| 21334 | if !name.starts_with("film ") { |
| 21335 | continue; |
| 21336 | } |
| 21337 | let (vf, cw, ch) = crate::probe::gate_crop(&path); |
| 21338 | let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48); |
| 21339 | let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize); |
| 21340 | let (mut tf_sse, mut tf_px) = (0f64, 0u64); |
| 21341 | for i in (8..pictures.len()).step_by(8) { |
| 21342 | arfs += 1; |
| 21343 | let cur = &pictures[i]; |
| 21344 | for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) { |
| 21345 | for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) { |
| 21346 | let block: Vec<u16> = (0..SIDE) |
| 21347 | .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec()) |
| 21348 | .collect(); |
| 21349 | n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0; |
| 21350 | n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0; |
| 21351 | // The temporal filter: each +-2 display neighbour is |
| 21352 | // motion-compensated onto this block and averaged in |
| 21353 | // with libaom's shape, a weight that falls with the |
| 21354 | // match's own mean squared error. |
| 21355 | let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect(); |
| 21356 | let mut wsum = 1.0f64; |
| 21357 | // `EC_ARF_TF_PAST=1` restricts the filter to the |
| 21358 | // DISPLAY-PAST neighbours -- the only ones the |
| 21359 | // encoder's own group buffer holds when it codes its |
| 21360 | // top ARF (the group's future is not buffered yet). |
| 21361 | let offs: &[isize] = match past { |
| 21362 | true => &[-2, -1], |
| 21363 | false => &[-2, -1, 1, 2], |
| 21364 | }; |
| 21365 | for &d in offs { |
| 21366 | let j = i as isize + d; |
| 21367 | let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j)) |
| 21368 | else { |
| 21369 | continue; |
| 21370 | }; |
| 21371 | let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by); |
| 21372 | let mut sse = 0f64; |
| 21373 | for row in 0..SIDE { |
| 21374 | for col in 0..SIDE { |
| 21375 | let d = f64::from(block[row * SIDE + col]) |
| 21376 | - f64::from(nb.y[(sy + row) * nb.width + sx + col]); |
| 21377 | sse += d * d; |
| 21378 | } |
| 21379 | } |
| 21380 | let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp(); |
| 21381 | for row in 0..SIDE { |
| 21382 | for col in 0..SIDE { |
| 21383 | acc[row * SIDE + col] += |
| 21384 | w * f64::from(nb.y[(sy + row) * nb.width + sx + col]); |
| 21385 | } |
| 21386 | } |
| 21387 | wsum += w; |
| 21388 | } |
| 21389 | let filtered: Vec<u16> = acc |
| 21390 | .iter() |
| 21391 | .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16) |
| 21392 | .collect(); |
| 21393 | for (a, b) in filtered.iter().zip(&block) { |
| 21394 | let d = f64::from(*a) - f64::from(*b); |
| 21395 | tf_sse += d * d; |
| 21396 | } |
| 21397 | tf_px += (SIDE * SIDE) as u64; |
| 21398 | ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0; |
| 21399 | px += (SIDE * SIDE) as u64; |
| 21400 | } |
| 21401 | } |
| 21402 | } |
| 21403 | let per = |v: u64| v as f64 / px.max(1) as f64; |
| 21404 | let mse = tf_sse / tf_px.max(1) as f64; |
| 21405 | println!( |
| 21406 | "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |", |
| 21407 | per(n8), |
| 21408 | per(n4), |
| 21409 | per(ntf), |
| 21410 | 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64, |
| 21411 | 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(), |
| 21412 | ); |
| 21413 | } |
| 21414 | } |
| 21415 | |
| 21416 | /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to |
| 21417 | /// hardwire the REGULAR kernel, so the encoder could not have coded a |
| 21418 | /// SMOOTH or SHARP frame even if the header had said so -- the search, |
| 21419 | /// the trials, the recon and the frame header now all read |
| 21420 | /// `FrameCtx::interp_filter`. Each of the three kernels codes its own |
| 21421 | /// distinct stream (a filter that never reached the prediction would code |
| 21422 | /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg |
| 21423 | /// reconstructs every frame of each of them exactly, which is what proves |
| 21424 | /// the header and the prediction agree. |
| 21425 | #[test] |
| 21426 | fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() { |
| 21427 | let _knobs = crate::speed::knob_write(); |
| 21428 | if !have_ffmpeg() { |
| 21429 | eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg"); |
| 21430 | return; |
| 21431 | } |
| 21432 | let (width, height) = (256usize, 128usize); |
| 21433 | // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so |
| 21434 | // all three kernels would code the same bytes and the test would pass |
| 21435 | // on a wiring that does nothing (class `fixture proves the symbol, not |
| 21436 | // the signal`). `panned_test_card` shifts by whole pixels, so the |
| 21437 | // search finds the sub-pel positions off the reconstruction instead: |
| 21438 | // three frames of a slow diagonal pan. |
| 21439 | let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect(); |
| 21440 | let mut streams = Vec::new(); |
| 21441 | for filter in [ |
| 21442 | ec_av1_syntax::InterpolationFilter::Eighttap, |
| 21443 | ec_av1_syntax::InterpolationFilter::EighttapSmooth, |
| 21444 | ec_av1_syntax::InterpolationFilter::EighttapSharp, |
| 21445 | ] { |
| 21446 | set_frame_interp(Some(filter)); |
| 21447 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 21448 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) |
| 21449 | .unwrap_or_else(|e| panic!("{filter:?}: {e}")); |
| 21450 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 21451 | assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count"); |
| 21452 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 21453 | assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma"); |
| 21454 | assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U"); |
| 21455 | assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V"); |
| 21456 | } |
| 21457 | streams.push((filter, encoded.stream)); |
| 21458 | } |
| 21459 | set_frame_interp(None); |
| 21460 | for (i, (fa, a)) in streams.iter().enumerate() { |
| 21461 | for (fb, b) in &streams[i + 1..] { |
| 21462 | assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes"); |
| 21463 | } |
| 21464 | } |
| 21465 | } |
| 21466 | |
| 21467 | |
| 21468 | /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With |
| 21469 | /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel |
| 21470 | /// residual outright (`round_to_valid_mv` rounds it away first), so the |
| 21471 | /// finest vector the encoder could commit to was a quarter pel. With the |
| 21472 | /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per |
| 21473 | /// non-zero component and the search's fourth stage refines to the |
| 21474 | /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the |
| 21475 | /// on arm, and -- the part that makes it a signal rather than a symbol |
| 21476 | /// count (class `fixture proves the symbol, not the signal`) -- that some |
| 21477 | /// of them come out ZERO, i.e. name a vector the off arm cannot code at |
| 21478 | /// all. Both streams are decoded by ffmpeg AND by this crate's own |
| 21479 | /// decoder and asserted sample-exact against the encoder's own |
| 21480 | /// reconstruction, which is what proves the header bit and the symbols |
| 21481 | /// agree. |
| 21482 | #[test] |
| 21483 | fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() { |
| 21484 | let _knobs = crate::speed::knob_write(); |
| 21485 | if !have_ffmpeg() { |
| 21486 | eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg"); |
| 21487 | return; |
| 21488 | } |
| 21489 | let (width, height) = (256usize, 128usize); |
| 21490 | let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect(); |
| 21491 | let mut arms = Vec::new(); |
| 21492 | for hp in [false, true] { |
| 21493 | set_high_precision_mv(Some(hp)); |
| 21494 | let _ = crate::tile::take_hp_symbols(); |
| 21495 | let fctx = &crate::decode::FrameCtx::for_encoder(); |
| 21496 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) |
| 21497 | .unwrap_or_else(|e| panic!("hp={hp}: {e}")); |
| 21498 | let (symbols, eighth) = crate::tile::take_hp_symbols(); |
| 21499 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); |
| 21500 | let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 21501 | assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count"); |
| 21502 | assert_eq!(ours.len(), pictures.len(), "hp={hp}: our decoder frame count"); |
| 21503 | for (i, e) in encoded.frames.iter().enumerate() { |
| 21504 | for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] { |
| 21505 | if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction) |
| 21506 | { |
| 21507 | panic!( |
| 21508 | "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \ |
| 21509 | the encoder reconstructed {want}" |
| 21510 | ); |
| 21511 | } |
| 21512 | } |
| 21513 | } |
| 21514 | arms.push((symbols, eighth, encoded.stream)); |
| 21515 | } |
| 21516 | set_high_precision_mv(None); |
| 21517 | let (off, on) = (&arms[0], &arms[1]); |
| 21518 | assert_eq!(off.0, 0, "a frame without the header bit codes no hp symbol"); |
| 21519 | assert!(on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0); |
| 21520 | assert!( |
| 21521 | on.1 > 0, |
| 21522 | "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)", |
| 21523 | on.0 |
| 21524 | ); |
| 21525 | assert_ne!(off.2, on.2, "the two arms coded the same bytes"); |
| 21526 | println!( |
| 21527 | "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B", |
| 21528 | off.0, |
| 21529 | off.2.len(), |
| 21530 | on.0, |
| 21531 | on.1, |
| 21532 | on.2.len() |
| 21533 | ); |
| 21534 | } |
| 21535 | } |