Pyramid round trip through both decoders, per-reference hit counter, pyramid arm in the BD gate
Browse files at this commitf025ec8e87a4a7b89ac40aa08b12a6221c2d10aeParent: d496905- test
- pyramid round trip through both decoders, per-reference hit counter, pyramid arm in the BD gate
2 changed files +215 -1
- crates/ec-av1/src/encode.rs +116 -1
- crates/ec-av1/src/encoder.rs +99 -0
crates/ec-av1/src/encode.rsmodified+116 -1
| @@ -1908,6 +1908,20 @@ pub(crate) fn take_tx_depth_hits() -> [usize; 3] { | |||
| 1908 | static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] = | 1908 | static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] = |
| 1909 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; | 1909 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 1910 | 1910 | ||
| 1911 | +/// How many 32x32-and-below inter blocks each reference frame won, indexed by | ||
| 1912 | +/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the | ||
| 1913 | +/// fire count a gate prints to see an extra reference reach a block at all | ||
| 1914 | +/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never | ||
| 1915 | +/// chosen is a pyramid that costs bytes and buys nothing). | ||
| 1916 | +static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = | ||
| 1917 | + [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; | ||
| 1918 | + | ||
| 1919 | +/// Reads [`REF_FRAME_HITS`] and zeroes it. | ||
| 1920 | +#[cfg(test)] | ||
| 1921 | +pub(crate) fn take_ref_frame_hits() -> [usize; 8] { | ||
| 1922 | + std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) | ||
| 1923 | +} | ||
| 1924 | + | ||
| 1911 | /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it. | 1925 | /// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it. |
| 1912 | #[cfg(test)] | 1926 | #[cfg(test)] |
| 1913 | pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] { | 1927 | pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] { |
| @@ -4555,6 +4569,12 @@ pub(crate) fn encode_inter_frame( | |||
| 4555 | .filter(|b| b.inter.is_some()) | 4569 | .filter(|b| b.inter.is_some()) |
| 4556 | .count() as f64 | 4570 | .count() as f64 |
| 4557 | / modes.len() as f64; | 4571 | / modes.len() as f64; |
| 4572 | + for block in blocks.iter().flat_map(Quadrant::blocks) { | ||
| 4573 | + if let Some(info) = block.inter { | ||
| 4574 | + let r = (info.ref_frame as usize).min(7); | ||
| 4575 | + REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 4576 | + } | ||
| 4577 | + } | ||
| 4558 | #[cfg(test)] | 4578 | #[cfg(test)] |
| 4559 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); | 4579 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 4560 | // This frame's header leaves `disable_frame_end_update_cdf` off, so it | 4580 | // This frame's header leaves `disable_frame_end_update_cdf` off, so it |
| @@ -7524,6 +7544,88 @@ mod tests { | |||
| 7524 | (ladder, wall) | 7544 | (ladder, wall) |
| 7525 | } | 7545 | } |
| 7526 | 7546 | ||
| 7547 | + /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from | ||
| 7548 | + /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`. Unset | ||
| 7549 | + /// keeps the flat one-key-then-all-inter ladder the baseline was measured | ||
| 7550 | + /// on, so the gate's default recipe is unchanged. | ||
| 7551 | + fn pyramid_from_env() -> Option<crate::encoder::Pyramid> { | ||
| 7552 | + let spec = std::env::var("EC_AV1_PYRAMID").ok()?; | ||
| 7553 | + let mut f = spec.split(':'); | ||
| 7554 | + let mini_gop = f.next()?.parse().ok()?; | ||
| 7555 | + let d = crate::encoder::Pyramid::default(); | ||
| 7556 | + Some(crate::encoder::Pyramid { | ||
| 7557 | + mini_gop, | ||
| 7558 | + arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), | ||
| 7559 | + leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), | ||
| 7560 | + }) | ||
| 7561 | + } | ||
| 7562 | + | ||
| 7563 | + /// [`our_ladder`] through the streaming facade with a coding pyramid: the | ||
| 7564 | + /// four points are the same `base_q_idx` ladder, but each stream is | ||
| 7565 | + /// reordered (hidden `ALTREF` first, `show_existing_frame` last per | ||
| 7566 | + /// group) and each level is coded at its own quantizer offset. Returns | ||
| 7567 | + /// the ladder, the wall, and — per pyramid level over the whole ladder — | ||
| 7568 | + /// how many frames and how many bytes it spent. | ||
| 7569 | + fn our_ladder_pyramid( | ||
| 7570 | + source: &[Picture], | ||
| 7571 | + width: usize, | ||
| 7572 | + height: usize, | ||
| 7573 | + pyramid: crate::encoder::Pyramid, | ||
| 7574 | + ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) { | ||
| 7575 | + use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; | ||
| 7576 | + let slot = |l: Level| match l { | ||
| 7577 | + Level::Key => 0, | ||
| 7578 | + Level::Arf => 1, | ||
| 7579 | + Level::Leaf => 2, | ||
| 7580 | + Level::ShowExisting => 3, | ||
| 7581 | + }; | ||
| 7582 | + let mut ladder = Vec::new(); | ||
| 7583 | + let mut wall = 0.0; | ||
| 7584 | + let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); | ||
| 7585 | + for &q in &[150u8, 120, 90, 60] { | ||
| 7586 | + let config = EncoderConfig { | ||
| 7587 | + width, | ||
| 7588 | + height, | ||
| 7589 | + base_q_idx: q, | ||
| 7590 | + gop: source.len(), | ||
| 7591 | + colour: Colour::Unspecified, | ||
| 7592 | + }; | ||
| 7593 | + let start = std::time::Instant::now(); | ||
| 7594 | + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); | ||
| 7595 | + let mut packets = Vec::new(); | ||
| 7596 | + for picture in source { | ||
| 7597 | + packets.extend(enc.encode_frames(picture).unwrap()); | ||
| 7598 | + } | ||
| 7599 | + packets.extend(enc.flush().unwrap()); | ||
| 7600 | + wall += start.elapsed().as_secs_f64(); | ||
| 7601 | + let mut stream = Vec::new(); | ||
| 7602 | + for p in &packets { | ||
| 7603 | + counts[slot(p.level)] += 1; | ||
| 7604 | + bytes[slot(p.level)] += p.data.len(); | ||
| 7605 | + stream.extend_from_slice(&p.data); | ||
| 7606 | + } | ||
| 7607 | + // [[gate-blind-to-hidden-frames]]: a reordered stream is only | ||
| 7608 | + // correct if the DISPLAY-order output still has one frame per | ||
| 7609 | + // source picture, in the right order -- checked against our own | ||
| 7610 | + // decoder as well as ffmpeg's, both below. | ||
| 7611 | + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); | ||
| 7612 | + assert_eq!(ours.len(), source.len(), "q={q}: our display-order count"); | ||
| 7613 | + let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); | ||
| 7614 | + for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { | ||
| 7615 | + assert!(d.y == o.y, "q={q} display frame {i}: ffmpeg differs from our decoder"); | ||
| 7616 | + } | ||
| 7617 | + let mean: f64 = decoded | ||
| 7618 | + .iter() | ||
| 7619 | + .zip(source) | ||
| 7620 | + .map(|(d, s)| psnr_all(d, s)) | ||
| 7621 | + .sum::<f64>() | ||
| 7622 | + / source.len() as f64; | ||
| 7623 | + ladder.push((mean, (stream.len() as f64).log10())); | ||
| 7624 | + } | ||
| 7625 | + ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); | ||
| 7626 | + (ladder, wall, counts, bytes) | ||
| 7627 | + } | ||
| 7628 | + | ||
| 7527 | /// Byte-exactness gate for encoder work that is meant to change only | 7629 | /// Byte-exactness gate for encoder work that is meant to change only |
| 7528 | /// how long the encoder takes. | 7630 | /// how long the encoder takes. |
| 7529 | /// | 7631 | /// |
| @@ -7726,7 +7828,20 @@ mod tests { | |||
| 7726 | let _ = crate::tile::take_inter_mode_hits(); | 7828 | let _ = crate::tile::take_inter_mode_hits(); |
| 7727 | let _ = crate::tile::take_drl_hits(); | 7829 | let _ = crate::tile::take_drl_hits(); |
| 7728 | let _ = crate::tile::take_ref_hits(); | 7830 | let _ = crate::tile::take_ref_hits(); |
| 7729 | - let (ours, ours_wall) = our_ladder(&source, width, height, fctx); | 7831 | + let (ours, ours_wall) = match pyramid_from_env() { |
| 7832 | + None => our_ladder(&source, width, height, fctx), | ||
| 7833 | + Some(pyramid) => { | ||
| 7834 | + let (ladder, wall, counts, bytes) = | ||
| 7835 | + our_ladder_pyramid(&source, width, height, pyramid); | ||
| 7836 | + eprintln!( | ||
| 7837 | + "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \ | ||
| 7838 | + show_existing {}; bytes key {} arf {} leaf {} show_existing {}", | ||
| 7839 | + counts[0], counts[1], counts[2], counts[3], | ||
| 7840 | + bytes[0], bytes[1], bytes[2], bytes[3], | ||
| 7841 | + ); | ||
| 7842 | + (ladder, wall) | ||
| 7843 | + } | ||
| 7844 | + }; | ||
| 7730 | // How often the inter split actually fired over this clip's four | 7845 | // How often the inter split actually fired over this clip's four |
| 7731 | // encodes, against the whole 32x32 that was the only outcome | 7846 | // encodes, against the whole 32x32 that was the only outcome |
| 7732 | // before (gate-blind-to-feature). | 7847 | // before (gate-blind-to-feature). |
crates/ec-av1/src/encoder.rsmodified+99 -0
| @@ -1336,6 +1336,105 @@ mod tests { | |||
| 1336 | .collect() | 1336 | .collect() |
| 1337 | } | 1337 | } |
| 1338 | 1338 | ||
| 1339 | + /// A pyramid stream reorders pictures: the hidden `ALTREF` of each | ||
| 1340 | + /// mini-GOP is coded before the leaves that precede it in display order, | ||
| 1341 | + /// and a `show_existing_frame` header puts it back. This pins the shape | ||
| 1342 | + /// (one packet per source picture plus one `show_existing_frame` per | ||
| 1343 | + /// group, `dts` monotone, `order` NOT monotone) and then decodes the | ||
| 1344 | + /// whole stream through OUR decoder and through ffmpeg/dav1d and requires | ||
| 1345 | + /// the two display-order outputs to agree sample for sample — the | ||
| 1346 | + /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never | ||
| 1347 | + /// output, or output twice, or output in the wrong position, changes the | ||
| 1348 | + /// display-order list and fails here. | ||
| 1349 | + #[test] | ||
| 1350 | + fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { | ||
| 1351 | + let (width, height) = (128usize, 64usize); | ||
| 1352 | + let config = EncoderConfig { | ||
| 1353 | + width, | ||
| 1354 | + height, | ||
| 1355 | + base_q_idx: 120, | ||
| 1356 | + gop: 32, | ||
| 1357 | + colour: Colour::Bt709Limited, | ||
| 1358 | + }; | ||
| 1359 | + let pyramid = Pyramid { | ||
| 1360 | + mini_gop: 4, | ||
| 1361 | + ..Pyramid::default() | ||
| 1362 | + }; | ||
| 1363 | + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); | ||
| 1364 | + let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect(); | ||
| 1365 | + let _ = crate::encode::take_ref_frame_hits(); | ||
| 1366 | + let mut packets = Vec::new(); | ||
| 1367 | + for picture in &sources { | ||
| 1368 | + packets.extend(enc.encode_frames(picture).unwrap()); | ||
| 1369 | + } | ||
| 1370 | + packets.extend(enc.flush().unwrap()); | ||
| 1371 | + | ||
| 1372 | + // Shape: every source picture is coded exactly once, and each closed | ||
| 1373 | + // group adds one `show_existing_frame` packet. | ||
| 1374 | + let coded: Vec<u64> = packets | ||
| 1375 | + .iter() | ||
| 1376 | + .filter(|p| p.level != Level::ShowExisting) | ||
| 1377 | + .map(|p| p.order) | ||
| 1378 | + .collect(); | ||
| 1379 | + let mut sorted = coded.clone(); | ||
| 1380 | + sorted.sort_unstable(); | ||
| 1381 | + assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture"); | ||
| 1382 | + assert_ne!(coded, sorted, "the pyramid never reordered anything"); | ||
| 1383 | + let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); | ||
| 1384 | + assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP"); | ||
| 1385 | + for (i, p) in packets.iter().enumerate() { | ||
| 1386 | + assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); | ||
| 1387 | + } | ||
| 1388 | + let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); | ||
| 1389 | + eprintln!( | ||
| 1390 | + "pyramid levels: key {} arf {} leaf {} show_existing {}", | ||
| 1391 | + hist(Level::Key), | ||
| 1392 | + hist(Level::Arf), | ||
| 1393 | + hist(Level::Leaf), | ||
| 1394 | + hist(Level::ShowExisting), | ||
| 1395 | + ); | ||
| 1396 | + assert_eq!(hist(Level::Arf), 2, "two hidden frames"); | ||
| 1397 | + let refs = crate::encode::take_ref_frame_hits(); | ||
| 1398 | + eprintln!( | ||
| 1399 | + "blocks per reference: LAST {} GOLDEN {} ALTREF {}", | ||
| 1400 | + refs[crate::mvstack::LAST_FRAME as usize], | ||
| 1401 | + refs[crate::mvstack::GOLDEN_FRAME as usize], | ||
| 1402 | + refs[crate::mvstack::ALTREF_FRAME as usize], | ||
| 1403 | + ); | ||
| 1404 | + // [[gate-blind-to-feature]]: the whole point of the hidden frame is | ||
| 1405 | + // that the leaves predict BACKWARD off it, which is also the only | ||
| 1406 | + // thing that exercises `ref_frame_sign_bias` in the MV stack. A green | ||
| 1407 | + // round trip in which `ALTREF_FRAME` never won a block would prove | ||
| 1408 | + // only that a hidden frame can be written and re-output. | ||
| 1409 | + assert!( | ||
| 1410 | + refs[crate::mvstack::ALTREF_FRAME as usize] > 0, | ||
| 1411 | + "no block predicted off the hidden ALTREF" | ||
| 1412 | + ); | ||
| 1413 | + | ||
| 1414 | + let stream = concat(&packets); | ||
| 1415 | + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); | ||
| 1416 | + assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); | ||
| 1417 | + if !have_ffmpeg() { | ||
| 1418 | + eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); | ||
| 1419 | + return; | ||
| 1420 | + } | ||
| 1421 | + let theirs = ffmpeg_decode_luma(&stream, width, height); | ||
| 1422 | + assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); | ||
| 1423 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 1424 | + let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); | ||
| 1425 | + assert_eq!(got.len(), b.len(), "frame {i}: luma size"); | ||
| 1426 | + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { | ||
| 1427 | + panic!( | ||
| 1428 | + "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", | ||
| 1429 | + at % width, | ||
| 1430 | + at / width, | ||
| 1431 | + got[at], | ||
| 1432 | + b[at], | ||
| 1433 | + ); | ||
| 1434 | + } | ||
| 1435 | + } | ||
| 1436 | + } | ||
| 1437 | + | ||
| 1339 | /// [`RateTarget::Quality`] is monotone: a higher quality dial never | 1438 | /// [`RateTarget::Quality`] is monotone: a higher quality dial never |
| 1340 | /// produces a smaller stream or a worse mean PSNR than a lower one, on | 1439 | /// produces a smaller stream or a worse mean PSNR than a lower one, on |
| 1341 | /// the same real clip. | 1440 | /// the same real clip. |