forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-split': 32x32 blocks in the AV1 tile writer

Browse files at this commit

7bce6fb0a6fe4e8ba9675567b2b0acb920f6e9d5Ahmet Kaan GümüşParent: 7ac6fa6a25e4a3
crates/ec-av1/src/cdf.rsmodified+40 -0
@@ -233,3 +233,43 @@ pub const DC_SIGN_LUMA: [[u16; 3]; 3] = [[16000, 32768, 0], [13056, 32768, 0], [
233 /// coefficient whose neighbours are all zero, in a transform of 32x32 or233 /// coefficient whose neighbours are all zero, in a transform of 32x32 or
234 /// larger (the table is shared from 32x32 up).234 /// larger (the table is shared from 32x32 up).
235 pub const COEFF_BR_LUMA: [u16; 5] = [9040, 14786, 18360, 32768, 0];235 pub const COEFF_BR_LUMA: [u16; 5] = [9040, 14786, 18360, 32768, 0];
236+
237+/// `Default_Partition_W32_Cdf` (spec 9.4): the ten partition types of a
238+/// 32x32 block, indexed by the context the blocks above and left give.
239+pub const PARTITION_W32: [[u16; 11]; 4] = [
240+ [
241+ 18462, 20920, 23124, 27647, 28227, 29049, 29519, 30178, 31544, 32768, 0,
242+ ],
243+ [
244+ 7689, 9060, 12056, 24992, 25660, 26182, 26951, 28041, 29052, 32768, 0,
245+ ],
246+ [
247+ 6015, 9009, 10062, 24544, 25409, 26545, 27071, 27526, 32047, 32768, 0,
248+ ],
249+ [
250+ 1394, 2208, 2796, 28614, 29061, 29466, 29840, 30185, 31899, 32768, 0,
251+ ],
252+];
253+
254+/// `Default_Uv_Mode_Cfl_Allowed_Cdf[0]` (spec 9.4): the fourteen chroma intra
255+/// modes — the thirteen the CFL-free table has, plus chroma from luma — for a
256+/// DC-predicted luma block. A block of 32x32 or smaller is offered CFL, so it
257+/// reads this table where a 64x64 block reads [`UV_MODE_NO_CFL`].
258+pub const UV_MODE_CFL_DC: [u16; 15] = [
259+ 10407, 11208, 12900, 13181, 13823, 14175, 14899, 15656, 15986, 20086, 20995, 22455, 24212,
260+ 32768, 0,
261+];
262+
263+/// `Default_Txb_Skip_Cdf[2][3][0]` (spec 9.4): the all-zero flag of a 32x32
264+/// luma transform block that covers its whole plane block, which is context 0.
265+pub const TXB_SKIP_LUMA_32: [u16; 3] = [30669, 32768, 0];
266+
267+/// `Default_Txb_Skip_Cdf[2][2][7]` (spec 9.4): the all-zero flag of a 16x16
268+/// chroma transform block that covers its whole plane block with no coded
269+/// neighbour, which is context 7.
270+pub const TXB_SKIP_CHROMA_16: [u16; 3] = [3648, 32768, 0];
271+
272+/// `Default_Coeff_Base_Eob_Cdf[2][3][0][0]` (spec 9.4): the level of the last
273+/// coefficient of a 32x32 luma transform block, less one, when that
274+/// coefficient is the DC.
275+pub const COEFF_BASE_EOB_LUMA_32: [u16; 4] = [2809, 19301, 32768, 0];
crates/ec-av1/src/tile.rsmodified+252 -57
@@ -16,6 +16,8 @@ use crate::msac::SymbolEncoder;
16 16
17 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.17 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
18 const PARTITION_NONE: usize = 0;18 const PARTITION_NONE: usize = 0;
19+/// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
20+const PARTITION_SPLIT: usize = 3;
19 /// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.21 /// `DC_PRED` (spec 6.10.2), as both the luma and the chroma mode.
20 const DC_PRED: usize = 0;22 const DC_PRED: usize = 0;
21 /// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.23 /// Side of a superblock in 4x4 mode-info units when 128x128 superblocks are off.
@@ -141,26 +143,7 @@ pub fn dc_key_frame_tile_levels(
141 ) -> Result<Vec<u8>> {143 ) -> Result<Vec<u8>> {
142 check_superblocks(mi_cols, mi_rows)?;144 check_superblocks(mi_cols, mi_rows)?;
143 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);145 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
144- if levels.len() != (sb_cols * sb_rows) as usize {146+ check_levels(levels, (sb_cols * sb_rows) as usize, base_q_idx)?;
145- return Err(Error::unsupported(
146- "AV1 tile",
147- "a DC-only key frame needs one level per 64x64 superblock",
148- ));
149- }
150- if levels.iter().any(|&l| l == 0 || l.abs() > MAX_LEVEL) {
151- return Err(Error::unsupported(
152- "AV1 tile",
153- "a DC-only key frame is written for levels -14..=14 without zero; \
154- wider levels need the Golomb tail",
155- ));
156- }
157- if !Q_CTX_2.contains(&base_q_idx) {
158- return Err(Error::unsupported(
159- "AV1 tile",
160- "the coefficient CDFs of only one q context are known, so \
161- base_q_idx must be 61..=120",
162- ));
163- }
164 147
165 // The sign of the DC each coded block left behind, for the two neighbours148 // The sign of the DC each coded block left behind, for the two neighbours
166 // the sign context is read from: one row of them above, and the block to149 // the sign context is read from: one row of them above, and the block to
@@ -172,7 +155,6 @@ pub fn dc_key_frame_tile_levels(
172 let mut left: Option<bool> = None;155 let mut left: Option<bool> = None;
173 for c in 0..sb_cols {156 for c in 0..sb_cols {
174 let dc_level = levels[(r * sb_cols + c) as usize];157 let dc_level = levels[(r * sb_cols + c) as usize];
175- let level = dc_level.abs();
176 let negative = dc_level < 0;158 let negative = dc_level < 0;
177 159
178 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);160 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]);
@@ -183,20 +165,141 @@ pub fn dc_key_frame_tile_levels(
183 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);165 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
184 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);166 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_NO_CFL[DC_PRED]);
185 167
186- // coeffs() for the luma plane (spec 5.11.39). The block size is the168+ write_dc_coeffs(
187- // transform size, so the all-zero flag's context is 0; a 64x64169+ &mut enc,
188- // transform codes only its top-left 32x32, which is the 1024-170+ dc_level,
189- // position end-of-block alphabet; an end-of-block of one is token 0171+ dc_sign_ctx(above[c as usize], left),
190- // with no extra bits; and a 64x64 transform's type set is DCT-only,172+ &cdf::TXB_SKIP_LUMA_64,
191- // so no transform type is coded either.
192- enc.symbol_fixed(0, &cdf::TXB_SKIP_LUMA_64);
193- enc.symbol_fixed(0, &cdf::EOB_PT_1024_LUMA);
194- enc.symbol_fixed(
195- (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,
196 &cdf::COEFF_BASE_EOB_LUMA_64,173 &cdf::COEFF_BASE_EOB_LUMA_64,
197 );174 );
198- // The base-range tail. Every neighbour of the DC is zero, so its175+
199- // magnitude context is 0 throughout.176+ // Both chroma transform blocks are all-zero. Their planes carry no
177+ // coded coefficient anywhere in the frame, so the neighbour halves
178+ // of their context stay 0 and only the offset for a transform block
179+ // that covers its whole plane block is left: context 7.
180+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32);
181+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32);
182+
183+ above[c as usize] = Some(negative);
184+ left = Some(negative);
185+ }
186+ }
187+ Ok(enc.finish())
188+}
189+
190+/// Writes the payload of a one-tile key frame in which every superblock is
191+/// split into four 32x32 DC-predicted blocks, each carrying one luma DC
192+/// coefficient and no chroma residual.
193+///
194+/// `levels` gives one level per 32x32 block in raster order across the frame,
195+/// so the grid is twice as wide and twice as tall as the superblock grid. The
196+/// blocks are coded in the z-order a superblock's split walks, but every
197+/// block's neighbours above and to its left are coded before it either way, so
198+/// the picture reads in raster order.
199+///
200+/// # Errors
201+/// As [`dc_key_frame_tile_levels`], with `levels` sized for the 32x32 grid.
202+pub fn split_dc_key_frame_tile(
203+ mi_cols: u32,
204+ mi_rows: u32,
205+ base_q_idx: u8,
206+ levels: &[i32],
207+) -> Result<Vec<u8>> {
208+ check_superblocks(mi_cols, mi_rows)?;
209+ let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
210+ let (cols, rows) = (sb_cols * 2, sb_rows * 2);
211+ check_levels(levels, (cols * rows) as usize, base_q_idx)?;
212+
213+ let mut above: Vec<Option<bool>> = vec![None; cols as usize];
214+ let mut left: Vec<Option<bool>> = vec![None; rows as usize];
215+
216+ let mut enc = SymbolEncoder::new();
217+ for sb_r in 0..sb_rows {
218+ // A decoder clears its left context at the start of every superblock
219+ // row, and so does the partition context the 64x64 symbol reads.
220+ left.iter_mut().for_each(|l| *l = None);
221+ for sb_c in 0..sb_cols {
222+ // The partition context of a 64x64 block reads the bit its
223+ // neighbours' block size sets at this depth: a 32x32 neighbour sets
224+ // it, and an uncoded one leaves it clear, so the context is just
225+ // which neighbours exist. The 32x32 blocks below read a bit their
226+ // own size leaves clear, so their context is 0 throughout.
227+ let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
228+ enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
229+
230+ for quadrant in 0..4 {
231+ let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
232+ let dc_level = levels[(r * cols + c) as usize];
233+ let negative = dc_level < 0;
234+
235+ enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
236+ enc.symbol_fixed(0, &cdf::SKIP[0]);
237+ enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
238+ // Chroma from luma is offered up to 32x32, so the block reads
239+ // the wider table even though it does not take the mode.
240+ enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL_DC);
241+
242+ write_dc_coeffs(
243+ &mut enc,
244+ dc_level,
245+ dc_sign_ctx(above[c as usize], left[r as usize]),
246+ &cdf::TXB_SKIP_LUMA_32,
247+ &cdf::COEFF_BASE_EOB_LUMA_32,
248+ );
249+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);
250+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);
251+
252+ above[c as usize] = Some(negative);
253+ left[r as usize] = Some(negative);
254+ }
255+ }
256+ }
257+ Ok(enc.finish())
258+}
259+
260+/// Shared by both DC writers: one level per block, none of them zero, and a
261+/// q index the coefficient CDFs are known for.
262+fn check_levels(levels: &[i32], blocks: usize, base_q_idx: u8) -> Result<()> {
263+ if levels.len() != blocks {
264+ return Err(Error::unsupported(
265+ "AV1 tile",
266+ "a DC-only key frame needs one level per coded block",
267+ ));
268+ }
269+ if levels.iter().any(|&l| l == 0 || l.abs() > MAX_LEVEL) {
270+ return Err(Error::unsupported(
271+ "AV1 tile",
272+ "a DC-only key frame is written for levels -14..=14 without zero; \
273+ wider levels need the Golomb tail",
274+ ));
275+ }
276+ if !Q_CTX_2.contains(&base_q_idx) {
277+ return Err(Error::unsupported(
278+ "AV1 tile",
279+ "the coefficient CDFs of only one q context are known, so \
280+ base_q_idx must be 61..=120",
281+ ));
282+ }
283+ Ok(())
284+}
285+
286+/// coeffs() for a luma transform block whose only coefficient is the DC (spec
287+/// 5.11.39). The block size is the transform size, so the all-zero flag's
288+/// context is 0; an end-of-block of one is token 0 of the position alphabet
289+/// with no extra bits; the transform sizes here are all DCT-only, so no
290+/// transform type is coded; and the DC's own neighbours are zero, so its
291+/// magnitude contexts are 0 throughout.
292+fn write_dc_coeffs(
293+ enc: &mut SymbolEncoder,
294+ dc_level: i32,
295+ sign_ctx: usize,
296+ txb_skip: &[u16],
297+ base_eob: &[u16],
298+) {
299+ let level = dc_level.abs();
300+ enc.symbol_fixed(0, txb_skip);
301+ enc.symbol_fixed(0, &cdf::EOB_PT_1024_LUMA);
302+ enc.symbol_fixed((level.min(NUM_BASE_LEVELS + 1) - 1) as usize, base_eob);
200 if level > NUM_BASE_LEVELS {303 if level > NUM_BASE_LEVELS {
201 let mut remaining = level - (NUM_BASE_LEVELS + 1);304 let mut remaining = level - (NUM_BASE_LEVELS + 1);
202 let mut sent = 0;305 let mut sent = 0;
@@ -211,23 +314,7 @@ pub fn dc_key_frame_tile_levels(
211 }314 }
212 }315 }
213 // The signs come after the levels, DC first (spec 5.11.39).316 // The signs come after the levels, DC first (spec 5.11.39).
214- enc.symbol_fixed(317+ enc.symbol_fixed(usize::from(dc_level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);
215- usize::from(negative),
216- &cdf::DC_SIGN_LUMA[dc_sign_ctx(above[c as usize], left)],
217- );
218-
219- // Both chroma transform blocks are all-zero. Their planes carry no
220- // coded coefficient anywhere in the frame, so the neighbour halves
221- // of their context stay 0 and only the offset for a transform block
222- // that covers its whole plane block is left: context 7.
223- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32);
224- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32);
225-
226- above[c as usize] = Some(negative);
227- left = Some(negative);
228- }
229- }
230- Ok(enc.finish())
231 }318 }
232 319
233 /// `Dc_Sign_Contexts` (spec 8.3.2): every 4x4 unit above and left of the block320 /// `Dc_Sign_Contexts` (spec 8.3.2): every 4x4 unit above and left of the block
@@ -500,6 +587,17 @@ mod tests {
500 /// hand back the decoded planes.587 /// hand back the decoded planes.
501 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {588 fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
502 let (w, h) = (64 * sb_cols, 64 * sb_rows);589 let (w, h) = (64 * sb_cols, 64 * sb_rows);
590+ let (seq, header) = frame_of(w, h);
591+ let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
592+ let mut stream = temporal_delimiter();
593+ stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
594+ stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
595+ ffmpeg_decode(&stream, w as usize, h as usize)
596+ }
597+
598+ /// A sequence and key frame header for a `w` by `h` frame of whole
599+ /// superblocks.
600+ fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
503 let mut seq = sequence_64();601 let mut seq = sequence_64();
504 seq.max_frame_width = w;602 seq.max_frame_width = w;
505 seq.max_frame_height = h;603 seq.max_frame_height = h;
@@ -509,16 +607,12 @@ mod tests {
509 header.upscaled_width = w;607 header.upscaled_width = w;
510 header.render_width = w;608 header.render_width = w;
511 header.render_height = h;609 header.render_height = h;
512- header.mi_cols = sb_cols * SB_MI;610+ header.mi_cols = w / 4;
513- header.mi_rows = sb_rows * SB_MI;611+ header.mi_rows = h / 4;
514 header.tile_info.mi_col_starts = vec![0, header.mi_cols];612 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
515 header.tile_info.mi_row_starts = vec![0, header.mi_rows];613 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
516 header.quantization.base_q_idx = Q_IDX;614 header.quantization.base_q_idx = Q_IDX;
517- let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();615+ (seq, header)
518- let mut stream = temporal_delimiter();
519- stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
520- stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
521- ffmpeg_decode(&stream, w as usize, h as usize)
522 }616 }
523 617
524 fn decoded_value(level: i32) -> u8 {618 fn decoded_value(level: i32) -> u8 {
@@ -595,8 +689,109 @@ mod tests {
595 }689 }
596 }690 }
597 691
692+ /// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
693+ /// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
694+ /// transform spreads its DC over a quarter of the samples a 64x64 one
695+ /// does, so the same level moves the picture further: level 14 is five
696+ /// sample values here against three there.
697+ const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
698+ (1, 0),
699+ (2, 1),
700+ (3, 1),
701+ (4, 1),
702+ (5, 2),
703+ (6, 2),
704+ (7, 3),
705+ (8, 3),
706+ (9, 3),
707+ (10, 4),
708+ (11, 4),
709+ (12, 4),
710+ (13, 5),
711+ (14, 5),
712+ (-1, 0),
713+ (-2, -1),
714+ (-3, -1),
715+ (-4, -1),
716+ (-5, -2),
717+ (-6, -2),
718+ (-7, -2),
719+ (-8, -3),
720+ (-9, -3),
721+ (-10, -4),
722+ (-11, -4),
723+ (-12, -4),
724+ (-13, -5),
725+ (-14, -5),
726+ ];
727+
728+ fn split_residual(level: i32) -> i32 {
729+ SPLIT_RESIDUAL_AT_Q100
730+ .iter()
731+ .find(|&&(l, _)| l == level)
732+ .map(|&(_, r)| r)
733+ .expect("the level is in the pinned table")
734+ }
735+
736+ /// Splitting a superblock puts three more syntax elements in front of every
737+ /// block — the split partition itself, the 32x32 partition below it and a
738+ /// chroma mode from the wider table CFL-capable blocks read — and moves the
739+ /// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
740+ /// arithmetic decoder, and the check is that all sixteen blocks still land
741+ /// on the grey their own level and their neighbours ask for.
742+ #[test]
743+ fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
744+ if !have_ffmpeg() {
745+ eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
746+ return;
747+ }
748+ // Four by four 32x32 blocks over two by two superblocks, so the walk
749+ // crosses superblock boundaries in both directions, and signs that
750+ // alternate so the DC sign context lands on all three of its values.
751+ let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
752+ let planes = decode_split_grid(&levels, 2, 2);
753+ let (luma, chroma) = planes.split_at(128 * 128);
754+
755+ let mut recon = [0i32; 16];
756+ for (block, level) in levels.iter().enumerate() {
757+ let (br, bc) = (block / 4, block % 4);
758+ let above = (br > 0).then(|| recon[block - 4] as u8);
759+ let left = (bc > 0).then(|| recon[block - 1] as u8);
760+ let want =
761+ (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
762+ recon[block] = want;
763+ for y in 0..32 {
764+ for x in 0..32 {
765+ let i = (br * 32 + y) * 128 + bc * 32 + x;
766+ assert_eq!(
767+ i32::from(luma[i]),
768+ want,
769+ "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
770+ column {bc}"
771+ );
772+ }
773+ }
774+ }
775+ for (i, &sample) in chroma.iter().enumerate() {
776+ assert_eq!(sample, 128, "chroma sample {i}");
777+ }
778+ }
779+
780+ /// Encode a grid of 32x32 blocks, each carrying its own DC level.
781+ fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
782+ let (w, h) = (64 * sb_cols, 64 * sb_rows);
783+ let (seq, header) = frame_of(w, h);
784+ let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
785+ let mut stream = temporal_delimiter();
786+ stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
787+ stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
788+ ffmpeg_decode(&stream, w as usize, h as usize)
789+ }
790+
598 #[test]791 #[test]
599 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {792 fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
793+ assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
794+ assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
600 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());795 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
601 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());796 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
602 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());797 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());