Rate-distortion quantisation
Browse files at this commit21ef1929241f6deddec8be5e7ea22533e63224bfParent: 0877a36- feat
- rate-distortion quantisation
6 changed files +340 -14
- crates/ec-h265/src/ctu.rs +75 -4
- crates/ec-h265/src/encoder.rs +13 -0
- crates/ec-h265/src/residual.rs +135 -2
- crates/ec-h265/src/transform.rs +40 -3
- crates/ec-h265/tests/conformance.rs +45 -0
- crates/ec-h265/tests/encode.rs +32 -5
crates/ec-h265/src/ctu.rsmodified+75 -4
| @@ -22,14 +22,32 @@ | |||
| 22 | //! which this encoder spends on the wavefront that makes one `encode` call use | 22 | //! which this encoder spends on the wavefront that makes one `encode` call use |
| 23 | //! every core instead. | 23 | //! every core instead. |
| 24 | 24 | ||
| 25 | -use crate::cabac::{CabacEncoder, CabacState, ctx}; | 25 | +use crate::cabac::{CabacEncoder, CabacState, Contexts, ctx}; |
| 26 | use crate::intra::{self, Availability, Refs}; | 26 | use crate::intra::{self, Availability, Refs}; |
| 27 | use crate::residual::{self, encode_residual}; | 27 | use crate::residual::{self, encode_residual}; |
| 28 | use crate::transform::{ | 28 | use crate::transform::{ |
| 29 | - chroma_qp, dequantize, forward_transform, inverse_transform, quantize, uses_dst, | 29 | + chroma_qp, dequantize, forward_transform, inverse_transform, quantize, quantize_offset, |
| 30 | + uses_dst, | ||
| 30 | }; | 31 | }; |
| 31 | use std::sync::atomic::{AtomicU8, Ordering}; | 32 | use std::sync::atomic::{AtomicU8, Ordering}; |
| 32 | 33 | ||
| 34 | +/// The rounding the rate-distortion level search starts from, as a divisor of | ||
| 35 | +/// the quantiser step: 2 is round-to-nearest, against the 3 the plain path | ||
| 36 | +/// uses. A search that only takes levels down measures the rounding it was | ||
| 37 | +/// handed, so it gets the wider one. Swept on 1080p film at the settled | ||
| 38 | +/// lambda: 1/2 +0.360 dB BD-PSNR against x265, 1/3 +0.315, 1/4 +0.118. | ||
| 39 | +const RDOQ_DEAD_ZONE: i64 = 2; | ||
| 40 | + | ||
| 41 | +/// The same rounding for the chroma path, swept on its own because the sparser | ||
| 42 | +/// chroma of an intra picture answered differently in ec-h264. | ||
| 43 | +/// | ||
| 44 | +/// Here it does not: coarser chroma rounding reads better and better on luma | ||
| 45 | +/// BD-PSNR (1/2 +0.360, 1/6 +0.525, 1/12 +0.568, 1/24 +0.585 dB) while the | ||
| 46 | +/// all-plane figure falls the whole way (+0.276, +0.231, +0.169, +0.128). That | ||
| 47 | +/// arm is chroma being starved to buy luma bits, which only a luma-only metric | ||
| 48 | +/// calls a gain, so chroma keeps luma's rounding. | ||
| 49 | +const RDOQ_DEAD_ZONE_C: i64 = 2; | ||
| 50 | + | ||
| 33 | /// `log2` of the smallest coding block this encoder makes: 8x8. | 51 | /// `log2` of the smallest coding block this encoder makes: 8x8. |
| 34 | pub const MIN_CB_LOG2: u32 = 3; | 52 | pub const MIN_CB_LOG2: u32 = 3; |
| 35 | 53 | ||
| @@ -151,6 +169,10 @@ pub struct CtuEncoder<'a> { | |||
| 151 | /// Whether an 8x8 coding unit may split into four 4x4 intra partitions. | 169 | /// Whether an 8x8 coding unit may split into four 4x4 intra partitions. |
| 152 | intra_nxn: bool, | 170 | intra_nxn: bool, |
| 153 | sign_hiding: bool, | 171 | sign_hiding: bool, |
| 172 | + /// Whether the levels get a rate-distortion search after quantisation. | ||
| 173 | + rdoq: bool, | ||
| 174 | + /// The counting CABAC engine that search prices its trials with. | ||
| 175 | + rdoq_enc: CabacEncoder, | ||
| 154 | /// `log2` of the smallest coding unit the search will produce. | 176 | /// `log2` of the smallest coding unit the search will produce. |
| 155 | min_cb_log2: u32, | 177 | min_cb_log2: u32, |
| 156 | /// Intra mode per 4x4 block of the band; 255 = not coded yet. | 178 | /// Intra mode per 4x4 block of the band; 255 = not coded yet. |
| @@ -183,6 +205,7 @@ impl<'a> CtuEncoder<'a> { | |||
| 183 | chroma_rd_weight: f64, | 205 | chroma_rd_weight: f64, |
| 184 | intra_nxn: bool, | 206 | intra_nxn: bool, |
| 185 | sign_hiding: bool, | 207 | sign_hiding: bool, |
| 208 | + rdoq: bool, | ||
| 186 | min_cb_log2: u32, | 209 | min_cb_log2: u32, |
| 187 | ) -> CtuEncoder<'a> { | 210 | ) -> CtuEncoder<'a> { |
| 188 | let band_rows = (height - band_y0).min(ctb_size); | 211 | let band_rows = (height - band_y0).min(ctb_size); |
| @@ -204,6 +227,8 @@ impl<'a> CtuEncoder<'a> { | |||
| 204 | chroma_rd_weight, | 227 | chroma_rd_weight, |
| 205 | intra_nxn, | 228 | intra_nxn, |
| 206 | sign_hiding, | 229 | sign_hiding, |
| 230 | + rdoq, | ||
| 231 | + rdoq_enc: CabacEncoder::counter(Contexts::new(qp)), | ||
| 207 | min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), | 232 | min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), |
| 208 | modes: vec![255; (width / 4) * (ctb_size / 4)], | 233 | modes: vec![255; (width / 4) * (ctb_size / 4)], |
| 209 | depths: vec![0; (width / 4) * (ctb_size / 4)], | 234 | depths: vec![0; (width / 4) * (ctb_size / 4)], |
| @@ -883,7 +908,30 @@ impl<'a> CtuEncoder<'a> { | |||
| 883 | } | 908 | } |
| 884 | let dst = uses_dst(n, true); | 909 | let dst = uses_dst(n, true); |
| 885 | forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst); | 910 | forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, n, dst); |
| 886 | - let mut nonzero = quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp); | 911 | + let mut nonzero = if self.rdoq { |
| 912 | + quantize_offset( | ||
| 913 | + &self.scratch.coeffs, | ||
| 914 | + &mut self.scratch.levels, | ||
| 915 | + n, | ||
| 916 | + self.qp, | ||
| 917 | + RDOQ_DEAD_ZONE, | ||
| 918 | + ) | ||
| 919 | + } else { | ||
| 920 | + quantize(&self.scratch.coeffs, &mut self.scratch.levels, n, self.qp) | ||
| 921 | + }; | ||
| 922 | + if self.rdoq && nonzero > 0 { | ||
| 923 | + nonzero = residual::rdoq( | ||
| 924 | + &self.scratch.coeffs, | ||
| 925 | + &mut self.scratch.levels, | ||
| 926 | + n, | ||
| 927 | + self.qp, | ||
| 928 | + 0, | ||
| 929 | + intra::scan_index(mode, n.trailing_zeros(), true), | ||
| 930 | + ctx::CBF_LUMA + 1, | ||
| 931 | + self.lambda, | ||
| 932 | + &mut self.rdoq_enc, | ||
| 933 | + ); | ||
| 934 | + } | ||
| 887 | if self.sign_hiding && nonzero > 0 { | 935 | if self.sign_hiding && nonzero > 0 { |
| 888 | nonzero = residual::hide_signs( | 936 | nonzero = residual::hide_signs( |
| 889 | &self.scratch.coeffs, | 937 | &self.scratch.coeffs, |
| @@ -942,12 +990,35 @@ impl<'a> CtuEncoder<'a> { | |||
| 942 | } | 990 | } |
| 943 | } | 991 | } |
| 944 | forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false); | 992 | forward_transform(&self.scratch.residual, &mut self.scratch.coeffs, cn, false); |
| 945 | - let mut nonzero = quantize( | 993 | + let mut nonzero = if self.rdoq { |
| 994 | + quantize_offset( | ||
| 995 | + &self.scratch.coeffs, | ||
| 996 | + &mut self.scratch.levels, | ||
| 997 | + cn, | ||
| 998 | + self.qp_c, | ||
| 999 | + RDOQ_DEAD_ZONE_C, | ||
| 1000 | + ) | ||
| 1001 | + } else { | ||
| 1002 | + quantize( | ||
| 946 | &self.scratch.coeffs, | 1003 | &self.scratch.coeffs, |
| 947 | &mut self.scratch.levels, | 1004 | &mut self.scratch.levels, |
| 948 | cn, | 1005 | cn, |
| 949 | self.qp_c, | 1006 | self.qp_c, |
| 1007 | + ) | ||
| 1008 | + }; | ||
| 1009 | + if self.rdoq && nonzero > 0 { | ||
| 1010 | + nonzero = residual::rdoq( | ||
| 1011 | + &self.scratch.coeffs, | ||
| 1012 | + &mut self.scratch.levels, | ||
| 1013 | + cn, | ||
| 1014 | + self.qp_c, | ||
| 1015 | + plane, | ||
| 1016 | + intra::scan_index(pred_mode, cn.trailing_zeros(), false), | ||
| 1017 | + ctx::CBF_CHROMA, | ||
| 1018 | + self.lambda, | ||
| 1019 | + &mut self.rdoq_enc, | ||
| 950 | ); | 1020 | ); |
| 1021 | + } | ||
| 951 | if self.sign_hiding && nonzero > 0 { | 1022 | if self.sign_hiding && nonzero > 0 { |
| 952 | nonzero = residual::hide_signs( | 1023 | nonzero = residual::hide_signs( |
| 953 | &self.scratch.coeffs, | 1024 | &self.scratch.coeffs, |
crates/ec-h265/src/encoder.rsmodified+13 -0
| @@ -144,6 +144,17 @@ pub struct EncoderConfig { | |||
| 144 | /// cost more than the signs save. Worth re-measuring once RDOQ lands: that | 144 | /// cost more than the signs save. Worth re-measuring once RDOQ lands: that |
| 145 | /// is where the gain in other encoders comes from. | 145 | /// is where the gain in other encoders comes from. |
| 146 | pub sign_hiding: bool, | 146 | pub sign_hiding: bool, |
| 147 | + | ||
| 148 | + /// Whether quantised levels get a rate-distortion search (RDOQ) that | ||
| 149 | + /// offers each small level the magnitudes below it and takes one when the | ||
| 150 | + /// squared error it gives up costs less than the bits it saves. | ||
| 151 | + /// | ||
| 152 | + /// On: worth +0.122 dB BD-PSNR on a 2560x1440 screen capture (-0.479 -> | ||
| 153 | + /// -0.357 against x265) and +0.114 dB on 1080p film (+0.246 -> +0.360), | ||
| 154 | + /// with the all-plane figures moving the same way. The rate is the CABAC | ||
| 155 | + /// coder's own price for the whole block, so dropping a level is priced | ||
| 156 | + /// with the significance map and last position that follow from it. | ||
| 157 | + pub rdoq: bool, | ||
| 147 | /// What the samples mean, written into the VUI. | 158 | /// What the samples mean, written into the VUI. |
| 148 | pub video_signal_type: Option<VideoSignalType>, | 159 | pub video_signal_type: Option<VideoSignalType>, |
| 149 | /// Sample aspect ratio. | 160 | /// Sample aspect ratio. |
| @@ -174,6 +185,7 @@ impl EncoderConfig { | |||
| 174 | min_cu_size: 8, | 185 | min_cu_size: 8, |
| 175 | intra_nxn: true, | 186 | intra_nxn: true, |
| 176 | sign_hiding: false, | 187 | sign_hiding: false, |
| 188 | + rdoq: true, | ||
| 177 | video_signal_type: None, | 189 | video_signal_type: None, |
| 178 | sample_aspect_ratio: None, | 190 | sample_aspect_ratio: None, |
| 179 | timing: None, | 191 | timing: None, |
| @@ -551,6 +563,7 @@ impl Encoder { | |||
| 551 | self.cfg.chroma_rd_weight, | 563 | self.cfg.chroma_rd_weight, |
| 552 | self.cfg.intra_nxn, | 564 | self.cfg.intra_nxn, |
| 553 | self.cfg.sign_hiding, | 565 | self.cfg.sign_hiding, |
| 566 | + self.cfg.rdoq, | ||
| 554 | self.cfg.min_cu_size.max(8).trailing_zeros(), | 567 | self.cfg.min_cu_size.max(8).trailing_zeros(), |
| 555 | ); | 568 | ); |
| 556 | for col in 0..cols { | 569 | for col in 0..cols { |
crates/ec-h265/src/residual.rsmodified+135 -2
| @@ -1,7 +1,7 @@ | |||
| 1 | //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5). | 1 | //! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5). |
| 2 | 2 | ||
| 3 | -use crate::cabac::{CabacEncoder, ctx}; | 3 | +use crate::cabac::{CabacEncoder, CabacState, ctx}; |
| 4 | -use crate::transform::ideal_level; | 4 | +use crate::transform::{coeff_ssd_scale, dequant_level, ideal_level}; |
| 5 | use std::sync::LazyLock; | 5 | use std::sync::LazyLock; |
| 6 | 6 | ||
| 7 | /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`. | 7 | /// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`. |
| @@ -195,6 +195,139 @@ pub fn hide_signs(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32, scan_id | |||
| 195 | levels[..n * n].iter().filter(|&&l| l != 0).count() | 195 | levels[..n * n].iter().filter(|&&l| l != 0).count() |
| 196 | } | 196 | } |
| 197 | 197 | ||
| 198 | +/// The largest level the rate-distortion search offers a smaller magnitude to. | ||
| 199 | +/// | ||
| 200 | +/// A big level carries real signal and never wins by shrinking, so bounding | ||
| 201 | +/// the search is what keeps it affordable: every trial re-codes the whole | ||
| 202 | +/// block. Swept on 1080p film, BD-PSNR-YUV against x265: 1 gives +0.244, the 2 | ||
| 203 | +/// kept here +0.276, and 3 +0.277 for strictly more trials. | ||
| 204 | +const RDOQ_MAX_LEVEL: i32 = 2; | ||
| 205 | + | ||
| 206 | +/// How much of the mode-decision lambda the level search uses. The bits are | ||
| 207 | +/// the coder's own count, not an estimate, so the scale starts at 1. | ||
| 208 | +/// | ||
| 209 | +/// The two clips disagree above it and the disagreement is small: on | ||
| 210 | +/// BD-PSNR-YUV against x265, 1080p film reads +0.276 at 1.0, +0.294 at 1.25 | ||
| 211 | +/// and +0.293 at 1.5, while a 2560x1440 screen capture reads -0.392, -0.408 | ||
| 212 | +/// and -0.441. The crossing sits just above 1.0, and the screen capture is the | ||
| 213 | +/// content still behind x265, so it takes the tie. | ||
| 214 | +const RDOQ_LAMBDA: f64 = 1.0; | ||
| 215 | + | ||
| 216 | +/// What one candidate set of levels costs in bits, priced by the CABAC coder | ||
| 217 | +/// itself against `base`'s context state. | ||
| 218 | +#[allow(clippy::too_many_arguments)] | ||
| 219 | +fn levels_bits( | ||
| 220 | + enc: &mut CabacEncoder, | ||
| 221 | + base: &CabacState, | ||
| 222 | + levels: &[i32], | ||
| 223 | + log2_size: u32, | ||
| 224 | + c_idx: usize, | ||
| 225 | + scan_idx: usize, | ||
| 226 | + cbf_ctx: usize, | ||
| 227 | + coded: bool, | ||
| 228 | +) -> u64 { | ||
| 229 | + enc.restore(base); | ||
| 230 | + let before = enc.bit_count(); | ||
| 231 | + enc.encode_bin(cbf_ctx, u32::from(coded)); | ||
| 232 | + if coded { | ||
| 233 | + encode_residual(enc, levels, log2_size, c_idx, scan_idx, false); | ||
| 234 | + } | ||
| 235 | + enc.bit_count() - before | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +/// Rate-distortion quantisation of one transform block: each small level is | ||
| 239 | +/// offered the magnitudes below it, and takes one when the squared error it | ||
| 240 | +/// gives up costs less than the bits it saves. | ||
| 241 | +/// | ||
| 242 | +/// The rate is the CABAC coder's own price for the whole block — `enc` is a | ||
| 243 | +/// counting engine, and every trial is priced from the same context state — so | ||
| 244 | +/// dropping a level is priced together with the significance map and the last | ||
| 245 | +/// position that follow from it, which is where most of the saving is. The | ||
| 246 | +/// distortion is the transform-domain error scaled back to samples by | ||
| 247 | +/// [`coeff_ssd_scale`], so `lambda` is the caller's sample-domain lambda. | ||
| 248 | +/// | ||
| 249 | +/// Returns the number of non-zero levels left. | ||
| 250 | +#[allow(clippy::too_many_arguments)] | ||
| 251 | +pub fn rdoq( | ||
| 252 | + coeffs: &[i32], | ||
| 253 | + levels: &mut [i32], | ||
| 254 | + n: usize, | ||
| 255 | + qp: i32, | ||
| 256 | + c_idx: usize, | ||
| 257 | + scan_idx: usize, | ||
| 258 | + cbf_ctx: usize, | ||
| 259 | + lambda: f64, | ||
| 260 | + enc: &mut CabacEncoder, | ||
| 261 | +) -> usize { | ||
| 262 | + let log2_size = n.trailing_zeros(); | ||
| 263 | + let scale = coeff_ssd_scale(n); | ||
| 264 | + let lambda = RDOQ_LAMBDA * lambda; | ||
| 265 | + let base = enc.snapshot(); | ||
| 266 | + let err = |level: i32, coeff: i32| { | ||
| 267 | + let d = f64::from(dequant_level(level, n, qp) - coeff); | ||
| 268 | + d * d | ||
| 269 | + }; | ||
| 270 | + | ||
| 271 | + let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum(); | ||
| 272 | + let bits = levels_bits( | ||
| 273 | + enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, true, | ||
| 274 | + ); | ||
| 275 | + let mut cost = scale * dist + lambda * bits as f64; | ||
| 276 | + | ||
| 277 | + // Highest scanning position first: dropping the last significant level is | ||
| 278 | + // what shortens the significance map and moves the coded last position, so | ||
| 279 | + // it is tried while the levels above it are already gone. | ||
| 280 | + let sub_scan = scan(log2_size - 2, scan_idx); | ||
| 281 | + let pos_scan = scan(2, scan_idx); | ||
| 282 | + let order: Vec<usize> = sub_scan | ||
| 283 | + .iter() | ||
| 284 | + .flat_map(|&(xs, ys)| { | ||
| 285 | + pos_scan.iter().map(move |&(xp, yp)| { | ||
| 286 | + (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize | ||
| 287 | + }) | ||
| 288 | + }) | ||
| 289 | + .collect(); | ||
| 290 | + for &i in order.iter().rev() { | ||
| 291 | + let level = levels[i]; | ||
| 292 | + if level == 0 || level.abs() > RDOQ_MAX_LEVEL { | ||
| 293 | + continue; | ||
| 294 | + } | ||
| 295 | + let mut tried = level.abs(); | ||
| 296 | + for candidate in [level.abs() - 1, 0] { | ||
| 297 | + if candidate == tried { | ||
| 298 | + continue; | ||
| 299 | + } | ||
| 300 | + tried = candidate; | ||
| 301 | + let keep = levels[i]; | ||
| 302 | + levels[i] = candidate * level.signum(); | ||
| 303 | + let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]); | ||
| 304 | + let any = levels[..n * n].iter().any(|&l| l != 0); | ||
| 305 | + let trial_bits = | ||
| 306 | + levels_bits(enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, any); | ||
| 307 | + let trial = scale * trial_dist + lambda * trial_bits as f64; | ||
| 308 | + if trial < cost { | ||
| 309 | + cost = trial; | ||
| 310 | + dist = trial_dist; | ||
| 311 | + } else { | ||
| 312 | + levels[i] = keep; | ||
| 313 | + } | ||
| 314 | + } | ||
| 315 | + } | ||
| 316 | + // And the block as a whole: zeroing it drops the coded-block flag as well | ||
| 317 | + // as every level, which no single-coefficient step can see. | ||
| 318 | + let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum(); | ||
| 319 | + let zero_bits = levels_bits( | ||
| 320 | + enc, &base, levels, log2_size, c_idx, scan_idx, cbf_ctx, false, | ||
| 321 | + ); | ||
| 322 | + if scale * zero_dist + lambda * zero_bits as f64 <= cost { | ||
| 323 | + levels[..n * n].fill(0); | ||
| 324 | + enc.restore(&base); | ||
| 325 | + return 0; | ||
| 326 | + } | ||
| 327 | + enc.restore(&base); | ||
| 328 | + levels[..n * n].iter().filter(|&&l| l != 0).count() | ||
| 329 | +} | ||
| 330 | + | ||
| 198 | /// Encode one transform block's levels. | 331 | /// Encode one transform block's levels. |
| 199 | /// | 332 | /// |
| 200 | /// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma | 333 | /// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma |
crates/ec-h265/src/transform.rsmodified+40 -3
| @@ -277,10 +277,27 @@ pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_typ | |||
| 277 | /// encoder in this class uses: it costs a little distortion at the rounding | 277 | /// encoder in this class uses: it costs a little distortion at the rounding |
| 278 | /// boundary and buys back more in rate. | 278 | /// boundary and buys back more in rate. |
| 279 | pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize { | 279 | pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize { |
| 280 | + quantize_offset(coeffs, levels, n, qp, 3) | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +/// [`quantize`] with the rounding written out: `dead_zone` is the divisor of | ||
| 284 | +/// the quantiser step the rounding offset is, so 3 is the intra default and 2 | ||
| 285 | +/// is round-to-nearest. | ||
| 286 | +/// | ||
| 287 | +/// A rate-distortion search over the levels wants the wider rounding: a search | ||
| 288 | +/// that only ever takes levels down measures the rounding it started from, not | ||
| 289 | +/// its own decisions. | ||
| 290 | +pub fn quantize_offset( | ||
| 291 | + coeffs: &[i32], | ||
| 292 | + levels: &mut [i32], | ||
| 293 | + n: usize, | ||
| 294 | + qp: i32, | ||
| 295 | + dead_zone: i64, | ||
| 296 | +) -> usize { | ||
| 280 | let log2n = n.trailing_zeros() as i32; | 297 | let log2n = n.trailing_zeros() as i32; |
| 281 | let qbits = 21 + qp / 6 - log2n; | 298 | let qbits = 21 + qp / 6 - log2n; |
| 282 | let scale = QUANT_SCALE[(qp % 6) as usize] as i64; | 299 | let scale = QUANT_SCALE[(qp % 6) as usize] as i64; |
| 283 | - let offset = (1i64 << qbits) / 3; | 300 | + let offset = (1i64 << qbits) / dead_zone; |
| 284 | let mut nonzero = 0; | 301 | let mut nonzero = 0; |
| 285 | for (i, &c) in coeffs[..n * n].iter().enumerate() { | 302 | for (i, &c) in coeffs[..n * n].iter().enumerate() { |
| 286 | let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32; | 303 | let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32; |
| @@ -305,15 +322,35 @@ pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> f64 { | |||
| 305 | 322 | ||
| 306 | /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies. | 323 | /// Scale levels back into coefficients, exactly as clause 8.6.3 specifies. |
| 307 | pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) { | 324 | pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) { |
| 325 | + for (i, &level) in levels[..n * n].iter().enumerate() { | ||
| 326 | + scaled[i] = dequant_level(level, n, qp); | ||
| 327 | + } | ||
| 328 | +} | ||
| 329 | + | ||
| 330 | +/// One level scaled back to a coefficient, the per-coefficient half of | ||
| 331 | +/// [`dequantize`]. A rate-distortion search over the levels prices one | ||
| 332 | +/// coefficient at a time and has no use for the whole block. | ||
| 333 | +pub fn dequant_level(level: i32, n: usize, qp: i32) -> i32 { | ||
| 308 | let log2n = n.trailing_zeros() as i32; | 334 | let log2n = n.trailing_zeros() as i32; |
| 309 | let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit | 335 | let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit |
| 310 | let round = 1i64 << (bd_shift - 1); | 336 | let round = 1i64 << (bd_shift - 1); |
| 311 | let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64; | 337 | let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64; |
| 312 | let shift = qp / 6; | 338 | let shift = qp / 6; |
| 313 | - for (i, &level) in levels[..n * n].iter().enumerate() { | ||
| 314 | let value = (((level as i64 * scale) << shift) + round) >> bd_shift; | 339 | let value = (((level as i64 * scale) << shift) + round) >> bd_shift; |
| 315 | - scaled[i] = value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32; | 340 | + value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32 |
| 316 | } | 341 | } |
| 342 | + | ||
| 343 | +/// What a squared error in the transform domain is worth as a squared error in | ||
| 344 | +/// the sample domain. | ||
| 345 | +/// | ||
| 346 | +/// The forward transform's shifts leave the DC at 128 times the mean residual | ||
| 347 | +/// whatever the block size, where an orthonormal transform would leave it at | ||
| 348 | +/// `n` times; the transform is otherwise orthogonal, so coefficient error | ||
| 349 | +/// energy is `(128 / n)^2` times sample error energy and this undoes it. A | ||
| 350 | +/// rate-distortion search over the levels needs it to weigh transform-domain | ||
| 351 | +/// error against a lambda calibrated on samples. | ||
| 352 | +pub fn coeff_ssd_scale(n: usize) -> f64 { | ||
| 353 | + (n * n) as f64 / (128.0 * 128.0) | ||
| 317 | } | 354 | } |
| 318 | 355 | ||
| 319 | /// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset. | 356 | /// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset. |
crates/ec-h265/tests/conformance.rsmodified+45 -0
| @@ -491,3 +491,48 @@ fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { | |||
| 491 | // Different pictures, different bitstreams. | 491 | // Different pictures, different bitstreams. |
| 492 | assert_ne!(coded[0].au, coded[1].au); | 492 | assert_ne!(coded[0].au, coded[1].au); |
| 493 | } | 493 | } |
| 494 | + | ||
| 495 | +/// Rate-distortion quantisation changes which levels are coded, so the streams | ||
| 496 | +/// it produces are a different set of bins from the plain quantiser's; ffmpeg | ||
| 497 | +/// has to read them back to the same samples the encoder reconstructed. | ||
| 498 | +#[test] | ||
| 499 | +fn rdoq_decodes_bit_exactly() { | ||
| 500 | + if !have_ffmpeg() { | ||
| 501 | + eprintln!("skipping: ffmpeg not installed"); | ||
| 502 | + return; | ||
| 503 | + } | ||
| 504 | + for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 505 | + let (source, coded) = encode_rdoq(w, h, 27, true); | ||
| 506 | + let (_, plain) = encode_rdoq(w, h, 27, false); | ||
| 507 | + let name = format!("rdoq-{w}x{h}"); | ||
| 508 | + assert_ne!( | ||
| 509 | + coded.au, plain.au, | ||
| 510 | + "{name}: the level search changed no byte, so it is not running" | ||
| 511 | + ); | ||
| 512 | + let path = write_au(&name, &coded); | ||
| 513 | + let decoded = match ffmpeg_decode(&path) { | ||
| 514 | + Ok(bytes) => bytes, | ||
| 515 | + Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 516 | + }; | ||
| 517 | + let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 518 | + assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 519 | + let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 520 | + assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); | ||
| 521 | + let quality = psnr(&planes_of(&source), &recon); | ||
| 522 | + assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 523 | + } | ||
| 524 | +} | ||
| 525 | + | ||
| 526 | +/// The natural frame coded with the level search on or off, everything else | ||
| 527 | +/// left at its default. | ||
| 528 | +fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { | ||
| 529 | + let mut cfg = EncoderConfig::new(width, height); | ||
| 530 | + cfg.rdoq = rdoq; | ||
| 531 | + cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 532 | + cfg.keep_recon = true; | ||
| 533 | + cfg.picture_hash = true; | ||
| 534 | + let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 535 | + let frame = natural_frame(width, height, 0); | ||
| 536 | + let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 537 | + (frame, coded) | ||
| 538 | +} | ||
crates/ec-h265/tests/encode.rsmodified+32 -5
| @@ -438,6 +438,9 @@ fn bd_psnr_vs_x265() { | |||
| 438 | if let Ok(v) = std::env::var("EC_H265_SDH") { | 438 | if let Ok(v) = std::env::var("EC_H265_SDH") { |
| 439 | cfg.sign_hiding = v != "0"; | 439 | cfg.sign_hiding = v != "0"; |
| 440 | } | 440 | } |
| 441 | + if let Ok(v) = std::env::var("EC_H265_RDOQ") { | ||
| 442 | + cfg.rdoq = v != "0"; | ||
| 443 | + } | ||
| 441 | if let Ok(v) = std::env::var("EC_H265_NXN") { | 444 | if let Ok(v) = std::env::var("EC_H265_NXN") { |
| 442 | cfg.intra_nxn = v != "0"; | 445 | cfg.intra_nxn = v != "0"; |
| 443 | } | 446 | } |
| @@ -542,7 +545,9 @@ fn bd_psnr_vs_x265() { | |||
| 542 | // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that | 545 | // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that |
| 543 | // shift. If the extrapolation share still exceeds 20% after measuring, the | 546 | // shift. If the extrapolation share still exceeds 20% after measuring, the |
| 544 | // shift is re-estimated from the geometric-mean bit ratio of the two full | 547 | // shift is re-estimated from the geometric-mean bit ratio of the two full |
| 545 | - // curves and the ladder is rebuilt — at most 2 extra alignment rounds | 548 | + // curves and the ladder is rebuilt; once the rates match and the curves |
| 549 | + // still do not meet, our ladder is drawn in towards its own centre until | ||
| 550 | + // its bitrate range fits inside the anchor's — at most 8 alignment rounds | ||
| 546 | // before the existing panic fires. | 551 | // before the existing panic fires. |
| 547 | const EXTRAP_LIMIT: f64 = 0.20; | 552 | const EXTRAP_LIMIT: f64 = 0.20; |
| 548 | let x265_qps = [22, 26, 30, 34]; | 553 | let x265_qps = [22, 26, 30, 34]; |
| @@ -589,9 +594,17 @@ fn bd_psnr_vs_x265() { | |||
| 589 | ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); | 594 | ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); |
| 590 | let mut mine: Vec<(f64, f64, f64)>; | 595 | let mut mine: Vec<(f64, f64, f64)>; |
| 591 | let mut our_qps: [i32; 4]; | 596 | let mut our_qps: [i32; 4]; |
| 597 | + // How wide our QP ladder is against the anchor's, as a fraction of its | ||
| 598 | + // spacing: one encoder can answer a QP step with far more bitrate than the | ||
| 599 | + // other, and a BD number needs both curves over the same range. | ||
| 600 | + let mut spread = 1.0_f64; | ||
| 592 | 601 | ||
| 593 | - for round in 0..=2u32 { | 602 | + for round in 0..=8u32 { |
| 594 | - our_qps = x265_qps.map(|q| (q + shift).clamp(1, 45)); | 603 | + our_qps = x265_qps.map(|q| { |
| 604 | + let centre = f64::from(probe_qp + shift); | ||
| 605 | + let offset = f64::from(q - probe_qp) * spread; | ||
| 606 | + ((centre + offset).round() as i32).clamp(1, 45) | ||
| 607 | + }); | ||
| 595 | mine = our_qps | 608 | mine = our_qps |
| 596 | .iter() | 609 | .iter() |
| 597 | .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) | 610 | .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) |
| @@ -621,12 +634,15 @@ fn bd_psnr_vs_x265() { | |||
| 621 | && anc_extrap <= EXTRAP_LIMIT | 634 | && anc_extrap <= EXTRAP_LIMIT |
| 622 | && cand_extrap_yuv <= EXTRAP_LIMIT | 635 | && cand_extrap_yuv <= EXTRAP_LIMIT |
| 623 | && anc_extrap_yuv <= EXTRAP_LIMIT; | 636 | && anc_extrap_yuv <= EXTRAP_LIMIT; |
| 624 | - if aligned || round == 2 { | 637 | + if aligned || round == 8 { |
| 625 | break; | 638 | break; |
| 626 | } | 639 | } |
| 627 | // Re-estimate the shift from the geometric-mean bit ratio of the two | 640 | // Re-estimate the shift from the geometric-mean bit ratio of the two |
| 628 | - // full curves, then rebuild the ladder. | 641 | + // full curves, then rebuild the ladder. A single-QP correction is |
| 642 | + // ignored: it is within the rounding of the estimate and only makes the | ||
| 643 | + // ladder oscillate between two neighbouring shifts. | ||
| 629 | let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; | 644 | let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; |
| 645 | + if delta.abs() > 1 { | ||
| 630 | shift += delta; | 646 | shift += delta; |
| 631 | eprintln!( | 647 | eprintln!( |
| 632 | "alignment round {}: shift {delta:+} -> {shift:+} \ | 648 | "alignment round {}: shift {delta:+} -> {shift:+} \ |
| @@ -635,6 +651,17 @@ fn bd_psnr_vs_x265() { | |||
| 635 | gm(&mine) / 1e6, | 651 | gm(&mine) / 1e6, |
| 636 | gm(&theirs) / 1e6, | 652 | gm(&theirs) / 1e6, |
| 637 | ); | 653 | ); |
| 654 | + continue; | ||
| 655 | + } | ||
| 656 | + // The rates match and the curves still do not overlap, so our ladder | ||
| 657 | + // spans a much wider bitrate range than the anchor's: their union is | ||
| 658 | + // then mostly outside what x265 measured and the cubic through its four | ||
| 659 | + // points extrapolates over most of it. Draw our ladder in. | ||
| 660 | + spread *= 0.5; | ||
| 661 | + eprintln!( | ||
| 662 | + "alignment round {}: ladder spread -> {spread:.2} of the anchor's", | ||
| 663 | + round + 1 | ||
| 664 | + ); | ||
| 638 | } | 665 | } |
| 639 | 666 | ||
| 640 | // A BD number over a range where the two QP ladders do not overlap is not a | 667 | // A BD number over a range where the two QP ladders do not overlap is not a |