Merge branch 'lane-av1cap' (d9ec4a06): the filter stage's capture decode is replaced by one final replay of the winning parameters; CDEF reads the replay's deblock cache
Browse files at this commit5 changed files +293 -48
- crates/ec-av1/src/decode.rs +115 -15
- crates/ec-av1/src/encode.rs +131 -28
- crates/ec-av1/src/encoder.rs +42 -0
- crates/ec-av1/src/mc.rs +4 -4
- crates/ec-av1/src/par.rs +1 -1
crates/ec-av1/src/decode.rsmodified+115 -15
| @@ -19766,6 +19766,27 @@ pub(crate) fn set_filter_replay_disabled(off: bool) { | |||
| 19766 | REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed); | 19766 | REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed); |
| 19767 | } | 19767 | } |
| 19768 | 19768 | ||
| 19769 | +// Test-only: run the capture decode `replay_final` replaced as well, and | ||
| 19770 | +// hold its picture and its `FilterStages` against the replay's | ||
| 19771 | +// (`encoder::tests::filter_replay_final_matches_the_capture_decode`). | ||
| 19772 | +// Thread-local, not a global: the filter stage runs on the frame thread the | ||
| 19773 | +// test itself drives, and a process-wide flag would put every test encoding | ||
| 19774 | +// in parallel with this one through the extra decode too. | ||
| 19775 | +#[cfg(test)] | ||
| 19776 | +thread_local! { | ||
| 19777 | + static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; | ||
| 19778 | +} | ||
| 19779 | + | ||
| 19780 | +#[cfg(test)] | ||
| 19781 | +pub(crate) fn set_verify_final_replay(on: bool) { | ||
| 19782 | + VERIFY_FINAL.set(on); | ||
| 19783 | +} | ||
| 19784 | + | ||
| 19785 | +#[cfg(test)] | ||
| 19786 | +pub(crate) fn verify_final_replay() -> bool { | ||
| 19787 | + VERIFY_FINAL.get() | ||
| 19788 | +} | ||
| 19789 | + | ||
| 19769 | /// Drop the armed flag and anything captured: the tile it belongs to is done. | 19790 | /// Drop the armed flag and anything captured: the tile it belongs to is done. |
| 19770 | pub(crate) fn clear_filter_replay() { | 19791 | pub(crate) fn clear_filter_replay() { |
| 19771 | REPLAY_ARMED.set(false); | 19792 | REPLAY_ARMED.set(false); |
| @@ -19845,6 +19866,45 @@ pub(crate) fn replay_filters( | |||
| 19845 | if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { | 19866 | if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { |
| 19846 | return None; | 19867 | return None; |
| 19847 | } | 19868 | } |
| 19869 | + replay_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture) | ||
| 19870 | +} | ||
| 19871 | + | ||
| 19872 | +/// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters, | ||
| 19873 | +/// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage | ||
| 19874 | +/// used to reach this picture by decoding that re-coded tile a second time | ||
| 19875 | +/// (10% of a 4K frame's encode), only because the loop-restoration search | ||
| 19876 | +/// needs the decoder's own post-CDEF plane | ||
| 19877 | +/// ([`FrameCtx::capture_stages`]). It is the same two kernel calls | ||
| 19878 | +/// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter | ||
| 19879 | +/// planes in the same order, so it is the same bytes -- pinned by | ||
| 19880 | +/// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which | ||
| 19881 | +/// runs the decode as well and holds picture and stages against it. | ||
| 19882 | +/// | ||
| 19883 | +/// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that | ||
| 19884 | +/// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF | ||
| 19885 | +/// snapshot and handed the post-CDEF plane over for both stages. | ||
| 19886 | +pub(crate) fn replay_final( | ||
| 19887 | + loop_filter: &LoopFilterParams, | ||
| 19888 | + cdef: &CdefParams, | ||
| 19889 | + idx_grid: &[u8], | ||
| 19890 | + want_stages: bool, | ||
| 19891 | + fctx: &FrameCtx, | ||
| 19892 | +) -> Option<(Picture, Option<FilterStages>)> { | ||
| 19893 | + #[cfg(test)] | ||
| 19894 | + if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 19895 | + return None; | ||
| 19896 | + } | ||
| 19897 | + replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx) | ||
| 19898 | +} | ||
| 19899 | + | ||
| 19900 | +fn replay_inner( | ||
| 19901 | + loop_filter: &LoopFilterParams, | ||
| 19902 | + cdef: &CdefParams, | ||
| 19903 | + // `Some((cdef_idx grid, capture the filter stages))` for the final | ||
| 19904 | + // replay; `None` for a scoring candidate, which always codes `bits == 0`. | ||
| 19905 | + final_pass: Option<(&[u8], bool)>, | ||
| 19906 | + fctx: &FrameCtx, | ||
| 19907 | +) -> Option<(Picture, Option<FilterStages>)> { | ||
| 19848 | REPLAY.with_borrow_mut(|slot| { | 19908 | REPLAY.with_borrow_mut(|slot| { |
| 19849 | let r = slot.as_mut()?; | 19909 | let r = slot.as_mut()?; |
| 19850 | let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter); | 19910 | let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter); |
| @@ -19881,9 +19941,29 @@ pub(crate) fn replay_filters( | |||
| 19881 | (y, u, v) | 19941 | (y, u, v) |
| 19882 | }; | 19942 | }; |
| 19883 | drop(cpt); | 19943 | drop(cpt); |
| 19944 | + // The winner's `cdef_idx` literals live in the re-coded tile, which | ||
| 19945 | + // nothing parses on this path -- hand the grid the encoder already | ||
| 19946 | + // chose straight to the filter (`bits == 0` leaves the grid the last | ||
| 19947 | + // parse sized, which is what every scoring candidate reads). | ||
| 19948 | + if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) { | ||
| 19949 | + fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec()); | ||
| 19950 | + } | ||
| 19884 | let ct = crate::par::timer(crate::par::S_CDEF); | 19951 | let ct = crate::par::timer(crate::par::S_CDEF); |
| 19885 | - apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx); | 19952 | + let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| { |
| 19953 | + (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref()) | ||
| 19954 | + }); | ||
| 19955 | + apply_cdef( | ||
| 19956 | + &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx, | ||
| 19957 | + pre, | ||
| 19958 | + ); | ||
| 19886 | drop(ct); | 19959 | drop(ct); |
| 19960 | + let stages = final_pass.and_then(|(_, want)| { | ||
| 19961 | + want.then(|| FilterStages { | ||
| 19962 | + deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], | ||
| 19963 | + cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()], | ||
| 19964 | + stride: [y.width, u.width, v.width], | ||
| 19965 | + }) | ||
| 19966 | + }); | ||
| 19887 | // The capture only happens on the shape whose tail is the two | 19967 | // The capture only happens on the shape whose tail is the two |
| 19888 | // filter calls and the crop (no superres, no loop restoration), so | 19968 | // filter calls and the crop (no superres, no loop restoration), so |
| 19889 | // what is left is that crop -- byte for byte the cropped return path | 19969 | // what is left is that crop -- byte for byte the cropped return path |
| @@ -19897,13 +19977,16 @@ pub(crate) fn replay_filters( | |||
| 19897 | let (fw, fh) = (r.frame_width, r.frame_height); | 19977 | let (fw, fh) = (r.frame_width, r.frame_height); |
| 19898 | if fw == r.width && fh == r.height { | 19978 | if fw == r.width && fh == r.height { |
| 19899 | fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); | 19979 | fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); |
| 19900 | - return Some(Picture { | 19980 | + return Some(( |
| 19901 | - width: r.width, | 19981 | + Picture { |
| 19902 | - height: r.height, | 19982 | + width: r.width, |
| 19903 | - y: y.data.into_owned(), | 19983 | + height: r.height, |
| 19904 | - u: u.data.into_owned(), | 19984 | + y: y.data.into_owned(), |
| 19905 | - v: v.data.into_owned(), | 19985 | + u: u.data.into_owned(), |
| 19906 | - }); | 19986 | + v: v.data.into_owned(), |
| 19987 | + }, | ||
| 19988 | + stages, | ||
| 19989 | + )); | ||
| 19907 | } | 19990 | } |
| 19908 | let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> { | 19991 | let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> { |
| 19909 | let mut out = Vec::with_capacity(w * h); | 19992 | let mut out = Vec::with_capacity(w * h); |
| @@ -19935,7 +20018,7 @@ pub(crate) fn replay_filters( | |||
| 19935 | r.scratch.push(plane.data.into_owned()); | 20018 | r.scratch.push(plane.data.into_owned()); |
| 19936 | } | 20019 | } |
| 19937 | } | 20020 | } |
| 19938 | - Some(out) | 20021 | + Some((out, stages)) |
| 19939 | }) | 20022 | }) |
| 19940 | } | 20023 | } |
| 19941 | 20024 | ||
| @@ -20655,6 +20738,13 @@ fn apply_cdef( | |||
| 20655 | // This frame header's own CROPPED luma size, for the straddling-unit | 20738 | // This frame header's own CROPPED luma size, for the straddling-unit |
| 20656 | // counter only -- CDEF itself walks the mi-rounded plane. | 20739 | // counter only -- CDEF itself walks the mi-rounded plane. |
| 20657 | (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, | 20740 | (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx, |
| 20741 | + // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter | ||
| 20742 | + // starts by copying all three (~19 MB at 4K). The encoder's filter | ||
| 20743 | + // replay already holds an untouched copy of exactly those planes -- its | ||
| 20744 | + // post-deblock cache, which is where the working planes were copied FROM | ||
| 20745 | + // -- so it hands them straight in and the copy does not happen. `None` | ||
| 20746 | + // (every decode) copies as before. | ||
| 20747 | + src: Option<(&[u16], &[u16], &[u16])>, | ||
| 20658 | ) { | 20748 | ) { |
| 20659 | // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling. | 20749 | // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling. |
| 20660 | if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") { | 20750 | if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") { |
| @@ -20674,9 +20764,15 @@ fn apply_cdef( | |||
| 20674 | // One entry per superblock (a few hundred at 4K), so this clone is not | 20764 | // One entry per superblock (a few hundred at 4K), so this clone is not |
| 20675 | // one of the per-frame copies lane-perf6 pooled below. | 20765 | // one of the per-frame copies lane-perf6 pooled below. |
| 20676 | let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone()); | 20766 | let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone()); |
| 20677 | - let src_y = scratch_from(&y.data); | 20767 | + let owned = src.is_none(); |
| 20678 | - let src_u = scratch_from(&u.data); | 20768 | + let (src_y, src_u, src_v) = match src { |
| 20679 | - let src_v = scratch_from(&v.data); | 20769 | + Some((a, b, c)) => (std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c)), |
| 20770 | + None => ( | ||
| 20771 | + std::borrow::Cow::Owned(scratch_from(&y.data)), | ||
| 20772 | + std::borrow::Cow::Owned(scratch_from(&u.data)), | ||
| 20773 | + std::borrow::Cow::Owned(scratch_from(&v.data)), | ||
| 20774 | + ), | ||
| 20775 | + }; | ||
| 20680 | // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`, | 20776 | // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`, |
| 20681 | // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`. | 20777 | // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`. |
| 20682 | let coeff_shift = i32::from(bit_depth(fctx)) - 8; | 20778 | let coeff_shift = i32::from(bit_depth(fctx)) - 8; |
| @@ -20691,9 +20787,11 @@ fn apply_cdef( | |||
| 20691 | y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift, | 20787 | y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift, |
| 20692 | damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx, | 20788 | damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx, |
| 20693 | ); | 20789 | ); |
| 20694 | - scratch_return(src_y); | 20790 | + if owned { |
| 20695 | - scratch_return(src_u); | 20791 | + scratch_return(src_y.into_owned()); |
| 20696 | - scratch_return(src_v); | 20792 | + scratch_return(src_u.into_owned()); |
| 20793 | + scratch_return(src_v.into_owned()); | ||
| 20794 | + } | ||
| 20697 | } | 20795 | } |
| 20698 | 20796 | ||
| 20699 | /// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop | 20797 | /// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop |
| @@ -23269,6 +23367,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( | |||
| 23269 | cdef, | 23367 | cdef, |
| 23270 | &neighbours, | 23368 | &neighbours, |
| 23271 | (frame_width as usize, frame_height as usize), fctx, | 23369 | (frame_width as usize, frame_height as usize), fctx, |
| 23370 | + None, | ||
| 23272 | ); | 23371 | ); |
| 23273 | dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); | 23372 | dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); |
| 23274 | dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); | 23373 | dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); |
| @@ -36084,6 +36183,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( | |||
| 36084 | cdef, | 36183 | cdef, |
| 36085 | &neighbours, | 36184 | &neighbours, |
| 36086 | (frame_width as usize, frame_height as usize), fctx, | 36185 | (frame_width as usize, frame_height as usize), fctx, |
| 36186 | + None, | ||
| 36087 | ); | 36187 | ); |
| 36088 | } | 36188 | } |
| 36089 | dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); | 36189 | dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); |
crates/ec-av1/src/encode.rsmodified+131 -28
| @@ -1566,7 +1566,7 @@ impl Plane<'_> { | |||
| 1566 | } | 1566 | } |
| 1567 | } | 1567 | } |
| 1568 | #[cfg(test)] | 1568 | #[cfg(test)] |
| 1569 | - let t = std::time::Instant::now(); | 1569 | + let t = stage_start(); |
| 1570 | let levels = | 1570 | let levels = |
| 1571 | forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); | 1571 | forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); |
| 1572 | // lane-av1speed2: 60% of the transform units of an inter stream carry | 1572 | // lane-av1speed2: 60% of the transform units of an inter stream carry |
| @@ -1580,7 +1580,7 @@ impl Plane<'_> { | |||
| 1580 | &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, | 1580 | &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, |
| 1581 | ); | 1581 | ); |
| 1582 | #[cfg(test)] | 1582 | #[cfg(test)] |
| 1583 | - stage_add(2, t.elapsed()); | 1583 | + stage_since(2, t); |
| 1584 | 1584 | ||
| 1585 | let reconstruction: Vec<u8> = if coded.is_empty() { | 1585 | let reconstruction: Vec<u8> = if coded.is_empty() { |
| 1586 | prediction.to_vec() | 1586 | prediction.to_vec() |
| @@ -1596,7 +1596,7 @@ impl Plane<'_> { | |||
| 1596 | // will code them with, so the search ranks modes -- and the partition | 1596 | // will code them with, so the search ranks modes -- and the partition |
| 1597 | // trial ranks trees -- by the bits they actually spend. | 1597 | // trial ranks trees -- by the bits they actually spend. |
| 1598 | #[cfg(test)] | 1598 | #[cfg(test)] |
| 1599 | - let t = std::time::Instant::now(); | 1599 | + let t = stage_start(); |
| 1600 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { | 1600 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 1601 | // What the search used before it could price a block exactly: a | 1601 | // What the search used before it could price a block exactly: a |
| 1602 | // level costs its magnitude's width plus a sign and a run. Kept | 1602 | // level costs its magnitude's width plus a sign and a run. Kept |
| @@ -1620,7 +1620,7 @@ impl Plane<'_> { | |||
| 1620 | } | 1620 | } |
| 1621 | }; | 1621 | }; |
| 1622 | #[cfg(test)] | 1622 | #[cfg(test)] |
| 1623 | - stage_add(3, t.elapsed()); | 1623 | + stage_since(3, t); |
| 1624 | Trial { | 1624 | Trial { |
| 1625 | levels, | 1625 | levels, |
| 1626 | reconstruction, | 1626 | reconstruction, |
| @@ -1666,7 +1666,7 @@ impl Plane<'_> { | |||
| 1666 | } | 1666 | } |
| 1667 | } | 1667 | } |
| 1668 | #[cfg(test)] | 1668 | #[cfg(test)] |
| 1669 | - let t = std::time::Instant::now(); | 1669 | + let t = stage_start(); |
| 1670 | let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); | 1670 | let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); |
| 1671 | // The same all-zero shortcut [`Self::trial_typed`] takes. | 1671 | // The same all-zero shortcut [`Self::trial_typed`] takes. |
| 1672 | let coded = dequant_and_inverse_typed_wh( | 1672 | let coded = dequant_and_inverse_typed_wh( |
| @@ -1680,7 +1680,7 @@ impl Plane<'_> { | |||
| 1680 | TxType::DctDct, | 1680 | TxType::DctDct, |
| 1681 | ); | 1681 | ); |
| 1682 | #[cfg(test)] | 1682 | #[cfg(test)] |
| 1683 | - stage_add(2, t.elapsed()); | 1683 | + stage_since(2, t); |
| 1684 | let reconstruction: Vec<u8> = if coded.is_empty() { | 1684 | let reconstruction: Vec<u8> = if coded.is_empty() { |
| 1685 | prediction.to_vec() | 1685 | prediction.to_vec() |
| 1686 | } else { | 1686 | } else { |
| @@ -1692,7 +1692,7 @@ impl Plane<'_> { | |||
| 1692 | }; | 1692 | }; |
| 1693 | let sse = self.block_sse(x, y, side, &reconstruction); | 1693 | let sse = self.block_sse(x, y, side, &reconstruction); |
| 1694 | #[cfg(test)] | 1694 | #[cfg(test)] |
| 1695 | - let t = std::time::Instant::now(); | 1695 | + let t = stage_start(); |
| 1696 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { | 1696 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 1697 | levels | 1697 | levels |
| 1698 | .iter() | 1698 | .iter() |
| @@ -1712,7 +1712,7 @@ impl Plane<'_> { | |||
| 1712 | } | 1712 | } |
| 1713 | }; | 1713 | }; |
| 1714 | #[cfg(test)] | 1714 | #[cfg(test)] |
| 1715 | - stage_add(3, t.elapsed()); | 1715 | + stage_since(3, t); |
| 1716 | Trial { | 1716 | Trial { |
| 1717 | levels, | 1717 | levels, |
| 1718 | reconstruction, | 1718 | reconstruction, |
| @@ -5035,6 +5035,24 @@ thread_local! { | |||
| 5035 | ]; | 5035 | ]; |
| 5036 | } | 5036 | } |
| 5037 | 5037 | ||
| 5038 | +/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and | ||
| 5039 | +/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran | ||
| 5040 | +/// per transform trial and per `mc::predict` call whether or not anyone was | ||
| 5041 | +/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile). | ||
| 5042 | +/// The clock is now read only when [`crate::par::stage_times`] is on, which | ||
| 5043 | +/// is what prints the breakdown in the first place. | ||
| 5044 | +#[cfg(test)] | ||
| 5045 | +pub(crate) fn stage_start() -> Option<std::time::Instant> { | ||
| 5046 | + crate::par::stage_times().then(std::time::Instant::now) | ||
| 5047 | +} | ||
| 5048 | + | ||
| 5049 | +#[cfg(test)] | ||
| 5050 | +pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) { | ||
| 5051 | + if let Some(t) = t { | ||
| 5052 | + stage_add(bucket, t.elapsed()); | ||
| 5053 | + } | ||
| 5054 | +} | ||
| 5055 | + | ||
| 5038 | #[cfg(test)] | 5056 | #[cfg(test)] |
| 5039 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { | 5057 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 5040 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); | 5058 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| @@ -5042,11 +5060,13 @@ pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { | |||
| 5042 | 5060 | ||
| 5043 | #[cfg(test)] | 5061 | #[cfg(test)] |
| 5044 | fn stage_reset() { | 5062 | fn stage_reset() { |
| 5063 | + crate::par::set_stage_times(true); | ||
| 5045 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); | 5064 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 5046 | } | 5065 | } |
| 5047 | 5066 | ||
| 5048 | #[cfg(test)] | 5067 | #[cfg(test)] |
| 5049 | fn stage_read() -> [std::time::Duration; 4] { | 5068 | fn stage_read() -> [std::time::Duration; 4] { |
| 5069 | + crate::par::set_stage_times(false); | ||
| 5050 | STAGE_NS.with(|c| { | 5070 | STAGE_NS.with(|c| { |
| 5051 | c.each_ref() | 5071 | c.each_ref() |
| 5052 | .map(|cell| std::time::Duration::from_nanos(cell.get())) | 5072 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| @@ -6018,7 +6038,6 @@ fn pick_and_apply_filters( | |||
| 6018 | lambda, | 6038 | lambda, |
| 6019 | ); | 6039 | ); |
| 6020 | drop(ft); | 6040 | drop(ft); |
| 6021 | - crate::decode::clear_filter_replay(); | ||
| 6022 | let (lf, cdef, idx_grid, picture) = search_result?; | 6041 | let (lf, cdef, idx_grid, picture) = search_result?; |
| 6023 | header.loop_filter = lf; | 6042 | header.loop_filter = lf; |
| 6024 | header.cdef = cdef; | 6043 | header.cdef = cdef; |
| @@ -6037,22 +6056,86 @@ fn pick_and_apply_filters( | |||
| 6037 | // an approximation inside the SEARCH only; the reconstruction this | 6056 | // an approximation inside the SEARCH only; the reconstruction this |
| 6038 | // function ends up splicing is always a real decode of the real tile. | 6057 | // function ends up splicing is always a real decode of the real tile. |
| 6039 | let lr_on = restoration_enabled(); | 6058 | let lr_on = restoration_enabled(); |
| 6040 | - fctx.capture_stages.set(lr_on); | 6059 | + // The `cdef_idx` literals live in the tile payload, so a frame that |
| 6041 | - let mut filtered = if idx_grid.is_empty() { | 6060 | + // chose a per-64x64 preset list codes its tiles a second time. |
| 6042 | - if lr_on { | 6061 | + if !idx_grid.is_empty() { |
| 6043 | - let _t = crate::par::timer(crate::par::S_CAPTURE); | 6062 | + *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?; |
| 6044 | - decode(&lf, &cdef, &hdr, tiles, &none_lr)? | 6063 | + } |
| 6045 | - } else { | 6064 | + // lane-av1cap: that re-coded tile used to be DECODED here as well -- |
| 6046 | - picture | 6065 | + // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop |
| 6066 | + // restoration search reads (`crate::decode::FrameCtx::capture_stages`) | ||
| 6067 | + // and the picture this function splices. Both come out of ONE more | ||
| 6068 | + // replay of the winning parameters on the same captured pre-filter | ||
| 6069 | + // planes every candidate was scored on: the same two filter kernels, on | ||
| 6070 | + // the same input, in the same order, so the same bytes. Re-coding the | ||
| 6071 | + // tile does not move the reconstruction the replay holds -- `cdef_idx` | ||
| 6072 | + // is an equiprobable literal, so it adapts no CDF and changes no | ||
| 6073 | + // residual. | ||
| 6074 | + let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx); | ||
| 6075 | + #[cfg(test)] | ||
| 6076 | + let replay_was_used = replayed.is_some(); | ||
| 6077 | + let (mut filtered, mut stages) = match replayed { | ||
| 6078 | + Some((picture, stages)) => (picture, stages), | ||
| 6079 | + // Nothing captured (the shapes [`crate::decode::FilterReplay`] | ||
| 6080 | + // refuses): every candidate was a full decode, so the winner's own | ||
| 6081 | + // picture stands, and the stages still need a capturing decode. | ||
| 6082 | + None => { | ||
| 6083 | + fctx.capture_stages.set(lr_on); | ||
| 6084 | + let picture = if idx_grid.is_empty() && !lr_on { | ||
| 6085 | + picture | ||
| 6086 | + } else { | ||
| 6087 | + let _t = crate::par::timer(crate::par::S_CAPTURE); | ||
| 6088 | + decode(&lf, &cdef, &hdr, tiles, &none_lr)? | ||
| 6089 | + }; | ||
| 6090 | + fctx.capture_stages.set(false); | ||
| 6091 | + (picture, crate::decode::take_filter_stages(fctx)) | ||
| 6047 | } | 6092 | } |
| 6048 | - } else { | ||
| 6049 | - let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; | ||
| 6050 | - let _t = crate::par::timer(crate::par::S_CAPTURE); | ||
| 6051 | - let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; | ||
| 6052 | - *tiles = coded; | ||
| 6053 | - picture | ||
| 6054 | }; | 6093 | }; |
| 6055 | - fctx.capture_stages.set(false); | 6094 | + #[cfg(test)] |
| 6095 | + if crate::decode::verify_final_replay() && replay_was_used { | ||
| 6096 | + fctx.capture_stages.set(lr_on); | ||
| 6097 | + let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?; | ||
| 6098 | + fctx.capture_stages.set(false); | ||
| 6099 | + let want_stages = crate::decode::take_filter_stages(fctx); | ||
| 6100 | + assert!( | ||
| 6101 | + (want.width, want.height) == (filtered.width, filtered.height) | ||
| 6102 | + && want.y == filtered.y | ||
| 6103 | + && want.u == filtered.u | ||
| 6104 | + && want.v == filtered.v, | ||
| 6105 | + "the final filter replay is not the capture decode it stands in for", | ||
| 6106 | + ); | ||
| 6107 | + // Only the frame's own cropped region: the plane is padded to the | ||
| 6108 | + // superblock grid and the columns past the mi extent are written by | ||
| 6109 | + // nothing (the decoder's plane pool leaves whatever the last frame | ||
| 6110 | + // put there), while the restoration search reads strictly inside | ||
| 6111 | + // `fw x fh` -- `restoration::lr_sample` clamps its column to | ||
| 6112 | + // `plane_w - 1` and its row to the frame's, and | ||
| 6113 | + // `filter_search::pick_restoration`'s own SSE walk never leaves the | ||
| 6114 | + // crop either. | ||
| 6115 | + let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| { | ||
| 6116 | + for row in 0..h { | ||
| 6117 | + let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]); | ||
| 6118 | + assert!( | ||
| 6119 | + x == y, | ||
| 6120 | + "{what}: the replayed filter stages are not the ones the capture \ | ||
| 6121 | + decode returns (row {row} of {h}, width {w}, stride {stride})", | ||
| 6122 | + ); | ||
| 6123 | + } | ||
| 6124 | + }; | ||
| 6125 | + match (&want_stages, &stages) { | ||
| 6126 | + (Some(a), Some(b)) => { | ||
| 6127 | + assert_eq!(a.stride, b.stride, "the captured plane strides moved"); | ||
| 6128 | + let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); | ||
| 6129 | + for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() { | ||
| 6130 | + region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked"); | ||
| 6131 | + region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed"); | ||
| 6132 | + } | ||
| 6133 | + } | ||
| 6134 | + (None, None) => {} | ||
| 6135 | + _ => panic!("one path captured filter stages and the other did not"), | ||
| 6136 | + } | ||
| 6137 | + } | ||
| 6138 | + crate::decode::clear_filter_replay(); | ||
| 6056 | let mut lr = LoopRestorationParams::default(); | 6139 | let mut lr = LoopRestorationParams::default(); |
| 6057 | if lr_on { | 6140 | if lr_on { |
| 6058 | let mut want = LoopRestorationParams { | 6141 | let mut want = LoopRestorationParams { |
| @@ -6062,7 +6145,7 @@ fn pick_and_apply_filters( | |||
| 6062 | }; | 6145 | }; |
| 6063 | want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; | 6146 | want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; |
| 6064 | let lrt = crate::par::timer(crate::par::S_LR); | 6147 | let lrt = crate::par::timer(crate::par::S_LR); |
| 6065 | - let units = match crate::decode::take_filter_stages(fctx) { | 6148 | + let units = match stages.take() { |
| 6066 | Some(stages) => crate::filter_search::pick_restoration( | 6149 | Some(stages) => crate::filter_search::pick_restoration( |
| 6067 | &stages, | 6150 | &stages, |
| 6068 | source[0], | 6151 | source[0], |
| @@ -6714,7 +6797,7 @@ fn search_inter_block( | |||
| 6714 | let source_block = luma.source_block(x, y, BLOCK); | 6797 | let source_block = luma.source_block(x, y, BLOCK); |
| 6715 | let (seeds, seed_n) = mv_seeds(stack); | 6798 | let (seeds, seed_n) = mv_seeds(stack); |
| 6716 | #[cfg(test)] | 6799 | #[cfg(test)] |
| 6717 | - let t = std::time::Instant::now(); | 6800 | + let t = stage_start(); |
| 6718 | let found = motion::search( | 6801 | let found = motion::search( |
| 6719 | ref_luma.0, | 6802 | ref_luma.0, |
| 6720 | ref_luma.1, | 6803 | ref_luma.1, |
| @@ -6731,7 +6814,7 @@ fn search_inter_block( | |||
| 6731 | 1, | 6814 | 1, |
| 6732 | ); | 6815 | ); |
| 6733 | #[cfg(test)] | 6816 | #[cfg(test)] |
| 6734 | - stage_add(0, t.elapsed()); | 6817 | + stage_since(0, t); |
| 6735 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); | 6818 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 6736 | // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so | 6819 | // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so |
| 6737 | // the same vector costs a different residual from each: take the index | 6820 | // the same vector costs a different residual from each: take the index |
| @@ -6814,7 +6897,7 @@ fn search_inter_block( | |||
| 6814 | if extra_ref_new_mv() && !skip_search { | 6897 | if extra_ref_new_mv() && !skip_search { |
| 6815 | let (gseeds, gn) = mv_seeds(gstack); | 6898 | let (gseeds, gn) = mv_seeds(gstack); |
| 6816 | #[cfg(test)] | 6899 | #[cfg(test)] |
| 6817 | - let t = std::time::Instant::now(); | 6900 | + let t = stage_start(); |
| 6818 | let gfound = motion::search( | 6901 | let gfound = motion::search( |
| 6819 | &g.y, | 6902 | &g.y, |
| 6820 | g.width, | 6903 | g.width, |
| @@ -6831,7 +6914,7 @@ fn search_inter_block( | |||
| 6831 | ref_distance(ref_frame), | 6914 | ref_distance(ref_frame), |
| 6832 | ); | 6915 | ); |
| 6833 | #[cfg(test)] | 6916 | #[cfg(test)] |
| 6834 | - stage_add(0, t.elapsed()); | 6917 | + stage_since(0, t); |
| 6835 | let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); | 6918 | let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); |
| 6836 | extra_new_mvs.push((ref_frame, gmv)); | 6919 | extra_new_mvs.push((ref_frame, gmv)); |
| 6837 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { | 6920 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { |
| @@ -9349,6 +9432,26 @@ mod tests { | |||
| 9349 | (width, height) | 9432 | (width, height) |
| 9350 | } | 9433 | } |
| 9351 | 9434 | ||
| 9435 | + /// lane-av1cap: the final filter replay against the capture decode it | ||
| 9436 | + /// replaced, at the block-padded and straddling sizes the whole-frame | ||
| 9437 | + /// tests cover -- `set_verify_final_replay` makes | ||
| 9438 | + /// [`pick_and_apply_filters`] run both on every frame and assert, per | ||
| 9439 | + /// frame, that the spliced picture and the two filter stages the | ||
| 9440 | + /// restoration search reads are bit-identical over the frame's own crop. | ||
| 9441 | + #[test] | ||
| 9442 | + fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() { | ||
| 9443 | + let fctx = &crate::decode::FrameCtx::new(); | ||
| 9444 | + crate::decode::set_verify_final_replay(true); | ||
| 9445 | + for &(width, height) in | ||
| 9446 | + &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)] | ||
| 9447 | + { | ||
| 9448 | + eprintln!("--- {width}x{height}"); | ||
| 9449 | + let picture = test_card(width, height); | ||
| 9450 | + let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); | ||
| 9451 | + } | ||
| 9452 | + crate::decode::set_verify_final_replay(false); | ||
| 9453 | + } | ||
| 9454 | + | ||
| 9352 | /// A key frame at an arbitrary even size round-trips through ffmpeg over | 9455 | /// A key frame at an arbitrary even size round-trips through ffmpeg over |
| 9353 | /// its own render rectangle: [`Encoded::reconstruction`] is exactly the | 9456 | /// its own render rectangle: [`Encoded::reconstruction`] is exactly the |
| 9354 | /// picture's own size, and what ffmpeg decodes over that same top-left | 9457 | /// picture's own size, and what ffmpeg decodes over that same top-left |
crates/ec-av1/src/encoder.rsmodified+42 -0
| @@ -2092,6 +2092,48 @@ mod tests { | |||
| 2092 | } | 2092 | } |
| 2093 | } | 2093 | } |
| 2094 | 2094 | ||
| 2095 | + /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced | ||
| 2096 | + /// the capture decode -- against that decode. `set_verify_final_replay` | ||
| 2097 | + /// makes `encode::pick_and_apply_filters` run both on every frame and | ||
| 2098 | + /// assert, per frame, that the spliced picture and the two filter stages | ||
| 2099 | + /// the loop-restoration search reads are bit-identical. | ||
| 2100 | + #[test] | ||
| 2101 | + fn filter_replay_final_matches_the_capture_decode() { | ||
| 2102 | + let _gate_lock = crate::stream::tests::lock_gate_counters(); | ||
| 2103 | + let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { | ||
| 2104 | + let config = EncoderConfig { | ||
| 2105 | + width, | ||
| 2106 | + height, | ||
| 2107 | + base_q_idx: 120, | ||
| 2108 | + gop: 2, | ||
| 2109 | + colour: Colour::Bt709Limited, | ||
| 2110 | + tile_cols_log2: tiles.0, | ||
| 2111 | + tile_rows_log2: tiles.1, | ||
| 2112 | + }; | ||
| 2113 | + let mut enc = Av1Encoder::new(config).unwrap(); | ||
| 2114 | + for packet in encode_all(&mut enc, sources) { | ||
| 2115 | + assert!(!packet.data.is_empty()); | ||
| 2116 | + } | ||
| 2117 | + }; | ||
| 2118 | + crate::decode::set_verify_final_replay(true); | ||
| 2119 | + // 320x160 crops (its coding surface is one superblock row taller); | ||
| 2120 | + // 320x192 is a whole number of superblocks. | ||
| 2121 | + for (width, height) in [(320usize, 160usize), (320, 192)] { | ||
| 2122 | + let sources: Vec<Picture> = | ||
| 2123 | + (0..4).map(|t| test_card(width, height, t * 3)).collect(); | ||
| 2124 | + run(&sources, width, height, (0, 0)); | ||
| 2125 | + } | ||
| 2126 | + // Real gate content, where the CDEF preset search actually chooses | ||
| 2127 | + // `bits > 0` and the tile is re-coded, one tile and four. | ||
| 2128 | + if let Some(sources) = h264_clip_frames(640, 384, 3) { | ||
| 2129 | + run(&sources, 640, 384, (0, 0)); | ||
| 2130 | + run(&sources, 640, 384, (1, 1)); | ||
| 2131 | + } else { | ||
| 2132 | + eprintln!("SKIP the gate-clip arm: no fixture or no ffmpeg"); | ||
| 2133 | + } | ||
| 2134 | + crate::decode::set_verify_final_replay(false); | ||
| 2135 | + } | ||
| 2136 | + | ||
| 2095 | /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- | 2137 | /// lane-av1fpar: where a frame's wall actually goes, stage by stage -- |
| 2096 | /// the per-tile search, the tile write, the frame-level filter search | 2138 | /// the per-tile search, the tile write, the frame-level filter search |
| 2097 | /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture | 2139 | /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture |
crates/ec-av1/src/mc.rsmodified+4 -4
| @@ -1137,7 +1137,7 @@ pub(crate) fn predict_with_filters_kern( | |||
| 1137 | hit!(INTER_PRED_HITS); | 1137 | hit!(INTER_PRED_HITS); |
| 1138 | 1138 | ||
| 1139 | #[cfg(test)] | 1139 | #[cfg(test)] |
| 1140 | - let stage_t = std::time::Instant::now(); | 1140 | + let stage_t = crate::encode::stage_start(); |
| 1141 | 1141 | ||
| 1142 | let x0 = x_q4.div_euclid(16); | 1142 | let x0 = x_q4.div_euclid(16); |
| 1143 | let xfrac = x_q4.rem_euclid(16) as usize; | 1143 | let xfrac = x_q4.rem_euclid(16) as usize; |
| @@ -1188,7 +1188,7 @@ pub(crate) fn predict_with_filters_kern( | |||
| 1188 | } | 1188 | } |
| 1189 | } | 1189 | } |
| 1190 | #[cfg(test)] | 1190 | #[cfg(test)] |
| 1191 | - crate::encode::stage_add(1, stage_t.elapsed()); | 1191 | + crate::encode::stage_since(1, stage_t); |
| 1192 | return; | 1192 | return; |
| 1193 | } | 1193 | } |
| 1194 | 1194 | ||
| @@ -1244,7 +1244,7 @@ pub(crate) fn predict_with_filters_kern( | |||
| 1244 | unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) }; | 1244 | unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) }; |
| 1245 | vpass_row_u16(&src[base..], block_w, stride, block_h, &v16, max, dst); | 1245 | vpass_row_u16(&src[base..], block_w, stride, block_h, &v16, max, dst); |
| 1246 | #[cfg(test)] | 1246 | #[cfg(test)] |
| 1247 | - crate::encode::stage_add(1, stage_t.elapsed()); | 1247 | + crate::encode::stage_since(1, stage_t); |
| 1248 | return; | 1248 | return; |
| 1249 | } | 1249 | } |
| 1250 | } | 1250 | } |
| @@ -1265,7 +1265,7 @@ pub(crate) fn predict_with_filters_kern( | |||
| 1265 | }); | 1265 | }); |
| 1266 | 1266 | ||
| 1267 | #[cfg(test)] | 1267 | #[cfg(test)] |
| 1268 | - crate::encode::stage_add(1, stage_t.elapsed()); | 1268 | + crate::encode::stage_since(1, stage_t); |
| 1269 | } | 1269 | } |
| 1270 | 1270 | ||
| 1271 | /// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h` | 1271 | /// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h` |
crates/ec-av1/src/par.rsmodified+1 -1
| @@ -531,7 +531,7 @@ static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] = | |||
| 531 | /// [`set_stage_times`] from a gate (the env snapshot is process-constant). | 531 | /// [`set_stage_times`] from a gate (the env snapshot is process-constant). |
| 532 | static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | 532 | static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 533 | 533 | ||
| 534 | -fn stage_times() -> bool { | 534 | +pub(crate) fn stage_times() -> bool { |
| 535 | match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) { | 535 | match STAGE_ON.load(std::sync::atomic::Ordering::Relaxed) { |
| 536 | 0 => { | 536 | 0 => { |
| 537 | let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES")); | 537 | let on = 1 + usize::from(crate::envflags::is_set("EC_AV1_STAGE_TIMES")); |