Merge branch 'main' into lane-av1comp4
Browse files at this commit2 changed files +409 -81
- crates/ec-av1/src/encode.rs +271 -70
- crates/ec-av1/src/transform.rs +138 -11
crates/ec-av1/src/encode.rsmodified+271 -70
| @@ -588,20 +588,37 @@ fn intra_predict_u8( | |||
| 588 | smooth_neighbor: bool, | 588 | smooth_neighbor: bool, |
| 589 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, | 589 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 590 | ) { | 590 | ) { |
| 591 | - let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect()); | 591 | + // Three heap allocations per call became three stack buffers: this runs |
| 592 | - let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect()); | 592 | + // once per mode per trial, and an edge is at most `bw + bh` samples while |
| 593 | - let mut dst16 = vec![0u16; dst.len()]; | 593 | + // a block is at most `BLOCK * BLOCK`. Same samples either way. |
| 594 | + let mut above_buf = [0u16; 2 * BLOCK]; | ||
| 595 | + let mut left_buf = [0u16; 2 * BLOCK]; | ||
| 596 | + let mut dst_buf = [0u16; BLOCK * BLOCK]; | ||
| 597 | + let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| { | ||
| 598 | + for (d, &v) in buf[..src.len()].iter_mut().zip(src) { | ||
| 599 | + *d = u16::from(v); | ||
| 600 | + } | ||
| 601 | + }; | ||
| 602 | + if let Some(s) = above { | ||
| 603 | + widen(s, &mut above_buf); | ||
| 604 | + } | ||
| 605 | + if let Some(s) = left { | ||
| 606 | + widen(s, &mut left_buf); | ||
| 607 | + } | ||
| 608 | + let above16 = above.map(|s| &above_buf[..s.len()]); | ||
| 609 | + let left16 = left.map(|s| &left_buf[..s.len()]); | ||
| 610 | + let dst16 = &mut dst_buf[..dst.len()]; | ||
| 594 | crate::intra::predict( | 611 | crate::intra::predict( |
| 595 | mode, | 612 | mode, |
| 596 | angle_delta, | 613 | angle_delta, |
| 597 | - above16.as_deref(), | 614 | + above16, |
| 598 | - left16.as_deref(), | 615 | + left16, |
| 599 | corner.map(u16::from), | 616 | corner.map(u16::from), |
| 600 | bw, | 617 | bw, |
| 601 | bh, | 618 | bh, |
| 602 | enable_edge_filter, | 619 | enable_edge_filter, |
| 603 | smooth_neighbor, | 620 | smooth_neighbor, |
| 604 | - &mut dst16, fctx, | 621 | + dst16, fctx, |
| 605 | ); | 622 | ); |
| 606 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { | 623 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { |
| 607 | *d = s as u8; | 624 | *d = s as u8; |
| @@ -1280,6 +1297,40 @@ impl Plane<'_> { | |||
| 1280 | /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps | 1297 | /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps |
| 1281 | /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. | 1298 | /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names. |
| 1282 | #[allow(clippy::too_many_arguments)] | 1299 | #[allow(clippy::too_many_arguments)] |
| 1300 | + /// Sum of absolute differences between the source block at `(x, y)` and a | ||
| 1301 | + /// `side x side` prediction, as the whole number it is. | ||
| 1302 | + /// | ||
| 1303 | + /// Bit-identical to the `f64` accumulation it replaces: every partial sum | ||
| 1304 | + /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds | ||
| 1305 | + /// exactly, so no add here rounds and the order of the adds cannot change | ||
| 1306 | + /// the result. Dropping the per-pixel `i / side` and `i % side` -- an | ||
| 1307 | + /// integer division per sample -- is what lets the row walk vectorize. | ||
| 1308 | + fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 { | ||
| 1309 | + let mut sad = 0u32; | ||
| 1310 | + for row in 0..side { | ||
| 1311 | + let source = &self.source[(y + row) * self.width + x..][..side]; | ||
| 1312 | + for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) { | ||
| 1313 | + sad += u32::from(s.abs_diff(p)); | ||
| 1314 | + } | ||
| 1315 | + } | ||
| 1316 | + f64::from(sad) | ||
| 1317 | + } | ||
| 1318 | + | ||
| 1319 | + /// Squared error between the source block at `(x, y)` and a reconstruction | ||
| 1320 | + /// of it. Exact for the same reason [`Self::block_sad`] is: the largest | ||
| 1321 | + /// total is `255^2 * 64 * 64`, under 2^28. | ||
| 1322 | + fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 { | ||
| 1323 | + let mut sse = 0u64; | ||
| 1324 | + for row in 0..side { | ||
| 1325 | + let source = &self.source[(y + row) * self.width + x..][..side]; | ||
| 1326 | + for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) { | ||
| 1327 | + let d = u32::from(s.abs_diff(r)); | ||
| 1328 | + sse += u64::from(d * d); | ||
| 1329 | + } | ||
| 1330 | + } | ||
| 1331 | + sse as f64 | ||
| 1332 | + } | ||
| 1333 | + | ||
| 1283 | fn trial_typed( | 1334 | fn trial_typed( |
| 1284 | &self, | 1335 | &self, |
| 1285 | at: At, | 1336 | at: At, |
| @@ -1329,19 +1380,12 @@ impl Plane<'_> { | |||
| 1329 | #[cfg(test)] | 1380 | #[cfg(test)] |
| 1330 | stage_add(2, t.elapsed()); | 1381 | stage_add(2, t.elapsed()); |
| 1331 | 1382 | ||
| 1332 | - let mut reconstruction = vec![0u8; side * side]; | 1383 | + let reconstruction: Vec<u8> = prediction |
| 1333 | - let mut sse = 0.0; | 1384 | + .iter() |
| 1334 | - for row in 0..side { | 1385 | + .zip(&coded) |
| 1335 | - for col in 0..side { | 1386 | + .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) |
| 1336 | - let i = row * side + col; | 1387 | + .collect(); |
| 1337 | - let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; | 1388 | + let sse = self.block_sse(x, y, side, &reconstruction); |
| 1338 | - reconstruction[i] = sample; | ||
| 1339 | - let error = f64::from( | ||
| 1340 | - i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), | ||
| 1341 | - ); | ||
| 1342 | - sse += error * error; | ||
| 1343 | - } | ||
| 1344 | - } | ||
| 1345 | // What the levels cost is priced through the same CDFs the tile writer | 1389 | // What the levels cost is priced through the same CDFs the tile writer |
| 1346 | // will code them with, so the search ranks modes -- and the partition | 1390 | // will code them with, so the search ranks modes -- and the partition |
| 1347 | // trial ranks trees -- by the bits they actually spend. | 1391 | // trial ranks trees -- by the bits they actually spend. |
| @@ -1389,16 +1433,7 @@ impl Plane<'_> { | |||
| 1389 | set: TxbSet, | 1433 | set: TxbSet, |
| 1390 | ) -> Trial { | 1434 | ) -> Trial { |
| 1391 | if skip { | 1435 | if skip { |
| 1392 | - let mut sse = 0.0; | 1436 | + let sse = self.block_sse(x, y, side, prediction); |
| 1393 | - for row in 0..side { | ||
| 1394 | - for col in 0..side { | ||
| 1395 | - let error = f64::from( | ||
| 1396 | - i32::from(self.source[(y + row) * self.width + x + col]) | ||
| 1397 | - - i32::from(prediction[row * side + col]), | ||
| 1398 | - ); | ||
| 1399 | - sse += error * error; | ||
| 1400 | - } | ||
| 1401 | - } | ||
| 1402 | return Trial { | 1437 | return Trial { |
| 1403 | levels: vec![0i32; side * side], | 1438 | levels: vec![0i32; side * side], |
| 1404 | reconstruction: prediction.to_vec(), | 1439 | reconstruction: prediction.to_vec(), |
| @@ -1421,19 +1456,12 @@ impl Plane<'_> { | |||
| 1421 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); | 1456 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); |
| 1422 | #[cfg(test)] | 1457 | #[cfg(test)] |
| 1423 | stage_add(2, t.elapsed()); | 1458 | stage_add(2, t.elapsed()); |
| 1424 | - let mut reconstruction = vec![0u8; side * side]; | 1459 | + let reconstruction: Vec<u8> = prediction |
| 1425 | - let mut sse = 0.0; | 1460 | + .iter() |
| 1426 | - for row in 0..side { | 1461 | + .zip(&coded) |
| 1427 | - for col in 0..side { | 1462 | + .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8) |
| 1428 | - let i = row * side + col; | 1463 | + .collect(); |
| 1429 | - let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; | 1464 | + let sse = self.block_sse(x, y, side, &reconstruction); |
| 1430 | - reconstruction[i] = sample; | ||
| 1431 | - let error = f64::from( | ||
| 1432 | - i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), | ||
| 1433 | - ); | ||
| 1434 | - sse += error * error; | ||
| 1435 | - } | ||
| 1436 | - } | ||
| 1437 | #[cfg(test)] | 1465 | #[cfg(test)] |
| 1438 | let t = std::time::Instant::now(); | 1466 | let t = std::time::Instant::now(); |
| 1439 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { | 1467 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| @@ -1518,17 +1546,13 @@ impl Plane<'_> { | |||
| 1518 | /// `source`), since [`Self::source`] itself is the whole plane, strided | 1546 | /// `source`), since [`Self::source`] itself is the whole plane, strided |
| 1519 | /// by [`Self::width`]. | 1547 | /// by [`Self::width`]. |
| 1520 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { | 1548 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 1521 | - (y..y + side) | 1549 | + rows_of(self.source, self.width, x, y, side) |
| 1522 | - .flat_map(|row| self.source[row * self.width + x..][..side].to_vec()) | ||
| 1523 | - .collect() | ||
| 1524 | } | 1550 | } |
| 1525 | 1551 | ||
| 1526 | /// The reconstructed samples of one square, so that a partition trial can | 1552 | /// The reconstructed samples of one square, so that a partition trial can |
| 1527 | /// be undone. | 1553 | /// be undone. |
| 1528 | fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> { | 1554 | fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 1529 | - (y..y + side) | 1555 | + rows_of(&self.reconstruction, self.width, x, y, side) |
| 1530 | - .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec()) | ||
| 1531 | - .collect() | ||
| 1532 | } | 1556 | } |
| 1533 | 1557 | ||
| 1534 | /// Puts a snapshot back. | 1558 | /// Puts a snapshot back. |
| @@ -1570,16 +1594,7 @@ impl Plane<'_> { | |||
| 1570 | false, | 1594 | false, |
| 1571 | &mut prediction, fctx, | 1595 | &mut prediction, fctx, |
| 1572 | ); | 1596 | ); |
| 1573 | - let sad: f64 = (0..side * side) | 1597 | + let sad = self.block_sad(x, y, side, &prediction); |
| 1574 | - .map(|i| { | ||
| 1575 | - let (row, col) = (i / side, i % side); | ||
| 1576 | - f64::from( | ||
| 1577 | - (i32::from(self.source[(y + row) * self.width + x + col]) | ||
| 1578 | - - i32::from(prediction[i])) | ||
| 1579 | - .abs(), | ||
| 1580 | - ) | ||
| 1581 | - }) | ||
| 1582 | - .sum(); | ||
| 1583 | (sad + lambda * mode_bits[usize::from(mode)], mode) | 1598 | (sad + lambda * mode_bits[usize::from(mode)], mode) |
| 1584 | }) | 1599 | }) |
| 1585 | .collect() | 1600 | .collect() |
| @@ -1627,17 +1642,8 @@ impl Plane<'_> { | |||
| 1627 | false, | 1642 | false, |
| 1628 | &mut prediction, fctx, | 1643 | &mut prediction, fctx, |
| 1629 | ); | 1644 | ); |
| 1630 | - let sad: f64 = if want_sad { | 1645 | + let sad = if want_sad { |
| 1631 | - (0..side * side) | 1646 | + self.block_sad(x, y, side, &prediction) |
| 1632 | - .map(|i| { | ||
| 1633 | - let (row, col) = (i / side, i % side); | ||
| 1634 | - f64::from( | ||
| 1635 | - (i32::from(self.source[(y + row) * self.width + x + col]) | ||
| 1636 | - - i32::from(prediction[i])) | ||
| 1637 | - .abs(), | ||
| 1638 | - ) | ||
| 1639 | - }) | ||
| 1640 | - .sum() | ||
| 1641 | } else { | 1647 | } else { |
| 1642 | 0.0 | 1648 | 0.0 |
| 1643 | }; | 1649 | }; |
| @@ -3941,6 +3947,19 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O | |||
| 3941 | 3947 | ||
| 3942 | /// The reconstructed samples one 32x32 square covers in all three planes, so | 3948 | /// The reconstructed samples one 32x32 square covers in all three planes, so |
| 3943 | /// that a partition trial can be undone. | 3949 | /// that a partition trial can be undone. |
| 3950 | +/// One square of a plane, row-major, the inverse of [`Plane::restore`]. | ||
| 3951 | +/// | ||
| 3952 | +/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces, | ||
| 3953 | +/// which allocated and freed a `Vec` per row of every block it copied -- | ||
| 3954 | +/// `Plane::snapshot` runs once per partition trial. | ||
| 3955 | +fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> { | ||
| 3956 | + let mut out = vec![0u8; side * side]; | ||
| 3957 | + for row in 0..side { | ||
| 3958 | + out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]); | ||
| 3959 | + } | ||
| 3960 | + out | ||
| 3961 | +} | ||
| 3962 | + | ||
| 3944 | fn snapshot( | 3963 | fn snapshot( |
| 3945 | luma: &Plane, | 3964 | luma: &Plane, |
| 3946 | chroma: &[Plane; 2], | 3965 | chroma: &[Plane; 2], |
| @@ -9850,11 +9869,26 @@ mod tests { | |||
| 9850 | width: usize, | 9869 | width: usize, |
| 9851 | height: usize, | 9870 | height: usize, |
| 9852 | frames: usize, | 9871 | frames: usize, |
| 9872 | + ) -> Vec<Picture> { | ||
| 9873 | + clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames) | ||
| 9874 | + } | ||
| 9875 | + | ||
| 9876 | + /// [`clip_frames`] with the filter chain spelled out, so a caller can ask | ||
| 9877 | + /// for a native-resolution CROP instead of a downscale (the downscale is | ||
| 9878 | + /// what destroys a screen capture's exact repeats -- class | ||
| 9879 | + /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces. | ||
| 9880 | + fn clip_frames_vf( | ||
| 9881 | + clip: &str, | ||
| 9882 | + skip: &str, | ||
| 9883 | + vf: &str, | ||
| 9884 | + width: usize, | ||
| 9885 | + height: usize, | ||
| 9886 | + frames: usize, | ||
| 9853 | ) -> Vec<Picture> { | 9887 | ) -> Vec<Picture> { |
| 9854 | let out = Command::new("ffmpeg") | 9888 | let out = Command::new("ffmpeg") |
| 9855 | .args(["-v", "error", "-ss", skip, "-i", clip]) | 9889 | .args(["-v", "error", "-ss", skip, "-i", clip]) |
| 9856 | .args(["-frames:v", &frames.to_string()]) | 9890 | .args(["-frames:v", &frames.to_string()]) |
| 9857 | - .args(["-vf", &format!("scale={width}:{height}")]) | 9891 | + .args(["-vf", vf]) |
| 9858 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | 9892 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 9859 | .output() | 9893 | .output() |
| 9860 | .expect("ffmpeg failed to run"); | 9894 | .expect("ffmpeg failed to run"); |
| @@ -10854,4 +10888,171 @@ mod tests { | |||
| 10854 | ); | 10888 | ); |
| 10855 | } | 10889 | } |
| 10856 | } | 10890 | } |
| 10891 | + /// The video stream's coded size, from ffprobe. | ||
| 10892 | + fn probe_dims(clip: &str) -> Option<(usize, usize)> { | ||
| 10893 | + let out = Command::new("ffprobe") | ||
| 10894 | + .args(["-v", "error", "-select_streams", "v:0"]) | ||
| 10895 | + .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"]) | ||
| 10896 | + .arg(clip) | ||
| 10897 | + .output() | ||
| 10898 | + .ok()?; | ||
| 10899 | + let text = String::from_utf8_lossy(&out.stdout); | ||
| 10900 | + let mut f = text.trim().split(','); | ||
| 10901 | + Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?)) | ||
| 10902 | + } | ||
| 10903 | + | ||
| 10904 | + /// The NATIVE-resolution screen arm of the BD gate. The default gate | ||
| 10905 | + /// downscales the OBS capture to 640x384, which destroys exactly the | ||
| 10906 | + /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist | ||
| 10907 | + /// for (class `gate-recipe-confound`), so every screen-tool decision taken | ||
| 10908 | + /// on that recipe is taken on content the tool cannot serve. This arm | ||
| 10909 | + /// crops -- never scales -- a superblock-aligned window out of the middle | ||
| 10910 | + /// of the capture at its own resolution (at most 1920x1024, so the wall | ||
| 10911 | + /// stays in the minutes) and runs the same 12-frame, four-quantizer | ||
| 10912 | + /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one | ||
| 10913 | + /// thread, with the same three-way (encoder / ffmpeg / our decoder) | ||
| 10914 | + /// sample-exactness assertion `our_ladder` makes. | ||
| 10915 | + /// | ||
| 10916 | + /// It is its own `--ignored` test so the default gate's wall does not | ||
| 10917 | + /// grow. Every variant is an environment knob, and each of those is a | ||
| 10918 | + /// `OnceLock` read once per process, so a variant is a separate run: | ||
| 10919 | + /// | ||
| 10920 | + /// cargo test -p ec-av1 --release --lib -- --ignored \ | ||
| 10921 | + /// bd_rate_screen_native --nocapture # baseline | ||
| 10922 | + /// EC_AV1_INTRABC=1 ... same command # intra block copy | ||
| 10923 | + /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound | ||
| 10924 | + /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles | ||
| 10925 | + /// EC_AV1_NATIVE_FILM=1 ... same command # + a film crop row | ||
| 10926 | + #[test] | ||
| 10927 | + #[ignore = "the native-resolution screen BD arm: minutes per row, needs ffmpeg"] | ||
| 10928 | + fn bd_rate_screen_native() { | ||
| 10929 | + if !have_ffmpeg() { | ||
| 10930 | + eprintln!("SKIP bd_rate_screen_native: no ffmpeg"); | ||
| 10931 | + return; | ||
| 10932 | + } | ||
| 10933 | + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); | ||
| 10934 | + let mut clips: Vec<(String, String)> = Vec::new(); | ||
| 10935 | + match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) { | ||
| 10936 | + Ok(manifest) => match manifest | ||
| 10937 | + .lines() | ||
| 10938 | + .skip(1) | ||
| 10939 | + .filter_map(|l| l.split('\t').next()) | ||
| 10940 | + .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) | ||
| 10941 | + { | ||
| 10942 | + Some(p) => clips.push(( | ||
| 10943 | + format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), | ||
| 10944 | + p.to_string(), | ||
| 10945 | + )), | ||
| 10946 | + None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), | ||
| 10947 | + }, | ||
| 10948 | + Err(e) => eprintln!("SKIP bd_rate_screen_native: no real-library manifest ({e})"), | ||
| 10949 | + } | ||
| 10950 | + // The film crop is an extra row, not a default-moving measurement. | ||
| 10951 | + if std::env::var("EC_AV1_NATIVE_FILM").ok().as_deref() == Some("1") { | ||
| 10952 | + let path = fixtures.join("video").join("h264-1080p-23.976-8bit.mp4"); | ||
| 10953 | + if path.exists() { | ||
| 10954 | + clips.push(( | ||
| 10955 | + "film 1080p (native crop)".to_string(), | ||
| 10956 | + path.to_str().unwrap().to_string(), | ||
| 10957 | + )); | ||
| 10958 | + } | ||
| 10959 | + } | ||
| 10960 | + if clips.is_empty() { | ||
| 10961 | + eprintln!("SKIP bd_rate_screen_native: no clip"); | ||
| 10962 | + return; | ||
| 10963 | + } | ||
| 10964 | + | ||
| 10965 | + let frames = 12usize; | ||
| 10966 | + let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] | ||
| 10967 | + .iter() | ||
| 10968 | + .map(|q| { | ||
| 10969 | + ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] | ||
| 10970 | + .map(String::from) | ||
| 10971 | + .to_vec() | ||
| 10972 | + }) | ||
| 10973 | + .collect(); | ||
| 10974 | + let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] | ||
| 10975 | + .iter() | ||
| 10976 | + .map(|q| { | ||
| 10977 | + vec![ | ||
| 10978 | + "-rav1e-params".to_string(), | ||
| 10979 | + format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), | ||
| 10980 | + ] | ||
| 10981 | + }) | ||
| 10982 | + .collect(); | ||
| 10983 | + println!( | ||
| 10984 | + "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \ | ||
| 10985 | + intrabc {}, palette maxcolors {}", | ||
| 10986 | + armed_tiles(), | ||
| 10987 | + crate::par::tile_threads(), | ||
| 10988 | + intrabc_enabled(), | ||
| 10989 | + palette_max_colors(), | ||
| 10990 | + ); | ||
| 10991 | + println!("| clip | size | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"); | ||
| 10992 | + println!("|---|---|---|---|---|---|"); | ||
| 10993 | + for (name, path) in &clips { | ||
| 10994 | + let fctx = &crate::decode::FrameCtx::new(); | ||
| 10995 | + let Some((nw, nh)) = probe_dims(path) else { | ||
| 10996 | + eprintln!("SKIP {name}: ffprobe gave no size"); | ||
| 10997 | + continue; | ||
| 10998 | + }; | ||
| 10999 | + // A whole number of 128-wide superblocks, at most 1920x1024, out | ||
| 11000 | + // of the middle of the frame; the offsets stay even for 4:2:0. | ||
| 11001 | + let cw = nw.min(1920) / 128 * 128; | ||
| 11002 | + let ch = nh.min(1024) / 128 * 128; | ||
| 11003 | + assert!(cw >= 128 && ch >= 128, "{name}: {nw}x{nh} is smaller than a superblock"); | ||
| 11004 | + let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1); | ||
| 11005 | + let source = clip_frames_vf( | ||
| 11006 | + path, | ||
| 11007 | + "0", | ||
| 11008 | + &format!("crop={cw}:{ch}:{x}:{y}"), | ||
| 11009 | + cw, | ||
| 11010 | + ch, | ||
| 11011 | + frames, | ||
| 11012 | + ); | ||
| 11013 | + SCREEN_FRAMES.iter().for_each(|c| { | ||
| 11014 | + c.store(0, std::sync::atomic::Ordering::Relaxed); | ||
| 11015 | + }); | ||
| 11016 | + let _ = crate::tile::take_palette_hits(); | ||
| 11017 | + let _ = crate::tile::take_palette_uv_hits(); | ||
| 11018 | + let _ = crate::tile::take_intrabc_hits(); | ||
| 11019 | + let _ = take_intrabc_search(); | ||
| 11020 | + let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx); | ||
| 11021 | + // gate-blind-to-feature: what the screen tools actually did at | ||
| 11022 | + // native resolution, over this clip's four encodes. | ||
| 11023 | + let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); | ||
| 11024 | + let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); | ||
| 11025 | + let palette = crate::tile::take_palette_hits(); | ||
| 11026 | + let palette_uv = crate::tile::take_palette_uv_hits(); | ||
| 11027 | + let ibc = crate::tile::take_intrabc_hits(); | ||
| 11028 | + let search = take_intrabc_search(); | ||
| 11029 | + eprintln!( | ||
| 11030 | + "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \ | ||
| 11031 | + palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \ | ||
| 11032 | + won {})", | ||
| 11033 | + 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64, | ||
| 11034 | + palette[0], | ||
| 11035 | + palette_uv[0], | ||
| 11036 | + ibc[0], | ||
| 11037 | + search[0], | ||
| 11038 | + search[1], | ||
| 11039 | + search[2], | ||
| 11040 | + ); | ||
| 11041 | + let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points); | ||
| 11042 | + let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points); | ||
| 11043 | + assert_monotone(&format!("{name}: ours"), &ours); | ||
| 11044 | + assert_monotone(&format!("{name}: libaom"), &aom); | ||
| 11045 | + assert_monotone(&format!("{name}: rav1e"), &rav1e); | ||
| 11046 | + let points = ours | ||
| 11047 | + .iter() | ||
| 11048 | + .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) | ||
| 11049 | + .collect::<Vec<_>>() | ||
| 11050 | + .join(", "); | ||
| 11051 | + println!( | ||
| 11052 | + "| {name} | {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", | ||
| 11053 | + bd_rate(&aom, &ours) * 100.0, | ||
| 11054 | + bd_rate(&rav1e, &ours) * 100.0, | ||
| 11055 | + ); | ||
| 11056 | + } | ||
| 11057 | + } | ||
| 10857 | } | 11058 | } |
crates/ec-av1/src/transform.rsmodified+138 -11
| @@ -1442,6 +1442,34 @@ fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] { | |||
| 1442 | cache[k][idx].get_or_init(|| build_axis_basis(n, kind)) | 1442 | cache[k][idx].get_or_init(|| build_axis_basis(n, kind)) |
| 1443 | } | 1443 | } |
| 1444 | 1444 | ||
| 1445 | +/// [`axis_basis`] transposed: `[i * n + u]` is basis function `u`'s sample | ||
| 1446 | +/// `i`. Both of [`forward_transform_2d_typed`]'s passes sum over the sample | ||
| 1447 | +/// index and are independent across the basis index, so this layout makes the | ||
| 1448 | +/// basis index the contiguous one and the two matmuls vectorize -- without | ||
| 1449 | +/// touching either sum's order, which is what keeps the levels bit-identical | ||
| 1450 | +/// to the strided `.map().sum()` this replaced. | ||
| 1451 | +fn axis_basis_t(n: usize, kind: TxType1d) -> &'static [f64] { | ||
| 1452 | + use std::sync::OnceLock; | ||
| 1453 | + static CACHE: OnceLock<[[OnceLock<Vec<f64>>; 5]; 3]> = OnceLock::new(); | ||
| 1454 | + let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new()))); | ||
| 1455 | + let k = match kind { | ||
| 1456 | + TxType1d::Dct => 0, | ||
| 1457 | + TxType1d::Adst => 1, | ||
| 1458 | + TxType1d::Identity => 2, | ||
| 1459 | + }; | ||
| 1460 | + let idx = (n.trailing_zeros() as usize).saturating_sub(2); | ||
| 1461 | + cache[k][idx].get_or_init(|| { | ||
| 1462 | + let basis = axis_basis(n, kind); | ||
| 1463 | + let mut t = vec![0.0f64; n * n]; | ||
| 1464 | + for u in 0..n { | ||
| 1465 | + for i in 0..n { | ||
| 1466 | + t[i * n + u] = basis[u * n + i]; | ||
| 1467 | + } | ||
| 1468 | + } | ||
| 1469 | + t | ||
| 1470 | + }) | ||
| 1471 | +} | ||
| 1472 | + | ||
| 1445 | /// [`forward_transform_2d`] for a block whose transform type is not | 1473 | /// [`forward_transform_2d`] for a block whose transform type is not |
| 1446 | /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode | 1474 | /// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode |
| 1447 | /// gets, since chroma never codes a `tx_type` symbol and the decoder derives | 1475 | /// gets, since chroma never codes a `tx_type` symbol and the decoder derives |
| @@ -1461,8 +1489,14 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType | |||
| 1461 | "a flipped ADST needs its residual mirrored before this basis applies" | 1489 | "a flipped ADST needs its residual mirrored before this basis applies" |
| 1462 | ); | 1490 | ); |
| 1463 | let (row_kind, col_kind) = tx_type.axes(); | 1491 | let (row_kind, col_kind) = tx_type.axes(); |
| 1464 | - let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); | 1492 | + let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind)); |
| 1465 | let mut rows = vec![0.0f64; side * side]; | 1493 | let mut rows = vec![0.0f64; side * side]; |
| 1494 | + // Which rows of `rows` the pass below actually fills; the column pass | ||
| 1495 | + // walks only those. A row of `+0.0` contributes `0.0 * b` terms, which | ||
| 1496 | + // are `+-0.0`, and adding either to a running sum that is never `-0.0` | ||
| 1497 | + // (it starts at `+0.0` and `x + -x` is `+0.0`) leaves it unchanged. | ||
| 1498 | + let mut filled: [usize; 64] = [0; 64]; | ||
| 1499 | + let mut nfilled = 0usize; | ||
| 1466 | // Zero in, zero out, and `rows` is already zero here -- the skip | 1500 | // Zero in, zero out, and `rows` is already zero here -- the skip |
| 1467 | // [`forward_rows`] takes for the same reason, which this path was | 1501 | // [`forward_rows`] takes for the same reason, which this path was |
| 1468 | // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68% | 1502 | // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68% |
| @@ -1476,12 +1510,16 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType | |||
| 1476 | continue; | 1510 | continue; |
| 1477 | } | 1511 | } |
| 1478 | any = true; | 1512 | any = true; |
| 1479 | - for v in 0..side { | 1513 | + filled[nfilled] = i; |
| 1480 | - rows[i * side + v] = source | 1514 | + nfilled += 1; |
| 1481 | - .iter() | 1515 | + let out = &mut rows[i * side..][..side]; |
| 1482 | - .zip(&hb[v * side..][..side]) | 1516 | + // `k` ascending is the term order the strided `.map().sum()` had, so |
| 1483 | - .map(|(&r, &b)| f64::from(r) * b) | 1517 | + // every lane's partial sums are the same values in the same order. |
| 1484 | - .sum(); | 1518 | + for (k, &r) in source.iter().enumerate() { |
| 1519 | + let r = f64::from(r); | ||
| 1520 | + for (o, &b) in out.iter_mut().zip(&hb[k * side..][..side]) { | ||
| 1521 | + *o += r * b; | ||
| 1522 | + } | ||
| 1485 | } | 1523 | } |
| 1486 | } | 1524 | } |
| 1487 | if !any { | 1525 | if !any { |
| @@ -1489,10 +1527,15 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType | |||
| 1489 | } | 1527 | } |
| 1490 | let mut out = vec![0.0f64; side * side]; | 1528 | let mut out = vec![0.0f64; side * side]; |
| 1491 | for u in 0..side { | 1529 | for u in 0..side { |
| 1492 | - let column = &vb[u * side..][..side]; | 1530 | + let acc = &mut out[u * side..][..side]; |
| 1493 | - for v in 0..side { | 1531 | + for &i in &filled[..nfilled] { |
| 1494 | - let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum(); | 1532 | + let c = vb[i * side + u]; |
| 1495 | - out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum; | 1533 | + for (a, &r) in acc.iter_mut().zip(&rows[i * side..][..side]) { |
| 1534 | + *a += r * c; | ||
| 1535 | + } | ||
| 1536 | + } | ||
| 1537 | + for a in acc.iter_mut() { | ||
| 1538 | + *a *= INVERSE_GAIN_RECIPROCAL; | ||
| 1496 | } | 1539 | } |
| 1497 | } | 1540 | } |
| 1498 | out | 1541 | out |
| @@ -2613,6 +2656,90 @@ mod tests { | |||
| 2613 | /// full-range noise. A single differing lane at any size would be a | 2656 | /// full-range noise. A single differing lane at any size would be a |
| 2614 | /// silent pixel drift on whatever stream first reaches it. | 2657 | /// silent pixel drift on whatever stream first reaches it. |
| 2615 | #[cfg(target_arch = "x86_64")] | 2658 | #[cfg(target_arch = "x86_64")] |
| 2659 | + /// [`forward_transform_2d_typed`]'s contiguous-basis passes are the | ||
| 2660 | + /// strided `.map().sum()` they replaced, bit for bit. | ||
| 2661 | + /// | ||
| 2662 | + /// The reordering is safe only because each output's terms stay in the | ||
| 2663 | + /// same order -- only the loop that iterates the *outputs* moved -- so | ||
| 2664 | + /// this compares raw bit patterns, not an epsilon: any reassociation | ||
| 2665 | + /// would show up here as a last-place difference at some size. | ||
| 2666 | + #[test] | ||
| 2667 | + fn the_typed_forward_transform_is_bit_identical_to_the_strided_form() { | ||
| 2668 | + fn strided(residual: &[i32], side: usize, tx_type: TxType) -> Vec<f64> { | ||
| 2669 | + let (row_kind, col_kind) = tx_type.axes(); | ||
| 2670 | + let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); | ||
| 2671 | + let mut rows = vec![0.0f64; side * side]; | ||
| 2672 | + for i in 0..side { | ||
| 2673 | + let source = &residual[i * side..][..side]; | ||
| 2674 | + if source.iter().all(|&r| r == 0) { | ||
| 2675 | + continue; | ||
| 2676 | + } | ||
| 2677 | + for v in 0..side { | ||
| 2678 | + rows[i * side + v] = source | ||
| 2679 | + .iter() | ||
| 2680 | + .zip(&hb[v * side..][..side]) | ||
| 2681 | + .map(|(&r, &b)| f64::from(r) * b) | ||
| 2682 | + .sum(); | ||
| 2683 | + } | ||
| 2684 | + } | ||
| 2685 | + let mut out = vec![0.0f64; side * side]; | ||
| 2686 | + for u in 0..side { | ||
| 2687 | + let column = &vb[u * side..][..side]; | ||
| 2688 | + for v in 0..side { | ||
| 2689 | + let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum(); | ||
| 2690 | + out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum; | ||
| 2691 | + } | ||
| 2692 | + } | ||
| 2693 | + out | ||
| 2694 | + } | ||
| 2695 | + let mut seed = 0x9E37_79B9_7F4A_7C15u64; | ||
| 2696 | + let mut next = move || { | ||
| 2697 | + seed ^= seed << 13; | ||
| 2698 | + seed ^= seed >> 7; | ||
| 2699 | + seed ^= seed << 17; | ||
| 2700 | + seed | ||
| 2701 | + }; | ||
| 2702 | + let types = [ | ||
| 2703 | + TxType::Idtx, | ||
| 2704 | + TxType::AdstAdst, | ||
| 2705 | + TxType::AdstDct, | ||
| 2706 | + TxType::DctAdst, | ||
| 2707 | + TxType::VDct, | ||
| 2708 | + TxType::HDct, | ||
| 2709 | + ]; | ||
| 2710 | + for side in [4usize, 8, 16, 32] { | ||
| 2711 | + for tx_type in types { | ||
| 2712 | + // ADST is undefined above 16 (the spec's 32+ sets are | ||
| 2713 | + // DCT/identity only), so those pairs never reach this path. | ||
| 2714 | + let adst = matches!(tx_type.axes(), (TxType1d::Adst, _) | (_, TxType1d::Adst)); | ||
| 2715 | + if side > 16 && adst { | ||
| 2716 | + continue; | ||
| 2717 | + } | ||
| 2718 | + for round in 0..8 { | ||
| 2719 | + // Round 0 is an all-zero residual and round 1 has whole | ||
| 2720 | + // zero rows, so both skips are exercised at every size. | ||
| 2721 | + let residual: Vec<i32> = (0..side * side) | ||
| 2722 | + .map(|i| match round { | ||
| 2723 | + 0 => 0, | ||
| 2724 | + 1 if (i / side) % 2 == 0 => 0, | ||
| 2725 | + _ => (next() % 511) as i32 - 255, | ||
| 2726 | + }) | ||
| 2727 | + .collect(); | ||
| 2728 | + let ours = forward_transform_2d_typed(&residual, side, tx_type); | ||
| 2729 | + let theirs = strided(&residual, side, tx_type); | ||
| 2730 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 2731 | + assert_eq!( | ||
| 2732 | + a.to_bits(), | ||
| 2733 | + b.to_bits(), | ||
| 2734 | + "{tx_type:?} {side}x{side} round {round} coefficient {i}: \ | ||
| 2735 | + {a} vs {b}" | ||
| 2736 | + ); | ||
| 2737 | + } | ||
| 2738 | + } | ||
| 2739 | + } | ||
| 2740 | + } | ||
| 2741 | + } | ||
| 2742 | + | ||
| 2616 | #[test] | 2743 | #[test] |
| 2617 | fn the_avx2_dct_matches_the_scalar_one_over_the_full_range() { | 2744 | fn the_avx2_dct_matches_the_scalar_one_over_the_full_range() { |
| 2618 | if !std::arch::is_x86_feature_detected!("avx2") { | 2745 | if !std::arch::is_x86_feature_detected!("avx2") { |