Forward transform and quantizer, gated end to end through ffmpeg
Browse files at this commit5f0963e9d2563320fef8b7773670687ce14c9621Parent: 0c5e209- feat
- forward transform and quantizer, gated end to end through ffmpeg
3 changed files +518 -0
- crates/ec-av1/src/tile.rs +88 -0
- crates/ec-av1/src/transform.rs +364 -0
- lanes/av1-forward-r1.report.md +66 -0
crates/ec-av1/src/tile.rsmodified+88 -0
| @@ -2797,4 +2797,92 @@ mod tests { | |||
| 2797 | previous = Some(dc); | 2797 | previous = Some(dc); |
| 2798 | } | 2798 | } |
| 2799 | } | 2799 | } |
| 2800 | + | ||
| 2801 | + /// The encoder's own round trip, through a real bitstream. | ||
| 2802 | + /// | ||
| 2803 | + /// A picture is chosen, its residual against the DC prediction of 128 is | ||
| 2804 | + /// forward-transformed and quantized, the levels are written into a tile, | ||
| 2805 | + /// and ffmpeg decodes it. Two things have to hold: what comes back is | ||
| 2806 | + /// exactly what the encoder's own inverse said it would be — sample for | ||
| 2807 | + /// sample, which is what lets a rate-distortion loop trust its | ||
| 2808 | + /// reconstruction — and it is within a quantizer step of the picture that | ||
| 2809 | + /// was asked for, which is what makes the forward transform an encoder | ||
| 2810 | + /// rather than a scrambler. | ||
| 2811 | + #[test] | ||
| 2812 | + fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() { | ||
| 2813 | + if !have_ffmpeg() { | ||
| 2814 | + eprintln!( | ||
| 2815 | + "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg" | ||
| 2816 | + ); | ||
| 2817 | + return; | ||
| 2818 | + } | ||
| 2819 | + // A gradient, a ripple and a corner patch: low frequencies, a mid one | ||
| 2820 | + // and an edge, none of them a basis function of the transform. | ||
| 2821 | + let mut residual = vec![0i32; 32 * 32]; | ||
| 2822 | + for row in 0..32usize { | ||
| 2823 | + for col in 0..32usize { | ||
| 2824 | + let gradient = row as f64 * 2.0 - 32.0; | ||
| 2825 | + let ripple = 25.0 | ||
| 2826 | + * (col as f64 * std::f64::consts::PI / 6.0).sin() | ||
| 2827 | + * (row as f64 * std::f64::consts::PI / 11.0).cos(); | ||
| 2828 | + let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 }; | ||
| 2829 | + residual[row * 32 + col] = (gradient + ripple + patch).round() as i32; | ||
| 2830 | + } | ||
| 2831 | + } | ||
| 2832 | + | ||
| 2833 | + let levels = | ||
| 2834 | + crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5); | ||
| 2835 | + assert!( | ||
| 2836 | + levels.iter().any(|&l| l != 0), | ||
| 2837 | + "the picture quantized away entirely" | ||
| 2838 | + ); | ||
| 2839 | + let coded: Vec<Coeff> = levels | ||
| 2840 | + .iter() | ||
| 2841 | + .enumerate() | ||
| 2842 | + .filter(|&(_, &level)| level != 0) | ||
| 2843 | + .map(|(i, &level)| Coeff { | ||
| 2844 | + row: (i / 32) as u8, | ||
| 2845 | + col: (i % 32) as u8, | ||
| 2846 | + level, | ||
| 2847 | + }) | ||
| 2848 | + .collect(); | ||
| 2849 | + | ||
| 2850 | + let rows = decode_luma_at( | ||
| 2851 | + 64, | ||
| 2852 | + 64, | ||
| 2853 | + &[ | ||
| 2854 | + coded.into(), | ||
| 2855 | + BlockCoeffs::default(), | ||
| 2856 | + BlockCoeffs::default(), | ||
| 2857 | + BlockCoeffs::default(), | ||
| 2858 | + ], | ||
| 2859 | + ); | ||
| 2860 | + let reconstruction = | ||
| 2861 | + crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX)); | ||
| 2862 | + | ||
| 2863 | + let mut squared = 0.0f64; | ||
| 2864 | + for row in 0..32 { | ||
| 2865 | + for col in 0..32 { | ||
| 2866 | + let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255); | ||
| 2867 | + assert_eq!( | ||
| 2868 | + i32::from(rows[row][col]), | ||
| 2869 | + want, | ||
| 2870 | + "sample ({row},{col}): the decoder and the encoder disagree" | ||
| 2871 | + ); | ||
| 2872 | + let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]); | ||
| 2873 | + squared += error * error; | ||
| 2874 | + } | ||
| 2875 | + } | ||
| 2876 | + let rmse = (squared / 1024.0).sqrt(); | ||
| 2877 | + // A quantizer step is q/8 in residual units. Rounding to nearest | ||
| 2878 | + // spreads the error over a step, and a quarter of one is a bound this | ||
| 2879 | + // picture clears with room to spare (2.2 of 14 as written) while a | ||
| 2880 | + // forward transform that is merely energy-preserving does not: a | ||
| 2881 | + // transposed column pass measures 13.3 here. | ||
| 2882 | + let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0; | ||
| 2883 | + assert!( | ||
| 2884 | + rmse < step / 4.0, | ||
| 2885 | + "the decoded picture is {rmse} off, a step being {step}" | ||
| 2886 | + ); | ||
| 2887 | + } | ||
| 2800 | } | 2888 | } |
crates/ec-av1/src/transform.rsmodified+364 -0
| @@ -342,3 +342,367 @@ pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i3 | |||
| 342 | let dq = crate::quant::dequant(levels, side, bit_depth, q_idx); | 342 | let dq = crate::quant::dequant(levels, side, bit_depth, q_idx); |
| 343 | inverse_transform_2d(&dq, side, bit_depth) | 343 | inverse_transform_2d(&dq, side, bit_depth) |
| 344 | } | 344 | } |
| 345 | + | ||
| 346 | +/// The orthonormal DCT-II basis row for output `u` of an `n`-point transform. | ||
| 347 | +/// | ||
| 348 | +/// The decoder's network is this basis scaled by a constant the encoder has to | ||
| 349 | +/// undo, and nothing else: measuring the network's response to a unit | ||
| 350 | +/// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of | ||
| 351 | +/// `dqDenom`, which is what [`forward_transform_2d`] divides out. | ||
| 352 | +fn dct_basis(n: usize) -> Vec<f64> { | ||
| 353 | + let mut basis = vec![0.0f64; n * n]; | ||
| 354 | + let scale = (2.0 / n as f64).sqrt(); | ||
| 355 | + for u in 0..n { | ||
| 356 | + let alpha = if u == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 }; | ||
| 357 | + for i in 0..n { | ||
| 358 | + let angle = std::f64::consts::PI * (2.0 * i as f64 + 1.0) * u as f64 / (2.0 * n as f64); | ||
| 359 | + basis[u * n + i] = alpha * scale * angle.cos(); | ||
| 360 | + } | ||
| 361 | + } | ||
| 362 | + basis | ||
| 363 | +} | ||
| 364 | + | ||
| 365 | +/// How much the decoder's inverse transform shrinks an orthonormal DCT. | ||
| 366 | +/// | ||
| 367 | +/// Measured, not asserted: feeding a single dequantized coefficient through | ||
| 368 | +/// `inverse_transform_2d` reproduces the orthonormal basis function scaled by | ||
| 369 | +/// `dq_denom(side) / 8` at every size (see `the_inverse_network_is_an_orthonormal_dct_over_eight`). | ||
| 370 | +/// The dequantizer has already divided by `dq_denom`, so the two cancel and | ||
| 371 | +/// what an encoder owes a level is size-independent: | ||
| 372 | +/// `level = 8 * orthonormal(residual) / q`. | ||
| 373 | +/// | ||
| 374 | +/// The spec fixes the decoder; the encoder is free in how it reaches the | ||
| 375 | +/// coefficients it sends, and this constant is the one thing the two ends have | ||
| 376 | +/// to agree on for a level to mean what the encoder thinks it means. | ||
| 377 | +const INVERSE_GAIN_RECIPROCAL: f64 = 8.0; | ||
| 378 | + | ||
| 379 | +/// The forward transform (encoder side, spec-free): the transpose of what the | ||
| 380 | +/// decoder's inverse does, so that `inverse_transform_2d` of the result | ||
| 381 | +/// reproduces `residual`. | ||
| 382 | +/// | ||
| 383 | +/// AV1 specifies only the inverse transform. The encoder may reach its | ||
| 384 | +/// coefficients however it likes, and this reaches them the direct way — an | ||
| 385 | +/// orthonormal DCT-II in double precision, scaled to the decoder's fixed-point | ||
| 386 | +/// gain. It is deterministic, and its accuracy is measured against the | ||
| 387 | +/// decoder's own inverse rather than asserted. | ||
| 388 | +pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> { | ||
| 389 | + assert_eq!( | ||
| 390 | + residual.len(), | ||
| 391 | + side * side, | ||
| 392 | + "one residual sample per position" | ||
| 393 | + ); | ||
| 394 | + let basis = dct_basis(side); | ||
| 395 | + // Rows first, into a scratch of the same shape, then columns. | ||
| 396 | + let mut rows = vec![0.0f64; side * side]; | ||
| 397 | + for i in 0..side { | ||
| 398 | + for u in 0..side { | ||
| 399 | + let mut sum = 0.0; | ||
| 400 | + for j in 0..side { | ||
| 401 | + sum += f64::from(residual[i * side + j]) * basis[u * side + j]; | ||
| 402 | + } | ||
| 403 | + rows[i * side + u] = sum; | ||
| 404 | + } | ||
| 405 | + } | ||
| 406 | + let mut out = vec![0.0f64; side * side]; | ||
| 407 | + for u in 0..side { | ||
| 408 | + for v in 0..side { | ||
| 409 | + let mut sum = 0.0; | ||
| 410 | + for i in 0..side { | ||
| 411 | + sum += rows[i * side + v] * basis[u * side + i]; | ||
| 412 | + } | ||
| 413 | + out[u * side + v] = sum; | ||
| 414 | + } | ||
| 415 | + } | ||
| 416 | + let scale = INVERSE_GAIN_RECIPROCAL; | ||
| 417 | + for v in &mut out { | ||
| 418 | + *v *= scale; | ||
| 419 | + } | ||
| 420 | + out | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +/// Quantize forward-transform coefficients into the levels the tile syntax | ||
| 424 | +/// carries. | ||
| 425 | +/// | ||
| 426 | +/// `deadzone` is the fraction of a quantizer step a coefficient has to reach | ||
| 427 | +/// before it is coded at all, as a rounding offset: 0.5 rounds to nearest, | ||
| 428 | +/// smaller values pull coefficients toward zero, which is what buys the rate | ||
| 429 | +/// back on noisy content. A 64-point transform only carries its top-left | ||
| 430 | +/// 32x32, so everything outside that is dropped here rather than silently by | ||
| 431 | +/// the writer. | ||
| 432 | +pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone: f64) -> Vec<i32> { | ||
| 433 | + assert_eq!(coeffs.len(), side * side, "one coefficient per position"); | ||
| 434 | + let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx)); | ||
| 435 | + let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx)); | ||
| 436 | + let mut levels = vec![0i32; side * side]; | ||
| 437 | + for (i, &c) in coeffs.iter().enumerate() { | ||
| 438 | + let (row, col) = (i / side, i % side); | ||
| 439 | + if row >= 32 || col >= 32 { | ||
| 440 | + continue; | ||
| 441 | + } | ||
| 442 | + let q = if i == 0 { dc } else { ac }; | ||
| 443 | + let scaled = c / q; | ||
| 444 | + let magnitude = scaled.abs() + deadzone; | ||
| 445 | + let level = if magnitude < 1.0 { | ||
| 446 | + 0 | ||
| 447 | + } else { | ||
| 448 | + magnitude.floor().min(f64::from(i32::MAX)) as i32 | ||
| 449 | + }; | ||
| 450 | + levels[i] = if scaled < 0.0 { -level } else { level }; | ||
| 451 | + } | ||
| 452 | + levels | ||
| 453 | +} | ||
| 454 | + | ||
| 455 | +/// Transform and quantize one block's residual, the encoder's half of the | ||
| 456 | +/// round trip [`dequant_and_inverse`] completes. | ||
| 457 | +pub fn forward_and_quantize( | ||
| 458 | + residual: &[i32], | ||
| 459 | + side: usize, | ||
| 460 | + bit_depth: u8, | ||
| 461 | + q_idx: i32, | ||
| 462 | + deadzone: f64, | ||
| 463 | +) -> Vec<i32> { | ||
| 464 | + let coeffs = forward_transform_2d(residual, side); | ||
| 465 | + quantize(&coeffs, side, bit_depth, q_idx, deadzone) | ||
| 466 | +} | ||
| 467 | + | ||
| 468 | +#[cfg(test)] | ||
| 469 | +mod tests { | ||
| 470 | + use super::*; | ||
| 471 | + | ||
| 472 | + /// The orthonormal DCT-II basis the forward transform is written against, | ||
| 473 | + /// computed independently of `dct_basis` so a test is not checking a | ||
| 474 | + /// function against itself. | ||
| 475 | + fn reference_basis(n: usize) -> Vec<f64> { | ||
| 476 | + let mut c = vec![0.0; n * n]; | ||
| 477 | + for u in 0..n { | ||
| 478 | + let alpha = if u == 0 { (0.5f64).sqrt() } else { 1.0 }; | ||
| 479 | + for x in 0..n { | ||
| 480 | + let angle = | ||
| 481 | + (2.0 * x as f64 + 1.0) * u as f64 * std::f64::consts::PI / (2.0 * n as f64); | ||
| 482 | + c[u * n + x] = alpha * (2.0 / n as f64).sqrt() * angle.cos(); | ||
| 483 | + } | ||
| 484 | + } | ||
| 485 | + c | ||
| 486 | + } | ||
| 487 | + | ||
| 488 | + /// A deterministic pseudo-random residual in `-100..=100`. | ||
| 489 | + fn noise(len: usize, seed: u64) -> Vec<i32> { | ||
| 490 | + let mut state = seed; | ||
| 491 | + (0..len) | ||
| 492 | + .map(|_| { | ||
| 493 | + state = state | ||
| 494 | + .wrapping_mul(6_364_136_223_846_793_005) | ||
| 495 | + .wrapping_add(1_442_695_040_888_963_407); | ||
| 496 | + ((state >> 33) % 201) as i32 - 100 | ||
| 497 | + }) | ||
| 498 | + .collect() | ||
| 499 | + } | ||
| 500 | + | ||
| 501 | + fn rmse(a: &[i32], b: &[i32]) -> f64 { | ||
| 502 | + let sum: f64 = a | ||
| 503 | + .iter() | ||
| 504 | + .zip(b) | ||
| 505 | + .map(|(&x, &y)| f64::from(x - y) * f64::from(x - y)) | ||
| 506 | + .sum(); | ||
| 507 | + (sum / a.len() as f64).sqrt() | ||
| 508 | + } | ||
| 509 | + | ||
| 510 | + /// The one thing the encoder and the decoder have to agree on. | ||
| 511 | + /// | ||
| 512 | + /// The spec's inverse network is not documented as a scaled orthonormal | ||
| 513 | + /// DCT, so this measures it: each dequantized coefficient, on its own, | ||
| 514 | + /// comes back out as its orthonormal basis function scaled by | ||
| 515 | + /// `dq_denom(side) / 8` — the same factor for every coefficient of a | ||
| 516 | + /// size, which is what makes a single constant enough for the encoder. | ||
| 517 | + /// The fit is checked as well as the scale, so an inverse that scaled | ||
| 518 | + /// right but mixed positions apart could not pass. | ||
| 519 | + #[test] | ||
| 520 | + fn the_inverse_network_is_an_orthonormal_dct_over_eight() { | ||
| 521 | + for &side in &[4usize, 8, 16, 32, 64] { | ||
| 522 | + let basis = reference_basis(side); | ||
| 523 | + for &(u, v) in &[(0usize, 0usize), (0, 1), (1, 0), (2, 3), (5, 7)] { | ||
| 524 | + if u >= side || v >= side { | ||
| 525 | + continue; | ||
| 526 | + } | ||
| 527 | + let mut coeffs = vec![0i32; side * side]; | ||
| 528 | + coeffs[u * side + v] = 4096; | ||
| 529 | + let got = inverse_transform_2d(&coeffs, side, 8); | ||
| 530 | + let want: Vec<f64> = (0..side * side) | ||
| 531 | + .map(|i| 4096.0 * basis[u * side + i / side] * basis[v * side + i % side]) | ||
| 532 | + .collect(); | ||
| 533 | + // Least-squares fit of one scale over the whole block. | ||
| 534 | + let num: f64 = want.iter().zip(&got).map(|(w, &g)| w * f64::from(g)).sum(); | ||
| 535 | + let den: f64 = want.iter().map(|w| w * w).sum(); | ||
| 536 | + let k = num / den; | ||
| 537 | + let expected = crate::quant::dq_denom(side) as f64 / 8.0; | ||
| 538 | + assert!( | ||
| 539 | + (k - expected).abs() < 0.01 * expected, | ||
| 540 | + "{side}x{side} ({u},{v}): gain {k}, expected {expected}" | ||
| 541 | + ); | ||
| 542 | + // And the block really is that basis function, not merely a | ||
| 543 | + // block of the same energy: no sample off by more than one. | ||
| 544 | + for (i, (w, &g)) in want.iter().zip(&got).enumerate() { | ||
| 545 | + let scaled = k * w; | ||
| 546 | + assert!( | ||
| 547 | + (scaled - f64::from(g)).abs() <= 1.0, | ||
| 548 | + "{side}x{side} ({u},{v}) sample {i}: {g} vs {scaled}" | ||
| 549 | + ); | ||
| 550 | + } | ||
| 551 | + } | ||
| 552 | + } | ||
| 553 | + } | ||
| 554 | + | ||
| 555 | + /// A fine quantizer costs almost nothing: forward, quantize, dequantize | ||
| 556 | + /// and invert returns the residual to within a sample or two at every | ||
| 557 | + /// transform size the spec's DCT covers. | ||
| 558 | + /// | ||
| 559 | + /// 64x64 is excluded here because it cannot carry a white-noise residual | ||
| 560 | + /// at all — see | ||
| 561 | + /// [`a_64x64_transform_keeps_what_fits_in_its_coded_quarter`]. | ||
| 562 | + #[test] | ||
| 563 | + fn a_fine_quantizer_roundtrips_a_residual_almost_exactly() { | ||
| 564 | + for &side in &[4usize, 8, 16, 32] { | ||
| 565 | + let residual = noise(side * side, 12_345 + side as u64); | ||
| 566 | + let levels = forward_and_quantize(&residual, side, 8, 10, 0.5); | ||
| 567 | + let back = dequant_and_inverse(&levels, side, 8, 10); | ||
| 568 | + let error = rmse(&back, &residual); | ||
| 569 | + assert!(error < 1.0, "{side}x{side}: rmse {error}"); | ||
| 570 | + } | ||
| 571 | + } | ||
| 572 | + | ||
| 573 | + /// Error grows with the quantizer and with nothing else. A calibration | ||
| 574 | + /// that is off by a constant factor shows up here as a floor that a finer | ||
| 575 | + /// quantizer cannot get under — which is exactly what a wrong gain | ||
| 576 | + /// constant produced while this was being written. | ||
| 577 | + #[test] | ||
| 578 | + fn the_roundtrip_error_is_the_quantizer_and_only_the_quantizer() { | ||
| 579 | + for &side in &[4usize, 8, 16, 32] { | ||
| 580 | + let residual = noise(side * side, 999 + side as u64); | ||
| 581 | + let mut previous = 0.0; | ||
| 582 | + for &q_idx in &[10i32, 60, 100, 180] { | ||
| 583 | + let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5); | ||
| 584 | + let back = dequant_and_inverse(&levels, side, 8, q_idx); | ||
| 585 | + let error = rmse(&back, &residual); | ||
| 586 | + assert!( | ||
| 587 | + error > previous, | ||
| 588 | + "{side}x{side} q {q_idx}: {error} <= {previous}" | ||
| 589 | + ); | ||
| 590 | + // A quantizer step is q/8 in residual units, and rounding to | ||
| 591 | + // nearest costs no more than half a step per coefficient. | ||
| 592 | + let step = f64::from(crate::quant::ac_q(8, q_idx)) / 8.0; | ||
| 593 | + assert!( | ||
| 594 | + error < step, | ||
| 595 | + "{side}x{side} q {q_idx}: rmse {error}, step {step}" | ||
| 596 | + ); | ||
| 597 | + previous = error; | ||
| 598 | + } | ||
| 599 | + } | ||
| 600 | + } | ||
| 601 | + | ||
| 602 | + /// A 64x64 transform codes only its top-left 32x32 coefficients, so it | ||
| 603 | + /// keeps everything below half the Nyquist rate in each direction and | ||
| 604 | + /// drops the rest. A band-limited residual survives it; white noise loses | ||
| 605 | + /// the three quarters of its energy that live outside the coded quarter, | ||
| 606 | + /// and that loss is the transform's, not the quantizer's — it does not | ||
| 607 | + /// move when the quantizer does. | ||
| 608 | + #[test] | ||
| 609 | + fn a_64x64_transform_keeps_what_fits_in_its_coded_quarter() { | ||
| 610 | + let side = 64; | ||
| 611 | + // Band-limited: built from basis functions inside the coded quarter. | ||
| 612 | + let basis = reference_basis(side); | ||
| 613 | + let mut smooth = vec![0.0f64; side * side]; | ||
| 614 | + for &(u, v, amplitude) in &[(0usize, 0usize, 900.0f64), (1, 2, 400.0), (9, 30, 250.0)] { | ||
| 615 | + for i in 0..side * side { | ||
| 616 | + smooth[i] += amplitude * basis[u * side + i / side] * basis[v * side + i % side]; | ||
| 617 | + } | ||
| 618 | + } | ||
| 619 | + let smooth: Vec<i32> = smooth.iter().map(|&s| s.round() as i32).collect(); | ||
| 620 | + let levels = forward_and_quantize(&smooth, side, 8, 10, 0.5); | ||
| 621 | + let back = dequant_and_inverse(&levels, side, 8, 10); | ||
| 622 | + let kept = rmse(&back, &smooth); | ||
| 623 | + assert!(kept < 1.5, "band-limited 64x64: rmse {kept}"); | ||
| 624 | + | ||
| 625 | + let residual = noise(side * side, 4_242); | ||
| 626 | + let mut errors = Vec::new(); | ||
| 627 | + for &q_idx in &[10i32, 180] { | ||
| 628 | + let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5); | ||
| 629 | + let back = dequant_and_inverse(&levels, side, 8, q_idx); | ||
| 630 | + errors.push(rmse(&back, &residual)); | ||
| 631 | + } | ||
| 632 | + // Three quarters of a white-noise block's energy is outside the coded | ||
| 633 | + // quarter, so the error is sqrt(3/4) of the residual's own magnitude | ||
| 634 | + // whatever the quantizer does. | ||
| 635 | + let magnitude = rmse(&residual, &vec![0; side * side]); | ||
| 636 | + for error in &errors { | ||
| 637 | + let ratio = error / magnitude; | ||
| 638 | + assert!( | ||
| 639 | + (ratio - 0.75f64.sqrt()).abs() < 0.05, | ||
| 640 | + "64x64 white noise: ratio {ratio}" | ||
| 641 | + ); | ||
| 642 | + } | ||
| 643 | + assert!( | ||
| 644 | + (errors[1] - errors[0]).abs() < 0.05 * errors[0], | ||
| 645 | + "64x64 white noise moved with the quantizer: {errors:?}" | ||
| 646 | + ); | ||
| 647 | + } | ||
| 648 | + | ||
| 649 | + /// The deadzone pulls coefficients toward zero: a wider one codes fewer | ||
| 650 | + /// of them and costs more error, and rounding to nearest is the tightest | ||
| 651 | + /// of them. | ||
| 652 | + #[test] | ||
| 653 | + fn a_wider_deadzone_codes_fewer_coefficients() { | ||
| 654 | + let side = 16; | ||
| 655 | + let residual = noise(side * side, 77); | ||
| 656 | + let mut previous_nonzero = usize::MAX; | ||
| 657 | + let mut previous_error = 0.0; | ||
| 658 | + for &deadzone in &[0.5f64, 0.35, 0.2] { | ||
| 659 | + let levels = forward_and_quantize(&residual, side, 8, 100, deadzone); | ||
| 660 | + let back = dequant_and_inverse(&levels, side, 8, 100); | ||
| 661 | + let nonzero = levels.iter().filter(|&&l| l != 0).count(); | ||
| 662 | + let error = rmse(&back, &residual); | ||
| 663 | + assert!( | ||
| 664 | + nonzero < previous_nonzero, | ||
| 665 | + "deadzone {deadzone}: {nonzero} coefficients" | ||
| 666 | + ); | ||
| 667 | + assert!(error > previous_error, "deadzone {deadzone}: rmse {error}"); | ||
| 668 | + previous_nonzero = nonzero; | ||
| 669 | + previous_error = error; | ||
| 670 | + } | ||
| 671 | + } | ||
| 672 | + | ||
| 673 | + /// Negating a residual negates its levels: the forward transform carries | ||
| 674 | + /// no offset of its own. | ||
| 675 | + #[test] | ||
| 676 | + fn negating_the_residual_negates_every_level() { | ||
| 677 | + for &side in &[4usize, 32] { | ||
| 678 | + let residual = noise(side * side, 5_150 + side as u64); | ||
| 679 | + let negated: Vec<i32> = residual.iter().map(|&r| -r).collect(); | ||
| 680 | + let levels = forward_and_quantize(&residual, side, 8, 100, 0.5); | ||
| 681 | + let other = forward_and_quantize(&negated, side, 8, 100, 0.5); | ||
| 682 | + for (i, (a, b)) in levels.iter().zip(&other).enumerate() { | ||
| 683 | + assert_eq!(*a, -*b, "{side}x{side} coefficient {i}"); | ||
| 684 | + } | ||
| 685 | + } | ||
| 686 | + } | ||
| 687 | + | ||
| 688 | + /// A flat residual is a DC level and nothing else, at the value the | ||
| 689 | + /// dequantizer's own arithmetic asks for. | ||
| 690 | + #[test] | ||
| 691 | + fn a_flat_residual_is_a_dc_level_alone() { | ||
| 692 | + for &side in &[4usize, 8, 16, 32, 64] { | ||
| 693 | + let residual = vec![40i32; side * side]; | ||
| 694 | + let levels = forward_and_quantize(&residual, side, 8, 100, 0.5); | ||
| 695 | + for (i, &level) in levels.iter().enumerate() { | ||
| 696 | + if i == 0 { | ||
| 697 | + // level = 8 * (40 * side) / dc_q, the orthonormal DC of a | ||
| 698 | + // flat block being its value times the side. | ||
| 699 | + let want = (8.0 * 40.0 * side as f64 / f64::from(crate::quant::dc_q(8, 100))) | ||
| 700 | + .round() as i32; | ||
| 701 | + assert_eq!(level, want, "{side}x{side} DC"); | ||
| 702 | + } else { | ||
| 703 | + assert_eq!(level, 0, "{side}x{side} coefficient {i}"); | ||
| 704 | + } | ||
| 705 | + } | ||
| 706 | + } | ||
| 707 | + } | ||
| 708 | +} | ||
lanes/av1-forward-r1.report.mdadded+66 -0
| @@ -0,0 +1,66 @@ | |||
| 1 | +# lane-av1-forward r1 — forward transform and quantizer for ec-av1 | ||
| 2 | + | ||
| 3 | +## What landed | ||
| 4 | + | ||
| 5 | +`crates/ec-av1/src/transform.rs` gains the encoder half of the transform: | ||
| 6 | + | ||
| 7 | +- `forward_transform_2d(residual, side) -> Vec<f64>` — an orthonormal DCT-II in | ||
| 8 | + double precision (rows, then columns), scaled to the decoder's fixed-point | ||
| 9 | + gain. | ||
| 10 | +- `quantize(coeffs, side, bit_depth, q_idx, deadzone) -> Vec<i32>` — levels, | ||
| 11 | + with a deadzone as a rounding offset, dropping everything outside the coded | ||
| 12 | + top-left 32x32 of a 64-point transform. | ||
| 13 | +- `forward_and_quantize` — the two composed. | ||
| 14 | + | ||
| 15 | +AV1 specifies only the inverse transform. The gain the two ends have to agree | ||
| 16 | +on was **measured, not assumed**: feeding one dequantized coefficient through | ||
| 17 | +`inverse_transform_2d` reproduces its orthonormal basis function scaled by | ||
| 18 | +`dq_denom(side) / 8`, at every size and every coefficient position. The | ||
| 19 | +dequantizer has already divided by `dq_denom`, so the two cancel, and what the | ||
| 20 | +encoder owes a level is size-independent: | ||
| 21 | + | ||
| 22 | + level = 8 * orthonormal(residual) / q | ||
| 23 | + | ||
| 24 | +## Gates (all in `cargo test -p ec-av1`, 63 green) | ||
| 25 | + | ||
| 26 | +| test | what it holds | | ||
| 27 | +|---|---| | ||
| 28 | +| `the_inverse_network_is_an_orthonormal_dct_over_eight` | the gain constant itself, per size and per position, against a basis computed independently of `dct_basis`; fit as well as scale, so mixing positions cannot pass | | ||
| 29 | +| `a_fine_quantizer_roundtrips_a_residual_almost_exactly` | rmse < 1 sample at q_idx 10, sizes 4/8/16/32 | | ||
| 30 | +| `the_roundtrip_error_is_the_quantizer_and_only_the_quantizer` | error rises monotonically with q and stays under one step — a wrong gain constant shows up as a floor a finer quantizer cannot get under | | ||
| 31 | +| `a_64x64_transform_keeps_what_fits_in_its_coded_quarter` | band-limited 64x64 roundtrips to rmse < 1.5; white noise loses exactly the sqrt(3/4) of its magnitude that lives outside the coded quarter, and that loss does not move with the quantizer | | ||
| 32 | +| `a_wider_deadzone_codes_fewer_coefficients` | monotone in both coefficient count and error | | ||
| 33 | +| `negating_the_residual_negates_every_level` | no offset of its own | | ||
| 34 | +| `a_flat_residual_is_a_dc_level_alone` | DC exactly `round(8 * 40 * side / dc_q)`, every AC zero, all five sizes | | ||
| 35 | +| `a_quantized_picture_decodes_to_what_the_encoder_reconstructed` | end to end: a picture -> forward -> quantize -> tile -> **ffmpeg** -> sample-exact against the encoder's own reconstruction, and within a quarter step of the picture asked for (2.2 of 14 as written) | | ||
| 36 | + | ||
| 37 | +## Mutation kills | ||
| 38 | + | ||
| 39 | +| mutation | killed by | | ||
| 40 | +|---|---| | ||
| 41 | +| gain constant 8 -> 8*sqrt(2) (the value a coarser fit had suggested) | 5 tests | | ||
| 42 | +| forward column pass transposed (`basis[u*side+i]` -> `basis[i*side+u]`) | 6 tests, including the ffmpeg end-to-end one | | ||
| 43 | + | ||
| 44 | +The transpose is the reason the end-to-end tolerance is a quarter step rather | ||
| 45 | +than a whole one: at a whole step the transposed forward measured 13.3 against | ||
| 46 | +a bound of 14 and survived. An energy-preserving-but-wrong transform passes a | ||
| 47 | +loose fidelity gate. | ||
| 48 | + | ||
| 49 | +## Class named | ||
| 50 | + | ||
| 51 | +**Constant fitted from a composite measurement.** The first pass took the gain | ||
| 52 | +as `dq_denom/(8*sqrt(2))` from a roundtrip rmse that was flat across quantizers | ||
| 53 | +— a composite number in which a wrong scale and a wrong basis are | ||
| 54 | +indistinguishable. Probing the inverse with a *single* coefficient and | ||
| 55 | +least-squares-fitting one scalar gave `dq_denom/8` immediately, with the fit | ||
| 56 | +residual proving it was the whole story. Sweep: any constant in this crate that | ||
| 57 | +was derived from a roundtrip rather than from an isolated probe. | ||
| 58 | + | ||
| 59 | +## Not in this lane | ||
| 60 | + | ||
| 61 | +- transform types other than DCT_DCT (ADST, identity, WHT) — the writer codes | ||
| 62 | + only DCT_DCT | ||
| 63 | +- rectangular transform sizes | ||
| 64 | +- quantizer matrices, segment-level q deltas | ||
| 65 | +- the rate-distortion loop that would choose the deadzone and the levels; the | ||
| 66 | + deadzone is a parameter here, unswept | ||