Merge branch 'lane-last2' (9a8e50dd): a second past reference (LAST2) for the leaf chain, witnessed, refuted on both films in both arms, ships off; the pins test encodes at the default preset whatever EC_AV1_SPEED says
Browse files at this commit3 changed files +481 -24
- crates/ec-av1/src/encode.rs +106 -20
- crates/ec-av1/src/encoder.rs +195 -4
- lanes/last2.report.md +180 -0
crates/ec-av1/src/encode.rsmodified+106 -20
| @@ -8303,6 +8303,17 @@ fn mv_component_bits(diff: i32) -> Option<f64> { | |||
| 8303 | Some(bits) | 8303 | Some(bits) |
| 8304 | } | 8304 | } |
| 8305 | 8305 | ||
| 8306 | +/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the | ||
| 8307 | +/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch, | ||
| 8308 | +/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's | ||
| 8309 | +/// value without the second motion search's wall. | ||
| 8310 | +fn last2_new_mv() -> bool { | ||
| 8311 | + match std::env::var("EC_AV1_LAST2_NEW").ok() { | ||
| 8312 | + Some(v) => v != "0", | ||
| 8313 | + None => true, | ||
| 8314 | + } | ||
| 8315 | +} | ||
| 8316 | + | ||
| 8306 | /// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its | 8317 | /// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its |
| 8307 | /// own -- a second motion search per block against that reference's picture, | 8318 | /// own -- a second motion search per block against that reference's picture, |
| 8308 | /// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it | 8319 | /// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it |
| @@ -9111,14 +9122,22 @@ fn search_inter_block( | |||
| 9111 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); | 9122 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 9112 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); | 9123 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 9113 | // `write_single_ref`'s own tree, at the fixed context this pricer uses | 9124 | // `write_single_ref`'s own tree, at the fixed context this pricer uses |
| 9114 | - // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN | 9125 | + // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0, LAST2 |
| 9115 | - // p1=0,p3=1,p5=1. | 9126 | + // p1=0,p3=0,p4=1 and GOLDEN p1=0,p3=1,p5=1. A BACKWARD reference |
| 9127 | + // (`ALTREF`, p1=1,p2=1) is priced as LAST here and always has been -- | ||
| 9128 | + // wrong by two symbols, but fixing it moves every shipped stream, so it | ||
| 9129 | + // is a lever of its own and not this lane's (lanes/last2.report.md). | ||
| 9116 | let single_ref_bits = |ref_frame: i8| { | 9130 | let single_ref_bits = |ref_frame: i8| { |
| 9131 | + use crate::mvstack::{GOLDEN_FRAME, LAST2_FRAME}; | ||
| 9117 | symbol_bits(&cdf::SINGLE_REF[0][0], 0) | 9132 | symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 9118 | - + if ref_frame == crate::mvstack::GOLDEN_FRAME { | 9133 | + + if ref_frame == GOLDEN_FRAME { |
| 9119 | symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) | 9134 | symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) |
| 9120 | } else { | 9135 | } else { |
| 9121 | - symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0) | 9136 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 9137 | + + symbol_bits( | ||
| 9138 | + &cdf::SINGLE_REF[0][3], | ||
| 9139 | + usize::from(ref_frame == LAST2_FRAME), | ||
| 9140 | + ) | ||
| 9122 | } | 9141 | } |
| 9123 | }; | 9142 | }; |
| 9124 | 9143 | ||
| @@ -9406,8 +9425,15 @@ fn search_inter_block( | |||
| 9406 | // prices out `margin` times better than LAST's best vector does -- | 9425 | // prices out `margin` times better than LAST's best vector does -- |
| 9407 | // one candidate evaluation (`motion::cost_at`) standing in for a | 9426 | // one candidate evaluation (`motion::cost_at`) standing in for a |
| 9408 | // whole search of ~50. | 9427 | // whole search of ~50. |
| 9428 | + // lane-last2: the SEARCH-FREE arm for the second past leaf picture | ||
| 9429 | + // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some | ||
| 9430 | + // neighbour already found, which is how GOLDEN/ALTREF were offered | ||
| 9431 | + // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's | ||
| 9432 | + // own value from the second motion search's wall. | ||
| 9433 | + let searched = extra_ref_new_mv() | ||
| 9434 | + && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv()); | ||
| 9409 | let margin = extra_new_skip_margin(); | 9435 | let margin = extra_new_skip_margin(); |
| 9410 | - let skip_search = extra_ref_new_mv() | 9436 | + let skip_search = searched |
| 9411 | && margin > 0.0 | 9437 | && margin > 0.0 |
| 9412 | && motion::cost_at( | 9438 | && motion::cost_at( |
| 9413 | &g.y, | 9439 | &g.y, |
| @@ -9425,7 +9451,7 @@ fn search_inter_block( | |||
| 9425 | fctx, | 9451 | fctx, |
| 9426 | ) * margin | 9452 | ) * margin |
| 9427 | <= found.cost; | 9453 | <= found.cost; |
| 9428 | - if extra_ref_new_mv() && !skip_search { | 9454 | + if searched && !skip_search { |
| 9429 | let (gseeds, gn) = mv_seeds(gstack); | 9455 | let (gseeds, gn) = mv_seeds(gstack); |
| 9430 | #[cfg(test)] | 9456 | #[cfg(test)] |
| 9431 | let t = stage_start(); | 9457 | let t = stage_start(); |
| @@ -10567,6 +10593,12 @@ pub(crate) struct PyramidFrame { | |||
| 10567 | /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a | 10593 | /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a |
| 10568 | /// pyramid, which is what makes `sign_bias`'s last entry true. | 10594 | /// pyramid, which is what makes `sign_bias`'s last entry true. |
| 10569 | pub altref_slot: u8, | 10595 | pub altref_slot: u8, |
| 10596 | + /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past | ||
| 10597 | + /// picture (the leaf chain alternates its refresh between two slots, so | ||
| 10598 | + /// the frame before `LAST` is still intact). `None` leaves | ||
| 10599 | + /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder | ||
| 10600 | + /// wrote before, and the caller then passes no `last2` picture either. | ||
| 10601 | + pub last2_slot: Option<u8>, | ||
| 10570 | /// `show_frame`: false for a hidden frame, output later by a | 10602 | /// `show_frame`: false for a hidden frame, output later by a |
| 10571 | /// `show_existing_frame` header. | 10603 | /// `show_existing_frame` header. |
| 10572 | pub show_frame: bool, | 10604 | pub show_frame: bool, |
| @@ -10602,7 +10634,14 @@ pub(crate) fn encode_inter_frame( | |||
| 10602 | // The frame two back, held in the slot this frame is about to refresh | 10634 | // The frame two back, held in the slot this frame is about to refresh |
| 10603 | // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two | 10635 | // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two |
| 10604 | // inter frames of a GOP, where the frame two back IS the key frame. | 10636 | // inter frames of a GOP, where the frame two back IS the key frame. |
| 10605 | - altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, | 10637 | + altref: Option<&Picture>, |
| 10638 | + // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown | ||
| 10639 | + // frame BEFORE `reference` on the leaf chain, offered to the 32x32 | ||
| 10640 | + // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF` | ||
| 10641 | + // take. `None` (every caller but the pyramid leaves) codes the frame | ||
| 10642 | + // with the reference set unchanged. | ||
| 10643 | + last2: Option<&Picture>, | ||
| 10644 | + fctx: &crate::decode::FrameCtx, | ||
| 10606 | // Where this frame sits in the coding-order pyramid; `None` is the flat | 10645 | // Where this frame sits in the coding-order pyramid; `None` is the flat |
| 10607 | // one-shown-frame-per-picture stream this encoder wrote before. | 10646 | // one-shown-frame-per-picture stream this encoder wrote before. |
| 10608 | pyramid: Option<PyramidFrame>, | 10647 | pyramid: Option<PyramidFrame>, |
| @@ -10683,6 +10722,14 @@ pub(crate) fn encode_inter_frame( | |||
| 10683 | // `GOLDEN_FRAME` is the key frame, order hint 0. Only | 10722 | // `GOLDEN_FRAME` is the key frame, order hint 0. Only |
| 10684 | // `frame::write_frame_header`'s `skipModeAllowed` reads this. | 10723 | // `frame::write_frame_header`'s `skipModeAllowed` reads this. |
| 10685 | header.order_hints = order_hints; | 10724 | header.order_hints = order_hints; |
| 10725 | + // lane-last2: `inter_frame_headers_slots` points every un-named | ||
| 10726 | + // reference at `last_slot`; the pyramid's leaf chain retains a second, | ||
| 10727 | + // older picture and names it here. The caller's `sign_bias` / | ||
| 10728 | + // `order_hints` entry 1 is derived from this same slot, so the stack | ||
| 10729 | + // scans and `skipModeAllowed` read what the decoder will. | ||
| 10730 | + if let Some(slot) = pyramid.and_then(|p| p.last2_slot) { | ||
| 10731 | + header.ref_frame_idx[1] = slot; | ||
| 10732 | + } | ||
| 10686 | header.reference_select = reference_select(); | 10733 | header.reference_select = reference_select(); |
| 10687 | // Armed HERE, not only beside the tile write below: `ref_distance`'s own | 10734 | // Armed HERE, not only beside the tile write below: `ref_distance`'s own |
| 10688 | // per-reference order-hint distance is read by the block SEARCH, which | 10735 | // per-reference order-hint distance is read by the block SEARCH, which |
| @@ -10918,6 +10965,7 @@ pub(crate) fn encode_inter_frame( | |||
| 10918 | // built once per tile job (`obmc_prediction`). | 10965 | // built once per tile job (`obmc_prediction`). |
| 10919 | let mut obmc_refs: [Option<&Picture>; 8] = [None; 8]; | 10966 | let mut obmc_refs: [Option<&Picture>; 8] = [None; 8]; |
| 10920 | obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference); | 10967 | obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference); |
| 10968 | + obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2; | ||
| 10921 | obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden; | 10969 | obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden; |
| 10922 | obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref; | 10970 | obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref; |
| 10923 | grid.set_tile_bounds( | 10971 | grid.set_tile_bounds( |
| @@ -11109,6 +11157,7 @@ pub(crate) fn encode_inter_frame( | |||
| 11109 | let stack = | 11157 | let stack = |
| 11110 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); | 11158 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 11111 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ | 11159 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ |
| 11160 | + (crate::mvstack::LAST2_FRAME, last2), | ||
| 11112 | (crate::mvstack::GOLDEN_FRAME, golden), | 11161 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 11113 | (crate::mvstack::ALTREF_FRAME, altref), | 11162 | (crate::mvstack::ALTREF_FRAME, altref), |
| 11114 | ] | 11163 | ] |
| @@ -11664,8 +11713,22 @@ pub(crate) fn encode_inter_frame( | |||
| 11664 | } | 11713 | } |
| 11665 | } | 11714 | } |
| 11666 | }); | 11715 | }); |
| 11716 | + let trial_last2 = last2.map(|l| { | ||
| 11717 | + if (l.width, l.height) == (fw, fh) { | ||
| 11718 | + l.clone() | ||
| 11719 | + } else { | ||
| 11720 | + Picture { | ||
| 11721 | + width: fw, | ||
| 11722 | + height: fh, | ||
| 11723 | + y: crop_plane(&l.y, l.width, fw, fh), | ||
| 11724 | + u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2), | ||
| 11725 | + v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2), | ||
| 11726 | + } | ||
| 11727 | + } | ||
| 11728 | + }); | ||
| 11667 | let mut refs: [Option<&Picture>; 8] = [None; 8]; | 11729 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 11668 | refs[1] = Some(&trial_ref); | 11730 | refs[1] = Some(&trial_ref); |
| 11731 | + refs[2] = trial_last2.as_ref(); | ||
| 11669 | refs[4] = trial_golden.as_ref(); | 11732 | refs[4] = trial_golden.as_ref(); |
| 11670 | refs[7] = trial_altref.as_ref(); | 11733 | refs[7] = trial_altref.as_ref(); |
| 11671 | let refpix = crate::decode::RefPix::ready(refs); | 11734 | let refpix = crate::decode::RefPix::ready(refs); |
| @@ -11941,7 +12004,9 @@ pub(crate) fn encode_sequence_with_ctx( | |||
| 11941 | render, | 12004 | render, |
| 11942 | Some(&carried.0), | 12005 | Some(&carried.0), |
| 11943 | Some(&golden), | 12006 | Some(&golden), |
| 11944 | - prev2.as_ref(), fctx, | 12007 | + prev2.as_ref(), |
| 12008 | + None, | ||
| 12009 | + fctx, | ||
| 11945 | None, | 12010 | None, |
| 11946 | &lookahead, | 12011 | &lookahead, |
| 11947 | )?; | 12012 | )?; |
| @@ -14644,7 +14709,7 @@ mod tests { | |||
| 14644 | let padded_pic = picture.padded_to(SUPERBLOCK); | 14709 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 14645 | let t = Instant::now(); | 14710 | let t = Instant::now(); |
| 14646 | let inter = | 14711 | let inter = |
| 14647 | - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap(); | 14712 | + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap(); |
| 14648 | let inter_t = t.elapsed(); | 14713 | let inter_t = t.elapsed(); |
| 14649 | eprintln!( | 14714 | eprintln!( |
| 14650 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ | 14715 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| @@ -14743,7 +14808,7 @@ mod tests { | |||
| 14743 | stage_reset(); | 14808 | stage_reset(); |
| 14744 | let t = Instant::now(); | 14809 | let t = Instant::now(); |
| 14745 | let inter = | 14810 | let inter = |
| 14746 | - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap(); | 14811 | + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap(); |
| 14747 | let total_t = t.elapsed(); | 14812 | let total_t = t.elapsed(); |
| 14748 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); | 14813 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 14749 | let accounted = motion_search + transform_quant + entropy; | 14814 | let accounted = motion_search + transform_quant + entropy; |
| @@ -14923,7 +14988,7 @@ mod tests { | |||
| 14923 | 0.5, | 14988 | 0.5, |
| 14924 | 1, | 14989 | 1, |
| 14925 | flat_order_hints(1, 0, false), | 14990 | flat_order_hints(1, 0, false), |
| 14926 | - (width, height), None, None, None, fctx, None, &[], | 14991 | + (width, height), None, None, None, None, fctx, None, &[], |
| 14927 | ) | 14992 | ) |
| 14928 | .unwrap(); | 14993 | .unwrap(); |
| 14929 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); | 14994 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| @@ -14941,7 +15006,7 @@ mod tests { | |||
| 14941 | 0.5, | 15006 | 0.5, |
| 14942 | 1, | 15007 | 1, |
| 14943 | flat_order_hints(1, 0, false), | 15008 | flat_order_hints(1, 0, false), |
| 14944 | - (width, height), None, None, None, fctx, None, &[], | 15009 | + (width, height), None, None, None, None, fctx, None, &[], |
| 14945 | ) | 15010 | ) |
| 14946 | .unwrap(); | 15011 | .unwrap(); |
| 14947 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); | 15012 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| @@ -15557,7 +15622,12 @@ mod tests { | |||
| 15557 | /// (`EC_AV1_ANGLE=0` restores that half). | 15622 | /// (`EC_AV1_ANGLE=0` restores that half). |
| 15558 | #[test] | 15623 | #[test] |
| 15559 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { | 15624 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { |
| 15560 | - let _knobs = crate::speed::knob_read(); | 15625 | + // These are DEFAULT-PRESET pins: a speed preset switches search levers |
| 15626 | + // off, so it legitimately moves every byte. Encode at speed 0 whatever | ||
| 15627 | + // `EC_AV1_SPEED` says (write guard: the preset is process-global). | ||
| 15628 | + let _knobs = crate::speed::knob_write(); | ||
| 15629 | + let was = crate::speed::speed(); | ||
| 15630 | + crate::speed::set_speed(0); | ||
| 15561 | if !have_ffmpeg() { | 15631 | if !have_ffmpeg() { |
| 15562 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); | 15632 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); |
| 15563 | return; | 15633 | return; |
| @@ -15620,13 +15690,16 @@ mod tests { | |||
| 15620 | // now. `EC_AV1_I64=0` restores 8557 / 33345. | 15690 | // now. `EC_AV1_I64=0` restores 8557 / 33345. |
| 15621 | let pins: [(u8, usize, u64); 2] = | 15691 | let pins: [(u8, usize, u64); 2] = |
| 15622 | [(150, 8562, 0x66f5_4ffc_aacf_964f), (60, 33357, 0x1d61_9ca4_e960_b044)]; | 15692 | [(150, 8562, 0x66f5_4ffc_aacf_964f), (60, 33357, 0x1d61_9ca4_e960_b044)]; |
| 15623 | - for (q, bytes, hash) in pins { | 15693 | + let coded: Vec<(u8, usize, u64)> = pins |
| 15624 | - let encoded = encode_sequence(&source, q, 0.5).unwrap(); | 15694 | + .iter() |
| 15625 | - assert_eq!( | 15695 | + .map(|&(q, _, _)| { |
| 15626 | - (encoded.stream.len(), fnv(&encoded.stream)), | 15696 | + let e = encode_sequence(&source, q, 0.5).unwrap(); |
| 15627 | - (bytes, hash), | 15697 | + (q, e.stream.len(), fnv(&e.stream)) |
| 15628 | - "q={q}: the encoder's stream moved" | 15698 | + }) |
| 15629 | - ); | 15699 | + .collect(); |
| 15700 | + crate::speed::set_speed(was); | ||
| 15701 | + for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) { | ||
| 15702 | + assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved"); | ||
| 15630 | } | 15703 | } |
| 15631 | } | 15704 | } |
| 15632 | 15705 | ||
| @@ -16934,6 +17007,19 @@ mod tests { | |||
| 16934 | mm.iter().sum::<usize>(), | 17007 | mm.iter().sum::<usize>(), |
| 16935 | ); | 17008 | ); |
| 16936 | print_inter_tx_census(name); | 17009 | print_inter_tx_census(name); |
| 17010 | + // lane-last2 (class `gate-blind-to-feature`): which reference the | ||
| 17011 | + // 32x32-and-below inter blocks of this clip's four encodes chose. | ||
| 17012 | + // The native table is the standing keep table, so a second past | ||
| 17013 | + // reference that never won a block has to be visible HERE and not | ||
| 17014 | + // only in a synthetic witness. | ||
| 17015 | + let rh = crate::encode::take_ref_frame_hits(); | ||
| 17016 | + let rtot: usize = rh.iter().sum(); | ||
| 17017 | + eprintln!( | ||
| 17018 | + "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \ | ||
| 17019 | + (LAST2 {:.1}%)", | ||
| 17020 | + rh[1], rh[2], rh[4], rh[7], rtot, | ||
| 17021 | + 100.0 * rh[2] as f64 / rtot.max(1) as f64, | ||
| 17022 | + ); | ||
| 16937 | let palette = crate::tile::take_palette_hits(); | 17023 | let palette = crate::tile::take_palette_hits(); |
| 16938 | let palette_uv = crate::tile::take_palette_uv_hits(); | 17024 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 16939 | let ibc = crate::tile::take_intrabc_hits(); | 17025 | let ibc = crate::tile::take_intrabc_hits(); |
crates/ec-av1/src/encoder.rsmodified+195 -4
| @@ -961,6 +961,50 @@ const ANCHOR_SLOTS: [u8; 2] = [3, 4]; | |||
| 961 | /// The slot the leaf chain refreshes and reads as `LAST_FRAME`. | 961 | /// The slot the leaf chain refreshes and reads as `LAST_FRAME`. |
| 962 | const LEAF_SLOT: u8 = 0; | 962 | const LEAF_SLOT: u8 = 0; |
| 963 | 963 | ||
| 964 | +/// lane-last2: the two slots the leaf chain alternates its refresh between | ||
| 965 | +/// once [`last2`] is on, so that the shown frame BEFORE `LAST_FRAME` is still | ||
| 966 | +/// in the DPB and can be named `LAST2_FRAME`. Slot 7 is the one the key frame | ||
| 967 | +/// writes and nothing has ever read back, so this costs no other level a slot; | ||
| 968 | +/// leaf `k` refreshes `LEAF_SLOTS[k % 2]`, which is the slot leaf `k - 2` | ||
| 969 | +/// wrote -- read before write, spec 7.20's decode order. | ||
| 970 | +const LEAF_SLOTS: [u8; 2] = [LEAF_SLOT, 7]; | ||
| 971 | + | ||
| 972 | +/// Whether the leaf chain retains that second past picture and offers it to | ||
| 973 | +/// the block search as `LAST2_FRAME` (`EC_AV1_LAST2=0` / `=1`). The census | ||
| 974 | +/// that priced the lever is `lanes/refs.report.md` §1; what it buys on the | ||
| 975 | +/// gate is `lanes/last2.report.md`. | ||
| 976 | +fn last2() -> bool { | ||
| 977 | + match LAST2_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 978 | + 0 => return false, | ||
| 979 | + 1 => return true, | ||
| 980 | + _ => {} | ||
| 981 | + } | ||
| 982 | + match std::env::var("EC_AV1_LAST2").ok() { | ||
| 983 | + Some(v) => v != "0", | ||
| 984 | + None => LAST2, | ||
| 985 | + } | ||
| 986 | +} | ||
| 987 | + | ||
| 988 | +/// A PROCESS-GLOBAL [`last2`] override that wins over the environment | ||
| 989 | +/// (`u8::MAX` = unset), the shape `crate::encode::set_frame_interp` has -- | ||
| 990 | +/// this crate's tests never call `set_var` (`crate::envflags`), so the | ||
| 991 | +/// witness turns the lever on through this while holding | ||
| 992 | +/// [`crate::speed::knob_write`]. | ||
| 993 | +static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 = | ||
| 994 | + std::sync::atomic::AtomicU8::new(u8::MAX); | ||
| 995 | + | ||
| 996 | +/// Sets [`LAST2_OVERRIDE`]; `None` clears it. | ||
| 997 | +#[allow(dead_code)] // set only from the `#[cfg(test)]` witness | ||
| 998 | +pub(crate) fn set_last2(on: Option<bool>) { | ||
| 999 | + LAST2_OVERRIDE.store( | ||
| 1000 | + on.map_or(u8::MAX, u8::from), | ||
| 1001 | + std::sync::atomic::Ordering::Relaxed, | ||
| 1002 | + ); | ||
| 1003 | +} | ||
| 1004 | + | ||
| 1005 | +/// [`last2`]'s default. | ||
| 1006 | +const LAST2: bool = false; | ||
| 1007 | + | ||
| 964 | /// The slot the mid-level hidden frame of a three-level group refreshes | 1008 | /// The slot the mid-level hidden frame of a three-level group refreshes |
| 965 | /// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf | 1009 | /// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf |
| 966 | /// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once. | 1010 | /// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once. |
| @@ -1108,6 +1152,11 @@ pub struct Av1Encoder { | |||
| 1108 | /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its | 1152 | /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its |
| 1109 | /// anchor. | 1153 | /// anchor. |
| 1110 | anchor: usize, | 1154 | anchor: usize, |
| 1155 | + /// lane-last2: the [`LEAF_SLOTS`] the last two SHOWN leaves refreshed, | ||
| 1156 | + /// most recent first, across mini-GOP boundaries (the first leaf of a | ||
| 1157 | + /// group reads the anchor as `LAST_FRAME`, so its `LAST2_FRAME` is the | ||
| 1158 | + /// previous group's last leaf). Cleared by every key frame. | ||
| 1159 | + leaf_hist: Vec<u8>, | ||
| 1111 | /// Coding-order position of the next packet — a packet's `dts`. | 1160 | /// Coding-order position of the next packet — a packet's `dts`. |
| 1112 | next_dts: u64, | 1161 | next_dts: u64, |
| 1113 | /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's | 1162 | /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's |
| @@ -1197,6 +1246,7 @@ impl Av1Encoder { | |||
| 1197 | pending: Vec::new(), | 1246 | pending: Vec::new(), |
| 1198 | held: std::collections::VecDeque::new(), | 1247 | held: std::collections::VecDeque::new(), |
| 1199 | anchor: 0, | 1248 | anchor: 0, |
| 1249 | + leaf_hist: Vec::new(), | ||
| 1200 | next_dts: 0, | 1250 | next_dts: 0, |
| 1201 | collected: None, | 1251 | collected: None, |
| 1202 | }) | 1252 | }) |
| @@ -1468,6 +1518,7 @@ impl Av1Encoder { | |||
| 1468 | self.carried_cdfs.as_ref().map(|c| &c.0), | 1518 | self.carried_cdfs.as_ref().map(|c| &c.0), |
| 1469 | self.golden.as_ref(), | 1519 | self.golden.as_ref(), |
| 1470 | self.prev2.as_ref(), | 1520 | self.prev2.as_ref(), |
| 1521 | + None, | ||
| 1471 | &self.fctx, | 1522 | &self.fctx, |
| 1472 | None, | 1523 | None, |
| 1473 | &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(), | 1524 | &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(), |
| @@ -1607,6 +1658,9 @@ impl Av1Encoder { | |||
| 1607 | )?; | 1658 | )?; |
| 1608 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); | 1659 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); |
| 1609 | self.anchor = 0; | 1660 | self.anchor = 0; |
| 1661 | + // Every leaf slot now holds the key frame, which `GOLDEN_FRAME` | ||
| 1662 | + // already names: the chain starts empty again. | ||
| 1663 | + self.leaf_hist.clear(); | ||
| 1610 | let cropped = crop_encoded(&encoded, render.0, render.1); | 1664 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1611 | if let Some(rate_loop) = self.rate_loop.as_mut() { | 1665 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1612 | rate_loop.update(Level::Key, 0, cropped.stream.len()); | 1666 | rate_loop.update(Level::Key, 0, cropped.stream.len()); |
| @@ -1626,6 +1680,10 @@ impl Av1Encoder { | |||
| 1626 | last_slot: u8, | 1680 | last_slot: u8, |
| 1627 | self_slot: u8, | 1681 | self_slot: u8, |
| 1628 | altref_slot: u8, | 1682 | altref_slot: u8, |
| 1683 | + // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot | ||
| 1684 | + // holding no picture, or the same one `LAST_FRAME` reads -- leaves | ||
| 1685 | + // the reference set exactly as it was before this lane. | ||
| 1686 | + last2_slot: Option<u8>, | ||
| 1629 | show_frame: bool, | 1687 | show_frame: bool, |
| 1630 | level: Level, | 1688 | level: Level, |
| 1631 | // The quantizer offset comes from the CALLER, not from `level`: a | 1689 | // The quantizer offset comes from the CALLER, not from `level`: a |
| @@ -1659,8 +1717,19 @@ impl Av1Encoder { | |||
| 1659 | .as_ref() | 1717 | .as_ref() |
| 1660 | .is_some_and(|s| s.order_hint > order_hint) | 1718 | .is_some_and(|s| s.order_hint > order_hint) |
| 1661 | }; | 1719 | }; |
| 1720 | + // A LAST2 slot only counts when it holds a picture that is not the | ||
| 1721 | + // one `LAST_FRAME` already names; otherwise the frame codes the | ||
| 1722 | + // reference set it always did. | ||
| 1723 | + let last2_slot = last2_slot | ||
| 1724 | + .filter(|&s| s != last_slot && self.dpb[s as usize].is_some()); | ||
| 1662 | let slots = [ | 1725 | let slots = [ |
| 1663 | - last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, | 1726 | + last_slot, |
| 1727 | + last2_slot.unwrap_or(last_slot), | ||
| 1728 | + last_slot, | ||
| 1729 | + GOLDEN_SLOT, | ||
| 1730 | + last_slot, | ||
| 1731 | + last_slot, | ||
| 1732 | + altref_slot, | ||
| 1664 | ]; | 1733 | ]; |
| 1665 | for (i, slot) in slots.into_iter().enumerate() { | 1734 | for (i, slot) in slots.into_iter().enumerate() { |
| 1666 | sign_bias[i] = ahead(slot, &self.dpb); | 1735 | sign_bias[i] = ahead(slot, &self.dpb); |
| @@ -1678,6 +1747,7 @@ impl Av1Encoder { | |||
| 1678 | .ok_or_else(|| { | 1747 | .ok_or_else(|| { |
| 1679 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") | 1748 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") |
| 1680 | })?; | 1749 | })?; |
| 1750 | + let last2 = last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone())); | ||
| 1681 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); | 1751 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); |
| 1682 | let altref = (altref_slot != GOLDEN_SLOT) | 1752 | let altref = (altref_slot != GOLDEN_SLOT) |
| 1683 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) | 1753 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) |
| @@ -1694,11 +1764,13 @@ impl Av1Encoder { | |||
| 1694 | start_cdfs.as_ref(), | 1764 | start_cdfs.as_ref(), |
| 1695 | golden.as_ref(), | 1765 | golden.as_ref(), |
| 1696 | altref.as_ref(), | 1766 | altref.as_ref(), |
| 1767 | + last2.as_ref(), | ||
| 1697 | &self.fctx, | 1768 | &self.fctx, |
| 1698 | Some(crate::encode::PyramidFrame { | 1769 | Some(crate::encode::PyramidFrame { |
| 1699 | last_slot, | 1770 | last_slot, |
| 1700 | self_slot, | 1771 | self_slot, |
| 1701 | altref_slot, | 1772 | altref_slot, |
| 1773 | + last2_slot, | ||
| 1702 | show_frame, | 1774 | show_frame, |
| 1703 | sign_bias, | 1775 | sign_bias, |
| 1704 | }), | 1776 | }), |
| @@ -1715,7 +1787,8 @@ impl Av1Encoder { | |||
| 1715 | "AV1 encode", | 1787 | "AV1 encode", |
| 1716 | format!( | 1788 | format!( |
| 1717 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ | 1789 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ |
| 1718 | - altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}", | 1790 | + altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \ |
| 1791 | + altref pic {}): {e}", | ||
| 1719 | golden.is_some(), | 1792 | golden.is_some(), |
| 1720 | altref.is_some(), | 1793 | altref.is_some(), |
| 1721 | ), | 1794 | ), |
| @@ -1758,6 +1831,13 @@ impl Av1Encoder { | |||
| 1758 | }; | 1831 | }; |
| 1759 | window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect() | 1832 | window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect() |
| 1760 | }; | 1833 | }; |
| 1834 | + // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME` | ||
| 1835 | + // names as `LAST2_FRAME` -- the most recent shown leaf that is not | ||
| 1836 | + // the one it already reads. `None` with the lever off, or before two | ||
| 1837 | + // distinct past pictures exist. | ||
| 1838 | + let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> { | ||
| 1839 | + last2().then(|| hist.iter().copied().find(|&s| s != last_slot)).flatten() | ||
| 1840 | + }; | ||
| 1761 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; | 1841 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; |
| 1762 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; | 1842 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; |
| 1763 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); | 1843 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); |
| @@ -1771,6 +1851,7 @@ impl Av1Encoder { | |||
| 1771 | anchor_slot, | 1851 | anchor_slot, |
| 1772 | next_anchor_slot, | 1852 | next_anchor_slot, |
| 1773 | GOLDEN_SLOT, | 1853 | GOLDEN_SLOT, |
| 1854 | + last2_of(&self.leaf_hist, anchor_slot), | ||
| 1774 | true, | 1855 | true, |
| 1775 | Level::Leaf, | 1856 | Level::Leaf, |
| 1776 | pyramid.leaf_q_offset, | 1857 | pyramid.leaf_q_offset, |
| @@ -1793,6 +1874,10 @@ impl Av1Encoder { | |||
| 1793 | true => next_anchor_slot, | 1874 | true => next_anchor_slot, |
| 1794 | false => GOLDEN_SLOT, | 1875 | false => GOLDEN_SLOT, |
| 1795 | }, | 1876 | }, |
| 1877 | + // The ARF levels take no LAST2: the anchor pair already gives a | ||
| 1878 | + // top ARF two distinct past anchors (`arf_altref`), and the mid | ||
| 1879 | + // and quarter frames have only the one past anchor in the DPB. | ||
| 1880 | + None, | ||
| 1796 | false, | 1881 | false, |
| 1797 | Level::Arf, | 1882 | Level::Arf, |
| 1798 | pyramid.arf_q_offset, | 1883 | pyramid.arf_q_offset, |
| @@ -1826,6 +1911,7 @@ impl Av1Encoder { | |||
| 1826 | anchor_slot, | 1911 | anchor_slot, |
| 1827 | MID_SLOT, | 1912 | MID_SLOT, |
| 1828 | next_anchor_slot, | 1913 | next_anchor_slot, |
| 1914 | + None, | ||
| 1829 | false, | 1915 | false, |
| 1830 | Level::Arf, | 1916 | Level::Arf, |
| 1831 | offset, | 1917 | offset, |
| @@ -1862,6 +1948,7 @@ impl Av1Encoder { | |||
| 1862 | last_slot, | 1948 | last_slot, |
| 1863 | QUARTER_SLOTS[i], | 1949 | QUARTER_SLOTS[i], |
| 1864 | altref_slot, | 1950 | altref_slot, |
| 1951 | + None, | ||
| 1865 | false, | 1952 | false, |
| 1866 | Level::Arf, | 1953 | Level::Arf, |
| 1867 | offset, | 1954 | offset, |
| @@ -1902,23 +1989,42 @@ impl Av1Encoder { | |||
| 1902 | packets.push(packet); | 1989 | packets.push(packet); |
| 1903 | continue; | 1990 | continue; |
| 1904 | } | 1991 | } |
| 1992 | + // The previous shown leaf's own slot: `LEAF_SLOT` with the | ||
| 1993 | + // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf | ||
| 1994 | + // refreshed. | ||
| 1995 | + let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT); | ||
| 1905 | let last_slot = match i { | 1996 | let last_slot = match i { |
| 1906 | 0 => anchor_slot, | 1997 | 0 => anchor_slot, |
| 1907 | i => inner | 1998 | i => inner |
| 1908 | .iter() | 1999 | .iter() |
| 1909 | .find(|(at, _)| at + 1 == i) | 2000 | .find(|(at, _)| at + 1 == i) |
| 1910 | - .map_or(LEAF_SLOT, |&(_, slot)| slot), | 2001 | + .map_or(prev_leaf, |&(_, slot)| slot), |
| 2002 | + }; | ||
| 2003 | + // Alternate the refresh: this leaf takes the leaf slot the | ||
| 2004 | + // PREVIOUS leaf did not, which is the one the leaf before that | ||
| 2005 | + // wrote and which this frame may still read as `LAST2_FRAME` | ||
| 2006 | + // (read before write). | ||
| 2007 | + let self_slot = match last2() { | ||
| 2008 | + true => LEAF_SLOTS | ||
| 2009 | + .into_iter() | ||
| 2010 | + .find(|&s| Some(s) != self.leaf_hist.first().copied()) | ||
| 2011 | + .unwrap_or(LEAF_SLOT), | ||
| 2012 | + false => LEAF_SLOT, | ||
| 1911 | }; | 2013 | }; |
| 2014 | + let last2_slot = last2_of(&self.leaf_hist, last_slot); | ||
| 1912 | let altref_slot = inner | 2015 | let altref_slot = inner |
| 1913 | .iter() | 2016 | .iter() |
| 1914 | .find(|(at, _)| *at > i) | 2017 | .find(|(at, _)| *at > i) |
| 1915 | .map_or(next_anchor_slot, |&(_, slot)| slot); | 2018 | .map_or(next_anchor_slot, |&(_, slot)| slot); |
| 2019 | + self.leaf_hist.insert(0, self_slot); | ||
| 2020 | + self.leaf_hist.truncate(2); | ||
| 1916 | packets.push(self.encode_pyramid_inter( | 2021 | packets.push(self.encode_pyramid_inter( |
| 1917 | *order, | 2022 | *order, |
| 1918 | picture, | 2023 | picture, |
| 1919 | last_slot, | 2024 | last_slot, |
| 1920 | - LEAF_SLOT, | 2025 | + self_slot, |
| 1921 | altref_slot, | 2026 | altref_slot, |
| 2027 | + last2_slot, | ||
| 1922 | true, | 2028 | true, |
| 1923 | Level::Leaf, | 2029 | Level::Leaf, |
| 1924 | pyramid.leaf_q_offset, | 2030 | pyramid.leaf_q_offset, |
| @@ -2917,6 +3023,91 @@ mod tests { | |||
| 2917 | assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})"); | 3023 | assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})"); |
| 2918 | } | 3024 | } |
| 2919 | 3025 | ||
| 3026 | + /// lane-last2's witness: a clip whose pictures ALTERNATE between two | ||
| 3027 | + /// textures, so for every leaf the picture two back is an exact match and | ||
| 3028 | + /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf | ||
| 3029 | + /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older | ||
| 3030 | + /// slot `LAST2_FRAME`; blocks must actually be CODED off it | ||
| 3031 | + /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen | ||
| 3032 | + /// proves only that the bookkeeping compiles), the stream must decode | ||
| 3033 | + /// sample-exact through OUR decoder and through ffmpeg, and the hidden | ||
| 3034 | + /// frames must still come out in display order. With the lever OFF the | ||
| 3035 | + /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a | ||
| 3036 | + /// measurement of this lane and not of the reference set we already had. | ||
| 3037 | + #[test] | ||
| 3038 | + fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() { | ||
| 3039 | + let _knobs = crate::speed::knob_write(); | ||
| 3040 | + crate::encode::force_screen(Some(false)); | ||
| 3041 | + let (width, height) = (128usize, 128usize); | ||
| 3042 | + let sources: Vec<Picture> = | ||
| 3043 | + (0..9).map(|t| test_card(width, height, (t % 2) * 24)).collect(); | ||
| 3044 | + let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) { | ||
| 3045 | + set_last2(Some(on)); | ||
| 3046 | + let config = EncoderConfig { | ||
| 3047 | + width, | ||
| 3048 | + height, | ||
| 3049 | + base_q_idx: 120, | ||
| 3050 | + gop: 32, | ||
| 3051 | + colour: Colour::Bt709Limited, | ||
| 3052 | + tile_cols_log2: 0, | ||
| 3053 | + tile_rows_log2: 0, | ||
| 3054 | + }; | ||
| 3055 | + let pyramid = Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }; | ||
| 3056 | + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); | ||
| 3057 | + let _ = crate::encode::take_ref_frame_hits(); | ||
| 3058 | + let mut packets = Vec::new(); | ||
| 3059 | + for picture in &sources { | ||
| 3060 | + packets.extend(enc.encode_frames(picture).unwrap()); | ||
| 3061 | + } | ||
| 3062 | + packets.extend(enc.flush().unwrap()); | ||
| 3063 | + let hits = crate::encode::take_ref_frame_hits(); | ||
| 3064 | + (hits, concat(&packets), packets) | ||
| 3065 | + }; | ||
| 3066 | + let (off_hits, off_stream, _) = run(false); | ||
| 3067 | + let (on_hits, stream, packets) = run(true); | ||
| 3068 | + set_last2(None); | ||
| 3069 | + eprintln!( | ||
| 3070 | + "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \ | ||
| 3071 | + on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)", | ||
| 3072 | + off_hits[1], off_hits[2], off_hits[4], off_hits[7], off_stream.len(), | ||
| 3073 | + on_hits[1], on_hits[2], on_hits[4], on_hits[7], stream.len(), | ||
| 3074 | + ); | ||
| 3075 | + assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF"); | ||
| 3076 | + assert!( | ||
| 3077 | + on_hits[2] >= 8, | ||
| 3078 | + "the picture two back matches exactly and only {} blocks were coded off LAST2", | ||
| 3079 | + on_hits[2], | ||
| 3080 | + ); | ||
| 3081 | + | ||
| 3082 | + // Display order and sample-exactness, both decoders (the same shape | ||
| 3083 | + // `pyramid_round_trip` gates the hidden frames with). | ||
| 3084 | + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); | ||
| 3085 | + assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); | ||
| 3086 | + if !have_ffmpeg() { | ||
| 3087 | + eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg"); | ||
| 3088 | + return; | ||
| 3089 | + } | ||
| 3090 | + let theirs = ffmpeg_decode_luma(&stream, width, height); | ||
| 3091 | + assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); | ||
| 3092 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 3093 | + let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); | ||
| 3094 | + assert_eq!(got.len(), b.len(), "frame {i}: luma size"); | ||
| 3095 | + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { | ||
| 3096 | + panic!( | ||
| 3097 | + "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", | ||
| 3098 | + at % width, | ||
| 3099 | + at / width, | ||
| 3100 | + got[at], | ||
| 3101 | + b[at], | ||
| 3102 | + ); | ||
| 3103 | + } | ||
| 3104 | + } | ||
| 3105 | + // The reordering itself is unchanged by the second leaf slot. | ||
| 3106 | + let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); | ||
| 3107 | + let arfs = packets.iter().filter(|p| p.level == Level::Arf).count(); | ||
| 3108 | + assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); | ||
| 3109 | + } | ||
| 3110 | + | ||
| 2920 | fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { | 3111 | fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { |
| 2921 | let (width, height) = (128usize, 128usize); | 3112 | let (width, height) = (128usize, 128usize); |
| 2922 | let config = EncoderConfig { | 3113 | let config = EncoderConfig { |
lanes/last2.report.mdadded+180 -0
| @@ -0,0 +1,180 @@ | |||
| 1 | +# lane-last2 — a second past reference (LAST2) on the pyramid | ||
| 2 | + | ||
| 3 | +> **HANDOVER (session closed mid-lane).** What is DONE: the DPB/slot | ||
| 4 | +> bookkeeping, the search offer at 32x32, the witness, and both 12-frame | ||
| 5 | +> arms on both films — the lever is REFUTED on the gate and ships OFF | ||
| 6 | +> (`LAST2 = false`, `EC_AV1_LAST2=1` turns it on). What is STILL OWED: | ||
| 7 | +> (a) the three suite split arms (`--skip stream::` / `stream:: --skip 10bit` | ||
| 8 | +> / `10bit`) were never run on this branch; (b) `cargo check --workspace | ||
| 9 | +> --all-targets` was green BEFORE the last two commits (the `EC_AV1_LAST2_NEW` | ||
| 10 | +> knob and the gate's reference census) — re-run it; (c) the preset-6 | ||
| 11 | +> invariant arm failed ONLY on | ||
| 12 | +> `the_encoders_own_streams_are_byte_identical_to_their_pins` (q=150: 9846 vs | ||
| 13 | +> the 8562 pin) with `EC_AV1_LAST2=0`, i.e. with every one of this lane's | ||
| 14 | +> paths switched off — the pins are DEFAULT-preset pins and `EC_AV1_SPEED=6` | ||
| 15 | +> moves the stream, so this is believed pre-existing and NOT this lane's, but | ||
| 16 | +> it was not confirmed against main; confirm it there first. Preset 0 with | ||
| 17 | +> `EC_COMP_MISMATCH=1` passed all six invariants including the pins. | ||
| 18 | +> (d) the compound `LAST_LAST2` step (charter step 4) was not built: with | ||
| 19 | +> LAST2 winning only 1.3–1.7% of inter blocks as a single reference and both | ||
| 20 | +> single-ref arms losing, its ceiling is too small to spend the wall on. | ||
| 21 | +> No long-GOP arm was run because nothing ships (same reasoning as lane-refs). | ||
| 22 | + | ||
| 23 | +Worktree `edith_codecs-last2`, branch `lane-last2` off main e6df5196. | ||
| 24 | +Charter: `lanes/refs.report.md` §6. Every gate arm is the prebuilt release | ||
| 25 | +lib-test binary running `bd_rate_screen_native` (12 pictures, `gop 12`, four | ||
| 26 | +quantizers, native `gate_crop` window), one film per arm | ||
| 27 | +(`EC_AV1_NATIVE_FILM` / `EC_AV1_NATIVE_FILM4K` / `EC_AV1_NATIVE_SCREEN`); every | ||
| 28 | +row is read off that log's own header line. | ||
| 29 | + | ||
| 30 | +## 0. The charter's ARF step is a stale premise (read this first) | ||
| 31 | + | ||
| 32 | +The charter orders "ARF level first". At the ARF level there is nothing to | ||
| 33 | +build: a group's top ARF ALREADY names two distinct past anchors -- | ||
| 34 | +`last_slot` = `ANCHOR_SLOTS[anchor]` (the previous group's top ARF, lag | ||
| 35 | +`mini_gop`) and, since lane-arfcen's `arf_altref` shipped ON, | ||
| 36 | +`altref_slot` = `ANCHOR_SLOTS[1 - anchor]`, which still holds the top ARF from | ||
| 37 | +TWO groups back (lag 2 * `mini_gop`) when the frame is coded. Those are | ||
| 38 | +exactly the census's (4, 8) ARF lags, and that reference is offered to the | ||
| 39 | +32x32 search through the `extra` path WITH its own `NEWMV` search | ||
| 40 | +(`EXTRA_REF_NEW_MV` = true, margin `EXTRA_NEW_SKIP_MARGIN` = 0.35). So the | ||
| 41 | +census's ARF row (film A 10.31%, film B 8.38% of prediction SAD) is a lever | ||
| 42 | +already banked by `arf_altref`, not an open one; naming the same slot again as | ||
| 43 | +`LAST2_FRAME` would offer the same picture twice. | ||
| 44 | + | ||
| 45 | +The open half of the census is the LEAF chain (film A 6.99%, film B 7.25%): | ||
| 46 | +a leaf has exactly one past picture in the DPB (`LEAF_SLOT`, or the mid / | ||
| 47 | +quarter hidden frame behind it) plus the key as `GOLDEN`. That is what this | ||
| 48 | +lane builds. | ||
| 49 | + | ||
| 50 | +## 1. The slot map | ||
| 51 | + | ||
| 52 | +| slot | holds | written by | read as | | ||
| 53 | +|---|---|---|---| | ||
| 54 | +| 0, 7 (`LEAF_SLOTS`) | the last two shown leaves | every leaf, alternating | `LAST_FRAME` and `LAST2_FRAME` of the next leaf | | ||
| 55 | +| 1 (`GOLDEN_SLOT`) | the key frame | the key | `GOLDEN_FRAME` everywhere | | ||
| 56 | +| 2 (`MID_SLOT`) | the mid ARF | the mid ARF | `LAST`/`ALTREF` of the leaves and quarters around it | | ||
| 57 | +| 3, 4 (`ANCHOR_SLOTS`) | this group's anchor and the next | the key, each top ARF | anchor = `LAST`, next = `ALTREF` | | ||
| 58 | +| 5, 6 (`QUARTER_SLOTS`) | the two quarter ARFs (off by default) | the quarter ARFs | `LAST`/`ALTREF` of the leaves beside them | | ||
| 59 | + | ||
| 60 | +Leaf `k` refreshes `LEAF_SLOTS[k % 2]`, i.e. the slot leaf `k - 2` wrote -- | ||
| 61 | +read before write. `Av1Encoder::leaf_hist` carries the last two leaf slots | ||
| 62 | +ACROSS mini-GOP boundaries (the first leaf of a group reads the anchor as | ||
| 63 | +`LAST`, so its `LAST2` is the previous group's last leaf) and is cleared by | ||
| 64 | +every key frame (which writes all eight slots with one picture `GOLDEN` | ||
| 65 | +already names). A leaf whose `LAST` is a hidden frame reads the previous leaf | ||
| 66 | +as `LAST2`. The hidden levels pass `None`: see §0. | ||
| 67 | + | ||
| 68 | +## 2. What changed | ||
| 69 | + | ||
| 70 | +`crates/ec-av1/src/encoder.rs` | ||
| 71 | +* `LEAF_SLOTS = [0, 7]`, `Av1Encoder::leaf_hist` (the last two leaf slots, | ||
| 72 | + cleared by every key frame), the leaf loop alternates `self_slot` and names | ||
| 73 | + the older slot; `encode_pyramid_inter` takes `last2_slot: Option<u8>`, | ||
| 74 | + drops it when it holds no picture or the same one `LAST` names, and derives | ||
| 75 | + `sign_bias[1]` / `order_hints[1]` from it through the existing `slots` array | ||
| 76 | + (so the writer and the decoder scan the same stacks). | ||
| 77 | +* `last2()` / `set_last2` — `EC_AV1_LAST2`, default OFF this lane, plus the | ||
| 78 | + process-global override the witness uses (this crate's tests never call | ||
| 79 | + `set_var`). | ||
| 80 | + | ||
| 81 | +`crates/ec-av1/src/encode.rs` | ||
| 82 | +* `PyramidFrame::last2_slot`; `encode_inter_frame` takes `last2: | ||
| 83 | + Option<&Picture>` and, when the slot is named, sets | ||
| 84 | + `header.ref_frame_idx[1]`. | ||
| 85 | +* The picture reaches: the 32x32 `extra` search list (`NEAREST`/`NEAR`/ | ||
| 86 | + `GLOBAL` plus the existing `EXTRA_REF_NEW_MV` search under | ||
| 87 | + `EXTRA_NEW_SKIP_MARGIN` — the charter's "free arm" and its seeded arm are | ||
| 88 | + the SAME code path here, since extra references already get a NEWMV), the | ||
| 89 | + OBMC neighbour picture table, and the trial decode's `RefPix` slot 2. | ||
| 90 | +* The RD pricer's `single_ref_bits` gained LAST2's `p4 = 1` leaf. | ||
| 91 | +* The native gate prints a per-clip reference census (`LAST / LAST2 / GOLDEN / | ||
| 92 | + ALTREF`), so the keep table can see whether the tool fires at all. | ||
| 93 | + | ||
| 94 | +The 16x16/8x8 leaves are NOT offered LAST2 as a single reference: that path | ||
| 95 | +(`code_square_inter`) takes no `extra` list at all, only compound pairs. The | ||
| 96 | +64x64 root goes through `search_skip_64`, likewise no `extra`. So this arm is | ||
| 97 | +the 32x32 level, which is where the existing extra references live too. | ||
| 98 | + | ||
| 99 | +## 3. The witness | ||
| 100 | + | ||
| 101 | +`encoder::tests::a_leaf_predicts_off_last2_when_the_picture_two_back_matches` | ||
| 102 | +(not ignored, 3.6 s): nine 128x128 pictures ALTERNATING between two textures, | ||
| 103 | +`mini_gop` 4, so every leaf's picture two back is an exact match. | ||
| 104 | + | ||
| 105 | +| lever | LAST | LAST2 | GOLDEN | ALTREF | stream | | ||
| 106 | +|---|---|---|---|---|---| | ||
| 107 | +| off | 67 | **0** | 18 | 8 | 2969 B | | ||
| 108 | +| on | 25 | **36** | 15 | 8 | 2300 B | | ||
| 109 | + | ||
| 110 | +36 blocks coded off LAST2 (0 with the lever off — the counter measures this | ||
| 111 | +lane and not the reference set we already had), −22.5% bytes on the clip the | ||
| 112 | +lever is built for, `decode_stream` and ffmpeg both reconstruct all nine | ||
| 113 | +display positions sample-exact, and one `show_existing_frame` per hidden frame | ||
| 114 | +survives. | ||
| 115 | + | ||
| 116 | +## 4. The 12-frame native gate | ||
| 117 | + | ||
| 118 | +Controls reproduce to the digit: film A +21.7 / −4.4, film B +26.9 / −0.6. | ||
| 119 | + | ||
| 120 | +| arm | film A (vs libaom / rav1e) | film B | wall ours, film A / film B | | ||
| 121 | +|---|---|---|---| | ||
| 122 | +| control (`EC_AV1_LAST2=0`) | +21.7 / −4.4 | +26.9 / −0.6 | 208.2 s / 165.0 s | | ||
| 123 | +| LAST2 at the 32x32 search, with its own NEWMV | +21.4 / −4.5 | **+27.3 / −0.1** | 242.0 s / 202.5 s | | ||
| 124 | + | ||
| 125 | +Film A moves 0.3 down on the libaom column and 0.1 UP on rav1e's; film B moves | ||
| 126 | +0.4 and 0.5 the WRONG way on both. The keep rule ("both film rows improve on | ||
| 127 | +both columns, or one ≥0.5 down and the other flat ±0.3") is not met — and the | ||
| 128 | +arm costs +16% / +23% encoder wall, on the stage the user's speed order is | ||
| 129 | +about. So the searched arm is refuted. | ||
| 130 | + | ||
| 131 | +| LAST2 search-FREE (`EC_AV1_LAST2_NEW=0`) | +21.5 / −4.5 | **+27.3 / −0.0** | 194.3 s / 171.3 s | | ||
| 132 | + | ||
| 133 | +The charter's "free arm" does not rescue it: film A is 0.2 down on libaom and | ||
| 134 | +0.1 up on rav1e, film B is 0.4 / 0.6 the wrong way on both columns. The wall | ||
| 135 | +comes back (194 s / 171 s against the control's 208 s / 165 s, i.e. inside the | ||
| 136 | +gate's own wall noise), so the cost of the searched arm was indeed the second | ||
| 137 | +motion search — but the reference itself does not pay for its own syntax. | ||
| 138 | + | ||
| 139 | +**The screen row** (`EC_AV1_NATIVE_SCREEN=1`, the keep rule's third column): | ||
| 140 | +control and the search-free arm are BYTE-IDENTICAL at all four quantizers | ||
| 141 | +(+19.8% / -30.5%, 143.6 s vs 144.1 s), and the census prints `LAST2 0 of 23942 | ||
| 142 | +inter blocks` — the screen clip's leaves never take the older picture, so the | ||
| 143 | +screen half of the keep rule is neutral either way and the decision rests on | ||
| 144 | +the two film rows. | ||
| 145 | + | ||
| 146 | +**Fire share, on the real film rows** (the census the gate now prints): | ||
| 147 | + | ||
| 148 | +| clip | LAST | LAST2 | GOLDEN | ALTREF | LAST2 share | | ||
| 149 | +|---|---|---|---|---|---| | ||
| 150 | +| film A | 41871 | 780 | 1349 | 916 | 1.7% | | ||
| 151 | +| film B | 39412 | 566 | 1894 | 1807 | 1.3% | | ||
| 152 | +| bars 1080p | 22626 | 58 | 4067 | 206 | 0.2% | | ||
| 153 | + | ||
| 154 | +So the tool DOES fire on real film (it is not a dead knob — the witness and | ||
| 155 | +these counters are the [[gate-blind-to-feature]] proof), it is simply chosen | ||
| 156 | +by 1 block in 60 and those blocks do not pay back the `single_ref` symbol they | ||
| 157 | +spend. Read against `refs.report.md` §1's census (38% of blocks preferring the | ||
| 158 | +older picture by SAD): a pure-SAD best-of-two over-counts the lever by more | ||
| 159 | +than an order of magnitude once the block also has NEAR/NEAREST/DRL off LAST, | ||
| 160 | +a backward `ALTREF` at every leaf, and a rate term. | ||
| 161 | + | ||
| 162 | +## 5. Decision | ||
| 163 | + | ||
| 164 | +`LAST2` ships **OFF** (`const LAST2: bool = false`). The machinery stays: it | ||
| 165 | +is the only way the census's remaining claim can ever be re-measured, it is | ||
| 166 | +witnessed end to end, and it costs the default path nothing (a `None` picture | ||
| 167 | +is filtered out of the `extra` list and the header is untouched — the pins are | ||
| 168 | +byte-identical with the lever off). | ||
| 169 | + | ||
| 170 | +## 6. Deferred / dropped | ||
| 171 | + | ||
| 172 | +* **The compound `LAST_LAST2` pair (charter step 4) — dropped, not deferred.** | ||
| 173 | + Its input is the single-reference arm, which loses on both films with a | ||
| 174 | + 1.5% fire share. | ||
| 175 | +* **The ARF-level LAST2 (charter step 1) — dropped as a stale premise**, §0. | ||
| 176 | +* **The RD pricer charges `ALTREF` as if it were `LAST`** (`single_ref_bits`, | ||
| 177 | + `encode.rs`): a backward reference codes `p1=1,p2=1`, two different symbols | ||
| 178 | + from LAST's `p1=0,p3=0,p4=0`. Left alone here because fixing it moves every | ||
| 179 | + shipped stream, so it needs its own gate arm — deferred, unblocked by a lane | ||
| 180 | + that can re-pin. Found while adding LAST2's own leaf to that same tree. | ||