Merge branch 'lane-av1fwd' (ea3cd233): encoder pricer keeps its CDF tables, filter search replays filters instead of re-decoding, zero-residual transform skips
Browse files at this commit5 changed files +371 -29
- crates/ec-av1/examples/enc_probe.rs +56 -0
- crates/ec-av1/src/decode.rs +157 -0
- crates/ec-av1/src/encode.rs +77 -3
- crates/ec-av1/src/tile.rs +47 -13
- crates/ec-av1/src/transform.rs +34 -13
crates/ec-av1/examples/enc_probe.rsadded+56 -0
| @@ -0,0 +1,56 @@ | |||
| 1 | +//! Encode-side profiling driver: the BD gate's own ladder, without ffmpeg's | ||
| 2 | +//! decode side or the reference encoders, so `perf record` attributes only | ||
| 3 | +//! our encoder. Also the byte-exactness gate for encoder-internal rewrites: | ||
| 4 | +//! it prints each point's stream length and a hash of its bytes. | ||
| 5 | +//! | ||
| 6 | +//! Usage: `enc_probe <clip> <width> <height> <frames> [q,q,..]` | ||
| 7 | + | ||
| 8 | +use std::process::Command; | ||
| 9 | + | ||
| 10 | +fn main() { | ||
| 11 | + let a: Vec<String> = std::env::args().skip(1).collect(); | ||
| 12 | + let (clip, width, height, frames) = ( | ||
| 13 | + a[0].clone(), | ||
| 14 | + a[1].parse::<usize>().unwrap(), | ||
| 15 | + a[2].parse::<usize>().unwrap(), | ||
| 16 | + a[3].parse::<usize>().unwrap(), | ||
| 17 | + ); | ||
| 18 | + let qs: Vec<u8> = a | ||
| 19 | + .get(4) | ||
| 20 | + .map_or_else(|| vec![150, 120, 90, 60], |s| s.split(',').map(|q| q.parse().unwrap()).collect()); | ||
| 21 | + | ||
| 22 | + let out = Command::new("ffmpeg") | ||
| 23 | + .args(["-v", "error", "-i", &clip, "-frames:v", &frames.to_string()]) | ||
| 24 | + .args(["-vf", &format!("scale={width}:{height}")]) | ||
| 25 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 26 | + .output() | ||
| 27 | + .expect("ffmpeg failed to run"); | ||
| 28 | + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); | ||
| 29 | + let (luma, chroma) = (width * height, width * height / 4); | ||
| 30 | + let frame_len = luma + 2 * chroma; | ||
| 31 | + let source: Vec<ec_av1::encode::Picture> = (0..frames) | ||
| 32 | + .map(|i| { | ||
| 33 | + let b = &out.stdout[i * frame_len..][..frame_len]; | ||
| 34 | + ec_av1::encode::Picture { | ||
| 35 | + width, | ||
| 36 | + height, | ||
| 37 | + y: b[..luma].iter().map(|&v| u16::from(v)).collect(), | ||
| 38 | + u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), | ||
| 39 | + v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), | ||
| 40 | + } | ||
| 41 | + }) | ||
| 42 | + .collect(); | ||
| 43 | + | ||
| 44 | + let start = std::time::Instant::now(); | ||
| 45 | + for q in qs { | ||
| 46 | + let e = ec_av1::encode::encode_sequence(&source, q, 0.5).unwrap(); | ||
| 47 | + // FNV-1a over the stream: a byte-exactness witness, not a checksum | ||
| 48 | + // with any other job. | ||
| 49 | + let mut h: u64 = 0xcbf2_9ce4_8422_2325; | ||
| 50 | + for &b in &e.stream { | ||
| 51 | + h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); | ||
| 52 | + } | ||
| 53 | + println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len()); | ||
| 54 | + } | ||
| 55 | + println!("wall {:.3}s", start.elapsed().as_secs_f64()); | ||
| 56 | +} | ||
crates/ec-av1/src/decode.rsmodified+157 -0
| @@ -6588,6 +6588,7 @@ struct BlkCell { | |||
| 6588 | /// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a | 6588 | /// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a |
| 6589 | /// chroma transform straddling the true, odd-sized frame edge see its | 6589 | /// chroma transform straddling the true, odd-sized frame edge see its |
| 6590 | /// neighbour's state clamped at its own subsampled edge rather than luma's. | 6590 | /// neighbour's state clamped at its own subsampled edge rather than luma's. |
| 6591 | +#[derive(Clone)] | ||
| 6591 | struct Neighbours { | 6592 | struct Neighbours { |
| 6592 | above: Vec<[Neighbour; 3]>, | 6593 | above: Vec<[Neighbour; 3]>, |
| 6593 | left: Vec<[Neighbour; 3]>, | 6594 | left: Vec<[Neighbour; 3]>, |
| @@ -19674,6 +19675,119 @@ fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> { | |||
| 19674 | PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p } | 19675 | PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p } |
| 19675 | } | 19676 | } |
| 19676 | 19677 | ||
| 19678 | +/// The pre-filter reconstruction of one coded frame, plus the per-block state | ||
| 19679 | +/// the loop filters read. | ||
| 19680 | +/// | ||
| 19681 | +/// The encoder's filter search ([`crate::filter_search::pick_filters`]) | ||
| 19682 | +/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter | ||
| 19683 | +/// sets to score each one, and the entropy decode and reconstruction it | ||
| 19684 | +/// repeats are identical every time -- both filters run after it, on the | ||
| 19685 | +/// finished planes. That re-parse was 24% of the encoder's profile. A caller | ||
| 19686 | +/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters | ||
| 19687 | +/// alone through [`replay_filters`]; the result is the same picture the full | ||
| 19688 | +/// decode would have returned, because it is the same two calls on a copy of | ||
| 19689 | +/// the same planes. | ||
| 19690 | +pub(crate) struct FilterReplay { | ||
| 19691 | + y: PlaneBuf<'static>, | ||
| 19692 | + u: PlaneBuf<'static>, | ||
| 19693 | + v: PlaneBuf<'static>, | ||
| 19694 | + neighbours: Neighbours, | ||
| 19695 | + frame_width: usize, | ||
| 19696 | + frame_height: usize, | ||
| 19697 | + width: usize, | ||
| 19698 | + height: usize, | ||
| 19699 | +} | ||
| 19700 | + | ||
| 19701 | +thread_local! { | ||
| 19702 | + /// Set by [`arm_filter_replay`] for the span of one decode. | ||
| 19703 | + static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; | ||
| 19704 | + /// What that decode captured, until [`clear_filter_replay`]. | ||
| 19705 | + static REPLAY: std::cell::RefCell<Option<FilterReplay>> = | ||
| 19706 | + const { std::cell::RefCell::new(None) }; | ||
| 19707 | +} | ||
| 19708 | + | ||
| 19709 | +/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]). | ||
| 19710 | +pub(crate) fn arm_filter_replay() { | ||
| 19711 | + REPLAY_ARMED.set(true); | ||
| 19712 | +} | ||
| 19713 | + | ||
| 19714 | +/// Drop the armed flag and anything captured: the tile it belongs to is done. | ||
| 19715 | +pub(crate) fn clear_filter_replay() { | ||
| 19716 | + REPLAY_ARMED.set(false); | ||
| 19717 | + REPLAY.with_borrow_mut(|r| *r = None); | ||
| 19718 | +} | ||
| 19719 | + | ||
| 19720 | +/// The capture itself, called from the decoder's own pre-filter point. Owns | ||
| 19721 | +/// copies of the planes, since the caller filters them in place. | ||
| 19722 | +fn capture_filter_replay( | ||
| 19723 | + y: &PlaneBuf<'_>, | ||
| 19724 | + u: &PlaneBuf<'_>, | ||
| 19725 | + v: &PlaneBuf<'_>, | ||
| 19726 | + neighbours: &Neighbours, | ||
| 19727 | + frame_width: usize, | ||
| 19728 | + frame_height: usize, | ||
| 19729 | + width: usize, | ||
| 19730 | + height: usize, | ||
| 19731 | +) { | ||
| 19732 | + if !REPLAY_ARMED.replace(false) { | ||
| 19733 | + return; | ||
| 19734 | + } | ||
| 19735 | + let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p }; | ||
| 19736 | + REPLAY.with_borrow_mut(|slot| { | ||
| 19737 | + *slot = Some(FilterReplay { | ||
| 19738 | + y: own(y), | ||
| 19739 | + u: own(u), | ||
| 19740 | + v: own(v), | ||
| 19741 | + neighbours: neighbours.clone(), | ||
| 19742 | + frame_width, | ||
| 19743 | + frame_height, | ||
| 19744 | + width, | ||
| 19745 | + height, | ||
| 19746 | + }); | ||
| 19747 | + }); | ||
| 19748 | +} | ||
| 19749 | + | ||
| 19750 | +/// The filter half of a captured decode, under new parameters: exactly the | ||
| 19751 | +/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a | ||
| 19752 | +/// copy of the captured planes. `None` when nothing is captured (the caller | ||
| 19753 | +/// then decodes for real). | ||
| 19754 | +pub(crate) fn replay_filters( | ||
| 19755 | + loop_filter: &LoopFilterParams, | ||
| 19756 | + cdef: &CdefParams, | ||
| 19757 | + fctx: &FrameCtx, | ||
| 19758 | +) -> Option<Picture> { | ||
| 19759 | + REPLAY.with_borrow(|slot| { | ||
| 19760 | + let r = slot.as_ref()?; | ||
| 19761 | + let copy = |p: &PlaneBuf<'_>| PlaneBuf { | ||
| 19762 | + data: std::borrow::Cow::Owned(p.data.to_vec()), | ||
| 19763 | + ..*p | ||
| 19764 | + }; | ||
| 19765 | + let (mut y, mut u, mut v) = (copy(&r.y), copy(&r.u), copy(&r.v)); | ||
| 19766 | + apply_deblock( | ||
| 19767 | + &mut y, | ||
| 19768 | + &mut u, | ||
| 19769 | + &mut v, | ||
| 19770 | + loop_filter, | ||
| 19771 | + &r.neighbours, | ||
| 19772 | + r.frame_width, | ||
| 19773 | + r.frame_height, | ||
| 19774 | + fctx, | ||
| 19775 | + ); | ||
| 19776 | + apply_cdef(&mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx); | ||
| 19777 | + // The capture only happens on the shape the decoder's own tail | ||
| 19778 | + // returns whole (no superres, no loop restoration, no crop), so this | ||
| 19779 | + // is that tail. | ||
| 19780 | + fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None); | ||
| 19781 | + Some(Picture { | ||
| 19782 | + width: r.width, | ||
| 19783 | + height: r.height, | ||
| 19784 | + y: y.data.into_owned(), | ||
| 19785 | + u: u.data.into_owned(), | ||
| 19786 | + v: v.data.into_owned(), | ||
| 19787 | + }) | ||
| 19788 | + }) | ||
| 19789 | +} | ||
| 19790 | + | ||
| 19677 | /// The output crop, taking the plane by value: a frame whose width is | 19791 | /// The output crop, taking the plane by value: a frame whose width is |
| 19678 | /// already superblock-aligned (only its height is padded) has a padded | 19792 | /// already superblock-aligned (only its height is padded) has a padded |
| 19679 | /// buffer whose stride equals the visible width, so the crop is a pure | 19793 | /// buffer whose stride equals the visible width, so the crop is a pure |
| @@ -22847,6 +22961,28 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( | |||
| 22847 | let _ = f.write_all(&crop_wide(&v)); | 22961 | let _ = f.write_all(&crop_wide(&v)); |
| 22848 | } | 22962 | } |
| 22849 | } | 22963 | } |
| 22964 | + // lane-av1fwd: the encoder's filter search re-decodes this same key | ||
| 22965 | + // frame tile per candidate -- capture it once (see [`FilterReplay`]), | ||
| 22966 | + // on the shape whose tail is the two filter calls and nothing else. | ||
| 22967 | + if superres(fctx).is_none() | ||
| 22968 | + && frame_width as usize == width | ||
| 22969 | + && frame_height as usize == height | ||
| 22970 | + && !(0..3).any(|p| { | ||
| 22971 | + lr.frame_restoration_type[p] != ec_av1_syntax::RestorationType::None | ||
| 22972 | + && lr.loop_restoration_size[p] != 0 | ||
| 22973 | + }) | ||
| 22974 | + { | ||
| 22975 | + capture_filter_replay( | ||
| 22976 | + &y, | ||
| 22977 | + &u, | ||
| 22978 | + &v, | ||
| 22979 | + &neighbours, | ||
| 22980 | + frame_width as usize, | ||
| 22981 | + frame_height as usize, | ||
| 22982 | + width, | ||
| 22983 | + height, | ||
| 22984 | + ); | ||
| 22985 | + } | ||
| 22850 | apply_deblock( | 22986 | apply_deblock( |
| 22851 | &mut y, | 22987 | &mut y, |
| 22852 | &mut u, | 22988 | &mut u, |
| @@ -35446,6 +35582,27 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( | |||
| 35446 | p.finish(); | 35582 | p.finish(); |
| 35447 | } | 35583 | } |
| 35448 | drop(pipe); | 35584 | drop(pipe); |
| 35585 | + // lane-av1fwd: the encoder scores ~25 filter candidates against this | ||
| 35586 | + // same coded tile ([`FilterReplay`]). Capture the reconstruction here, | ||
| 35587 | + // before either filter has touched it -- but only on the shape whose | ||
| 35588 | + // tail is exactly `apply_deblock` + `apply_cdef` and nothing else. | ||
| 35589 | + if !pipelined | ||
| 35590 | + && !lr_active | ||
| 35591 | + && superres(fctx).is_none() | ||
| 35592 | + && frame_width as usize == width | ||
| 35593 | + && frame_height as usize == height | ||
| 35594 | + { | ||
| 35595 | + capture_filter_replay( | ||
| 35596 | + &y, | ||
| 35597 | + &u, | ||
| 35598 | + &v, | ||
| 35599 | + &neighbours, | ||
| 35600 | + frame_width as usize, | ||
| 35601 | + frame_height as usize, | ||
| 35602 | + width, | ||
| 35603 | + height, | ||
| 35604 | + ); | ||
| 35605 | + } | ||
| 35449 | if pipelined { | 35606 | if pipelined { |
| 35450 | cdef_scan_counters(&neighbours); | 35607 | cdef_scan_counters(&neighbours); |
| 35451 | } else { | 35608 | } else { |
crates/ec-av1/src/encode.rsmodified+77 -3
| @@ -3042,6 +3042,7 @@ pub(crate) fn encode_key_frame_inner( | |||
| 3042 | &mut chroma, | 3042 | &mut chroma, |
| 3043 | [&picture_y8, &picture_u8, &picture_v8], | 3043 | [&picture_y8, &picture_u8, &picture_v8], |
| 3044 | true, | 3044 | true, |
| 3045 | + fctx, | ||
| 3045 | |lf, cdef, h| { | 3046 | |lf, cdef, h| { |
| 3046 | crate::decode::decode_key_frame_tile( | 3047 | crate::decode::decode_key_frame_tile( |
| 3047 | &tile, | 3048 | &tile, |
| @@ -3107,6 +3108,7 @@ fn pick_and_apply_filters( | |||
| 3107 | chroma: &mut [Plane<'_>; 2], | 3108 | chroma: &mut [Plane<'_>; 2], |
| 3108 | source: [&[u8]; 3], | 3109 | source: [&[u8]; 3], |
| 3109 | search: bool, | 3110 | search: bool, |
| 3111 | + fctx: &crate::decode::FrameCtx, | ||
| 3110 | decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>, | 3112 | decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result<Picture>, |
| 3111 | ) -> Result<()> { | 3113 | ) -> Result<()> { |
| 3112 | if !search { | 3114 | if !search { |
| @@ -3117,13 +3119,25 @@ fn pick_and_apply_filters( | |||
| 3117 | // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: | 3119 | // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: |
| 3118 | // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. | 3120 | // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. |
| 3119 | let damping = 3 + (header.quantization.base_q_idx >> 6); | 3121 | let damping = 3 + (header.quantization.base_q_idx >> 6); |
| 3120 | - let (lf, cdef, filtered) = crate::filter_search::pick_filters( | 3122 | + // Every candidate scores the same coded tile: decode it once and re-run |
| 3121 | - |lf, cdef| decode(lf, cdef, &hdr), | 3123 | + // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of |
| 3124 | + // the encoder's profile before this). | ||
| 3125 | + crate::decode::clear_filter_replay(); | ||
| 3126 | + let search_result = crate::filter_search::pick_filters( | ||
| 3127 | + |lf, cdef| { | ||
| 3128 | + if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { | ||
| 3129 | + return Ok(picture); | ||
| 3130 | + } | ||
| 3131 | + crate::decode::arm_filter_replay(); | ||
| 3132 | + decode(lf, cdef, &hdr) | ||
| 3133 | + }, | ||
| 3122 | source, | 3134 | source, |
| 3123 | luma.width, | 3135 | luma.width, |
| 3124 | (fw, fh), | 3136 | (fw, fh), |
| 3125 | damping, | 3137 | damping, |
| 3126 | - )?; | 3138 | + ); |
| 3139 | + crate::decode::clear_filter_replay(); | ||
| 3140 | + let (lf, cdef, filtered) = search_result?; | ||
| 3127 | header.loop_filter = lf; | 3141 | header.loop_filter = lf; |
| 3128 | header.cdef = cdef; | 3142 | header.cdef = cdef; |
| 3129 | let dec_cw = filtered.width.div_ceil(2); | 3143 | let dec_cw = filtered.width.div_ceil(2); |
| @@ -4234,6 +4248,7 @@ pub(crate) fn encode_inter_frame( | |||
| 4234 | // `TxMode::Select` too (it used to skip and leave every inter frame | 4248 | // `TxMode::Select` too (it used to skip and leave every inter frame |
| 4235 | // unfiltered once Select became the default). | 4249 | // unfiltered once Select became the default). |
| 4236 | true, | 4250 | true, |
| 4251 | + fctx, | ||
| 4237 | |lf, cdef, h| { | 4252 | |lf, cdef, h| { |
| 4238 | crate::decode::decode_inter_frame_tile( | 4253 | crate::decode::decode_inter_frame_tile( |
| 4239 | &tile, | 4254 | &tile, |
| @@ -7056,6 +7071,46 @@ mod tests { | |||
| 7056 | (ladder, wall) | 7071 | (ladder, wall) |
| 7057 | } | 7072 | } |
| 7058 | 7073 | ||
| 7074 | + /// Byte-exactness gate for encoder work that is meant to change only | ||
| 7075 | + /// how long the encoder takes. | ||
| 7076 | + /// | ||
| 7077 | + /// The BD gate above measures quality, which a speed lane can move by a | ||
| 7078 | + /// hair without failing anything; this pins the streams themselves. | ||
| 7079 | + /// Every number below was measured 2026-09-06 (lane-av1fwd) and is | ||
| 7080 | + /// identical at `a6649c4e`, the merge before that lane's three exact | ||
| 7081 | + /// speed steps. | ||
| 7082 | + #[test] | ||
| 7083 | + fn the_encoders_own_streams_are_byte_identical_to_their_pins() { | ||
| 7084 | + if !have_ffmpeg() { | ||
| 7085 | + eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); | ||
| 7086 | + return; | ||
| 7087 | + } | ||
| 7088 | + let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) | ||
| 7089 | + .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); | ||
| 7090 | + if !clip.exists() { | ||
| 7091 | + eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip"); | ||
| 7092 | + return; | ||
| 7093 | + } | ||
| 7094 | + let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4); | ||
| 7095 | + // FNV-1a over the stream: a witness that every coded bit is where it | ||
| 7096 | + // was, which a byte count alone is not. | ||
| 7097 | + let fnv = |b: &[u8]| { | ||
| 7098 | + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { | ||
| 7099 | + (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) | ||
| 7100 | + }) | ||
| 7101 | + }; | ||
| 7102 | + let pins: [(u8, usize, u64); 2] = | ||
| 7103 | + [(150, 7823, 0x81db_18bb_91be_0d89), (60, 28189, 0x25fb_2fce_1bd1_e000)]; | ||
| 7104 | + for (q, bytes, hash) in pins { | ||
| 7105 | + let encoded = encode_sequence(&source, q, 0.5).unwrap(); | ||
| 7106 | + assert_eq!( | ||
| 7107 | + (encoded.stream.len(), fnv(&encoded.stream)), | ||
| 7108 | + (bytes, hash), | ||
| 7109 | + "q={q}: the encoder's stream moved" | ||
| 7110 | + ); | ||
| 7111 | + } | ||
| 7112 | + } | ||
| 7113 | + | ||
| 7059 | /// A ladder is only a ladder if both axes rise together. | 7114 | /// A ladder is only a ladder if both axes rise together. |
| 7060 | fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { | 7115 | fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { |
| 7061 | assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); | 7116 | assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); |
| @@ -7092,6 +7147,25 @@ mod tests { | |||
| 7092 | /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | | 7147 | /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s | |
| 7093 | /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | | 7148 | /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s | |
| 7094 | /// | 7149 | /// |
| 7150 | + /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long | ||
| 7151 | + /// the encoder takes -- every stream it writes is byte-identical, so the | ||
| 7152 | + /// BD columns are this box's own re-run of the same recipe rather than a | ||
| 7153 | + /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs | ||
| 7154 | + /// rav1e). What moved is the wall of the four encodes: | ||
| 7155 | + /// | ||
| 7156 | + /// | clip | wall ours before | after | instructions:u before -> after | | ||
| 7157 | + /// |---|---|---|---| | ||
| 7158 | + /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) | | ||
| 7159 | + /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) | | ||
| 7160 | + /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) | | ||
| 7161 | + /// | ||
| 7162 | + /// Three exact steps, none of which touches a coded bit: the coefficient | ||
| 7163 | + /// rate pricer stopped rebuilding every CDF table per candidate | ||
| 7164 | + /// (`tile::coeff_bits`), the filter search stopped re-decoding its own | ||
| 7165 | + /// tile once per candidate (`decode::FilterReplay`), and the forward | ||
| 7166 | + /// transform stopped transforming the all-zero residual that 70% of its | ||
| 7167 | + /// calls carry. | ||
| 7168 | + /// | ||
| 7095 | /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): | 7169 | /// The three steps of that lane, same recipe (vs libaom, then vs rav1e): |
| 7096 | /// | 7170 | /// |
| 7097 | /// | step | 1080p | 2160p | screen | | 7171 | /// | step | 1080p | 2160p | screen | |
crates/ec-av1/src/tile.rsmodified+47 -13
| @@ -9,6 +9,7 @@ | |||
| 9 | //! It is the skeleton the block modes, transform sizes and coefficients hang | 9 | //! It is the skeleton the block modes, transform sizes and coefficients hang |
| 10 | //! off as they arrive. | 10 | //! off as they arrive. |
| 11 | 11 | ||
| 12 | +use std::cell::RefCell; | ||
| 12 | use std::sync::LazyLock; | 13 | use std::sync::LazyLock; |
| 13 | 14 | ||
| 14 | use ec_core::{Error, Result}; | 15 | use ec_core::{Error, Result}; |
| @@ -2131,18 +2132,48 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { | |||
| 2131 | default_scan(TX32), | 2132 | default_scan(TX32), |
| 2132 | ] | 2133 | ] |
| 2133 | }); | 2134 | }); |
| 2134 | - let mut cdfs = Cdfs::new(q_ctx); | 2135 | + // `Cdfs::new` builds every table a tile writer adapts -- tens of |
| 2135 | - let mut coding = cdfs.txb(set, DC_PRED); | 2136 | + // kilobytes -- and this function is called once per priced candidate: |
| 2136 | - let scan = match coding.side { | 2137 | + // together with the copy behind it that was 9% of the encoder's profile |
| 2137 | - TX4 => &SCANS[0], | 2138 | + // (`__memmove` 6.0% + `Cdfs::new` 3.4%, both under this call). Only the |
| 2138 | - TX8 => &SCANS[1], | 2139 | + // tables `write_coeffs` touches change, so keep one scratch `Cdfs` per |
| 2139 | - TX16 => &SCANS[2], | 2140 | + // q-context per thread beside a pristine one and restore just those from |
| 2140 | - _ => &SCANS[3], | 2141 | + // it. The state the price is taken against is identical to a fresh |
| 2141 | - }; | 2142 | + // `Cdfs::new(q_ctx)`, so every price is bit-identical. |
| 2142 | - let mut enc = SymbolEncoder::new(); | 2143 | + thread_local! { |
| 2143 | - enc.reset_bits(); | 2144 | + static PRICING: RefCell<[Option<Box<(Cdfs, Cdfs)>>; 4]> = |
| 2144 | - write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); | 2145 | + const { RefCell::new([None, None, None, None]) }; |
| 2145 | - enc.bits() | 2146 | + } |
| 2147 | + PRICING.with_borrow_mut(|slots| { | ||
| 2148 | + let slot = slots[q_ctx.min(3)] | ||
| 2149 | + .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx)))); | ||
| 2150 | + let (pristine, scratch) = (&mut slot.0, &mut slot.1); | ||
| 2151 | + let src = pristine.txb(set, DC_PRED); | ||
| 2152 | + let mut coding = scratch.txb(set, DC_PRED); | ||
| 2153 | + coding.txb_skip.copy_from_slice(src.txb_skip); | ||
| 2154 | + coding.eob_pt.copy_from_slice(src.eob_pt); | ||
| 2155 | + if let (Some(dst), Some(src)) = (coding.eob_pt_class1.as_mut(), src.eob_pt_class1) { | ||
| 2156 | + dst.copy_from_slice(src); | ||
| 2157 | + } | ||
| 2158 | + *coding.eob_extra = *src.eob_extra; | ||
| 2159 | + *coding.base = *src.base; | ||
| 2160 | + *coding.base_eob = *src.base_eob; | ||
| 2161 | + *coding.br = *src.br; | ||
| 2162 | + *coding.dc_sign = *src.dc_sign; | ||
| 2163 | + if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) { | ||
| 2164 | + dst.copy_from_slice(src); | ||
| 2165 | + } | ||
| 2166 | + let scan = match coding.side { | ||
| 2167 | + TX4 => &SCANS[0], | ||
| 2168 | + TX8 => &SCANS[1], | ||
| 2169 | + TX16 => &SCANS[2], | ||
| 2170 | + _ => &SCANS[3], | ||
| 2171 | + }; | ||
| 2172 | + let mut enc = SymbolEncoder::new(); | ||
| 2173 | + enc.reset_bits(); | ||
| 2174 | + write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); | ||
| 2175 | + enc.bits() | ||
| 2176 | + }) | ||
| 2146 | } | 2177 | } |
| 2147 | 2178 | ||
| 2148 | /// What the partition symbol of a block of `side` samples costs, in bits, when | 2179 | /// What the partition symbol of a block of `side` samples costs, in bits, when |
| @@ -2152,7 +2183,10 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { | |||
| 2152 | /// than it is — because the search that reads it runs before the tile knows | 2183 | /// than it is — because the search that reads it runs before the tile knows |
| 2153 | /// what its neighbours will be. | 2184 | /// what its neighbours will be. |
| 2154 | pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { | 2185 | pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { |
| 2155 | - let cdfs = Cdfs::new(2); | 2186 | + // Read-only, and the same tables every call: built once (see |
| 2187 | + // [`coeff_bits`] for why that matters here). | ||
| 2188 | + static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2)); | ||
| 2189 | + let cdfs = &*CDFS; | ||
| 2156 | let cdf: &[u16] = match side { | 2190 | let cdf: &[u16] = match side { |
| 2157 | SB => &cdfs.partition_w64[0], | 2191 | SB => &cdfs.partition_w64[0], |
| 2158 | BLOCK => &cdfs.partition_w32[0], | 2192 | BLOCK => &cdfs.partition_w32[0], |
crates/ec-av1/src/transform.rsmodified+34 -13
| @@ -1463,8 +1463,19 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType | |||
| 1463 | let (row_kind, col_kind) = tx_type.axes(); | 1463 | let (row_kind, col_kind) = tx_type.axes(); |
| 1464 | let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); | 1464 | let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind)); |
| 1465 | let mut rows = vec![0.0f64; side * side]; | 1465 | let mut rows = vec![0.0f64; side * side]; |
| 1466 | + // Zero in, zero out, and `rows` is already zero here -- the skip | ||
| 1467 | + // [`forward_rows`] takes for the same reason, which this path was | ||
| 1468 | + // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68% | ||
| 1469 | + // of the 1.9M calls here carry an all-zero residual, and another 6.5M | ||
| 1470 | + // individual rows of the rest are zero. A row of zeros contributes only | ||
| 1471 | + // `0.0 * b` terms, and a sum of zeros is `+0.0`, so this is exact. | ||
| 1472 | + let mut any = false; | ||
| 1466 | for i in 0..side { | 1473 | for i in 0..side { |
| 1467 | let source = &residual[i * side..][..side]; | 1474 | let source = &residual[i * side..][..side]; |
| 1475 | + if source.iter().all(|&r| r == 0) { | ||
| 1476 | + continue; | ||
| 1477 | + } | ||
| 1478 | + any = true; | ||
| 1468 | for v in 0..side { | 1479 | for v in 0..side { |
| 1469 | rows[i * side + v] = source | 1480 | rows[i * side + v] = source |
| 1470 | .iter() | 1481 | .iter() |
| @@ -1473,6 +1484,9 @@ pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType | |||
| 1473 | .sum(); | 1484 | .sum(); |
| 1474 | } | 1485 | } |
| 1475 | } | 1486 | } |
| 1487 | + if !any { | ||
| 1488 | + return rows; | ||
| 1489 | + } | ||
| 1476 | let mut out = vec![0.0f64; side * side]; | 1490 | let mut out = vec![0.0f64; side * side]; |
| 1477 | for u in 0..side { | 1491 | for u in 0..side { |
| 1478 | let column = &vb[u * side..][..side]; | 1492 | let column = &vb[u * side..][..side]; |
| @@ -1914,20 +1928,20 @@ pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone | |||
| 1914 | let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx)); | 1928 | let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx)); |
| 1915 | let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx)); | 1929 | let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx)); |
| 1916 | let mut levels = vec![0i32; side * side]; | 1930 | let mut levels = vec![0i32; side * side]; |
| 1917 | - for (i, &c) in coeffs.iter().enumerate() { | 1931 | + let coded = side.min(32); |
| 1918 | - let (row, col) = (i / side, i % side); | 1932 | + for row in 0..coded { |
| 1919 | - if row >= 32 || col >= 32 { | 1933 | + for col in 0..coded { |
| 1920 | - continue; | 1934 | + let i = row * side + col; |
| 1935 | + let q = if i == 0 { dc } else { ac }; | ||
| 1936 | + let scaled = coeffs[i] / q; | ||
| 1937 | + let magnitude = scaled.abs() + deadzone; | ||
| 1938 | + let level = if magnitude < 1.0 { | ||
| 1939 | + 0 | ||
| 1940 | + } else { | ||
| 1941 | + magnitude.floor().min(f64::from(i32::MAX)) as i32 | ||
| 1942 | + }; | ||
| 1943 | + levels[i] = if scaled < 0.0 { -level } else { level }; | ||
| 1921 | } | 1944 | } |
| 1922 | - let q = if i == 0 { dc } else { ac }; | ||
| 1923 | - let scaled = c / q; | ||
| 1924 | - let magnitude = scaled.abs() + deadzone; | ||
| 1925 | - let level = if magnitude < 1.0 { | ||
| 1926 | - 0 | ||
| 1927 | - } else { | ||
| 1928 | - magnitude.floor().min(f64::from(i32::MAX)) as i32 | ||
| 1929 | - }; | ||
| 1930 | - levels[i] = if scaled < 0.0 { -level } else { level }; | ||
| 1931 | } | 1945 | } |
| 1932 | levels | 1946 | levels |
| 1933 | } | 1947 | } |
| @@ -1941,6 +1955,13 @@ pub fn forward_and_quantize( | |||
| 1941 | q_idx: i32, | 1955 | q_idx: i32, |
| 1942 | deadzone: f64, | 1956 | deadzone: f64, |
| 1943 | ) -> Vec<i32> { | 1957 | ) -> Vec<i32> { |
| 1958 | + // 72% of this encoder's forward DCTs are of an all-zero residual | ||
| 1959 | + // (measured over the BD gate's own ladder, lane-av1fwd): every row and | ||
| 1960 | + // every column of the network is skipped for them anyway, so the levels | ||
| 1961 | + // are zero without allocating the row pass's buffer at all. | ||
| 1962 | + if residual.iter().all(|&r| r == 0) { | ||
| 1963 | + return vec![0i32; side * side]; | ||
| 1964 | + } | ||
| 1944 | // Fused: the levels are formed straight off the fixed-point coefficients, | 1965 | // Fused: the levels are formed straight off the fixed-point coefficients, |
| 1945 | // so neither the `Vec<f64>` of coefficients nor the pass that reads it | 1966 | // so neither the `Vec<f64>` of coefficients nor the pass that reads it |
| 1946 | // exists. | 1967 | // exists. |