From 6a838332e78e748ce3508662733eb2f44d7521bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 00:47:13 +0300 Subject: [PATCH] feat(av1): dequantization and the inverse DCT An encoder that cannot say what the decoder will show cannot choose coefficients by what they cost against what they are worth. This adds the decode-side arithmetic to ec-av1: the dequantizer of spec 7.12.3 and the inverse DCT of 7.13, written from the specification's own butterfly stage list so that one network serves every size from 4 to 64. The gate is agreement with a real decoder, sample for sample: two key frames whose first block carries coefficients from DC to the far corner decode under ffmpeg to exactly 128 plus the residual this code computes, over all 1024 and 4096 samples. Beneath that sit the two tables of decoder-pinned DC residuals the tile tests already carried, all 28 levels of each, plus structural gates for the transpose, the sign rounding, and the row shifts of the four sizes the frame syntax cannot reach. Mutation-checked: a cosine table entry off by one, and an 8x8 row shift off by one, each fail a named test. --- crates/ec-av1/src/lib.rs | 2 + crates/ec-av1/src/quant.rs | 215 +++++++++++++++++++++ crates/ec-av1/src/tile.rs | 260 +++++++++++++++++++++++++ crates/ec-av1/src/transform.rs | 344 +++++++++++++++++++++++++++++++++ lanes/av1-fdct-r1.report.md | 50 +++++ 5 files changed, 871 insertions(+) create mode 100644 crates/ec-av1/src/quant.rs create mode 100644 crates/ec-av1/src/transform.rs create mode 100644 lanes/av1-fdct-r1.report.md diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 25983b07..9ea3d260 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -17,5 +17,7 @@ pub mod cdf; pub mod frame; pub mod msac; pub mod obu; +pub mod quant; pub mod sequence; pub mod tile; +pub mod transform; diff --git a/crates/ec-av1/src/quant.rs b/crates/ec-av1/src/quant.rs new file mode 100644 index 00000000..229a7355 --- /dev/null +++ b/crates/ec-av1/src/quant.rs @@ -0,0 +1,215 @@ +//! Dequantization lookups (spec 7.12.2). +//! +//! AV1 reuses VP9's quantizer tables verbatim, and they are vendored here +//! rather than borrowed from `ec-vp9-syntax` so that the AV1 encoder does not +//! depend on a VP9 crate for a table its own spec prints. Both are indexed +//! `[(BitDepth - 8) >> 1][Clip3(0, 255, b)]`. + +/// `dc_qlookup` (spec 8.6.1), for 8-, 10- and 12-bit. +static DC_QLOOKUP: [[i16; 256]; 3] = [ + [ + 4, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 26, + 27, 28, 29, 30, 31, 32, 32, 33, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 43, 43, 44, 45, 46, + 47, 48, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65, + 66, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83, + 84, 85, 85, 87, 88, 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111, + 113, 114, 116, 117, 118, 120, 121, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, + 146, 148, 150, 152, 154, 156, 158, 161, 164, 166, 169, 172, 174, 177, 180, 182, 185, 187, + 190, 192, 195, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 230, 233, 237, 240, 243, + 247, 250, 253, 257, 261, 265, 269, 272, 276, 280, 284, 288, 292, 296, 300, 304, 309, 313, + 317, 322, 326, 330, 335, 340, 344, 349, 354, 359, 364, 369, 374, 379, 384, 389, 395, 400, + 406, 411, 417, 423, 429, 435, 441, 447, 454, 461, 467, 475, 482, 489, 497, 505, 513, 522, + 530, 539, 549, 559, 569, 579, 590, 602, 614, 626, 640, 654, 668, 684, 700, 717, 736, 755, + 775, 796, 819, 843, 869, 896, 925, 955, 988, 1022, 1058, 1098, 1139, 1184, 1232, 1282, + 1336, + ], + [ + 4, 9, 10, 13, 15, 17, 20, 22, 25, 28, 31, 34, 37, 40, 43, 47, 50, 53, 57, 60, 64, 68, 71, + 75, 78, 82, 86, 90, 93, 97, 101, 105, 109, 113, 116, 120, 124, 128, 132, 136, 140, 143, + 147, 151, 155, 159, 163, 166, 170, 174, 178, 182, 185, 189, 193, 197, 200, 204, 208, 212, + 215, 219, 223, 226, 230, 233, 237, 241, 244, 248, 251, 255, 259, 262, 266, 269, 273, 276, + 280, 283, 287, 290, 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 327, 331, 334, 337, + 343, 350, 356, 362, 369, 375, 381, 387, 394, 400, 406, 412, 418, 424, 430, 436, 442, 448, + 454, 460, 466, 472, 478, 484, 490, 499, 507, 516, 525, 533, 542, 550, 559, 567, 576, 584, + 592, 601, 609, 617, 625, 634, 644, 655, 666, 676, 687, 698, 708, 718, 729, 739, 749, 759, + 770, 782, 795, 807, 819, 831, 844, 856, 868, 880, 891, 906, 920, 933, 947, 961, 975, 988, + 1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105, 1120, 1137, 1153, 1170, 1186, 1202, 1218, + 1236, 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379, 1398, 1416, 1436, 1456, 1476, 1496, + 1516, 1537, 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717, 1741, 1766, 1791, 1817, 1844, + 1871, 1900, 1929, 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197, 2236, 2276, 2319, 2363, + 2410, 2458, 2508, 2561, 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102, 3188, 3280, 3375, + 3478, 3586, 3702, 3823, 3953, 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347, + ], + [ + 4, 12, 18, 25, 33, 41, 50, 60, 70, 80, 91, 103, 115, 127, 140, 153, 166, 180, 194, 208, + 222, 237, 251, 266, 281, 296, 312, 327, 343, 358, 374, 390, 405, 421, 437, 453, 469, 484, + 500, 516, 532, 548, 564, 580, 596, 611, 627, 643, 659, 674, 690, 706, 721, 737, 752, 768, + 783, 798, 814, 829, 844, 859, 874, 889, 904, 919, 934, 949, 964, 978, 993, 1008, 1022, + 1037, 1051, 1065, 1080, 1094, 1108, 1122, 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234, + 1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342, 1368, 1393, 1419, 1444, 1469, 1494, 1519, + 1544, 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741, 1765, 1789, 1814, 1838, 1862, 1885, + 1909, 1933, 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199, 2233, 2267, 2300, 2334, 2367, + 2400, 2434, 2467, 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788, 2830, 2872, 2913, 2954, + 2995, 3036, 3076, 3127, 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517, 3565, 3621, 3677, + 3733, 3788, 3843, 3897, 3951, 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420, 4479, 4546, + 4612, 4677, 4742, 4807, 4871, 4942, 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517, 5591, + 5665, 5745, 5825, 5905, 5984, 6063, 6149, 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867, + 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715, 7832, 7958, 8085, 8214, 8352, 8492, 8635, + 8788, 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245, 10465, 10702, 10946, 11210, 11482, + 11776, 12081, 12409, 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812, 16356, 16943, + 17575, 18237, 18949, 19718, 20521, 21387, + ], +]; + +/// `ac_qlookup` (spec 8.6.1), for 8-, 10- and 12-bit. +static AC_QLOOKUP: [[i16; 256]; 3] = [ + [ + 4, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, + 99, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 155, 158, 161, 164, 167, 170, 173, + 176, 179, 182, 185, 188, 191, 194, 197, 200, 203, 207, 211, 215, 219, 223, 227, 231, 235, + 239, 243, 247, 251, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 311, 317, 323, + 329, 335, 341, 347, 353, 359, 366, 373, 380, 387, 394, 401, 408, 416, 424, 432, 440, 448, + 456, 465, 474, 483, 492, 501, 510, 520, 530, 540, 550, 560, 571, 582, 593, 604, 615, 627, + 639, 651, 663, 676, 689, 702, 715, 729, 743, 757, 771, 786, 801, 816, 832, 848, 864, 881, + 898, 915, 933, 951, 969, 988, 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151, 1173, 1196, + 1219, 1243, 1267, 1292, 1317, 1343, 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567, 1597, + 1628, 1660, 1692, 1725, 1759, 1793, 1828, + ], + [ + 4, 9, 11, 13, 16, 18, 21, 24, 27, 30, 33, 37, 40, 44, 48, 51, 55, 59, 63, 67, 71, 75, 79, + 83, 88, 92, 96, 100, 105, 109, 114, 118, 122, 127, 131, 136, 140, 145, 149, 154, 158, 163, + 168, 172, 177, 181, 186, 190, 195, 199, 204, 208, 213, 217, 222, 226, 231, 235, 240, 244, + 249, 253, 258, 262, 267, 271, 275, 280, 284, 289, 293, 297, 302, 306, 311, 315, 319, 324, + 328, 332, 337, 341, 345, 349, 354, 358, 362, 367, 371, 375, 379, 384, 388, 392, 396, 401, + 409, 417, 425, 433, 441, 449, 458, 466, 474, 482, 490, 498, 506, 514, 523, 531, 539, 547, + 555, 563, 571, 579, 588, 596, 604, 616, 628, 640, 652, 664, 676, 688, 700, 713, 725, 737, + 749, 761, 773, 785, 797, 809, 825, 841, 857, 873, 889, 905, 922, 938, 954, 970, 986, 1002, + 1018, 1038, 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198, 1218, 1242, 1266, 1290, 1314, + 1338, 1362, 1386, 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603, 1631, 1663, 1695, 1727, + 1759, 1791, 1823, 1859, 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159, 2199, 2239, 2283, + 2327, 2371, 2415, 2459, 2507, 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915, 2971, 3027, + 3083, 3143, 3203, 3263, 3327, 3391, 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952, 4028, + 4104, 4184, 4264, 4348, 4432, 4516, 4604, 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372, + 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268, 6388, 6512, 6640, 6768, 6900, 7036, 7172, + 7312, + ], + [ + 4, 13, 19, 27, 35, 44, 54, 64, 75, 87, 99, 112, 126, 139, 154, 168, 183, 199, 214, 230, + 247, 263, 280, 297, 314, 331, 349, 366, 384, 402, 420, 438, 456, 475, 493, 511, 530, 548, + 567, 586, 604, 623, 642, 660, 679, 698, 716, 735, 753, 772, 791, 809, 828, 846, 865, 884, + 902, 920, 939, 957, 976, 994, 1012, 1030, 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175, + 1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317, 1335, 1352, 1370, 1387, 1405, 1422, 1440, + 1457, 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595, 1627, 1660, 1693, 1725, 1758, 1791, + 1824, 1856, 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118, 2150, 2183, 2216, 2248, 2281, + 2313, 2346, 2378, 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750, 2798, 2847, 2895, 2943, + 2992, 3040, 3088, 3137, 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619, 3684, 3748, 3812, + 3876, 3941, 4005, 4069, 4149, 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791, 4871, 4967, + 5064, 5160, 5256, 5352, 5448, 5544, 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410, 6522, + 6650, 6778, 6906, 7034, 7162, 7290, 7435, 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635, + 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028, 10220, 10412, 10604, 10812, 11020, 11228, + 11437, 11661, 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565, 13821, 14093, 14365, + 14637, 14925, 15213, 15502, 15806, 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414, + 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486, 21902, 22334, 22766, 23214, 23662, + 24126, 24590, 25070, 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247, + ], +]; + +/// The bit depth's row in both tables, or `None` for a depth AV1 cannot code. +fn depth_row(bit_depth: u8) -> Option { + match bit_depth { + 8 => Some(0), + 10 => Some(1), + 12 => Some(2), + _ => None, + } +} + +/// `dc_q(b)` (spec 7.12.2): the DC dequantization scale for quantizer index `b`. +/// +/// Out-of-range indices are clamped the way the spec clamps them; an +/// impossible bit depth falls back to the 8-bit row rather than panicking. +pub fn dc_q(bit_depth: u8, b: i32) -> i32 { + i32::from(DC_QLOOKUP[depth_row(bit_depth).unwrap_or(0)][b.clamp(0, 255) as usize]) +} + +/// `ac_q(b)` (spec 7.12.2): the AC dequantization scale for quantizer index `b`. +pub fn ac_q(bit_depth: u8, b: i32) -> i32 { + i32::from(AC_QLOOKUP[depth_row(bit_depth).unwrap_or(0)][b.clamp(0, 255) as usize]) +} + +/// `dqDenom` (spec 7.12.3): what the dequantized coefficient is divided by, +/// which is driven by the transform's area rather than its side. +pub fn dq_denom(side: usize) -> i64 { + match side * side { + 0..=256 => 1, + 257..=1024 => 2, + _ => 4, + } +} + +/// Dequantize one coefficient (spec 7.12.3 steps a-f): scale by the DC or AC +/// quantizer, mask to 24 bits, divide by the transform's denominator toward +/// zero, and clip to the coefficient range. +pub fn dequant_coeff(level: i32, is_dc: bool, bit_depth: u8, q_idx: i32, side: usize) -> i32 { + let q = i64::from(if is_dc { + dc_q(bit_depth, q_idx) + } else { + ac_q(bit_depth, q_idx) + }); + let dq = i64::from(level) * q; + let sign = if dq < 0 { -1 } else { 1 }; + let dq2 = sign * ((dq.abs() & 0xFF_FFFF) / dq_denom(side)); + let bound = 1i64 << (7 + u32::from(bit_depth)); + dq2.clamp(-bound, bound - 1) as i32 +} + +/// Dequantize a whole raster-order coefficient grid of a `side` x `side` +/// transform. +pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec { + levels + .iter() + .enumerate() + .map(|(i, &l)| dequant_coeff(l, i == 0, bit_depth, q_idx, side)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Anchors from the spec tables, and the clamping at both edges. + #[test] + fn table_anchors() { + assert_eq!((dc_q(8, 0), ac_q(8, 0)), (4, 4)); + assert_eq!((dc_q(8, 255), ac_q(8, 255)), (1336, 1828)); + assert_eq!((dc_q(8, 100), ac_q(8, 100)), (93, 112)); + assert_eq!(dc_q(8, -5), dc_q(8, 0)); + assert_eq!(ac_q(8, 9999), ac_q(8, 255)); + } + + /// The denominator is an area threshold, not a side one: 16x16 divides by + /// one, 32x32 by two and 64x64 by four. + #[test] + fn denominator_follows_the_area() { + assert_eq!([4, 8, 16, 32, 64].map(dq_denom), [1, 1, 1, 2, 4]); + } + + /// Negative levels round toward zero, so a level and its negation + /// dequantize to values that differ only in sign. + #[test] + fn dequant_is_symmetric_in_sign() { + for side in [32, 64] { + for level in 1..20 { + assert_eq!( + dequant_coeff(level, false, 8, 100, side), + -dequant_coeff(-level, false, 8, 100, side), + "side {side} level {level}" + ); + } + } + } +} diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index efbd0010..f08cf69b 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -2537,4 +2537,264 @@ mod tests { } } } + + /// The whole point of the inverse transform living in the encoder is that + /// it predicts the decoder without asking one. The residual a DC-only + /// 64x64 transform produces has already been pinned from a real decoder in + /// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both + /// signs, has to come back out of `dequant_and_inverse` exactly. + #[test] + fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() { + for (level, _) in DECODED_AT_Q100 { + let mut levels = vec![0i32; 64 * 64]; + levels[0] = level; + let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX)); + let want = dc_residual(level); + assert!( + residual.iter().all(|&r| r == want), + "level {level}: want a flat {want}, got {}..{} (first {})", + residual.iter().min().unwrap(), + residual.iter().max().unwrap(), + residual[0] + ); + } + } + + /// The same gate at the other transform size the encoder codes: a split + /// superblock's 32x32 blocks, whose residuals are pinned in + /// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized + /// coefficient by different denominators, so a size-blind dequantizer + /// passes one table and fails the other. + #[test] + fn the_inverse_transform_reproduces_the_pinned_split_residuals() { + for (level, want) in SPLIT_RESIDUAL_AT_Q100 { + let mut levels = vec![0i32; 32 * 32]; + levels[0] = level; + let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX)); + assert!( + residual.iter().all(|&r| r == want), + "level {level}: want a flat {want}, got {}..{} (first {})", + residual.iter().min().unwrap(), + residual.iter().max().unwrap(), + residual[0] + ); + } + } + + /// A DC-only transform is flat, which is exactly the case that cannot tell + /// a transposed or mis-permuted butterfly network from a correct one. An AC + /// coefficient in the first row must vary along the row and stay constant + /// down each column, and the one in the first column the other way round; + /// a transposed network swaps the two. + #[test] + fn a_single_ac_coefficient_varies_along_its_own_axis() { + for side in [4, 8, 16, 32, 64] { + let mut horizontal = vec![0i32; side * side]; + horizontal[1] = 100; + let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX)); + let mut vertical = vec![0i32; side * side]; + vertical[side] = 100; + let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX)); + for row in 0..side { + for col in 0..side { + assert_eq!( + h[row * side + col], + h[col], + "{side}: a first-row coefficient is constant down column {col}" + ); + assert_eq!( + v[row * side + col], + v[row * side], + "{side}: a first-column coefficient is constant along row {row}" + ); + } + } + // The two are each other's transpose. Only to within a rounding + // step: the spec rounds halves up rather than away from zero, so a + // basis function and its transpose can land a count apart where + // the row and column passes round opposite ways. + assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies"); + for row in 0..side { + for col in 0..side { + let (a, b) = (h[row * side + col], v[col * side + row]); + assert!( + (a - b).abs() <= 1, + "{side}: transpose at ({row},{col}): {a} vs {b}" + ); + } + } + } + } + + /// Negating every level negates every residual, to within the one count + /// the spec's round-halves-up leaves behind. A dequantizer that rounded a + /// negative coefficient away from zero instead of toward it would shift a + /// whole basis function, not a count of it, so the bound is what makes + /// this a test rather than a restatement. + #[test] + fn negating_the_levels_negates_the_residual() { + for side in [32, 64] { + for level in [1, 2, 3, 5, 9, 14, 40, 100] { + let mut levels = vec![0i32; side * side]; + levels[0] = level; + levels[1] = -level; + levels[side + 1] = level * 2; + let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX)); + let negated: Vec = levels.iter().map(|&l| -l).collect(); + let neg = + crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX)); + let worst = pos + .iter() + .zip(&neg) + .map(|(&p, &n)| (p + n).abs()) + .max() + .expect("the block is not empty"); + assert!(worst <= 1, "side {side} level {level}: off by {worst}"); + } + } + } + + /// The pinned tables above are DC-only, and a flat residual cannot tell a + /// correct butterfly network from one that is merely correct at DC. This + /// is the same claim against a real decoder and with real AC content: the + /// top-left block of a key frame predicts a flat mid-grey with no + /// neighbours to read, so what ffmpeg shows there is exactly 128 plus the + /// residual the encoder's own inverse transform computes. Every sample has + /// to agree, not most of them. + #[test] + fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() { + if !have_ffmpeg() { + eprintln!( + "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg" + ); + return; + } + // A DC, two low-frequency terms of each orientation, a diagonal and a + // far corner, with both signs among them. + let coeffs = [ + (0u8, 0u8, 9i32), + (0, 1, -14), + (1, 0, 7), + (0, 3, 5), + (3, 0, -3), + (2, 2, 11), + (7, 5, -6), + (31, 31, 4), + ]; + let block: BlockCoeffs = coeffs + .iter() + .map(|&(row, col, level)| Coeff { row, col, level }) + .collect::>() + .into(); + let rows = decode_luma_at( + 64, + 64, + &[ + block, + BlockCoeffs::default(), + BlockCoeffs::default(), + BlockCoeffs::default(), + ], + ); + + let mut levels = vec![0i32; 32 * 32]; + for &(row, col, level) in &coeffs { + levels[usize::from(row) * 32 + usize::from(col)] = level; + } + let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX)); + for row in 0..32 { + for col in 0..32 { + let want = (128 + residual[row * 32 + col]).clamp(0, 255); + assert_eq!( + i32::from(rows[row][col]), + want, + "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}", + rows[row][col] + ); + } + } + // The block is not flat, so the agreement is about the transform and + // not about a prediction both sides got trivially right. + let (lo, hi) = ( + rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(), + rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(), + ); + assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}"); + } + + /// The same against the other transform size, the 64x64 one a whole + /// superblock carries. Only its top-left 32x32 can hold coefficients, and + /// the spec zeroes the rest before the row transform — a 64-point network + /// that read the missing half as anything else would disagree here. + #[test] + fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() { + if !have_ffmpeg() { + eprintln!( + "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg" + ); + return; + } + let coeffs = [ + (0u8, 0u8, 12i32), + (0, 2, -9), + (2, 0, 6), + (1, 1, -5), + (5, 9, 8), + (31, 0, -4), + (0, 31, 3), + ]; + let block: BlockCoeffs = coeffs + .iter() + .map(|&(row, col, level)| Coeff { row, col, level }) + .collect::>() + .into(); + let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]); + + let mut levels = vec![0i32; 64 * 64]; + for &(row, col, level) in &coeffs { + levels[usize::from(row) * 64 + usize::from(col)] = level; + } + let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX)); + for row in 0..64 { + for col in 0..64 { + let want = (128 + residual[row * 64 + col]).clamp(0, 255); + assert_eq!( + i32::from(rows[row][col]), + want, + "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}", + rows[row][col] + ); + } + } + } + + /// The AV1 transforms are normalized so that a quantized level means the + /// same thing at every size: doubling the transform's side halves what a + /// DC level is worth, which is the job the per-size row shift and the + /// dequantizer's denominator split between them. The frame syntax only + /// codes 32x32 and 64x64 transforms, so this is what holds the four + /// smaller sizes' shifts to the spec's table — a shift wrong by one at any + /// size doubles or halves that size's step alone. + #[test] + fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() { + let mut previous: Option = None; + for side in [4usize, 8, 16, 32, 64] { + let mut levels = vec![0i32; side * side]; + levels[0] = 100; + let residual = + crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX)); + let dc = residual[0]; + assert!( + residual.iter().all(|&r| r == dc), + "side {side}: a DC coefficient reconstructs flat" + ); + if let Some(previous) = previous { + assert!( + (dc * 2 - previous).abs() <= 1, + "side {side}: {dc} is not half of the previous size's {previous}" + ); + } + previous = Some(dc); + } + } } diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs new file mode 100644 index 00000000..be75cb4d --- /dev/null +++ b/crates/ec-av1/src/transform.rs @@ -0,0 +1,344 @@ +//! The inverse transform (spec 7.13), so the encoder can reconstruct exactly +//! what a decoder will show. +//! +//! Only the inverse DCT is here, which is all this encoder's subset codes: a +//! square `DCT_DCT` transform per block. The butterfly network is the spec's +//! own, stage for stage — every stage's rounding and intermediate clamp is +//! part of the bitstream contract, so a mathematically equal but differently +//! rounded DCT would drift away from the decoder by a sample here and there. + +/// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded. +static COS128_LOOKUP: [i32; 65] = [ + 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822, + 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967, + 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660, + 1567, 1474, 1380, 1285, 1189, 1092, 995, 897, 799, 700, 601, 501, 401, 301, 201, 101, 0, +]; + +/// The fixed-point position of the cosine table. +const COS_BITS: usize = 12; + +/// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table. +fn cos128(angle: i32) -> i32 { + let angle2 = (angle & 255) as usize; + match angle2 { + 0..=64 => COS128_LOOKUP[angle2], + 65..=128 => -COS128_LOOKUP[128 - angle2], + 129..=192 => -COS128_LOOKUP[angle2 - 128], + _ => COS128_LOOKUP[256 - angle2], + } +} + +/// `sin128(angle)` (spec 7.13.2.1). +fn sin128(angle: i32) -> i32 { + cos128(angle - 64) +} + +/// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`. +fn brev(num_bits: u32, x: usize) -> usize { + (0..num_bits).fold(0, |t, i| t | (((x >> i) & 1) << (num_bits - 1 - i))) +} + +/// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up. +fn round2(x: i32, n: usize) -> i32 { + if n == 0 { + x + } else { + // The intermediate can exceed 32 bits before the shift brings it + // back, which is why it is done in 64. + ((i64::from(x) + (1i64 << (n - 1))) >> n) as i32 + } +} + +/// `Clip3` against a signed integer of `r` bits, which is what bounds every +/// intermediate of the transform. +fn clamp_range(x: i32, r: usize) -> i32 { + let hi = ((1i64 << (r - 1)) - 1) as i32; + let lo = (-(1i64 << (r - 1))) as i32; + x.clamp(lo, hi) +} + +/// `B(a, b, angle, flip, r)` (spec 7.13.2.1): a butterfly rotation, and an +/// exchange of the two entries when `flip` is set. +fn butterfly(t: &mut [i32], a: usize, b: usize, angle: i32, flip: bool, _r: usize) { + let (ta, tb) = (i64::from(t[a]), i64::from(t[b])); + let (c, s) = (i64::from(cos128(angle)), i64::from(sin128(angle))); + let x = ta * c - tb * s; + let y = ta * s + tb * c; + t[a] = ((x + (1 << (COS_BITS - 1))) >> COS_BITS) as i32; + t[b] = ((y + (1 << (COS_BITS - 1))) >> COS_BITS) as i32; + if flip { + t.swap(a, b); + } +} + +/// `H(a, b, flip, r)` (spec 7.13.2.1): a Hadamard rotation, with the indices +/// exchanged when `flip` is set. +fn hadamard(t: &mut [i32], a: usize, b: usize, flip: bool, r: usize) { + let (a, b) = if flip { (b, a) } else { (a, b) }; + let (x, y) = (t[a], t[b]); + t[a] = clamp_range(x.wrapping_add(y), r); + t[b] = clamp_range(x.wrapping_sub(y), r); +} + +/// The inverse DCT array permutation (spec 7.13.2.2): an in-place bit-reversal +/// of the first `1 << n` entries. +fn permute(t: &mut [i32], n: u32) { + let n0 = 1usize << n; + let copy: Vec = t[..n0].to_vec(); + for (i, v) in t[..n0].iter_mut().enumerate() { + *v = copy[brev(n, i)]; + } +} + +/// The inverse DCT process (spec 7.13.2.3): an in-place inverse DCT of the +/// first `1 << n` entries of `t`, clamping intermediates to `r` bits. +/// +/// The stage list is the spec's, in the spec's order; the guards on `n` are +/// what make one network serve every transform size from 4 to 64. +pub fn inverse_dct(t: &mut [i32], n: u32, r: usize) { + assert!((2..=6).contains(&n), "the inverse DCT is defined for 4..64"); + permute(t, n); + + if n == 6 { + for i in 0..16 { + butterfly(t, 32 + i, 63 - i, 63 - 4 * brev(4, i) as i32, false, r); + } + } + if n >= 5 { + for i in 0..8 { + butterfly( + t, + 16 + i, + 31 - i, + 6 + ((brev(3, 7 - i) as i32) << 3), + false, + r, + ); + } + } + if n == 6 { + for i in 0..16 { + hadamard(t, 32 + i * 2, 33 + i * 2, i & 1 == 1, r); + } + } + if n >= 4 { + for i in 0..4 { + butterfly( + t, + 8 + i, + 15 - i, + 12 + ((brev(2, 3 - i) as i32) << 4), + false, + r, + ); + } + } + if n >= 5 { + for i in 0..8 { + hadamard(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r); + } + } + if n == 6 { + for i in 0..4 { + for j in 0..2 { + let angle = 60 - 16 * brev(2, i) as i32 + 64 * j as i32; + butterfly(t, 62 - i * 4 - j, 33 + i * 4 + j, angle, true, r); + } + } + } + if n >= 3 { + for i in 0..2 { + butterfly(t, 4 + i, 7 - i, 56 - 32 * i as i32, false, r); + } + } + if n >= 4 { + for i in 0..4 { + hadamard(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r); + } + } + if n >= 5 { + for i in 0..2 { + for j in 0..2 { + let angle = 24 + ((j as i32) << 6) + ((1 - i as i32) << 5); + butterfly(t, 30 - 4 * i - j, 17 + 4 * i + j, angle, true, r); + } + } + } + if n == 6 { + for i in 0..8 { + for j in 0..2 { + hadamard(t, 32 + i * 4 + j, 35 + i * 4 - j, i & 1 == 1, r); + } + } + } + for i in 0..2 { + butterfly(t, 2 * i, 2 * i + 1, 32 + 16 * i as i32, i == 0, r); + } + if n >= 3 { + for i in 0..2 { + hadamard(t, 4 + 2 * i, 5 + 2 * i, i == 1, r); + } + } + if n >= 4 { + for i in 0..2 { + butterfly(t, 14 - i, 9 + i, 48 + 64 * i as i32, true, r); + } + } + if n >= 5 { + for i in 0..4 { + for j in 0..2 { + hadamard(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r); + } + } + } + if n == 6 { + for i in 0..2 { + for j in 0..4 { + let angle = 56 - (i as i32) * 32 + ((j as i32) >> 1) * 64; + butterfly(t, 61 - i * 8 - j, 34 + i * 8 + j, angle, true, r); + } + } + } + for i in 0..2 { + hadamard(t, i, 3 - i, false, r); + } + if n >= 3 { + butterfly(t, 6, 5, 32, true, r); + } + if n >= 4 { + for i in 0..2 { + for j in 0..2 { + hadamard(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r); + } + } + } + if n >= 5 { + for i in 0..4 { + butterfly(t, 29 - i, 18 + i, 48 + ((i as i32) >> 1) * 64, true, r); + } + } + if n == 6 { + for i in 0..4 { + for j in 0..4 { + hadamard(t, 32 + 8 * i + j, 39 + 8 * i - j, i & 1 == 1, r); + } + } + } + if n >= 3 { + for i in 0..4 { + hadamard(t, i, 7 - i, false, r); + } + } + if n >= 4 { + for i in 0..2 { + butterfly(t, 13 - i, 10 + i, 32, true, r); + } + } + if n >= 5 { + for i in 0..2 { + for j in 0..4 { + hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r); + } + } + } + if n == 6 { + for i in 0..8 { + butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r); + } + } + if n >= 4 { + for i in 0..8 { + hadamard(t, i, 15 - i, false, r); + } + } + if n >= 5 { + for i in 0..4 { + butterfly(t, 27 - i, 20 + i, 32, true, r); + } + } + if n == 6 { + for i in 0..8 { + hadamard(t, 32 + i, 47 - i, false, r); + hadamard(t, 48 + i, 63 - i, true, r); + } + } + if n >= 5 { + for i in 0..16 { + hadamard(t, i, 31 - i, false, r); + } + } + if n == 6 { + for i in 0..8 { + butterfly(t, 55 - i, 40 + i, 32, true, r); + } + } + if n == 6 { + for i in 0..32 { + hadamard(t, i, 63 - i, false, r); + } + } +} + +/// `Transform_Row_Shift` (spec 7.13.3) for the square transforms. +fn row_shift(log2: u32) -> usize { + match log2 { + 2 => 0, + 3 => 1, + _ => 2, + } +} + +/// The 2D inverse transform (spec 7.13.3) for a square `DCT_DCT` block. +/// +/// `dequant` is the dequantized coefficient grid in raster order; the returned +/// residual is in the same order. A 64-point transform only ever carries +/// coefficients in its first 32 rows and columns, and the spec zeroes the rest +/// before the row transform, which is what the `< 32` guard does. +pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec { + let log2 = side.trailing_zeros(); + assert_eq!(1usize << log2, side, "the transform is square"); + assert_eq!(dequant.len(), side * side, "one coefficient per position"); + let row_clamp = usize::from(bit_depth) + 8; + let col_clamp = (usize::from(bit_depth) + 6).max(16); + let mut residual = vec![0i32; side * side]; + + let mut t = [0i32; 64]; + for i in 0..side { + for j in 0..side { + t[j] = if i < 32 && j < 32 { + dequant[i * side + j] + } else { + 0 + }; + } + inverse_dct(&mut t, log2, row_clamp); + for j in 0..side { + // The row's output is shifted, then clamped before the column + // transform reads it back. + residual[i * side + j] = clamp_range(round2(t[j], row_shift(log2)), col_clamp); + } + } + + for j in 0..side { + for i in 0..side { + t[i] = residual[i * side + j]; + } + inverse_dct(&mut t, log2, col_clamp); + for i in 0..side { + residual[i * side + j] = round2(t[i], 4); + } + } + residual +} + +/// Dequantize (spec 7.12.3) and inverse transform one square `DCT_DCT` block, +/// returning its residual in raster order. +/// +/// This is the encoder's model of what the decoder will add to its prediction, +/// so it follows the spec's dequantization exactly, truncation toward zero and +/// all. +pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec { + let dq = crate::quant::dequant(levels, side, bit_depth, q_idx); + inverse_transform_2d(&dq, side, bit_depth) +} diff --git a/lanes/av1-fdct-r1.report.md b/lanes/av1-fdct-r1.report.md new file mode 100644 index 00000000..99b26400 --- /dev/null +++ b/lanes/av1-fdct-r1.report.md @@ -0,0 +1,50 @@ +# lane-av1-fdct r1 — dequantization and the inverse DCT + +## What landed + +`ec-av1` can now compute the residual a decoder will add to its prediction, +which is the piece an encoder needs before it can choose coefficients by +rate-distortion rather than by construction. + +- `crates/ec-av1/src/quant.rs` — `dc_q`/`ac_q` (spec 7.12.2) over the vendored + 8/10/12-bit tables, `dq_denom` and the per-coefficient dequantization of spec + 7.12.3 steps a-f (the 24-bit mask, the divide toward zero, the clip). +- `crates/ec-av1/src/transform.rs` — `cos128`/`sin128`, `brev`, the butterfly + `B` and Hadamard `H` of spec 7.13.2.1, the array permutation of 7.13.2.2, the + whole inverse DCT stage list of 7.13.2.3 for `n = 2..6`, and the 2D driver of + 7.13.3 for square `DCT_DCT`. Written from the specification text, not + transcribed from another encoder. + +## Evidence + +`cargo test --release -p ec-av1` — 55 passed, 0 failed. + +The gates, in order of what they would catch: + +| test | claim | +|---|---| +| `the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block` | eight coefficients, both signs, DC to the far corner; every one of 1024 samples equals what ffmpeg decodes | +| `..._for_a_64x64_block` | the same at 64x64, where the spec zeroes the untransmitted half before the row transform; all 4096 samples | +| `the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals` | all 28 levels of `DECODED_AT_Q100`, the table pinned from a real decoder | +| `the_inverse_transform_reproduces_the_pinned_split_residuals` | all 28 levels of `SPLIT_RESIDUAL_AT_Q100` | +| `a_single_ac_coefficient_varies_along_its_own_axis` | a row basis is constant down its columns and is the transpose of the column basis, at every size | +| `a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles` | holds the row shifts of the four sizes the frame syntax cannot reach | +| `negating_the_levels_negates_the_residual` | the dequantizer rounds toward zero, not down | + +Mutation kills run by hand, both reverted: + +- one `Cos128_Lookup` entry off by one (2896 -> 2897): 2 tests fail. +- the 8x8 row shift 1 -> 0: `a_dc_level_is_worth_half...` fails. Without that + test the mutation survived, which is why it exists — the frame syntax only + codes 32x32 and 64x64, so nothing else reaches the small sizes. + +`cargo clippy --release -p ec-av1 --all-targets`: clean. `cargo fmt -p ec-av1` +applied. + +## Not in this lane + +- ADST, identity and WHT transforms, and the rectangular sizes. The encoder + codes none of them; the DCT stage list is already general over `n = 2..6`. +- Quantization matrices (`using_qmatrix`), which the frame header never sets. +- Choosing coefficients with this: the residual model is here, the + rate-distortion loop that would consume it is the next lane.