forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

census.rs314 lines, 12.1 KiBHistoryRawDownload
1//! Syntax census: what a stream actually codes, per frame, read off the
2//! decoder itself (`EC_AV1_BITCENSUS=1`).
3//!
4//! Every number here is a decode-side observation, so OUR stream and any
5//! other encoder's stream are measured by the same reader -- which is the
6//! whole point: a BD-rate gap says our stream is bigger, it never says which
7//! syntax it is bigger in. The accountant is off by default and costs one
8//! relaxed atomic load per symbol when off.
9//!
10//! Bits are charged per CDF TABLE, not per hand-labelled call site: a tile
11//! registers the address range of every field of its `Cdfs` (see
12//! [`register_cdfs`]), and [`charge`] maps the table a symbol read to that
13//! field's name. So a new coding tool joins the census the day its CDF joins
14//! the struct, with no call-site edits (class `gate-blind-to-feature`).
15//!
16//! Run it through `examples/syntax_census.rs`; `EC_AV1_THREADS` must be 1
17//! (the default) so the frame the counters attribute to is the frame being
18//! parsed.
19
20use std::collections::BTreeMap;
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Mutex, OnceLock};
23
24static ON: AtomicBool = AtomicBool::new(false);
25
26/// Whether the accountant is armed (`EC_AV1_BITCENSUS=1`, read once).
27#[inline]
28pub fn on() -> bool {
29 static INIT: OnceLock<bool> = OnceLock::new();
30
31 *INIT.get_or_init(|| {
32 let armed = crate::envflags::var("EC_AV1_BITCENSUS").ok().as_deref() == Some("1");
33 ON.store(armed, Ordering::Relaxed);
34 armed
35 })
36}
37
38/// The per-symbol fast path: one relaxed load, nothing else, when off.
39#[inline]
40pub(crate) fn armed() -> bool {
41 ON.load(Ordering::Relaxed)
42}
43
44/// One coded frame's census.
45#[derive(Default, Debug, Clone)]
46pub struct Frame {
47 /// Decode-order index.
48 pub idx: usize,
49 /// `key` (intra), `arf` (coded but not shown) or `leaf` (coded and shown).
50 pub kind: &'static str,
51 /// `base_q_idx`.
52 pub qindex: u8,
53 /// `OrderHint` of this frame, i.e. its display position (lane-arfcen).
54 pub order_hint: u32,
55 /// `OrderHints[LAST..=ALTREF]`, so a row can name its references' display
56 /// distance rather than only which slot it read (lane-arfcen).
57 pub ref_hints: [u32; 7],
58 /// Tile payload bytes of this frame.
59 pub bytes: usize,
60 /// `delta_q_present`.
61 pub delta_q: bool,
62 /// `segmentation_enabled`.
63 pub segmentation: bool,
64 /// `loop_filter_level[0..2]`.
65 pub lf: [u8; 2],
66 /// `cdef_bits`, `cdef_y_pri_strength[0]`, `cdef_uv_pri_strength[0]`.
67 pub cdef: [u8; 3],
68 /// `FrameRestorationType` per plane.
69 pub lr: [u8; 3],
70 /// Coded block shapes: (width, height) in pixels -> block count.
71 pub blocks: BTreeMap<(u16, u16), u64>,
72 /// Luma area (in 4x4 units) coded intra / single-ref inter / compound.
73 pub area: [u64; 3],
74 /// Luma area per reference frame slot (index 0 = intra, 1..=7 =
75 /// LAST..ALTREF as `ref_frame` names them).
76 pub refs: [u64; 8],
77 /// Luma area with `skip` set.
78 pub skip_area: u64,
79 /// NEWMV / GLOBALMV / NEARESTMV / NEARMV blocks (single-ref reads).
80 pub modes: [u64; 4],
81 /// Coded motion vectors bucketed by max(|x|,|y|) in eighth-pel:
82 /// 0, <=8 (1px), <=32, <=128, <=512, >512.
83 pub mv: [u64; 6],
84 /// Published luma transform shapes: (width, height) in pixels -> count.
85 pub tx: BTreeMap<(u16, u16), u64>,
86 /// Coded `tx_type` symbols: (CDF row length, symbol) -> count. The row
87 /// length names the transform SET (17 = all 16 types, 13, 8, 6 = the
88 /// reduced sets); symbol 0 is that set's first inverse-table entry.
89 pub tx_type: BTreeMap<(u8, u8), u64>,
90 /// Per-CDF-table (symbol count, bits).
91 pub families: BTreeMap<&'static str, (u64, f64)>,
92}
93
94#[derive(Default)]
95struct State {
96 frames: Vec<Frame>,
97 /// Sorted (start address, end address, field name) of the live tile's
98 /// `Cdfs`.
99 tables: Vec<(usize, usize, &'static str)>,
100 /// Area of the block most recently published, so `compound` can move it.
101 last_block_area: u64,
102}
103
104fn state() -> &'static Mutex<State> {
105 static S: OnceLock<Mutex<State>> = OnceLock::new();
106 S.get_or_init(|| Mutex::new(State::default()))
107}
108
109fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
110 f(&mut state().lock().unwrap_or_else(std::sync::PoisonError::into_inner))
111}
112
113fn cur(s: &mut State) -> &mut Frame {
114 if s.frames.is_empty() {
115 s.frames.push(Frame::default());
116 }
117 s.frames.last_mut().expect("pushed above")
118}
119
120/// Every frame censused since the last call, and clears the record.
121pub fn take() -> Vec<Frame> {
122 with(|s| std::mem::take(&mut s.frames))
123}
124
125/// Opens a new frame's row -- called once per coded frame, before its tiles.
126pub(crate) fn frame_start(header: &ec_av1_syntax::FrameHeader, bytes: usize, idx: usize) {
127 if !armed() {
128 return;
129 }
130 let kind = match (header.frame_is_intra, header.show_frame) {
131 (true, _) => "key",
132 (false, false) => "arf",
133 (false, true) => "leaf",
134 };
135 with(|s| {
136 s.frames.push(Frame {
137 idx,
138 kind,
139 qindex: header.quantization.base_q_idx,
140 order_hint: header.order_hint,
141 ref_hints: header.order_hints,
142 bytes,
143 delta_q: header.delta.q_present,
144 segmentation: header.segmentation.enabled,
145 lf: [header.loop_filter.level[0], header.loop_filter.level[1]],
146 cdef: [
147 header.cdef.bits,
148 header.cdef.y_pri_strength[0],
149 header.cdef.uv_pri_strength[0],
150 ],
151 lr: [
152 header.loop_restoration.frame_restoration_type[0] as u8,
153 header.loop_restoration.frame_restoration_type[1] as u8,
154 header.loop_restoration.frame_restoration_type[2] as u8,
155 ],
156 ..Frame::default()
157 });
158 });
159}
160
161/// Registers the address range of every CDF table of the tile's own `Cdfs`,
162/// so [`charge`] can name the family a symbol was read with. Called once per
163/// tile, right where the tile's symbol decoder is built.
164pub(crate) fn register_cdfs(c: &crate::cdf_state::Cdfs) {
165 if !armed() {
166 return;
167 }
168 macro_rules! ranges {
169 ($($name:ident),* $(,)?) => {
170 vec![$({
171 let start = std::ptr::addr_of!(c.$name) as usize;
172 (start, start + std::mem::size_of_val(&c.$name), stringify!($name))
173 }),*]
174 };
175 }
176 let mut tables: Vec<(usize, usize, &'static str)> = ranges![
177 partition_w128, partition_w64, partition_w32, txfm_partition, skip, kf_y_mode,
178 uv_mode_no_cfl, uv_mode_cfl, cfl_sign, cfl_alpha, angle_delta, txb_skip_luma_16,
179 txb_skip_luma_8, txb_skip_luma_4, txb_skip_chroma_8, txb_skip_chroma_4, eob_pt_256_luma, eob_pt_64_luma,
180 eob_pt_64_chroma, eob_pt_16_chroma, eob_pt_16_luma, eob_pt_16_luma_class1, eob_pt_64_luma_class1, eob_pt_16_chroma_class1,
181 eob_pt_64_chroma_class1, eob_pt_128_chroma_class1, eob_pt_128_luma_class1, eob_pt_32_chroma_class1, eob_pt_256_luma_class1, eob_pt_256_chroma_class1,
182 eob_pt_512_luma_class1, eob_pt_512_chroma_class1, eob_pt_1024_luma_class1, eob_pt_1024_chroma_class1, eob_pt_32_luma, eob_pt_32_luma_class1,
183 eob_extra_luma_16, eob_extra_luma_8, eob_extra_luma_4, eob_extra_chroma_8, eob_extra_chroma_4, base_luma_16,
184 base_luma_8, base_luma_4, base_chroma_8, base_chroma_4, base_eob_luma_16, base_eob_luma_8,
185 base_eob_luma_4, base_eob_chroma_8, base_eob_chroma_4, br_luma_16, br_luma_8, br_luma_4,
186 br_chroma_8, br_chroma_4, partition_w16, partition_w8, txb_skip_luma_32, txb_skip_luma_64,
187 txb_skip_chroma_16, txb_skip_chroma_32, eob_pt_1024_luma, eob_pt_1024_chroma, eob_pt_256_chroma, eob_pt_512_luma,
188 eob_pt_128_chroma, eob_pt_512_chroma, eob_pt_128_luma, eob_pt_32_chroma, eob_extra_luma_32, eob_extra_luma_64,
189 eob_extra_chroma_16, eob_extra_chroma_32, base_luma_32, base_luma_64, base_chroma_16, base_chroma_32,
190 base_eob_luma_32, base_eob_luma_64, base_eob_chroma_16, base_eob_chroma_32, br_luma_32, br_chroma_16,
191 br_chroma_32, dc_sign_luma, intra_tx_type_16, intra_tx_type_8, intra_tx_type_8_set1, intra_tx_type_4,
192 intra_tx_type_4_set1, inter_tx_type_32, inter_tx_type_16, inter_tx_type_8, inter_tx_type_16_set2, inter_tx_type_8_set1,
193 inter_tx_type_4, inter_tx_type_4_set1, dc_sign_chroma, intra_inter, single_ref, comp_mode,
194 skip_mode, obmc, motion_mode, interintra, interintra_mode, wedge_interintra,
195 compound_type, wedge_idx, inter_compound_mode, comp_ref_type, uni_comp_ref, comp_ref,
196 comp_bwdref, comp_group_idx, compound_idx, y_mode, new_mv, zero_mv,
197 ref_mv, drl_mode, mv_joint, mv_comp, dv_joint, dv_comp,
198 filter_intra, filter_intra_mode, tx_size_cat0, tx_size_cat1, tx_size_cat2, tx_size_cat3,
199 switchable_interp, palette_y_mode, palette_y_size, palette_uv_mode, palette_uv_size, palette_y_color_index,
200 palette_uv_color_index, intrabc, restore_wiener, restore_sgrproj, restore_switchable, segment_id,
201 segment_pred, delta_q, delta_lf, delta_lf_multi
202 ];
203 tables.sort_unstable();
204 with(|s| s.tables = tables);
205}
206
207/// Charges `bits` to whichever CDF table `addr` falls inside.
208pub(crate) fn charge(addr: usize, bits: f64) {
209 with(|s| {
210 let name = match s.tables.partition_point(|t| t.0 <= addr) {
211 0 => "unregistered",
212 i if s.tables[i - 1].1 > addr => s.tables[i - 1].2,
213 _ => "unregistered",
214 };
215 let e = cur(s).families.entry(name).or_default();
216 e.0 += 1;
217 e.1 += bits;
218 });
219}
220
221/// Charges raw (equiprobable) bits, which no CDF names.
222pub(crate) fn charge_literal(bits: u32) {
223 with(|s| {
224 let e = cur(s).families.entry("literal").or_default();
225 e.0 += u64::from(bits);
226 e.1 += f64::from(bits);
227 });
228}
229
230/// One coded block, from the neighbour publisher every block routes through.
231pub(crate) fn block(w_mi: usize, h_mi: usize, is_inter: bool, ref_frame: i8, skip: bool) {
232 if !armed() {
233 return;
234 }
235 let area = (w_mi * h_mi) as u64;
236 with(|s| {
237 s.last_block_area = area;
238 let f = cur(s);
239 *f.blocks.entry(((w_mi * 4) as u16, (h_mi * 4) as u16)).or_default() += 1;
240 f.area[usize::from(is_inter)] += area;
241 f.refs[(ref_frame.max(0) as usize).min(7)] += area;
242 if skip {
243 f.skip_area += area;
244 }
245 });
246}
247
248/// The block just published is compound (two references) -- called from the
249/// compound-context publisher, which runs right after [`block`].
250pub(crate) fn compound() {
251 if !armed() {
252 return;
253 }
254 with(|s| {
255 let area = s.last_block_area;
256 let f = cur(s);
257 f.area[1] = f.area[1].saturating_sub(area);
258 f.area[2] += area;
259 });
260}
261
262/// One block's published luma transform shape.
263pub(crate) fn tx(w_px: u8, h_px: u8) {
264 if !armed() {
265 return;
266 }
267 with(|s| *cur(s).tx.entry((u16::from(w_px), u16::from(h_px))).or_default() += 1);
268}
269
270/// One coded motion vector (a NEWMV read).
271pub(crate) fn mv(x: i32, y: i32) {
272 if !armed() {
273 return;
274 }
275 let m = x.abs().max(y.abs());
276 let bucket = match m {
277 0 => 0,
278 1..=8 => 1,
279 9..=32 => 2,
280 33..=128 => 3,
281 129..=512 => 4,
282 _ => 5,
283 };
284 with(|s| cur(s).mv[bucket] += 1);
285}
286
287/// One single-ref inter mode decision: 0 NEWMV, 1 GLOBALMV, 2 NEARESTMV,
288/// 3 NEARMV.
289pub(crate) fn mode(which: usize) {
290 if !armed() {
291 return;
292 }
293 with(|s| cur(s).modes[which] += 1);
294}
295
296/// One coded `tx_type` symbol, with the CDF row length that names its set.
297pub(crate) fn tx_type(len: usize, symbol: usize) {
298 if !armed() {
299 return;
300 }
301 with(|s| *cur(s).tx_type.entry((len as u8, symbol as u8)).or_default() += 1);
302}
303
304/// One coded block of an INTRA frame, from the `blk_grid` publisher every
305/// block writes -- a no-op on an inter frame, where [`block`] (the inter
306/// neighbour publisher, which knows the reference) counts instead.
307pub(crate) fn block_intra_frame(w_mi: usize, h_mi: usize, skip: bool) {
308 if !armed() {
309 return;
310 }
311 if with(|s| cur(s).kind == "key") {
312 block(w_mi, h_mi, false, 0, skip);
313 }
314}