forge
Explore
Log in

Don't you dare go Hollow

Code a DC coefficient in the key frame tile

Browse files at this commit

c68b3bd00f565f352bb7ed22e3a178f0110bc271Ahmet Kaan GümüşParent: 304ec65
  • feat
    • code a DC coefficient in the key frame tile
Show full message
feat(av1): code a DC coefficient in the key frame tile

The tile writer could only say "this block is skipped". It now carries a
single luma DC coefficient through the full coefficient syntax: the
all-zero flag, the end-of-block position, the base level, the base-range
tail for levels above two, and the sign with its neighbour-derived
context. Chroma stays all-zero, so the two chroma flags sit immediately
after the luma block and a desync in it lands on them first.

The q-context CDFs this crate carries are the ones for base_q_idx 61..=120,
so the writer refuses a base_q_idx outside that band rather than coding
against tables the decoder will not be using. Levels are bounded at
+/-14, which is what the base syntax reaches before the Golomb tail.

The gate decodes each level -14..=14 through ffmpeg and asserts the whole
64x64 luma plane lands on a pinned value, chroma is untouched at 128, the
sequence is monotone in the level, and the sign moves the picture the way
it should. The pinned values come from the decoder, not from a derivation:
there is no inverse transform in this crate yet to derive them with.
crates/ec-av1/src/cdf.rsmodified+37 -0
@@ -196,3 +196,40 @@ pub const UV_MODE_NO_CFL: [[u16; 14]; 13] = [
196 0,196 0,
197 ],197 ],
198 ];198 ];
199+
200+// The coefficient CDFs below are the q-context-2 tables (`base_q_idx` 61..=120,
201+// spec 8.3.2's `Default_..._Cdf[2]`), which is the context the frames this
202+// crate writes today sit in. The other three sets arrive with the rate control
203+// that can leave that band.
204+
205+/// `Default_Txb_Skip_Cdf[2][4][0]` (spec 9.4): the all-zero flag of a 64x64
206+/// luma transform block whose block size is the transform size, so its
207+/// context is 0.
208+pub const TXB_SKIP_LUMA_64: [u16; 3] = [28573, 32768, 0];
209+
210+/// `Default_Txb_Skip_Cdf[2][3][7]` (spec 9.4): the all-zero flag of a 32x32
211+/// chroma transform block that covers its whole plane block with no coded
212+/// neighbour, which is context 7.
213+pub const TXB_SKIP_CHROMA_32: [u16; 3] = [5124, 32768, 0];
214+
215+/// `Default_Eob_Pt_1024_Cdf[2][0][0]` (spec 9.4): the end-of-block position
216+/// token of a luma transform block with 1024 coded coefficient positions —
217+/// what a 64x64 transform has, since only its top-left 32x32 is coded.
218+pub const EOB_PT_1024_LUMA: [u16; 12] = [
219+ 2784, 3831, 7041, 10521, 14847, 18844, 23155, 26682, 29229, 31045, 32768, 0,
220+];
221+
222+/// `Default_Coeff_Base_Eob_Cdf[2][4][0][0]` (spec 9.4): the level of the last
223+/// coefficient of a 64x64 luma transform block, less one, when that
224+/// coefficient is the DC.
225+pub const COEFF_BASE_EOB_LUMA_64: [u16; 4] = [935, 3382, 32768, 0];
226+
227+/// `Default_Dc_Sign_Cdf[2][0]` (spec 9.4): the sign of a luma DC coefficient,
228+/// indexed by whether the neighbouring blocks' DC signs lean negative (1),
229+/// positive (2) or neither (0).
230+pub const DC_SIGN_LUMA: [[u16; 3]; 3] = [[16000, 32768, 0], [13056, 32768, 0], [18816, 32768, 0]];
231+
232+/// `Default_Coeff_Br_Cdf[2][3][0][0]` (spec 9.4): a base-range increment of a
233+/// coefficient whose neighbours are all zero, in a transform of 32x32 or
234+/// larger (the table is shared from 32x32 up).
235+pub const COEFF_BR_LUMA: [u16; 5] = [9040, 14786, 18360, 32768, 0];
crates/ec-av1/src/tile.rsmodified+253 -11
@@ -21,6 +21,36 @@ const DC_PRED: usize = 0;
21 /// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.21 /// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
22 const SB_MI: u32 = 16;22 const SB_MI: u32 = 16;
23 23
24+/// `NUM_BASE_LEVELS` (spec 3): levels above this carry a base-range tail.
25+const NUM_BASE_LEVELS: i32 = 2;
26+/// `COEFF_BASE_RANGE` (spec 3): how far the base-range tail reaches before the
27+/// Golomb tail takes over.
28+const COEFF_BASE_RANGE: i32 = 12;
29+/// `BR_CDF_SIZE - 1` (spec 3): the largest increment one base-range symbol
30+/// carries.
31+const BR_STEP: i32 = 3;
32+/// The largest level the base and base-range syntax carry between them.
33+const MAX_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
34+/// The q-context band whose default CDFs [`crate::cdf`] carries.
35+const Q_CTX_2: std::ops::RangeInclusive<u8> = 61..=120;
36+
37+/// Both writers here code whole superblocks only: a partial one forces the
38+/// partition syntax down the block tree, which they do not code yet.
39+fn check_superblocks(mi_cols: u32, mi_rows: u32) -> Result<()> {
40+ if mi_cols == 0
41+ || mi_rows == 0
42+ || !mi_cols.is_multiple_of(SB_MI)
43+ || !mi_rows.is_multiple_of(SB_MI)
44+ {
45+ return Err(Error::unsupported(
46+ "AV1 tile",
47+ "a key frame is written only for frames that are a whole number \
48+ of 64x64 superblocks",
49+ ));
50+ }
51+ Ok(())
52+}
53+
24 /// Writes the payload of a one-tile key frame in which every superblock is a54 /// Writes the payload of a one-tile key frame in which every superblock is a
25 /// skipped 64x64 DC-predicted block.55 /// skipped 64x64 DC-predicted block.
26 ///56 ///
@@ -32,17 +62,7 @@ const SB_MI: u32 = 16;
32 /// a partial superblock forces the partition syntax down the block tree, which62 /// a partial superblock forces the partition syntax down the block tree, which
33 /// this writer does not code yet.63 /// this writer does not code yet.
34 pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {64 pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
35- if mi_cols == 065+ check_superblocks(mi_cols, mi_rows)?;
36- || mi_rows == 0
37- || !mi_cols.is_multiple_of(SB_MI)
38- || !mi_rows.is_multiple_of(SB_MI)
39- {
40- return Err(Error::unsupported(
41- "AV1 tile",
42- "a flat key frame is written only for frames that are a whole \
43- number of 64x64 superblocks",
44- ));
45- }
46 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);66 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
47 67
48 let mut enc = SymbolEncoder::new();68 let mut enc = SymbolEncoder::new();
@@ -74,6 +94,114 @@ pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result<Vec<u8>> {
74 Ok(enc.finish())94 Ok(enc.finish())
75 }95 }
76 96
97+/// Writes the payload of a one-tile key frame in which every superblock is a
98+/// 64x64 DC-predicted block carrying one luma DC coefficient of `dc_level` and
99+/// no chroma residual.
100+///
101+/// `dc_level` is a quantised level, not a sample value: the decoder multiplies
102+/// it by the frame's DC quantiser and inverse-transforms it over the whole
103+/// block, so the picture it makes is a flat grey some distance either side of
104+/// the mid-grey a zero level gives. `base_q_idx` is the frame header's, and
105+/// picks the coefficient CDFs.
106+///
107+/// # Errors
108+/// Returns an error when the frame is not a whole number of 64x64 superblocks,
109+/// when `dc_level` is outside the range the base and base-range syntax carry
110+/// (`-14..=14` without zero), or when `base_q_idx` is outside the q-context
111+/// band whose default CDFs this crate carries.
112+pub fn dc_key_frame_tile(
113+ mi_cols: u32,
114+ mi_rows: u32,
115+ base_q_idx: u8,
116+ dc_level: i32,
117+) -> Result<Vec<u8>> {
118+ check_superblocks(mi_cols, mi_rows)?;
119+ if dc_level == 0 || dc_level.abs() > MAX_LEVEL {
120+ return Err(Error::unsupported(
121+ "AV1 tile",
122+ "a DC-only key frame is written for levels -14..=14 without zero; \
123+ wider levels need the Golomb tail",
124+ ));
125+ }
126+ if !Q_CTX_2.contains(&base_q_idx) {
127+ return Err(Error::unsupported(
128+ "AV1 tile",
129+ "the coefficient CDFs of only one q context are known, so \
130+ base_q_idx must be 61..=120",
131+ ));
132+ }
133+ let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
134+ let level = dc_level.abs();
135+ let negative = dc_level < 0;
136+
137+ let mut enc = SymbolEncoder::new();
138+ for r in 0..sb_rows {
139+ for c in 0..sb_cols {
140+ enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
141+
142+ // Nothing is skipped now, so every neighbour's skip flag is 0 and
143+ // the skip context stays 0 across the frame.
144+ enc.symbol_fixed(0, &cdf::SKIP[0]);
145+ enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
146+ enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
147+
148+ // coeffs() for the luma plane (spec 5.11.39). The block size is the
149+ // transform size, so the all-zero flag's context is 0; a 64x64
150+ // transform codes only its top-left 32x32, which is the 1024-
151+ // position end-of-block alphabet; an end-of-block of one is token 0
152+ // with no extra bits; and a 64x64 transform's type set is DCT-only,
153+ // so no transform type is coded either.
154+ enc.symbol_fixed(0, &cdf::TXB_SKIP_LUMA_64);
155+ enc.symbol_fixed(0, &cdf::EOB_PT_1024_LUMA);
156+ enc.symbol_fixed(
157+ (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,
158+ &cdf::COEFF_BASE_EOB_LUMA_64,
159+ );
160+ // The base-range tail. Every neighbour of the DC is zero, so its
161+ // magnitude context is 0 throughout.
162+ if level > NUM_BASE_LEVELS {
163+ let mut left = level - (NUM_BASE_LEVELS + 1);
164+ let mut sent = 0;
165+ while sent < COEFF_BASE_RANGE {
166+ let k = left.min(BR_STEP);
167+ enc.symbol_fixed(k as usize, &cdf::COEFF_BR_LUMA);
168+ if k < BR_STEP {
169+ break;
170+ }
171+ left -= k;
172+ sent += BR_STEP;
173+ }
174+ }
175+ // The signs come after the levels, DC first (spec 5.11.39).
176+ enc.symbol_fixed(
177+ usize::from(negative),
178+ &cdf::DC_SIGN_LUMA[dc_sign_ctx(r, c, negative)],
179+ );
180+
181+ // Both chroma transform blocks are all-zero. Their planes carry no
182+ // coded coefficient anywhere in the frame, so the neighbour halves
183+ // of their context stay 0 and only the offset for a transform block
184+ // that covers its whole plane block is left: context 7.
185+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32);
186+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32);
187+ }
188+ }
189+ Ok(enc.finish())
190+}
191+
192+/// `Dc_Sign_Contexts` (spec 8.3.2) for a frame every block of which carries a
193+/// DC of the same sign: each of the sixteen 4x4 units above and left of the
194+/// block votes its neighbour's sign, so the count is 0, +-16 or +-32 and the
195+/// table's three-way split reduces to "no coded neighbour, or which way they
196+/// lean". The left column is cleared at the start of every superblock row.
197+fn dc_sign_ctx(sb_row: u32, sb_col: u32, negative: bool) -> usize {
198+ let neighbours = i32::from(sb_row > 0) + i32::from(sb_col > 0);
199+ if neighbours == 0 {
200+ return 0;
201+ }
202+ if negative { 1 } else { 2 }
203+}
204+
77 #[cfg(test)]205 #[cfg(test)]
78 mod tests {206 mod tests {
79 use super::*;207 use super::*;
@@ -215,6 +343,120 @@ mod tests {
215 }343 }
216 }344 }
217 345
346+ /// The one q-context whose CDFs this crate carries; the decoded table
347+ /// below is pinned at this quantiser and nowhere else.
348+ const Q_IDX: u8 = 100;
349+
350+ /// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
351+ fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
352+ let seq = sequence_64();
353+ let mut header = flat_key_frame();
354+ header.quantization.base_q_idx = Q_IDX;
355+ let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
356+ let mut stream = temporal_delimiter();
357+ stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
358+ stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
359+ ffmpeg_decode(&stream, 64, 64)
360+ }
361+
362+ /// What a reference decoder makes of each DC level at `base_q_idx` 100:
363+ /// the level times the DC quantiser, inverse-transformed over a whole
364+ /// 64x64 block — which spreads one coefficient over 4096 samples, so a
365+ /// level moves the picture by a sample or two, not by tens. These numbers
366+ /// are pinned from the decoder rather than derived: this crate has no
367+ /// inverse transform of its own yet to derive them with. What the test
368+ /// asserts around them — flat planes, untouched chroma, monotone in the
369+ /// level, and the sign going the right way — is derived, and it is what a
370+ /// desync in the coefficient syntax breaks first.
371+ const DECODED_AT_Q100: [(i32, u8); 28] = [
372+ (1, 128),
373+ (2, 128),
374+ (3, 129),
375+ (4, 129),
376+ (5, 129),
377+ (6, 129),
378+ (7, 129),
379+ (8, 129),
380+ (9, 130),
381+ (10, 130),
382+ (11, 130),
383+ (12, 130),
384+ (13, 130),
385+ (14, 131),
386+ (-1, 128),
387+ (-2, 128),
388+ (-3, 128),
389+ (-4, 127),
390+ (-5, 127),
391+ (-6, 127),
392+ (-7, 127),
393+ (-8, 127),
394+ (-9, 126),
395+ (-10, 126),
396+ (-11, 126),
397+ (-12, 126),
398+ (-13, 126),
399+ (-14, 126),
400+ ];
401+
402+ #[test]
403+ fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
404+ if !have_ffmpeg() {
405+ eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
406+ return;
407+ }
408+ let mut seen = Vec::new();
409+ for (level, want) in DECODED_AT_Q100 {
410+ let planes = decode_dc_frame(level);
411+ let (luma, chroma) = planes.split_at(64 * 64);
412+ for (i, &sample) in luma.iter().enumerate() {
413+ assert_eq!(sample, want, "luma sample {i} at dc level {level}");
414+ }
415+ // The chroma transform blocks are all-zero, so both planes stay at
416+ // the prediction. A desync in the luma coefficient syntax lands
417+ // here first: the chroma flags are the next symbols after it.
418+ for (i, &sample) in chroma.iter().enumerate() {
419+ assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
420+ }
421+ seen.push((level, want));
422+ }
423+ // The picture moves off mid-grey the way the level says: up for a
424+ // positive level, down for a negative one, and never back towards it
425+ // as the level grows.
426+ for w in seen.windows(2) {
427+ let ((prev_level, prev), (level, value)) = (w[0], w[1]);
428+ if prev_level.signum() != level.signum() {
429+ continue;
430+ }
431+ if level > 0 {
432+ assert!(
433+ value >= prev,
434+ "level {level} decoded below level {prev_level}"
435+ );
436+ assert!(value >= 128, "a positive level darkened the picture");
437+ } else {
438+ assert!(
439+ value <= prev,
440+ "level {level} decoded above level {prev_level}"
441+ );
442+ assert!(value <= 128, "a negative level brightened the picture");
443+ }
444+ }
445+ assert!(
446+ DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
447+ && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
448+ "the pinned table has to move the picture both ways"
449+ );
450+ }
451+
452+ #[test]
453+ fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
454+ assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
455+ assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
456+ assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
457+ assert!(dc_key_frame_tile(16, 16, 40, 3).is_err());
458+ }
459+
218 #[test]460 #[test]
219 fn partial_superblocks_are_refused() {461 fn partial_superblocks_are_refused() {
220 assert!(flat_key_frame_tile(16, 20).is_err());462 assert!(flat_key_frame_tile(16, 20).is_err());