forge
Explore
Log in

Don't you dare go Hollow

The six directional intra modes, and a mode-rate term

Browse files at this commit

223aa7cf7fafaca6c86c6ca1ffc62a37dfb2c662Ahmet Kaan GümüşParent: 35f59c2
  • feat
    • the six directional intra modes, and a mode-rate term
Show full message
feat(av1): the six directional intra modes, and a mode-rate term

Adds D45, D67, D113, D135, D157 and D203 per spec 7.11.2.4, with the
edge construction of 7.11.2.2 and the availability the decoder derives
from clear_block_decoded_flags: for the 32x32 quadrants of a superblock
the above row reaches past the superblock's right edge (sbWidth4 is
measured to the tile's end column) for all but the last quadrant, and
the left column continues below only for the first.

The mode search now also pays for naming a mode, scored through the tile
writer's own CDFs -- the KF_Y_MODE symbol under the neighbours' context,
the ANGLE_DELTA zero symbol, and the chroma mode symbol the luma mode
indexes. Without it a directional mode looked free and cost 1.1% rate on
a picture that did not want one. With it, and with LAMBDA_SCALE re-swept
to 0.1, the same picture costs 0.41% and the clips that do want a
direction gain up to 0.35%.

ffmpeg decodes all thirteen modes bit-exactly at 128x96 and 160x96.
crates/ec-av1/src/encode.rsmodified+336 -67
@@ -21,12 +21,13 @@ use ec_av1_syntax::{
2121 };
2222 use ec_core::{Error, Result};
2323
24+use crate::cdf;
2425 use crate::frame::frame_obu;
25-use crate::intra::{DC_PRED, NON_DIRECTIONAL};
26+use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};
2627 use crate::obu::temporal_delimiter;
2728 use crate::quant::ac_q;
2829 use crate::sequence::sequence_header_obu;
29-use crate::tile::{BlockCoeffs, Coeff, Superblock, sb_coeff_key_frame_tile};
30+use crate::tile::{BlockCoeffs, Coeff, INTRA_MODE_CTX, Superblock, sb_coeff_key_frame_tile};
3031 use crate::transform::{dequant_and_inverse, forward_and_quantize};
3132
3233 /// The side of the luma blocks this encoder codes, in samples.
@@ -35,13 +36,14 @@ const BLOCK: usize = 32;
3536 /// How heavily the mode search weighs rate against squared error, in units of
3637 /// the quantizer's reconstruction step squared per bit.
3738 ///
38-/// Swept over three clips and two synthetic pictures at 0, 0.05, 0.1, 0.2, 0.4
39-/// and 0.8 (`probe_lambda`, and the table in the lane report): 0 leaves half the
40-/// saving on the table on a picture that runs one way (-35.6% against -59.5% on
41-/// stripes), and everything from 0.1 up gives a little back on screen capture
42-/// (-10.7% against -11.5%) and on a hand-held clip. 0.05 is the best point on
43-/// every clip measured.
44-const LAMBDA_SCALE: f64 = 0.05;
39+/// Swept twice over three of his clips and three synthetic pictures
40+/// (`probe_lambda` and `probe_directional`, and the tables in the two lane
41+/// reports). The first sweep, before the mode symbol was costed, put the best
42+/// point at 0.05; costing it moved the point to 0.1, where the directional
43+/// modes stop costing rate on the pictures that do not want them (+0.05% on
44+/// screen capture against +0.19% at 0.05) without giving up any of what they
45+/// save on the pictures that do (-53.0% on a diagonal).
46+const LAMBDA_SCALE: f64 = 0.1;
4547
4648 /// One 8-bit planar 4:2:0 picture.
4749 #[derive(Clone, Debug, PartialEq, Eq)]
@@ -235,17 +237,26 @@ impl Plane<'_> {
235237 /// The reconstructed samples a block at `(x, y)` predicts from: the row
236238 /// above it, the column to its left and the sample between them, each
237239 /// missing where the block sits against an edge of the frame.
240+ ///
241+ /// `reach` says whether the samples above the block's right and below its
242+ /// left are decoded, which is what a directional mode reads into; where
243+ /// they are not, or where the frame ends first, the edge is shorter and
244+ /// the predictor repeats its last sample, exactly as the decoder's clamp
245+ /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
238246 fn edges(
239247 &self,
240248 x: usize,
241249 y: usize,
242250 side: usize,
251+ reach: Reach,
243252 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
253+ let across = (x + if reach.above_right { 2 * side } else { side }).min(self.width);
254+ let down = (y + if reach.below_left { 2 * side } else { side }).min(self.height);
244255 let above =
245- (y > 0).then(|| self.reconstruction[(y - 1) * self.width + x..][..side].to_vec());
256+ (y > 0).then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
246257 let left = (x > 0).then(|| {
247- (0..side)
248- .map(|i| self.reconstruction[(y + i) * self.width + x - 1])
258+ (y..down)
259+ .map(|row| self.reconstruction[row * self.width + x - 1])
249260 .collect::<Vec<_>>()
250261 });
251262 let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
@@ -255,16 +266,9 @@ impl Plane<'_> {
255266 /// Codes one block under one mode without committing it: hands back the
256267 /// levels, the block the decoder would reconstruct, the squared error
257268 /// against the source and an estimate of what the levels cost in bits.
258- fn trial(
259- &self,
260- x: usize,
261- y: usize,
262- side: usize,
263- mode: u8,
264- base_q_idx: u8,
265- deadzone: f64,
266- ) -> Trial {
267- let (above, left, corner) = self.edges(x, y, side);
269+ fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial {
270+ let At { x, y, side, reach } = at;
271+ let (above, left, corner) = self.edges(x, y, side, reach);
268272 let mut prediction = vec![0u8; side * side];
269273 crate::intra::predict(
270274 mode,
@@ -323,33 +327,19 @@ impl Plane<'_> {
323327 }
324328
325329 /// Codes one block under a fixed mode, committing it.
326- fn code_block(
327- &mut self,
328- x: usize,
329- y: usize,
330- side: usize,
331- mode: u8,
332- base_q_idx: u8,
333- deadzone: f64,
334- ) -> Vec<Coeff> {
335- let trial = self.trial(x, y, side, mode, base_q_idx, deadzone);
336- self.commit(x, y, side, &trial);
337- coeffs(&trial.levels, side)
330+ fn code_block(&mut self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Vec<Coeff> {
331+ let trial = self.trial(at, mode, base_q_idx, deadzone);
332+ self.commit(at.x, at.y, at.side, &trial);
333+ coeffs(&trial.levels, at.side)
338334 }
339335
340336 /// Codes one block under every mode the search offers and commits the one
341337 /// whose squared error and estimated rate come out cheapest.
342- fn search_block(
343- &mut self,
344- x: usize,
345- y: usize,
346- side: usize,
347- search: &Search,
348- ) -> (Vec<Coeff>, u8) {
338+ fn search_block(&mut self, at: At, search: &Search, mode_bits: &[f64; 13]) -> (Vec<Coeff>, u8) {
349339 let mut best: Option<(f64, u8, Trial)> = None;
350340 for &mode in search.modes {
351- let trial = self.trial(x, y, side, mode, search.base_q_idx, search.deadzone);
352- let cost = trial.sse + search.lambda * trial.bits;
341+ let trial = self.trial(at, mode, search.base_q_idx, search.deadzone);
342+ let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
353343 if best
354344 .as_ref()
355345 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
@@ -358,11 +348,89 @@ impl Plane<'_> {
358348 }
359349 }
360350 let (_, mode, trial) = best.expect("the search offers at least one mode");
361- self.commit(x, y, side, &trial);
362- (coeffs(&trial.levels, side), mode)
351+ self.commit(at.x, at.y, at.side, &trial);
352+ (coeffs(&trial.levels, at.side), mode)
353+ }
354+}
355+
356+/// Where one block sits in its plane, and how far past its own edges its
357+/// prediction may read.
358+#[derive(Clone, Copy)]
359+struct At {
360+ x: usize,
361+ y: usize,
362+ side: usize,
363+ reach: Reach,
364+}
365+
366+/// Which of the samples past a block's own edges the decoder has decoded by
367+/// the time it predicts the block, and so which a directional mode may read.
368+///
369+/// The decoder derives these from its `BlockDecoded` flags, which are cleared
370+/// per superblock (`clear_block_decoded_flags`, spec 7.4): the row above the
371+/// superblock counts as decoded out to the end of the *tile*, while the column
372+/// to its left counts only as far as the superblock's own height, and every
373+/// position inside the superblock starts undecoded. For the four 32x32
374+/// quadrants of a 64x64 superblock that comes to: the samples above-right are
375+/// decoded for all but the last quadrant -- the one whose above-right lies
376+/// inside the superblock to the right, which raster order has not reached --
377+/// and the samples below-left only for the first, the only one whose left
378+/// column continues into the superblock beside it.
379+#[derive(Clone, Copy)]
380+struct Reach {
381+ above_right: bool,
382+ below_left: bool,
383+}
384+
385+impl Reach {
386+ /// The reach of the quadrant coded `quadrant`-th in a superblock, counting
387+ /// in raster order among the four.
388+ fn quadrant(quadrant: usize) -> Self {
389+ Self {
390+ above_right: quadrant != 3,
391+ below_left: quadrant == 0,
392+ }
393+ }
394+
395+ /// Neither, which is all a mode that reads no further than its own edges
396+ /// needs.
397+ fn none() -> Self {
398+ Self {
399+ above_right: false,
400+ below_left: false,
401+ }
363402 }
364403 }
365404
405+/// What one symbol costs against a CDF, in bits.
406+fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
407+ let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
408+ let probability = f64::from(cdf[symbol] - low) / 32768.0;
409+ -probability.log2()
410+}
411+
412+/// What the tile writer spends to say a block is coded in each of the thirteen
413+/// modes, given the modes of the blocks above it and to its left: the luma mode
414+/// symbol against the CDF those two neighbours pick, the angle delta a
415+/// directional mode carries, and the chroma mode symbol, whose CDF the luma
416+/// mode itself indexes.
417+///
418+/// Without this the search is blind to what a mode costs to name, which is not
419+/// a rounding error: a directional mode on a picture that does not run that way
420+/// is a rate loss the squared error never sees.
421+fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
422+ let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
423+ [INTRA_MODE_CTX[usize::from(left_mode)]];
424+ std::array::from_fn(|mode| {
425+ let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
426+ symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
427+ } else {
428+ 0.0
429+ };
430+ symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
431+ })
432+}
433+
366434 /// What the luma mode search picks between, and under what terms.
367435 struct Search<'a> {
368436 base_q_idx: u8,
@@ -405,15 +473,16 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
405473 /// when its planes are not 4:2:0 of that size, or when the tile writer refuses
406474 /// the quantizer index.
407475 pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
408- encode_key_frame_with_modes(picture, base_q_idx, deadzone, &NON_DIRECTIONAL)
476+ encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES)
409477 }
410478
411479 /// Encodes one picture as a key frame, choosing each block's luma mode from
412480 /// `modes` alone.
413481 ///
414482 /// This is what an ablation measures against: `&[DC_PRED]` is the encoder
415-/// before the mode search, and [`NON_DIRECTIONAL`] is what
416-/// [`encode_key_frame`] uses.
483+/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
484+/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
485+/// uses.
417486 ///
418487 /// # Errors
419488 /// The same as [`encode_key_frame`], and additionally when `modes` is empty or
@@ -431,7 +500,7 @@ pub fn encode_key_frame_with_modes(
431500 "a mode search needs at least one mode to choose from",
432501 ));
433502 }
434- if let Some(bad) = modes.iter().find(|m| !NON_DIRECTIONAL.contains(m)) {
503+ if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
435504 return Err(Error::unsupported(
436505 "AV1 encode",
437506 format!("intra mode {bad} is not one the encoder predicts"),
@@ -471,6 +540,12 @@ pub fn encode_key_frame_with_modes(
471540 };
472541
473542 let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK);
543+ // The luma mode of the block above and of the block to the left, which is
544+ // what picks the CDF the next block's mode is coded against -- the same
545+ // bookkeeping the tile writer keeps, so that the search is costing the
546+ // symbol the writer will actually write.
547+ let mut above_mode = vec![DC_PRED; cols];
548+ let mut left_mode = vec![DC_PRED; rows];
474549 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
475550 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
476551 let mut modes = Vec::with_capacity(cols * rows);
@@ -486,13 +561,44 @@ pub fn encode_key_frame_with_modes(
486561 continue;
487562 }
488563 let (x, y) = (col * BLOCK, row * BLOCK);
489- let (luma_coeffs, mode) = luma.search_block(x, y, BLOCK, &search);
564+ let (luma_coeffs, mode) = luma.search_block(
565+ At {
566+ x,
567+ y,
568+ side: BLOCK,
569+ reach: Reach::quadrant(quadrant),
570+ },
571+ &search,
572+ &mode_bits(above_mode[col], left_mode[row]),
573+ );
574+ above_mode[col] = mode;
575+ left_mode[row] = mode;
490576 modes.push(mode);
491577 blocks.push(BlockCoeffs {
492578 // Chroma is predicted DC because that is the mode the tile
493579 // writer codes for it.
494- u: chroma[0].code_block(x / 2, y / 2, BLOCK / 2, DC_PRED, base_q_idx, deadzone),
495- v: chroma[1].code_block(x / 2, y / 2, BLOCK / 2, DC_PRED, base_q_idx, deadzone),
580+ u: chroma[0].code_block(
581+ At {
582+ x: x / 2,
583+ y: y / 2,
584+ side: BLOCK / 2,
585+ reach: Reach::none(),
586+ },
587+ DC_PRED,
588+ base_q_idx,
589+ deadzone,
590+ ),
591+ v: chroma[1].code_block(
592+ At {
593+ x: x / 2,
594+ y: y / 2,
595+ side: BLOCK / 2,
596+ reach: Reach::none(),
597+ },
598+ DC_PRED,
599+ base_q_idx,
600+ deadzone,
601+ ),
496602 luma: luma_coeffs,
497603 mode,
498604 });
@@ -523,7 +629,7 @@ pub fn encode_key_frame_with_modes(
523629 #[cfg(test)]
524630 mod tests {
525631 use super::*;
526- use crate::intra::{H_PRED, V_PRED};
632+ use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
527633 use std::io::Write;
528634 use std::process::{Command, Stdio};
529635
@@ -718,6 +824,21 @@ mod tests {
718824 picture
719825 }
720826
827+ /// Where two planes first disagree, and by how much: a mismatch reported as
828+ /// a position says which block and which sample of it went wrong, which a
829+ /// pair of thousand-sample arrays does not.
830+ fn first_difference(ours: &[u8], theirs: &[u8], width: usize) -> Option<String> {
831+ let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
832+ let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
833+ Some(format!(
834+ "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
835+ i % width,
836+ i / width,
837+ ours[i],
838+ theirs[i]
839+ ))
840+ }
841+
721842 /// Every mode the encoder offers has to predict what the decoder predicts,
722843 /// not just the ones a particular picture happens to choose: each is forced
723844 /// over a whole picture and the reconstruction gated against ffmpeg.
@@ -727,17 +848,30 @@ mod tests {
727848 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
728849 return;
729850 }
730- let picture = test_card(128, 96);
731- for mode in NON_DIRECTIONAL {
732- let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();
733- let decoded = ffmpeg_decode(&encoded.stream, 128, 96);
734- assert_eq!(decoded.y, encoded.reconstruction.y, "mode {mode}: luma");
735- assert_eq!(decoded.u, encoded.reconstruction.u, "mode {mode}: U");
736- assert_eq!(decoded.v, encoded.reconstruction.v, "mode {mode}: V");
737- assert!(
738- encoded.modes.iter().all(|&m| m == mode),
739- "mode {mode}: the encoder coded something else"
740- );
851+ // 128 wide is a whole number of superblocks and 160 is not: the last
852+ // superblock of a 160-wide row is half a one, whose blocks have no
853+ // above-right samples inside the frame at all.
854+ for (width, height) in [(128, 96), (160, 96)] {
855+ let picture = test_card(width, height);
856+ for mode in KEY_FRAME_MODES {
857+ let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();
858+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
859+ for (plane, ours, theirs, stride) in [
860+ ("luma", &encoded.reconstruction.y, &decoded.y, width),
861+ ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
862+ ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
863+ ] {
864+ assert!(
865+ first_difference(ours, theirs, stride).is_none(),
866+ "{width}x{height} mode {mode}, {plane}: {}",
867+ first_difference(ours, theirs, stride).unwrap()
868+ );
869+ }
870+ assert!(
871+ encoded.modes.iter().all(|&m| m == mode),
872+ "mode {mode}: the encoder coded something else"
873+ );
874+ }
741875 }
742876 }
743877
@@ -749,7 +883,13 @@ mod tests {
749883 fn the_search_picks_the_direction_the_picture_runs() {
750884 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
751885 let picture = stripes(128, 96, vertical);
752- let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
886+ // Only the pair, because on stripes a third mode predicts exactly
887+ // what the right one of the pair does -- PAETH reads the corner and
888+ // the left column, which a striped picture makes equal -- and the
889+ // tie then goes to whichever is cheaper to name, which is not what
890+ // this gate is about.
891+ let encoded =
892+ encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED]).unwrap();
753893 // The first block of the picture has neither neighbour, so it
754894 // cannot tell the modes apart; every other one can.
755895 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
@@ -832,16 +972,145 @@ mod tests {
832972 }
833973 }
834974
975+ /// The pictures a sweep is measured over: two synthetic ones, plus a frame
976+ /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
977+ fn sweep_pictures() -> Vec<(String, Picture)> {
978+ let mut pictures = vec![
979+ ("test card".to_string(), test_card(160, 96)),
980+ ("stripes".to_string(), stripes(160, 96, true)),
981+ ("diagonal".to_string(), diagonal(160, 96, true)),
982+ ];
983+ if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
984+ for entry in clips.split(':').filter(|e| !e.is_empty()) {
985+ let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
986+ let name = path.rsplit('/').next().unwrap_or(path).to_string();
987+ pictures.push((name, clip_frame(path, skip, 640, 352)));
988+ }
989+ }
990+ pictures
991+ }
992+
993+ /// What the six directional modes are worth, per picture, at whatever
994+ /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
995+ /// no further, and how often the search picks one.
996+ #[test]
997+ #[ignore = "a sweep, not a gate"]
998+ fn probe_directional() {
999+ for (name, picture) in sweep_pictures() {
1000+ let dc = ladder(&picture, &[DC_PRED]);
1001+ let flat = ladder(&picture, &NON_DIRECTIONAL);
1002+ let all = ladder(&picture, &KEY_FRAME_MODES);
1003+ let encoded = encode_key_frame(&picture, 90, 0.5).unwrap();
1004+ let directional = encoded
1005+ .modes
1006+ .iter()
1007+ .filter(|&&m| (3..=8).contains(&m))
1008+ .count();
1009+ // A picture whose ladders sit at different fidelities altogether
1010+ // has no BD-rate to report -- see the flat-sample-window class.
1011+ let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
1012+ a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
1013+ };
1014+ let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
1015+ if overlap(a, b) {
1016+ format!("{:+.2}%", bd_rate(a, b) * 100.0)
1017+ } else {
1018+ "no overlap".to_string()
1019+ }
1020+ };
1021+ println!(
1022+ "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
1023+ against(&flat, &all),
1024+ against(&dc, &all),
1025+ encoded.modes.len(),
1026+ );
1027+ }
1028+ }
1029+
1030+ /// A picture whose stripes run along a diagonal, one way or the other.
1031+ /// This is to the directional modes what [`stripes`] is to the vertical and
1032+ /// horizontal pair: a predictor that walked the edge in the wrong direction
1033+ /// would answer the two pictures the same way round.
1034+ fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
1035+ let mut picture = Picture::grey(width, height);
1036+ for y in 0..height {
1037+ for x in 0..width {
1038+ let along = if down_right { x + height - y } else { x + y };
1039+ picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
1040+ }
1041+ }
1042+ picture
1043+ }
1044+
1045+ /// The mode picked by the most blocks of a picture, ignoring the first
1046+ /// block, which has no neighbours to tell the modes apart with.
1047+ fn favourite_mode(picture: &Picture) -> (u8, usize, usize) {
1048+ let encoded = encode_key_frame(picture, 100, 0.5).unwrap();
1049+ let blocks = &encoded.modes[1..];
1050+ let mut counts = [0usize; 13];
1051+ for &mode in blocks {
1052+ counts[usize::from(mode)] += 1;
1053+ }
1054+ let (mode, count) = counts
1055+ .iter()
1056+ .enumerate()
1057+ .max_by_key(|&(_, count)| *count)
1058+ .expect("thirteen modes");
1059+ (mode as u8, *count, blocks.len())
1060+ }
1061+
1062+ /// The search has to follow a diagonal the way it runs: stripes down and to
1063+ /// the right are cheapest predicted at 135 degrees, stripes down and to the
1064+ /// left at 45. A walk that stepped the wrong way along the edge, or read
1065+ /// the above row where it should read the left column, would swap these.
1066+ #[test]
1067+ fn the_search_picks_the_diagonal_the_picture_runs() {
1068+ for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
1069+ let picture = diagonal(160, 96, down_right);
1070+ let (mode, count, blocks) = favourite_mode(&picture);
1071+ assert_eq!(
1072+ mode, want,
1073+ "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
1074+ );
1075+ }
1076+ }
1077+
1078+ /// What the directional modes are for: a picture that runs along a diagonal
1079+ /// costs far less to code with them than the seven that read only their own
1080+ /// edges can manage, and a picture that runs no particular way costs no
1081+ /// more. The second half is the one that bites: a mode set the search
1082+ /// cannot price is a mode set that loses rate on content that does not want
1083+ /// it, which is what costing the mode symbol is for.
1084+ #[test]
1085+ fn the_diagonals_beat_the_modes_that_read_no_further() {
1086+ for (name, picture, want) in [
1087+ ("down-right", diagonal(160, 96, true), -0.20),
1088+ ("down-left", diagonal(160, 96, false), -0.20),
1089+ ("test card", test_card(160, 96), 0.01),
1090+ ] {
1091+ let saved = bd_rate(
1092+ &ladder(&picture, &NON_DIRECTIONAL),
1093+ &ladder(&picture, &KEY_FRAME_MODES),
1094+ );
1095+ assert!(
1096+ saved < want,
1097+ "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
1098+ saved * 100.0,
1099+ -want * 100.0
1100+ );
1101+ }
1102+ }
1103+
8351104 /// A mode the encoder cannot predict must be refused rather than coded as
8361105 /// something else, and a search with nothing to choose from likewise.
8371106 #[test]
8381107 fn a_mode_the_encoder_cannot_predict_is_refused() {
8391108 let picture = test_card(64, 64);
840- let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[3])
1109+ let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13])
8411110 .unwrap_err()
8421111 .to_string();
8431112 assert!(
844- message.contains("intra mode 3"),
1113+ message.contains("intra mode 13"),
8451114 "the refusal must name the mode, got {message}"
8461115 );
8471116 assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err());
crates/ec-av1/src/intra.rsmodified+203 -34
@@ -1,9 +1,12 @@
11 //! Intra prediction, the half of spec 7.11.2 a key frame needs.
22 //!
3-//! The seven modes here are the ones that read no further than the row above
4-//! and the column to the left of the block: the eight directional modes reach
5-//! past a block's own width into samples whose availability the decoder tracks
6-//! in its own bookkeeping, and are not written yet.
3+//! All thirteen key-frame intra modes: the seven that read no further than the
4+//! row above and the column to the left of the block, and the six that steer
5+//! along an angle and reach past the block's own width into the samples above
6+//! its right and below its left. Whether those further samples are decoded is
7+//! not this module's business -- the caller passes the samples it has, and the
8+//! edge is extended by repeating the last one, which is what the decoder does
9+//! with its own `BlockDecoded` bookkeeping (spec 7.11.2.2).
710
811 /// The average of the neighbours (spec 7.11.2.5).
912 pub const DC_PRED: u8 = 0;
@@ -19,8 +22,40 @@ pub const SMOOTH_V_PRED: u8 = 10;
1922 pub const SMOOTH_H_PRED: u8 = 11;
2023 /// Whichever of above, left and the corner is nearest their gradient.
2124 pub const PAETH_PRED: u8 = 12;
25+/// Down-left along 45 degrees.
26+pub const D45_PRED: u8 = 3;
27+/// Down-right along 135 degrees.
28+pub const D135_PRED: u8 = 4;
29+/// Down-right, steeper: 113 degrees.
30+pub const D113_PRED: u8 = 5;
31+/// Down-right, shallower: 157 degrees.
32+pub const D157_PRED: u8 = 6;
33+/// Up-right along 203 degrees.
34+pub const D203_PRED: u8 = 7;
35+/// Down-left, steeper: 67 degrees.
36+pub const D67_PRED: u8 = 8;
2237
23-/// The modes this module predicts, in the order a search should try them.
38+/// Every mode a key frame's luma block can be coded with, in the order a
39+/// search should try them: the cheap ones first, so an early one is likely to
40+/// be the one that survives.
41+pub const KEY_FRAME_MODES: [u8; 13] = [
42+ DC_PRED,
43+ V_PRED,
44+ H_PRED,
45+ SMOOTH_PRED,
46+ SMOOTH_V_PRED,
47+ SMOOTH_H_PRED,
48+ PAETH_PRED,
49+ D45_PRED,
50+ D67_PRED,
51+ D113_PRED,
52+ D135_PRED,
53+ D157_PRED,
54+ D203_PRED,
55+];
56+
57+/// The modes that read no further than the row above and the column to the
58+/// left, in the order a search should try them.
2459 pub const NON_DIRECTIONAL: [u8; 7] = [
2560 DC_PRED,
2661 V_PRED,
@@ -51,26 +86,75 @@ fn round2(value: i32, shift: u32) -> i32 {
5186 (value + (1 << (shift - 1))) >> shift
5287 }
5388
89+/// `Dr_Intra_Derivative` (spec 9.3): how far along the edge one row of the
90+/// block moves, in 64ths of a sample, for the angles a delta can reach.
91+fn dr_intra_derivative(angle: u16) -> i32 {
92+ match angle {
93+ 3 => 1023,
94+ 6 => 547,
95+ 9 => 372,
96+ 14 => 273,
97+ 17 => 215,
98+ 20 => 178,
99+ 23 => 151,
100+ 26 => 132,
101+ 29 => 116,
102+ 32 => 102,
103+ 36 => 90,
104+ 39 => 80,
105+ 42 => 71,
106+ 45 => 64,
107+ 48 => 57,
108+ 51 => 51,
109+ 54 => 45,
110+ 58 => 40,
111+ 61 => 35,
112+ 64 => 31,
113+ 67 => 27,
114+ 70 => 23,
115+ 73 => 19,
116+ 76 => 15,
117+ 81 => 11,
118+ 84 => 7,
119+ 87 => 3,
120+ other => panic!("no derivative is tabulated for {other} degrees"),
121+ }
122+}
123+
124+/// `Mode_To_Angle` (spec 9.3), zero for the modes that have no angle.
125+const MODE_TO_ANGLE: [u16; 13] = [0, 90, 180, 45, 135, 113, 157, 203, 67, 0, 0, 0, 0];
126+
54127 /// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2):
55-/// a side that does not exist is filled from the side that does, and the corner
56-/// falls back the same way.
128+/// a side that does not exist is filled from the side that does, a side that
129+/// runs out is extended by repeating its last sample, and the corner falls back
130+/// the same way.
131+///
132+/// Both arrays hold the corner first, so the spec's index `-1` is index 0 here
133+/// and they run out to the spec's `w + h - 1`.
57134 struct Edges {
58135 above: Vec<i32>,
59136 left: Vec<i32>,
60- corner: i32,
61137 }
62138
63139 impl Edges {
64140 fn build(above: Option<&[u8]>, left: Option<&[u8]>, corner: Option<u8>, side: usize) -> Self {
141+ // A directional mode reads out to w + h - 1 either way.
142+ let want = side * 2;
143+ let extend = |samples: &[u8]| {
144+ let mut row: Vec<i32> = samples.iter().map(|&s| i32::from(s)).collect();
145+ let last = *row.last().expect("an edge that exists has samples");
146+ row.resize(want, last);
147+ row
148+ };
65149 let above_row = match (above, left) {
66- (Some(a), _) => a.iter().map(|&s| i32::from(s)).collect(),
67- (None, Some(l)) => vec![i32::from(l[0]); side],
68- (None, None) => vec![127; side],
150+ (Some(a), _) => extend(a),
151+ (None, Some(l)) => vec![i32::from(l[0]); want],
152+ (None, None) => vec![127; want],
69153 };
70154 let left_col = match (left, above) {
71- (Some(l), _) => l.iter().map(|&s| i32::from(s)).collect(),
72- (None, Some(a)) => vec![i32::from(a[0]); side],
73- (None, None) => vec![129; side],
155+ (Some(l), _) => extend(l),
156+ (None, Some(a)) => vec![i32::from(a[0]); want],
157+ (None, None) => vec![129; want],
74158 };
75159 let corner = match (corner, above, left) {
76160 (Some(c), Some(_), Some(_)) => i32::from(c),
@@ -78,20 +162,38 @@ impl Edges {
78162 (_, None, Some(l)) => i32::from(l[0]),
79163 (_, None, None) => 128,
80164 };
165+ let with_corner = |edge: Vec<i32>| {
166+ let mut v = Vec::with_capacity(want + 1);
167+ v.push(corner);
168+ v.extend(edge);
169+ v
170+ };
81171 Self {
82- above: above_row,
83- left: left_col,
84- corner,
172+ above: with_corner(above_row),
173+ left: with_corner(left_col),
85174 }
86175 }
176+
177+ /// `AboveRow[i]`, where `i` may be the spec's `-1`.
178+ fn above(&self, i: i32) -> i32 {
179+ self.above[usize::try_from(i + 1).expect("an edge is read no further back than the corner")]
180+ }
181+
182+ /// `LeftCol[i]`, where `i` may be the spec's `-1`.
183+ fn left(&self, i: i32) -> i32 {
184+ self.left[usize::try_from(i + 1).expect("an edge is read no further back than the corner")]
185+ }
87186 }
88187
89188 /// Predicts one square block into `dst`, row-major and `side * side` long.
90189 ///
91190 /// `above` is the reconstructed row above the block and `left` its
92-/// reconstructed left column, each `side` samples long, and `corner` the
93-/// sample diagonally above-left; `None` where the block sits against an edge
94-/// of the frame.
191+/// reconstructed left column, each at least `side` samples long, and `corner`
192+/// the sample diagonally above-left; `None` where the block sits against an
193+/// edge of the frame. A directional mode reads out to `2 * side`: pass the
194+/// samples above-right and below-left where the decoder has them decoded, and
195+/// the edge is extended by repetition where it does not, which is what the
196+/// decoder's own clamp to `aboveLimit` and `leftLimit` comes to.
95197 ///
96198 /// # Panics
97199 /// Panics on a mode this module does not predict, or when `dst` is not
@@ -106,32 +208,41 @@ pub fn predict(
106208 ) {
107209 assert_eq!(dst.len(), side * side, "the destination is the block");
108210 let edges = Edges::build(above, left, corner, side);
109- let (a, l) = (&edges.above, &edges.left);
211+ let angle = MODE_TO_ANGLE[usize::from(mode)];
212+ if matches!(
213+ mode,
214+ D45_PRED | D67_PRED | D113_PRED | D135_PRED | D157_PRED | D203_PRED
215+ ) {
216+ directional(angle, &edges, side, dst);
217+ return;
218+ }
110219 let weights = &SM_WEIGHTS[side..side * 2];
111220 for row in 0..side {
112221 for col in 0..side {
222+ let (r, c) = (row as i32, col as i32);
223+ let last = side as i32 - 1;
113224 let value = match mode {
114- DC_PRED => dc(above, left),
115- V_PRED => a[col],
116- H_PRED => l[row],
225+ DC_PRED => dc(above, left, side),
226+ V_PRED => edges.above(c),
227+ H_PRED => edges.left(r),
117228 SMOOTH_PRED => round2(
118- i32::from(weights[row]) * a[col]
119- + (256 - i32::from(weights[row])) * l[side - 1]
120- + i32::from(weights[col]) * l[row]
121- + (256 - i32::from(weights[col])) * a[side - 1],
229+ i32::from(weights[row]) * edges.above(c)
230+ + (256 - i32::from(weights[row])) * edges.left(last)
231+ + i32::from(weights[col]) * edges.left(r)
232+ + (256 - i32::from(weights[col])) * edges.above(last),
122233 9,
123234 ),
124235 SMOOTH_V_PRED => round2(
125- i32::from(weights[row]) * a[col]
126- + (256 - i32::from(weights[row])) * l[side - 1],
236+ i32::from(weights[row]) * edges.above(c)
237+ + (256 - i32::from(weights[row])) * edges.left(last),
127238 8,
128239 ),
129240 SMOOTH_H_PRED => round2(
130- i32::from(weights[col]) * l[row]
131- + (256 - i32::from(weights[col])) * a[side - 1],
241+ i32::from(weights[col]) * edges.left(r)
242+ + (256 - i32::from(weights[col])) * edges.above(last),
132243 8,
133244 ),
134- PAETH_PRED => paeth(a[col], l[row], edges.corner),
245+ PAETH_PRED => paeth(edges.above(c), edges.left(r), edges.above(-1)),
135246 other => panic!("intra mode {other} is not one this module predicts"),
136247 };
137248 dst[row * side + col] = value.clamp(0, 255) as u8;
@@ -139,8 +250,66 @@ pub fn predict(
139250 }
140251 }
141252
253+/// Directional intra prediction (spec 7.11.2.4), with the intra edge filter off
254+/// -- which is what our sequence header says -- so nothing here upsamples.
255+fn directional(angle: u16, edges: &Edges, side: usize, dst: &mut [u8]) {
256+ let n = side as i32;
257+ // The furthest sample the walk can reach, past which the edge is flat.
258+ let max_base = n + n - 1;
259+ let blend = |edge: &dyn Fn(i32) -> i32, base: i32, shift: i32| {
260+ round2(edge(base) * (32 - shift) + edge(base + 1) * shift, 5)
261+ };
262+ let above = |i: i32| edges.above(i);
263+ let left = |i: i32| edges.left(i);
264+ for row in 0..n {
265+ for col in 0..n {
266+ let value = if angle < 90 {
267+ let dx = dr_intra_derivative(angle);
268+ let idx = (row + 1) * dx;
269+ let base = (idx >> 6) + col;
270+ let shift = (idx >> 1) & 0x1F;
271+ if base < max_base {
272+ blend(&above, base, shift)
273+ } else {
274+ above(max_base)
275+ }
276+ } else if angle > 180 {
277+ let dy = dr_intra_derivative(270 - angle);
278+ let idx = (col + 1) * dy;
279+ let base = (idx >> 6) + row;
280+ let shift = (idx >> 1) & 0x1F;
281+ if base < max_base {
282+ blend(&left, base, shift)
283+ } else {
284+ left(max_base)
285+ }
286+ } else {
287+ // The two zones meet here: a ray that leaves through the row
288+ // above is read there, and one that leaves through the column
289+ // to the left is read there instead.
290+ let dx = dr_intra_derivative(180 - angle);
291+ let idx = (col << 6) - (row + 1) * dx;
292+ let base = idx >> 6;
293+ if base >= -1 {
294+ blend(&above, base, (idx >> 1) & 0x1F)
295+ } else {
296+ let dy = dr_intra_derivative(angle - 90);
297+ let idx = (row << 6) - (col + 1) * dy;
298+ blend(&left, idx >> 6, (idx >> 1) & 0x1F)
299+ }
300+ };
301+ dst[(row * n + col) as usize] = value.clamp(0, 255) as u8;
302+ }
303+ }
304+}
305+
142306 /// `dc_predict` (spec 7.11.2.5): the average of whichever neighbours exist.
143-fn dc(above: Option<&[u8]>, left: Option<&[u8]>) -> i32 {
307+///
308+/// Only the block's own `side` samples of each edge count: what a directional
309+/// mode reaches past them is no part of the average.
310+fn dc(above: Option<&[u8]>, left: Option<&[u8]>, side: usize) -> i32 {
311+ let above = above.map(|a| &a[..side.min(a.len())]);
312+ let left = left.map(|l| &l[..side.min(l.len())]);
144313 let average = |samples: &[u8]| {
145314 let sum: u32 = samples.iter().map(|&s| u32::from(s)).sum();
146315 ((sum + (samples.len() as u32 >> 1)) / samples.len() as u32) as i32
crates/ec-av1/src/tile.rsmodified+1 -1
@@ -51,7 +51,7 @@ const INTRA_MODES: usize = 13;
5151
5252 /// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
5353 /// its neighbours in when they pick the CDF for the next block's mode.
54-const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
54+pub(crate) const INTRA_MODE_CTX: [usize; INTRA_MODES] = [0, 1, 2, 3, 4, 4, 4, 4, 3, 0, 1, 2, 0];
5555
5656 /// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
5757 /// +3, so `MAX_ANGLE_DELTA` is the middle of it.
lanes/av1-directional-r1.report.mdadded+85 -0
@@ -0,0 +1,85 @@
1+# lane-av1-directional r1 — the six directional intra modes
2+
3+Adds AV1's six directional intra predictors (D45, D67, D113, D135, D157, D203)
4+to `ec-av1`, with the availability derivation the decoder actually uses, and
5+puts the cost of *naming* a mode into the mode search — which was the honest
6+finding left open by `av1-predict-r1`.
7+
8+## What landed
9+
10+- `crates/ec-av1/src/intra.rs`: `directional()` per spec 7.11.2.4, all three
11+ zones (`pAngle < 90` walks the above row, `> 180` walks the left column,
12+ `90..180` walks the above row while `base >= -1` and falls to the left
13+ column below that), `Dr_Intra_Derivative` and `Mode_To_Angle` tabulated.
14+ Edges now carry the spec's index −1 (the corner) at slot 0 and are extended
15+ to `2 * side` by repeating the last sample. `enable_intra_edge_filter` is
16+ false in our sequence header, so no filtering and no upsampling apply.
17+- `crates/ec-av1/src/encode.rs`: `Reach` — which of the above-right and
18+ below-left samples a block may read, derived from `clear_block_decoded_flags`
19+ (spec 7.4). For the four 32x32 quadrants of a 64x64 superblock: above-right
20+ available for quadrants 0, 1, 2 (not 3), below-left only for quadrant 0.
21+- `mode_bits()` — what the tile writer spends to name each of the thirteen
22+ modes, scored through the writer's own CDFs: the KF_Y_MODE symbol under the
23+ context the two neighbouring modes pick, the ANGLE_DELTA zero symbol a
24+ directional mode carries, and the UV_MODE_CFL DC symbol, whose row the luma
25+ mode indexes. The encoder tracks neighbour modes exactly as the writer does.
26+- `LAMBDA_SCALE` re-swept with the mode cost in: 0.05 → 0.1.
27+
28+## Gates
29+
30+| Gate | Result |
31+|---|---|
32+| `ffmpeg` decodes our stream to the encoder's own prediction, all 13 modes, 128x96 and 160x96 | bit-exact, 0 differing samples |
33+| the search picks the diagonal the picture runs (D135 / D45 test cards) | pass |
34+| directional modes cost no more than 1% rate on a picture that does not want them | +0.41% |
35+| full suite `cargo test --release -p ec-av1` | 75 passed, 0 failed, 2 ignored |
36+| `cargo clippy --release -p ec-av1 --all-targets` | 0 warnings |
37+
38+The 160x96 width is in the shape gate on purpose: it makes the last superblock
39+of a row partial, which is where a wrong above-right derivation shows up.
40+
41+## Mutations killed
42+
43+| Mutation | Caught by |
44+|---|---|
45+| above-right always available | ffmpeg mismatch, mode 3, first at (63, 64) |
46+| below-left always available | ffmpeg mismatch, mode 7 |
47+| 45° derivative off by one (`1023` → `1022`) | ffmpeg mismatch, mode 3 |
48+| zone 2 reads the left column instead of the above row | ffmpeg mismatch, modes 4/5/6 |
49+
50+Restore run after the four: 12 passed, 0 failed.
51+
52+## His data — this branch against `main`, same frame each row
53+
54+One key frame per clip, 640x352 crop, `base_q_idx` 100. The skip is recorded
55+here because `av1-predict-r1` did not record its own, and its screen-capture
56+row (4808 B / 46.06 dB) is a *different frame* of the same file, not a
57+regression — that clip is 6.5 s long and its frames differ by 8 dB across it.
58+
59+| clip | skip | main bytes | main PSNR | this branch | PSNR | Δ rate |
60+|---|---|---|---|---|---|---|
61+| ReelC (1080p film) | 1920 s | 19125 | 40.61 dB | 19134 | 40.59 dB | +0.05% |
62+| OBS screen capture | 5 s | 9144 | 43.52 dB | 9112 | 43.52 dB | −0.35% |
63+| reela | 5 s | 7535 | 44.76 dB | 7518 | 44.76 dB | −0.23% |
64+
65+On synthetic pictures that genuinely run diagonally the same code is worth
66+−53.0% rate. The difference is block size: at 32x32, directional modes fire on
67+8 of 220 blocks in the film frame and 5 of 220 in the screen capture.
68+
69+## Dispositions
70+
71+- **accepted** — directional modes move real 640x352 frames by ≤0.35%. They
72+ are correct, bit-exact and default-on; the win they are capable of waits on
73+ block sizes below 32x32 and on the partition decision, which is its own lane.
74+- **accepted** — ReelC is +0.05% rate / −0.02 dB, inside the noise of a single
75+ frame and the price of the lambda move that pays for the other two clips.
76+- **fix-now, done in this lane** — the search's blindness to mode signalling
77+ cost, left open by `av1-predict-r1`. Costed through the writer's CDFs above.
78+
79+## Not in this lane
80+
81+Angle deltas other than zero; block sizes other than 32x32 and the partition
82+decision; a coefficient rate term scored through the writer's CDFs (the mode
83+half is now done, the level half is still the magnitude estimate); transform
84+types beyond DCT_DCT; CDF adaptation; inter frames; pictures whose dimensions
85+are not a multiple of 32.