forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-directional': the six directional intra modes and a mode-rate term

Browse files at this commit

eba2ab8e414ede2ca47bca55934a1db128a6a3bfAhmet Kaan GümüşParent: 35f59c2223aa7c
crates/ec-av1/src/encode.rsmodified+336 -67
@@ -21,12 +21,13 @@ use ec_av1_syntax::{
21 };21 };
22 use ec_core::{Error, Result};22 use ec_core::{Error, Result};
23 23
24+use crate::cdf;
24 use crate::frame::frame_obu;25 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};
26 use crate::obu::temporal_delimiter;27 use crate::obu::temporal_delimiter;
27 use crate::quant::ac_q;28 use crate::quant::ac_q;
28 use crate::sequence::sequence_header_obu;29 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};
30 use crate::transform::{dequant_and_inverse, forward_and_quantize};31 use crate::transform::{dequant_and_inverse, forward_and_quantize};
31 32
32 /// The side of the luma blocks this encoder codes, in samples.33 /// The side of the luma blocks this encoder codes, in samples.
@@ -35,13 +36,14 @@ const BLOCK: usize = 32;
35 /// How heavily the mode search weighs rate against squared error, in units of36 /// How heavily the mode search weighs rate against squared error, in units of
36 /// the quantizer's reconstruction step squared per bit.37 /// the quantizer's reconstruction step squared per bit.
37 ///38 ///
38-/// Swept over three clips and two synthetic pictures at 0, 0.05, 0.1, 0.2, 0.439+/// Swept twice over three of his clips and three synthetic pictures
39-/// and 0.8 (`probe_lambda`, and the table in the lane report): 0 leaves half the40+/// (`probe_lambda` and `probe_directional`, and the tables in the two lane
40-/// saving on the table on a picture that runs one way (-35.6% against -59.5% on41+/// reports). The first sweep, before the mode symbol was costed, put the best
41-/// stripes), and everything from 0.1 up gives a little back on screen capture42+/// point at 0.05; costing it moved the point to 0.1, where the directional
42-/// (-10.7% against -11.5%) and on a hand-held clip. 0.05 is the best point on43+/// modes stop costing rate on the pictures that do not want them (+0.05% on
43-/// every clip measured.44+/// screen capture against +0.19% at 0.05) without giving up any of what they
44-const LAMBDA_SCALE: f64 = 0.05;45+/// save on the pictures that do (-53.0% on a diagonal).
46+const LAMBDA_SCALE: f64 = 0.1;
45 47
46 /// One 8-bit planar 4:2:0 picture.48 /// One 8-bit planar 4:2:0 picture.
47 #[derive(Clone, Debug, PartialEq, Eq)]49 #[derive(Clone, Debug, PartialEq, Eq)]
@@ -235,17 +237,26 @@ impl Plane<'_> {
235 /// The reconstructed samples a block at `(x, y)` predicts from: the row237 /// The reconstructed samples a block at `(x, y)` predicts from: the row
236 /// above it, the column to its left and the sample between them, each238 /// above it, the column to its left and the sample between them, each
237 /// missing where the block sits against an edge of the frame.239 /// 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).
238 fn edges(246 fn edges(
239 &self,247 &self,
240 x: usize,248 x: usize,
241 y: usize,249 y: usize,
242 side: usize,250 side: usize,
251+ reach: Reach,
243 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {252 ) -> (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);
244 let above =255 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());
246 let left = (x > 0).then(|| {257 let left = (x > 0).then(|| {
247- (0..side)258+ (y..down)
248- .map(|i| self.reconstruction[(y + i) * self.width + x - 1])259+ .map(|row| self.reconstruction[row * self.width + x - 1])
249 .collect::<Vec<_>>()260 .collect::<Vec<_>>()
250 });261 });
251 let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);262 let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
@@ -255,16 +266,9 @@ impl Plane<'_> {
255 /// Codes one block under one mode without committing it: hands back the266 /// Codes one block under one mode without committing it: hands back the
256 /// levels, the block the decoder would reconstruct, the squared error267 /// levels, the block the decoder would reconstruct, the squared error
257 /// against the source and an estimate of what the levels cost in bits.268 /// against the source and an estimate of what the levels cost in bits.
258- fn trial(269+ fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial {
259- &self,270+ let At { x, y, side, reach } = at;
260- x: usize,271+ let (above, left, corner) = self.edges(x, y, side, reach);
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);
268 let mut prediction = vec![0u8; side * side];272 let mut prediction = vec![0u8; side * side];
269 crate::intra::predict(273 crate::intra::predict(
270 mode,274 mode,
@@ -323,33 +327,19 @@ impl Plane<'_> {
323 }327 }
324 328
325 /// Codes one block under a fixed mode, committing it.329 /// Codes one block under a fixed mode, committing it.
326- fn code_block(330+ fn code_block(&mut self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Vec<Coeff> {
327- &mut self,331+ let trial = self.trial(at, mode, base_q_idx, deadzone);
328- x: usize,332+ self.commit(at.x, at.y, at.side, &trial);
329- y: usize,333+ coeffs(&trial.levels, at.side)
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)
338 }334 }
339 335
340 /// Codes one block under every mode the search offers and commits the one336 /// Codes one block under every mode the search offers and commits the one
341 /// whose squared error and estimated rate come out cheapest.337 /// whose squared error and estimated rate come out cheapest.
342- fn search_block(338+ fn search_block(&mut self, at: At, search: &Search, mode_bits: &[f64; 13]) -> (Vec<Coeff>, u8) {
343- &mut self,
344- x: usize,
345- y: usize,
346- side: usize,
347- search: &Search,
348- ) -> (Vec<Coeff>, u8) {
349 let mut best: Option<(f64, u8, Trial)> = None;339 let mut best: Option<(f64, u8, Trial)> = None;
350 for &mode in search.modes {340 for &mode in search.modes {
351- let trial = self.trial(x, y, side, mode, search.base_q_idx, search.deadzone);341+ let trial = self.trial(at, mode, search.base_q_idx, search.deadzone);
352- let cost = trial.sse + search.lambda * trial.bits;342+ let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
353 if best343 if best
354 .as_ref()344 .as_ref()
355 .is_none_or(|(best_cost, _, _)| cost < *best_cost)345 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
@@ -358,11 +348,89 @@ impl Plane<'_> {
358 }348 }
359 }349 }
360 let (_, mode, trial) = best.expect("the search offers at least one mode");350 let (_, mode, trial) = best.expect("the search offers at least one mode");
361- self.commit(x, y, side, &trial);351+ self.commit(at.x, at.y, at.side, &trial);
362- (coeffs(&trial.levels, side), mode)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+ }
363 }402 }
364 }403 }
365 404
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+
366 /// What the luma mode search picks between, and under what terms.434 /// What the luma mode search picks between, and under what terms.
367 struct Search<'a> {435 struct Search<'a> {
368 base_q_idx: u8,436 base_q_idx: u8,
@@ -405,15 +473,16 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
405 /// when its planes are not 4:2:0 of that size, or when the tile writer refuses473 /// when its planes are not 4:2:0 of that size, or when the tile writer refuses
406 /// the quantizer index.474 /// the quantizer index.
407 pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {475 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)
409 }477 }
410 478
411 /// Encodes one picture as a key frame, choosing each block's luma mode from479 /// Encodes one picture as a key frame, choosing each block's luma mode from
412 /// `modes` alone.480 /// `modes` alone.
413 ///481 ///
414 /// This is what an ablation measures against: `&[DC_PRED]` is the encoder482 /// This is what an ablation measures against: `&[DC_PRED]` is the encoder
415-/// before the mode search, and [`NON_DIRECTIONAL`] is what483+/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
416-/// [`encode_key_frame`] uses.484+/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
485+/// uses.
417 ///486 ///
418 /// # Errors487 /// # Errors
419 /// The same as [`encode_key_frame`], and additionally when `modes` is empty or488 /// The same as [`encode_key_frame`], and additionally when `modes` is empty or
@@ -431,7 +500,7 @@ pub fn encode_key_frame_with_modes(
431 "a mode search needs at least one mode to choose from",500 "a mode search needs at least one mode to choose from",
432 ));501 ));
433 }502 }
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)) {
435 return Err(Error::unsupported(504 return Err(Error::unsupported(
436 "AV1 encode",505 "AV1 encode",
437 format!("intra mode {bad} is not one the encoder predicts"),506 format!("intra mode {bad} is not one the encoder predicts"),
@@ -471,6 +540,12 @@ pub fn encode_key_frame_with_modes(
471 };540 };
472 541
473 let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK);542 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];
474 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));549 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
475 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);550 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
476 let mut modes = Vec::with_capacity(cols * rows);551 let mut modes = Vec::with_capacity(cols * rows);
@@ -486,13 +561,44 @@ pub fn encode_key_frame_with_modes(
486 continue;561 continue;
487 }562 }
488 let (x, y) = (col * BLOCK, row * BLOCK);563 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;
490 modes.push(mode);576 modes.push(mode);
491 blocks.push(BlockCoeffs {577 blocks.push(BlockCoeffs {
492 // Chroma is predicted DC because that is the mode the tile578 // Chroma is predicted DC because that is the mode the tile
493 // writer codes for it.579 // writer codes for it.
494- u: chroma[0].code_block(x / 2, y / 2, BLOCK / 2, DC_PRED, base_q_idx, deadzone),580+ u: chroma[0].code_block(
495- v: chroma[1].code_block(x / 2, y / 2, BLOCK / 2, DC_PRED, base_q_idx, deadzone),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+ ),
496 luma: luma_coeffs,602 luma: luma_coeffs,
497 mode,603 mode,
498 });604 });
@@ -523,7 +629,7 @@ pub fn encode_key_frame_with_modes(
523 #[cfg(test)]629 #[cfg(test)]
524 mod tests {630 mod tests {
525 use super::*;631 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};
527 use std::io::Write;633 use std::io::Write;
528 use std::process::{Command, Stdio};634 use std::process::{Command, Stdio};
529 635
@@ -718,6 +824,21 @@ mod tests {
718 picture824 picture
719 }825 }
720 826
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+
721 /// Every mode the encoder offers has to predict what the decoder predicts,842 /// Every mode the encoder offers has to predict what the decoder predicts,
722 /// not just the ones a particular picture happens to choose: each is forced843 /// not just the ones a particular picture happens to choose: each is forced
723 /// over a whole picture and the reconstruction gated against ffmpeg.844 /// over a whole picture and the reconstruction gated against ffmpeg.
@@ -727,17 +848,30 @@ mod tests {
727 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");848 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
728 return;849 return;
729 }850 }
730- let picture = test_card(128, 96);851+ // 128 wide is a whole number of superblocks and 160 is not: the last
731- for mode in NON_DIRECTIONAL {852+ // superblock of a 160-wide row is half a one, whose blocks have no
732- let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();853+ // above-right samples inside the frame at all.
733- let decoded = ffmpeg_decode(&encoded.stream, 128, 96);854+ for (width, height) in [(128, 96), (160, 96)] {
734- assert_eq!(decoded.y, encoded.reconstruction.y, "mode {mode}: luma");855+ let picture = test_card(width, height);
735- assert_eq!(decoded.u, encoded.reconstruction.u, "mode {mode}: U");856+ for mode in KEY_FRAME_MODES {
736- assert_eq!(decoded.v, encoded.reconstruction.v, "mode {mode}: V");857+ let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();
737- assert!(858+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
738- encoded.modes.iter().all(|&m| m == mode),859+ for (plane, ours, theirs, stride) in [
739- "mode {mode}: the encoder coded something else"860+ ("luma", &encoded.reconstruction.y, &decoded.y, width),
740- );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+ }
741 }875 }
742 }876 }
743 877
@@ -749,7 +883,13 @@ mod tests {
749 fn the_search_picks_the_direction_the_picture_runs() {883 fn the_search_picks_the_direction_the_picture_runs() {
750 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {884 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
751 let picture = stripes(128, 96, vertical);885 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();
753 // The first block of the picture has neither neighbour, so it893 // The first block of the picture has neither neighbour, so it
754 // cannot tell the modes apart; every other one can.894 // cannot tell the modes apart; every other one can.
755 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();895 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
@@ -832,16 +972,145 @@ mod tests {
832 }972 }
833 }973 }
834 974
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+
835 /// A mode the encoder cannot predict must be refused rather than coded as1104 /// A mode the encoder cannot predict must be refused rather than coded as
836 /// something else, and a search with nothing to choose from likewise.1105 /// something else, and a search with nothing to choose from likewise.
837 #[test]1106 #[test]
838 fn a_mode_the_encoder_cannot_predict_is_refused() {1107 fn a_mode_the_encoder_cannot_predict_is_refused() {
839 let picture = test_card(64, 64);1108 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])
841 .unwrap_err()1110 .unwrap_err()
842 .to_string();1111 .to_string();
843 assert!(1112 assert!(
844- message.contains("intra mode 3"),1113+ message.contains("intra mode 13"),
845 "the refusal must name the mode, got {message}"1114 "the refusal must name the mode, got {message}"
846 );1115 );
847 assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err());1116 assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err());
crates/ec-av1/src/intra.rsmodified+203 -34
@@ -1,9 +1,12 @@
1 //! Intra prediction, the half of spec 7.11.2 a key frame needs.1 //! Intra prediction, the half of spec 7.11.2 a key frame needs.
2 //!2 //!
3-//! The seven modes here are the ones that read no further than the row above3+//! All thirteen key-frame intra modes: the seven that read no further than the
4-//! and the column to the left of the block: the eight directional modes reach4+//! row above and the column to the left of the block, and the six that steer
5-//! past a block's own width into samples whose availability the decoder tracks5+//! along an angle and reach past the block's own width into the samples above
6-//! in its own bookkeeping, and are not written yet.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).
7 10
8 /// The average of the neighbours (spec 7.11.2.5).11 /// The average of the neighbours (spec 7.11.2.5).
9 pub const DC_PRED: u8 = 0;12 pub const DC_PRED: u8 = 0;
@@ -19,8 +22,40 @@ pub const SMOOTH_V_PRED: u8 = 10;
19 pub const SMOOTH_H_PRED: u8 = 11;22 pub const SMOOTH_H_PRED: u8 = 11;
20 /// Whichever of above, left and the corner is nearest their gradient.23 /// Whichever of above, left and the corner is nearest their gradient.
21 pub const PAETH_PRED: u8 = 12;24 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;
22 37
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.
24 pub const NON_DIRECTIONAL: [u8; 7] = [59 pub const NON_DIRECTIONAL: [u8; 7] = [
25 DC_PRED,60 DC_PRED,
26 V_PRED,61 V_PRED,
@@ -51,26 +86,75 @@ fn round2(value: i32, shift: u32) -> i32 {
51 (value + (1 << (shift - 1))) >> shift86 (value + (1 << (shift - 1))) >> shift
52 }87 }
53 88
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+
54 /// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2):127 /// 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 corner128+/// a side that does not exist is filled from the side that does, a side that
56-/// falls back the same way.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`.
57 struct Edges {134 struct Edges {
58 above: Vec<i32>,135 above: Vec<i32>,
59 left: Vec<i32>,136 left: Vec<i32>,
60- corner: i32,
61 }137 }
62 138
63 impl Edges {139 impl Edges {
64 fn build(above: Option<&[u8]>, left: Option<&[u8]>, corner: Option<u8>, side: usize) -> Self {140 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+ };
65 let above_row = match (above, left) {149 let above_row = match (above, left) {
66- (Some(a), _) => a.iter().map(|&s| i32::from(s)).collect(),150+ (Some(a), _) => extend(a),
67- (None, Some(l)) => vec![i32::from(l[0]); side],151+ (None, Some(l)) => vec![i32::from(l[0]); want],
68- (None, None) => vec![127; side],152+ (None, None) => vec![127; want],
69 };153 };
70 let left_col = match (left, above) {154 let left_col = match (left, above) {
71- (Some(l), _) => l.iter().map(|&s| i32::from(s)).collect(),155+ (Some(l), _) => extend(l),
72- (None, Some(a)) => vec![i32::from(a[0]); side],156+ (None, Some(a)) => vec![i32::from(a[0]); want],
73- (None, None) => vec![129; side],157+ (None, None) => vec![129; want],
74 };158 };
75 let corner = match (corner, above, left) {159 let corner = match (corner, above, left) {
76 (Some(c), Some(_), Some(_)) => i32::from(c),160 (Some(c), Some(_), Some(_)) => i32::from(c),
@@ -78,20 +162,38 @@ impl Edges {
78 (_, None, Some(l)) => i32::from(l[0]),162 (_, None, Some(l)) => i32::from(l[0]),
79 (_, None, None) => 128,163 (_, None, None) => 128,
80 };164 };
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+ };
81 Self {171 Self {
82- above: above_row,172+ above: with_corner(above_row),
83- left: left_col,173+ left: with_corner(left_col),
84- corner,
85 }174 }
86 }175 }
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+ }
87 }186 }
88 187
89 /// Predicts one square block into `dst`, row-major and `side * side` long.188 /// Predicts one square block into `dst`, row-major and `side * side` long.
90 ///189 ///
91 /// `above` is the reconstructed row above the block and `left` its190 /// `above` is the reconstructed row above the block and `left` its
92-/// reconstructed left column, each `side` samples long, and `corner` the191+/// reconstructed left column, each at least `side` samples long, and `corner`
93-/// sample diagonally above-left; `None` where the block sits against an edge192+/// the sample diagonally above-left; `None` where the block sits against an
94-/// of the frame.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.
95 ///197 ///
96 /// # Panics198 /// # Panics
97 /// Panics on a mode this module does not predict, or when `dst` is not199 /// Panics on a mode this module does not predict, or when `dst` is not
@@ -106,32 +208,41 @@ pub fn predict(
106 ) {208 ) {
107 assert_eq!(dst.len(), side * side, "the destination is the block");209 assert_eq!(dst.len(), side * side, "the destination is the block");
108 let edges = Edges::build(above, left, corner, side);210 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+ }
110 let weights = &SM_WEIGHTS[side..side * 2];219 let weights = &SM_WEIGHTS[side..side * 2];
111 for row in 0..side {220 for row in 0..side {
112 for col in 0..side {221 for col in 0..side {
222+ let (r, c) = (row as i32, col as i32);
223+ let last = side as i32 - 1;
113 let value = match mode {224 let value = match mode {
114- DC_PRED => dc(above, left),225+ DC_PRED => dc(above, left, side),
115- V_PRED => a[col],226+ V_PRED => edges.above(c),
116- H_PRED => l[row],227+ H_PRED => edges.left(r),
117 SMOOTH_PRED => round2(228 SMOOTH_PRED => round2(
118- i32::from(weights[row]) * a[col]229+ i32::from(weights[row]) * edges.above(c)
119- + (256 - i32::from(weights[row])) * l[side - 1]230+ + (256 - i32::from(weights[row])) * edges.left(last)
120- + i32::from(weights[col]) * l[row]231+ + i32::from(weights[col]) * edges.left(r)
121- + (256 - i32::from(weights[col])) * a[side - 1],232+ + (256 - i32::from(weights[col])) * edges.above(last),
122 9,233 9,
123 ),234 ),
124 SMOOTH_V_PRED => round2(235 SMOOTH_V_PRED => round2(
125- i32::from(weights[row]) * a[col]236+ i32::from(weights[row]) * edges.above(c)
126- + (256 - i32::from(weights[row])) * l[side - 1],237+ + (256 - i32::from(weights[row])) * edges.left(last),
127 8,238 8,
128 ),239 ),
129 SMOOTH_H_PRED => round2(240 SMOOTH_H_PRED => round2(
130- i32::from(weights[col]) * l[row]241+ i32::from(weights[col]) * edges.left(r)
131- + (256 - i32::from(weights[col])) * a[side - 1],242+ + (256 - i32::from(weights[col])) * edges.above(last),
132 8,243 8,
133 ),244 ),
134- PAETH_PRED => paeth(a[col], l[row], edges.corner),245+ PAETH_PRED => paeth(edges.above(c), edges.left(r), edges.above(-1)),
135 other => panic!("intra mode {other} is not one this module predicts"),246 other => panic!("intra mode {other} is not one this module predicts"),
136 };247 };
137 dst[row * side + col] = value.clamp(0, 255) as u8;248 dst[row * side + col] = value.clamp(0, 255) as u8;
@@ -139,8 +250,66 @@ pub fn predict(
139 }250 }
140 }251 }
141 252
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+
142 /// `dc_predict` (spec 7.11.2.5): the average of whichever neighbours exist.306 /// `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())]);
144 let average = |samples: &[u8]| {313 let average = |samples: &[u8]| {
145 let sum: u32 = samples.iter().map(|&s| u32::from(s)).sum();314 let sum: u32 = samples.iter().map(|&s| u32::from(s)).sum();
146 ((sum + (samples.len() as u32 >> 1)) / samples.len() as u32) as i32315 ((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;
51 51
52 /// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts52 /// `Intra_Mode_Context` (spec 9.3): the five-way class each intra mode puts
53 /// its neighbours in when they pick the CDF for the next block's mode.53 /// 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];
55 55
56 /// The symbol an angle delta of zero codes as: the alphabet runs from -3 to56 /// The symbol an angle delta of zero codes as: the alphabet runs from -3 to
57 /// +3, so `MAX_ANGLE_DELTA` is the middle of it.57 /// +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.