Rate-distortion optimised quantisation behind a preset lever
Browse files at this commit4cc1d86ce2f8065427c96bdab8c76cd6b376764fParent: e7e40c6- feat
- rate-distortion optimised quantisation behind a preset lever
7 changed files +352 -21
- crates/ec-av1/src/encode.rs +98 -4
- crates/ec-av1/src/speed.rs +7 -0
- crates/ec-av1/src/tile.rs +168 -17
- crates/ec-av1/src/transform.rs +60 -0
- lanes/rdoq-arm.sh +7 -0
- lanes/rdoq-ctl.log +6 -0
- lanes/rdoq-r1.log +6 -0
crates/ec-av1/src/encode.rsmodified+98 -4
| @@ -42,7 +42,8 @@ use crate::tile::{ | |||
| 42 | }; | 42 | }; |
| 43 | use crate::transform::{ | 43 | use crate::transform::{ |
| 44 | TxType, dequant_and_inverse_typed_wh, forward_and_quantize, | 44 | TxType, dequant_and_inverse_typed_wh, forward_and_quantize, |
| 45 | - forward_and_quantize_typed, | 45 | + forward_and_quantize_scaled, forward_and_quantize_typed, |
| 46 | + forward_and_quantize_typed_scaled, | ||
| 46 | }; | 47 | }; |
| 47 | 48 | ||
| 48 | /// The side of the larger of the two luma blocks this encoder codes, in | 49 | /// The side of the larger of the two luma blocks this encoder codes, in |
| @@ -428,6 +429,41 @@ pub fn take_b64_root_hits() -> usize { | |||
| 428 | B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) | 429 | B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) |
| 429 | } | 430 | } |
| 430 | 431 | ||
| 432 | +/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq). | ||
| 433 | +/// Preset-gated: it re-prices the block once per candidate level, so it buys | ||
| 434 | +/// bits with wall (see `crate::speed::RDOQ` for the per-preset table). | ||
| 435 | +/// | ||
| 436 | +/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser -- | ||
| 437 | +/// which is what the byte pins are taken under when they name it. | ||
| 438 | +fn rdoq_on() -> bool { | ||
| 439 | + static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { | ||
| 440 | + crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0") | ||
| 441 | + }); | ||
| 442 | + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ)) | ||
| 443 | +} | ||
| 444 | + | ||
| 445 | +/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in | ||
| 446 | +/// units of one squared AC quantiser step -- the search's own | ||
| 447 | +/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency. | ||
| 448 | +/// | ||
| 449 | +/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`], | ||
| 450 | +/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock | ||
| 451 | +/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here: | ||
| 452 | +/// corner-cut, ceiling = a superblock the temporal map weighs away from the | ||
| 453 | +/// frame average has its coefficients optimised at the frame's weight. The | ||
| 454 | +/// upgrade is one `lambda` field on the trial call sites, which is the whole | ||
| 455 | +/// mode-search argument list. | ||
| 456 | +/// `EC_AV1_RDOQ_LAMBDA` multiplies it (the rate-term calibration sweep). | ||
| 457 | +fn rdoq_lambda() -> f64 { | ||
| 458 | + static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| { | ||
| 459 | + crate::envflags::var("EC_AV1_RDOQ_LAMBDA") | ||
| 460 | + .ok() | ||
| 461 | + .and_then(|v| v.parse().ok()) | ||
| 462 | + .unwrap_or(1.0) | ||
| 463 | + }); | ||
| 464 | + lambda_scale() * *MULT | ||
| 465 | +} | ||
| 466 | + | ||
| 431 | /// [`B64_ROOT`], or what `EC_AV1_B64` names. | 467 | /// [`B64_ROOT`], or what `EC_AV1_B64` names. |
| 432 | fn b64_root() -> bool { | 468 | fn b64_root() -> bool { |
| 433 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { | 469 | static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| { |
| @@ -1836,8 +1872,26 @@ impl Plane<'_> { | |||
| 1836 | } | 1872 | } |
| 1837 | #[cfg(test)] | 1873 | #[cfg(test)] |
| 1838 | let t = stage_start(); | 1874 | let t = stage_start(); |
| 1839 | - let levels = | 1875 | + // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the |
| 1840 | - forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); | 1876 | + // reconstruction below and the price further down are both of the |
| 1877 | + // grid this trial would really code. | ||
| 1878 | + let (levels, rdoq_bits) = if rdoq_on() { | ||
| 1879 | + let (mut levels, scaled) = forward_and_quantize_typed_scaled( | ||
| 1880 | + residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, | ||
| 1881 | + ); | ||
| 1882 | + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); | ||
| 1883 | + let bits = crate::tile::rdoq( | ||
| 1884 | + &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(), | ||
| 1885 | + ); | ||
| 1886 | + (levels, Some(bits)) | ||
| 1887 | + } else { | ||
| 1888 | + ( | ||
| 1889 | + forward_and_quantize_typed( | ||
| 1890 | + residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, | ||
| 1891 | + ), | ||
| 1892 | + None, | ||
| 1893 | + ) | ||
| 1894 | + }; | ||
| 1841 | // lane-av1speed2: 60% of the transform units of an inter stream carry | 1895 | // lane-av1speed2: 60% of the transform units of an inter stream carry |
| 1842 | // no coefficient at all, and the square entry point re-inflates that | 1896 | // no coefficient at all, and the square entry point re-inflates that |
| 1843 | // case into `side * side` zeros (one allocate-and-memset per trial) | 1897 | // case into `side * side` zeros (one allocate-and-memset per trial) |
| @@ -1876,6 +1930,9 @@ impl Plane<'_> { | |||
| 1876 | .filter(|&&level| level != 0) | 1930 | .filter(|&&level| level != 0) |
| 1877 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) | 1931 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 1878 | .sum() | 1932 | .sum() |
| 1933 | + } else if let Some(bits) = rdoq_bits { | ||
| 1934 | + // Already priced, against the grid the pass settled on. | ||
| 1935 | + bits | ||
| 1879 | } else { | 1936 | } else { |
| 1880 | { | 1937 | { |
| 1881 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); | 1938 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); |
| @@ -1948,7 +2005,21 @@ impl Plane<'_> { | |||
| 1948 | } | 2005 | } |
| 1949 | #[cfg(test)] | 2006 | #[cfg(test)] |
| 1950 | let t = stage_start(); | 2007 | let t = stage_start(); |
| 1951 | - let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); | 2008 | + // lane-rdoq, as in [`Self::trial_typed`]. |
| 2009 | + let (levels, rdoq_bits) = if rdoq_on() { | ||
| 2010 | + let (mut levels, scaled) = | ||
| 2011 | + forward_and_quantize_scaled(residual, side, 8, i32::from(base_q_idx), deadzone); | ||
| 2012 | + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); | ||
| 2013 | + let bits = crate::tile::rdoq( | ||
| 2014 | + &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(), | ||
| 2015 | + ); | ||
| 2016 | + (levels, Some(bits)) | ||
| 2017 | + } else { | ||
| 2018 | + ( | ||
| 2019 | + forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone), | ||
| 2020 | + None, | ||
| 2021 | + ) | ||
| 2022 | + }; | ||
| 1952 | // The same all-zero shortcut [`Self::trial_typed`] takes. | 2023 | // The same all-zero shortcut [`Self::trial_typed`] takes. |
| 1953 | let coded = dequant_and_inverse_typed_wh( | 2024 | let coded = dequant_and_inverse_typed_wh( |
| 1954 | &levels, | 2025 | &levels, |
| @@ -1990,6 +2061,8 @@ impl Plane<'_> { | |||
| 1990 | .filter(|&&level| level != 0) | 2061 | .filter(|&&level| level != 0) |
| 1991 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) | 2062 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 1992 | .sum() | 2063 | .sum() |
| 2064 | + } else if let Some(bits) = rdoq_bits { | ||
| 2065 | + bits | ||
| 1993 | } else { | 2066 | } else { |
| 1994 | { | 2067 | { |
| 1995 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); | 2068 | let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); |
| @@ -14812,6 +14885,27 @@ mod tests { | |||
| 14812 | // the real side, a screen clip none of them. | 14885 | // the real side, a screen clip none of them. |
| 14813 | let (price_default, price_real) = crate::tile::take_pricing_hits(); | 14886 | let (price_default, price_real) = crate::tile::take_pricing_hits(); |
| 14814 | eprintln!("{name}: pricer armings default={price_default} real={price_real}"); | 14887 | eprintln!("{name}: pricer armings default={price_default} real={price_real}"); |
| 14888 | + // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan | ||
| 14889 | + // of every priced block): what the deadzone quantiser handed the | ||
| 14890 | + // RDOQ pass and what the pass changed, over every TRIAL block of | ||
| 14891 | + // this row's four encodes -- not over the coded stream, so it is | ||
| 14892 | + // the bits AT STAKE in the search, not in the bitstream. | ||
| 14893 | + let rq = crate::tile::take_rdoq_stats(); | ||
| 14894 | + if rq[0] > 0 { | ||
| 14895 | + eprintln!( | ||
| 14896 | + "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \ | ||
| 14897 | + zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)", | ||
| 14898 | + rq[0], | ||
| 14899 | + rq[1], | ||
| 14900 | + 100.0 * rq[2] as f64 / rq[1].max(1) as f64, | ||
| 14901 | + 100.0 * rq[3] as f64 / rq[1].max(1) as f64, | ||
| 14902 | + rq[4], | ||
| 14903 | + rq[5], | ||
| 14904 | + rq[7] as f64 / 64.0, | ||
| 14905 | + rq[6] as f64 / 64.0, | ||
| 14906 | + 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64, | ||
| 14907 | + ); | ||
| 14908 | + } | ||
| 14815 | // lane-av1obmc2: the same motion_mode census the 640x384 gate | 14909 | // lane-av1obmc2: the same motion_mode census the 640x384 gate |
| 14816 | // prints (class `gate-blind-to-feature`) -- how many blocks coded | 14910 | // prints (class `gate-blind-to-feature`) -- how many blocks coded |
| 14817 | // the symbol at each footprint and how many took OBMC. Without it | 14911 | // the symbol at each footprint and how many took OBMC. Without it |
crates/ec-av1/src/speed.rsmodified+7 -0
| @@ -169,6 +169,13 @@ pub(crate) fn at<T: Copy>(table: &[T; 11]) -> T { | |||
| 169 | /// (screen). So it is on at every preset. | 169 | /// (screen). So it is on at every preset. |
| 170 | pub(crate) const B64_ROOT: [bool; 11] = [crate::encode::B64_ROOT; 11]; | 170 | pub(crate) const B64_ROOT: [bool; 11] = [crate::encode::B64_ROOT; 11]; |
| 171 | 171 | ||
| 172 | +/// `encode::rdoq_on`: rate-distortion optimised quantisation | ||
| 173 | +/// ([`crate::tile::rdoq`], lane-rdoq). Provisional table -- the wall/BD | ||
| 174 | +/// measurement per preset is in `lanes/rdoq.report.md`. | ||
| 175 | +pub(crate) const RDOQ: [bool; 11] = [ | ||
| 176 | + true, true, true, false, false, false, false, false, false, false, false, | ||
| 177 | +]; | ||
| 178 | + | ||
| 172 | /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split | 179 | /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split |
| 173 | /// trial is withheld. The single biggest wall lever in the tile search. | 180 | /// trial is withheld. The single biggest wall lever in the tile search. |
| 174 | pub(crate) const SPLIT_RD: [f64; 11] = [ | 181 | pub(crate) const SPLIT_RD: [f64; 11] = [ |
crates/ec-av1/src/tile.rsmodified+168 -17
| @@ -13,7 +13,7 @@ use std::cell::RefCell; | |||
| 13 | #[cfg(test)] | 13 | #[cfg(test)] |
| 14 | use std::collections::BTreeMap; | 14 | use std::collections::BTreeMap; |
| 15 | use std::sync::LazyLock; | 15 | use std::sync::LazyLock; |
| 16 | -use std::sync::atomic::{AtomicUsize, Ordering}; | 16 | +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; |
| 17 | 17 | ||
| 18 | use ec_core::{Error, Result}; | 18 | use ec_core::{Error, Result}; |
| 19 | 19 | ||
| @@ -4428,6 +4428,26 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { | |||
| 4428 | /// blocks mostly code nothing narrows `txb_skip` far below where it started. | 4428 | /// blocks mostly code nothing narrows `txb_skip` far below where it started. |
| 4429 | /// A whole-block luma transform still reads context 0 -- that is what the | 4429 | /// A whole-block luma transform still reads context 0 -- that is what the |
| 4430 | /// writer codes (`write_luma_tus`, `n == 1`), not an approximation. | 4430 | /// writer codes (`write_luma_tus`, `n == 1`), not an approximation. |
| 4431 | +/// The default scan of one transform size, built once per size: the search | ||
| 4432 | +/// prices thirteen modes for every block, and the scan is the same table | ||
| 4433 | +/// every time. | ||
| 4434 | +fn scan_of(side: usize) -> &'static Vec<u16> { | ||
| 4435 | + static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| { | ||
| 4436 | + [ | ||
| 4437 | + default_scan(TX4), | ||
| 4438 | + default_scan(TX8), | ||
| 4439 | + default_scan(TX16), | ||
| 4440 | + default_scan(TX32), | ||
| 4441 | + ] | ||
| 4442 | + }); | ||
| 4443 | + match side { | ||
| 4444 | + TX4 => &SCANS[0], | ||
| 4445 | + TX8 => &SCANS[1], | ||
| 4446 | + TX16 => &SCANS[2], | ||
| 4447 | + _ => &SCANS[3], | ||
| 4448 | + } | ||
| 4449 | +} | ||
| 4450 | + | ||
| 4431 | pub(crate) fn coeff_bits( | 4451 | pub(crate) fn coeff_bits( |
| 4432 | grid: &[i32], | 4452 | grid: &[i32], |
| 4433 | set: TxbSet, | 4453 | set: TxbSet, |
| @@ -4441,16 +4461,6 @@ pub(crate) fn coeff_bits( | |||
| 4441 | skip_ctx: usize, | 4461 | skip_ctx: usize, |
| 4442 | sign_ctx: usize, | 4462 | sign_ctx: usize, |
| 4443 | ) -> f64 { | 4463 | ) -> f64 { |
| 4444 | - /// Built once per size: the search prices thirteen modes for every block, | ||
| 4445 | - /// and the scan is the same table every time. | ||
| 4446 | - static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| { | ||
| 4447 | - [ | ||
| 4448 | - default_scan(TX4), | ||
| 4449 | - default_scan(TX8), | ||
| 4450 | - default_scan(TX16), | ||
| 4451 | - default_scan(TX32), | ||
| 4452 | - ] | ||
| 4453 | - }); | ||
| 4454 | // `Cdfs::new` builds every table a tile writer adapts -- tens of | 4464 | // `Cdfs::new` builds every table a tile writer adapts -- tens of |
| 4455 | // kilobytes -- and this function is called once per priced candidate: | 4465 | // kilobytes -- and this function is called once per priced candidate: |
| 4456 | // together with the copy behind it that was 9% of the encoder's profile | 4466 | // together with the copy behind it that was 9% of the encoder's profile |
| @@ -4483,12 +4493,7 @@ pub(crate) fn coeff_bits( | |||
| 4483 | if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) { | 4493 | if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) { |
| 4484 | dst.copy_from_slice(src); | 4494 | dst.copy_from_slice(src); |
| 4485 | } | 4495 | } |
| 4486 | - let scan = match coding.side { | 4496 | + let scan = scan_of(coding.side); |
| 4487 | - TX4 => &SCANS[0], | ||
| 4488 | - TX8 => &SCANS[1], | ||
| 4489 | - TX16 => &SCANS[2], | ||
| 4490 | - _ => &SCANS[3], | ||
| 4491 | - }; | ||
| 4492 | let mut enc = SymbolEncoder::pricer(); | 4497 | let mut enc = SymbolEncoder::pricer(); |
| 4493 | write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None); | 4498 | write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None); |
| 4494 | enc.bits() | 4499 | enc.bits() |
| @@ -4520,6 +4525,152 @@ pub(crate) fn coeff_bits( | |||
| 4520 | }) | 4525 | }) |
| 4521 | } | 4526 | } |
| 4522 | 4527 | ||
| 4528 | +/// Rate-distortion optimised quantisation (lane-rdoq): the pass every | ||
| 4529 | +/// reference encoder runs after the quantiser and this one did not have. | ||
| 4530 | +/// | ||
| 4531 | +/// The deadzone quantiser rounds each coefficient on its own, blind to what | ||
| 4532 | +/// the coded level costs. Every reference decides that per coefficient | ||
| 4533 | +/// against the entropy coder (libaom `av1_optimize_txb`, rav1e | ||
| 4534 | +/// `optimize_txb`): a level is lowered toward zero when the bits it gives | ||
| 4535 | +/// back are worth more than the squared error it adds, which also shortens | ||
| 4536 | +/// the eob when the tail levels go to zero. | ||
| 4537 | +/// | ||
| 4538 | +/// Mirroring rav1e's shape without its incremental cost model: the candidate | ||
| 4539 | +/// set per coefficient is `{level, level - 1, .., 0}` walked one step at a | ||
| 4540 | +/// time in REVERSE scan order (the tail first, so a dropped tail is retried | ||
| 4541 | +/// against the shorter eob it leaves), and each candidate is priced by | ||
| 4542 | +/// re-coding the whole block through [`coeff_bits`] -- the same CDFs, the | ||
| 4543 | +/// same neighbour contexts and the same writer the search already prices | ||
| 4544 | +/// with, so no second cost model can drift from the writer (class | ||
| 4545 | +/// `table-and-reader-move-together`). That costs one `write_coeffs` per | ||
| 4546 | +/// candidate instead of rav1e's table lookup, which is why this is a preset | ||
| 4547 | +/// lever (`crate::speed::RDOQ`) and not unconditional. | ||
| 4548 | +/// | ||
| 4549 | +/// `levels` is the side-strided grid the inverse transform and the writer | ||
| 4550 | +/// will read, `scaled` the pre-rounding `coeff / q` of each position | ||
| 4551 | +/// (`crate::transform::forward_and_quantize_scaled`). `lambda` is the rate | ||
| 4552 | +/// weight in units of ONE SQUARED AC QUANTISER STEP: the search's own | ||
| 4553 | +/// `sse + lambda * bits` is `step^2 * (sum (scaled - level)^2 + LAMBDA_SCALE | ||
| 4554 | +/// * bits)` once the pixel-domain error of a level is written through the | ||
| 4555 | +/// orthonormal transform (`(coeff - level * q) / 8`, `INVERSE_GAIN_RECIPROCAL`), | ||
| 4556 | +/// so `step^2` divides out of every comparison here and the DC's different | ||
| 4557 | +/// quantiser is the only per-position weight left. | ||
| 4558 | +/// | ||
| 4559 | +/// Returns what the block's levels cost after the pass, so the caller prices | ||
| 4560 | +/// the tile it will actually write and never the pre-RDOQ grid. | ||
| 4561 | +#[allow(clippy::too_many_arguments)] | ||
| 4562 | +pub(crate) fn rdoq( | ||
| 4563 | + levels: &mut [i32], | ||
| 4564 | + scaled: &[f32], | ||
| 4565 | + side: usize, | ||
| 4566 | + base_q_idx: u8, | ||
| 4567 | + set: TxbSet, | ||
| 4568 | + skip_ctx: usize, | ||
| 4569 | + sign_ctx: usize, | ||
| 4570 | + lambda: f64, | ||
| 4571 | +) -> f64 { | ||
| 4572 | + // A 64-point transform carries its top-left 32x32 alone, and that corner | ||
| 4573 | + // is what the writer and the pricer take (`coded_corner`). | ||
| 4574 | + let coded = side.min(TX32); | ||
| 4575 | + let q_ctx = crate::decode::q_ctx_of(base_q_idx); | ||
| 4576 | + let mut dense = if coded == side { Vec::new() } else { vec![0i32; coded * coded] }; | ||
| 4577 | + fn price( | ||
| 4578 | + levels: &[i32], | ||
| 4579 | + dense: &mut [i32], | ||
| 4580 | + side: usize, | ||
| 4581 | + coded: usize, | ||
| 4582 | + set: TxbSet, | ||
| 4583 | + q_ctx: usize, | ||
| 4584 | + skip_ctx: usize, | ||
| 4585 | + sign_ctx: usize, | ||
| 4586 | + ) -> f64 { | ||
| 4587 | + if dense.is_empty() { | ||
| 4588 | + return coeff_bits(levels, set, q_ctx, skip_ctx, sign_ctx); | ||
| 4589 | + } | ||
| 4590 | + for row in 0..coded { | ||
| 4591 | + dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]); | ||
| 4592 | + } | ||
| 4593 | + coeff_bits(dense, set, q_ctx, skip_ctx, sign_ctx) | ||
| 4594 | + } | ||
| 4595 | + let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx); | ||
| 4596 | + // The DC has its own quantiser, so its squared error per unit of level is | ||
| 4597 | + // `(dc_q / ac_q)^2` of an AC coefficient's. | ||
| 4598 | + let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx))); | ||
| 4599 | + let ac = f64::from(crate::quant::ac_q(8, i32::from(base_q_idx))); | ||
| 4600 | + let dc_weight = (dc / ac) * (dc / ac); | ||
| 4601 | + let census = crate::envflags::env_flag!("EC_AV1_RDOQ_CENSUS"); | ||
| 4602 | + if census { | ||
| 4603 | + census_block(levels, scaled, side, coded, bits); | ||
| 4604 | + } | ||
| 4605 | + for &position in scan_of(coded).iter().rev() { | ||
| 4606 | + let (row, col) = (usize::from(position) / coded, usize::from(position) % coded); | ||
| 4607 | + let i = row * side + col; | ||
| 4608 | + if levels[i] == 0 { | ||
| 4609 | + continue; | ||
| 4610 | + } | ||
| 4611 | + let s = f64::from(scaled[i]); | ||
| 4612 | + let weight = if i == 0 { dc_weight } else { 1.0 }; | ||
| 4613 | + loop { | ||
| 4614 | + let level = levels[i]; | ||
| 4615 | + let candidate = level - level.signum(); | ||
| 4616 | + levels[i] = candidate; | ||
| 4617 | + let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx); | ||
| 4618 | + let distortion = weight | ||
| 4619 | + * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2)); | ||
| 4620 | + if distortion + lambda * (after - bits) < 0.0 { | ||
| 4621 | + bits = after; | ||
| 4622 | + if census { | ||
| 4623 | + RDOQ_STATS[if candidate == 0 { 4 } else { 5 }].fetch_add(1, Ordering::Relaxed); | ||
| 4624 | + } | ||
| 4625 | + if candidate == 0 { | ||
| 4626 | + break; | ||
| 4627 | + } | ||
| 4628 | + } else { | ||
| 4629 | + levels[i] = level; | ||
| 4630 | + break; | ||
| 4631 | + } | ||
| 4632 | + } | ||
| 4633 | + } | ||
| 4634 | + if census { | ||
| 4635 | + RDOQ_STATS[6].fetch_add((bits * 64.0) as u64, Ordering::Relaxed); | ||
| 4636 | + } | ||
| 4637 | + bits | ||
| 4638 | +} | ||
| 4639 | + | ||
| 4640 | +/// blocks, coded coefficients, +-1 levels, trailing +-1 levels (a run of them | ||
| 4641 | +/// at the end of the scan), zeroed coefficients, lowered coefficients, bits | ||
| 4642 | +/// after the pass * 64, bits before the pass * 64. | ||
| 4643 | +pub(crate) static RDOQ_STATS: [AtomicU64; 8] = [ | ||
| 4644 | + AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), | ||
| 4645 | + AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), | ||
| 4646 | +]; | ||
| 4647 | + | ||
| 4648 | +/// The pre-pass half of [`RDOQ_STATS`] (`EC_AV1_RDOQ_CENSUS`): what the | ||
| 4649 | +/// quantiser handed the pass, which is the instrument for how much is at | ||
| 4650 | +/// stake before any decision is taken. | ||
| 4651 | +fn census_block(levels: &[i32], _scaled: &[f32], side: usize, coded: usize, bits: f64) { | ||
| 4652 | + let scan = scan_of(coded); | ||
| 4653 | + let at = |p: u16| levels[usize::from(p) / coded * side + usize::from(p) % coded]; | ||
| 4654 | + let nonzero = scan.iter().filter(|&&p| at(p) != 0).count(); | ||
| 4655 | + let ones = scan.iter().filter(|&&p| at(p).abs() == 1).count(); | ||
| 4656 | + let trailing = scan | ||
| 4657 | + .iter() | ||
| 4658 | + .rev() | ||
| 4659 | + .skip_while(|&&p| at(p) == 0) | ||
| 4660 | + .take_while(|&&p| at(p).abs() == 1) | ||
| 4661 | + .count(); | ||
| 4662 | + RDOQ_STATS[0].fetch_add(1, Ordering::Relaxed); | ||
| 4663 | + RDOQ_STATS[1].fetch_add(nonzero as u64, Ordering::Relaxed); | ||
| 4664 | + RDOQ_STATS[2].fetch_add(ones as u64, Ordering::Relaxed); | ||
| 4665 | + RDOQ_STATS[3].fetch_add(trailing as u64, Ordering::Relaxed); | ||
| 4666 | + RDOQ_STATS[7].fetch_add((bits * 64.0) as u64, Ordering::Relaxed); | ||
| 4667 | +} | ||
| 4668 | + | ||
| 4669 | +/// Reads and clears [`RDOQ_STATS`]. | ||
| 4670 | +pub fn take_rdoq_stats() -> [u64; 8] { | ||
| 4671 | + std::array::from_fn(|i| RDOQ_STATS[i].swap(0, Ordering::Relaxed)) | ||
| 4672 | +} | ||
| 4673 | + | ||
| 4523 | thread_local! { | 4674 | thread_local! { |
| 4524 | /// The default tables every price falls back to, one pristine/scratch | 4675 | /// The default tables every price falls back to, one pristine/scratch |
| 4525 | /// pair per q-context (see [`coeff_bits`] for why the pair is kept). | 4676 | /// pair per q-context (see [`coeff_bits`] for why the pair is kept). |
crates/ec-av1/src/transform.rsmodified+60 -0
| @@ -1554,6 +1554,35 @@ pub fn forward_and_quantize_typed( | |||
| 1554 | quantize(&coeffs, side, bit_depth, q_idx, deadzone) | 1554 | quantize(&coeffs, side, bit_depth, q_idx, deadzone) |
| 1555 | } | 1555 | } |
| 1556 | 1556 | ||
| 1557 | +/// [`forward_and_quantize_typed`] that also hands back each coded position's | ||
| 1558 | +/// pre-rounding scaled coefficient (`coeff / q`, the exact real-valued level | ||
| 1559 | +/// the quantiser rounded). The RDOQ pass ([`crate::tile::rdoq`]) prices | ||
| 1560 | +/// `level - 1` against `level` and needs the distance to both, which the | ||
| 1561 | +/// levels alone no longer carry. | ||
| 1562 | +pub fn forward_and_quantize_typed_scaled( | ||
| 1563 | + residual: &[i32], | ||
| 1564 | + side: usize, | ||
| 1565 | + bit_depth: u8, | ||
| 1566 | + q_idx: i32, | ||
| 1567 | + deadzone: f64, | ||
| 1568 | + tx_type: TxType, | ||
| 1569 | +) -> (Vec<i32>, Vec<f32>) { | ||
| 1570 | + let coeffs = forward_transform_2d_typed(residual, side, tx_type); | ||
| 1571 | + let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx)); | ||
| 1572 | + let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx)); | ||
| 1573 | + let mut scaled = vec![0f32; side * side]; | ||
| 1574 | + let coded = side.min(32); | ||
| 1575 | + for row in 0..coded { | ||
| 1576 | + for col in 0..coded { | ||
| 1577 | + let i = row * side + col; | ||
| 1578 | + scaled[i] = (coeffs[i] / if i == 0 { dc } else { ac }) as f32; | ||
| 1579 | + } | ||
| 1580 | + } | ||
| 1581 | + // Same levels as the plain entry point: this is the same division the | ||
| 1582 | + // quantiser does, and the levels come from the quantiser itself. | ||
| 1583 | + (quantize(&coeffs, side, bit_depth, q_idx, deadzone), scaled) | ||
| 1584 | +} | ||
| 1585 | + | ||
| 1557 | /// How much the decoder's inverse transform shrinks an orthonormal DCT. | 1586 | /// How much the decoder's inverse transform shrinks an orthonormal DCT. |
| 1558 | /// | 1587 | /// |
| 1559 | /// Measured, not asserted: feeding a single dequantized coefficient through | 1588 | /// Measured, not asserted: feeding a single dequantized coefficient through |
| @@ -1997,6 +2026,34 @@ pub fn forward_and_quantize( | |||
| 1997 | bit_depth: u8, | 2026 | bit_depth: u8, |
| 1998 | q_idx: i32, | 2027 | q_idx: i32, |
| 1999 | deadzone: f64, | 2028 | deadzone: f64, |
| 2029 | +) -> Vec<i32> { | ||
| 2030 | + forward_and_quantize_into(residual, side, bit_depth, q_idx, deadzone, None) | ||
| 2031 | +} | ||
| 2032 | + | ||
| 2033 | +/// [`forward_and_quantize`] plus the pre-rounding scaled coefficients, for the | ||
| 2034 | +/// same reason [`forward_and_quantize_typed_scaled`] exists. The levels are | ||
| 2035 | +/// bit-identical: it is the one loop below, with the value it rounds also | ||
| 2036 | +/// written out. | ||
| 2037 | +pub fn forward_and_quantize_scaled( | ||
| 2038 | + residual: &[i32], | ||
| 2039 | + side: usize, | ||
| 2040 | + bit_depth: u8, | ||
| 2041 | + q_idx: i32, | ||
| 2042 | + deadzone: f64, | ||
| 2043 | +) -> (Vec<i32>, Vec<f32>) { | ||
| 2044 | + let mut scaled = vec![0f32; side * side]; | ||
| 2045 | + let levels = | ||
| 2046 | + forward_and_quantize_into(residual, side, bit_depth, q_idx, deadzone, Some(&mut scaled)); | ||
| 2047 | + (levels, scaled) | ||
| 2048 | +} | ||
| 2049 | + | ||
| 2050 | +fn forward_and_quantize_into( | ||
| 2051 | + residual: &[i32], | ||
| 2052 | + side: usize, | ||
| 2053 | + bit_depth: u8, | ||
| 2054 | + q_idx: i32, | ||
| 2055 | + deadzone: f64, | ||
| 2056 | + mut scaled_out: Option<&mut [f32]>, | ||
| 2000 | ) -> Vec<i32> { | 2057 | ) -> Vec<i32> { |
| 2001 | // 72% of this encoder's forward DCTs are of an all-zero residual | 2058 | // 72% of this encoder's forward DCTs are of an all-zero residual |
| 2002 | // (measured over the BD gate's own ladder, lane-av1fwd): every row and | 2059 | // (measured over the BD gate's own ladder, lane-av1fwd): every row and |
| @@ -2023,6 +2080,9 @@ pub fn forward_and_quantize( | |||
| 2023 | } | 2080 | } |
| 2024 | for u in 0..coded { | 2081 | for u in 0..coded { |
| 2025 | let scaled = f64::from(t[u]) * if u == 0 && v == 0 { dc } else { ac }; | 2082 | let scaled = f64::from(t[u]) * if u == 0 && v == 0 { dc } else { ac }; |
| 2083 | + if let Some(out) = scaled_out.as_deref_mut() { | ||
| 2084 | + out[u * side + v] = scaled as f32; | ||
| 2085 | + } | ||
| 2026 | let magnitude = scaled.abs() + deadzone; | 2086 | let magnitude = scaled.abs() + deadzone; |
| 2027 | let level = if magnitude < 1.0 { | 2087 | let level = if magnitude < 1.0 { |
| 2028 | 0 | 2088 | 0 |
lanes/rdoq-arm.shadded+7 -0
| @@ -0,0 +1,7 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +# lane-rdoq: one native-gate arm (all five rows) under a named env set. | ||
| 3 | +# usage: rdoq-arm.sh <name> <ENV=VAL ...> | ||
| 4 | +name=$1; shift | ||
| 5 | +B=$HOME/.cache/cargo-target-rdoq/release/deps/ec_av1-8fef0196ab10338d | ||
| 6 | +systemd-run --user --unit rq-$name -p MemoryMax=8G --collect --working-directory=$PWD \ | ||
| 7 | + bash -c "env EC_AV1_NATIVE_FILM=1 EC_AV1_NATIVE_FILM4K=1 EC_AV1_NATIVE_SCREEN=1 $* $B --ignored --nocapture --test-threads 1 bd_rate_screen_native > lanes/rdoq-$name.log 2>&1; echo RC=\$? >> lanes/rdoq-$name.log" | ||
lanes/rdoq-ctl.logadded+6 -0
| @@ -0,0 +1,6 @@ | |||
| 1 | + | ||
| 2 | +running 1 test | ||
| 3 | +test encode::tests::bd_rate_screen_native ... | ||
| 4 | +native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128 | ||
| 5 | +| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) | | ||
| 6 | +|---|---|---|---|---| | ||
lanes/rdoq-r1.logadded+6 -0
| @@ -0,0 +1,6 @@ | |||
| 1 | + | ||
| 2 | +running 1 test | ||
| 3 | +test encode::tests::bd_rate_screen_native ... | ||
| 4 | +native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128 | ||
| 5 | +| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) | | ||
| 6 | +|---|---|---|---|---| | ||