forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-loop': multi-frame AV1 encoding, ffmpeg-exact

Browse files at this commit

90a3d10c337d35bfb9819350ca322e4d34a61c3eAhmet Kaan GümüşParent: 748d06c50130dc
crates/ec-av1/src/encode.rsmodified+916 -3
@@ -25,12 +25,15 @@ use crate::cdf;
25 use crate::cdf_state::TxbSet;25 use crate::cdf_state::TxbSet;
26 use crate::frame::frame_obu;26 use crate::frame::frame_obu;
27 use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};27 use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};
28+use crate::mc;
29+use crate::motion;
30+use crate::mvstack::{MiGrid, MiInfo, MvStack, find_mv_stack};
28 use crate::obu::temporal_delimiter;31 use crate::obu::temporal_delimiter;
29 use crate::quant::ac_q;32 use crate::quant::ac_q;
30 use crate::sequence::sequence_header_obu;33 use crate::sequence::sequence_header_obu;
31 use crate::tile::{34 use crate::tile::{
32- BlockCoeffs, Coeff, INTRA_MODE_CTX, Quadrant, Superblock, partition_bits,35+ BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
33- sb_coeff_key_frame_tile,36+ sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile,
34 };37 };
35 use crate::transform::{dequant_and_inverse, forward_and_quantize};38 use crate::transform::{dequant_and_inverse, forward_and_quantize};
36 39
@@ -141,6 +144,11 @@ pub struct Encoded {
141 /// are coded — raster order among the quadrants of each superblock, and144 /// are coded — raster order among the quadrants of each superblock, and
142 /// among the four 16x16 blocks of a quadrant that was split.145 /// among the four 16x16 blocks of a quadrant that was split.
143 pub modes: Vec<u8>,146 pub modes: Vec<u8>,
147+ /// The fraction of this frame's 32x32 blocks that were coded inter (any
148+ /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
149+ /// for a key frame, which has no such choice — so a caller can tell a
150+ /// frame with no motion worth coding from one that never got the chance.
151+ pub inter_block_share: f64,
144 }152 }
145 153
146 /// The sequence and frame headers a picture of this size is coded under: one154 /// The sequence and frame headers a picture of this size is coded under: one
@@ -405,6 +413,82 @@ impl Plane<'_> {
405 }413 }
406 }414 }
407 415
416+ /// [`Self::trial`] with the prediction already built, so that an inter
417+ /// block's motion-compensated prediction can go through the same
418+ /// residual/quantize/reconstruct path an intra block's does. `skip`
419+ /// takes the prediction as the reconstruction outright, coding no
420+ /// residual at all — what a `NEARESTMV` block that names no coefficients
421+ /// codes.
422+ #[allow(clippy::too_many_arguments)]
423+ fn code_from_prediction(
424+ &self,
425+ x: usize,
426+ y: usize,
427+ side: usize,
428+ prediction: &[u8],
429+ skip: bool,
430+ base_q_idx: u8,
431+ deadzone: f64,
432+ set: TxbSet,
433+ ) -> Trial {
434+ if skip {
435+ let mut sse = 0.0;
436+ for row in 0..side {
437+ for col in 0..side {
438+ let error = f64::from(
439+ i32::from(self.source[(y + row) * self.width + x + col])
440+ - i32::from(prediction[row * side + col]),
441+ );
442+ sse += error * error;
443+ }
444+ }
445+ return Trial {
446+ levels: vec![0i32; side * side],
447+ reconstruction: prediction.to_vec(),
448+ sse,
449+ bits: 0.0,
450+ };
451+ }
452+ let mut residual = vec![0i32; side * side];
453+ for row in 0..side {
454+ for col in 0..side {
455+ residual[row * side + col] =
456+ i32::from(self.source[(y + row) * self.width + x + col])
457+ - i32::from(prediction[row * side + col]);
458+ }
459+ }
460+ let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
461+ let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
462+ let mut reconstruction = vec![0u8; side * side];
463+ let mut sse = 0.0;
464+ for row in 0..side {
465+ for col in 0..side {
466+ let i = row * side + col;
467+ let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
468+ reconstruction[i] = sample;
469+ let error = f64::from(
470+ i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
471+ );
472+ sse += error * error;
473+ }
474+ }
475+ let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
476+ levels
477+ .iter()
478+ .filter(|&&level| level != 0)
479+ .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
480+ .sum()
481+ } else {
482+ crate::tile::coeff_bits(&levels, set)
483+ };
484+ Trial {
485+ levels,
486+ reconstruction,
487+ sse,
488+ bits,
489+ }
490+ }
491+
408 /// Writes a trial's reconstruction back into the plane.492 /// Writes a trial's reconstruction back into the plane.
409 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {493 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
410 for row in 0..side {494 for row in 0..side {
@@ -427,6 +511,16 @@ impl Plane<'_> {
427 (coeffs(&trial.levels, at.side), trial.sse, trial.bits)511 (coeffs(&trial.levels, at.side), trial.sse, trial.bits)
428 }512 }
429 513
514+ /// The source samples of one square, contiguous — what a motion search
515+ /// compares its candidates' predictions against ([`motion::search`]'s
516+ /// `source`), since [`Self::source`] itself is the whole plane, strided
517+ /// by [`Self::width`].
518+ fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
519+ (y..y + side)
520+ .flat_map(|row| self.source[row * self.width + x..][..side].to_vec())
521+ .collect()
522+ }
523+
430 /// The reconstructed samples of one square, so that a partition trial can524 /// The reconstructed samples of one square, so that a partition trial can
431 /// be undone.525 /// be undone.
432 fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {526 fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
@@ -897,6 +991,614 @@ fn encode_key_frame_inner(
897 Ok(Encoded {991 Ok(Encoded {
898 stream,992 stream,
899 modes,993 modes,
994+ inter_block_share: 0.0,
995+ reconstruction: Picture {
996+ width: luma.width,
997+ height: luma.height,
998+ y: luma.reconstruction,
999+ u: u.reconstruction,
1000+ v: v.reconstruction,
1001+ },
1002+ })
1003+}
1004+
1005+/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
1006+/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
1007+/// since every block this crate's inter tile writer codes is 32x32.
1008+const SIZE_GROUP_32: usize = 3;
1009+
1010+/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
1011+/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
1012+/// stack this encoder builds is ever asked to predict against.
1013+const LAST_FRAME: i8 = 1;
1014+
1015+/// What an inter frame's intra branch spends to name each of the thirteen
1016+/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
1017+/// context, since an inter frame's intra blocks do not read their
1018+/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
1019+/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
1020+/// state, so it is built once per frame.
1021+fn inter_mode_bits() -> [f64; 13] {
1022+ std::array::from_fn(|mode| {
1023+ let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
1024+ symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
1025+ } else {
1026+ 0.0
1027+ };
1028+ symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
1029+ + angle
1030+ + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
1031+ })
1032+}
1033+
1034+/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
1035+/// [`mc::predict`] takes, in the units of the plane it predicts into.
1036+///
1037+/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
1038+/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
1039+/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
1040+/// domain. `luma` picks which.
1041+fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
1042+ (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
1043+}
1044+
1045+/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
1046+/// that module): the magnitude an `MV_CLASS_n` component's own bits start
1047+/// counting from.
1048+fn mv_class_base(class: usize) -> i32 {
1049+ if class == 0 { 0 } else { 2i32 << (class + 2) }
1050+}
1051+
1052+/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
1053+/// `tile::mv_class_of`.
1054+fn mv_class_of(z: i32) -> usize {
1055+ let mut class = 0;
1056+ while class < 10 && mv_class_base(class + 1) <= z {
1057+ class += 1;
1058+ }
1059+ class
1060+}
1061+
1062+/// What [`crate::tile::write_mv_component`] (private to that module) would
1063+/// spend coding one non-zero motion vector component, against the same
1064+/// static default CDFs the writer starts a frame from — the same
1065+/// static-table approximation [`mode_bits`] costs the luma mode symbol
1066+/// through, not the tile writer's own adapting state, which this encoder has
1067+/// no way to read without duplicating it block for block.
1068+///
1069+/// Returns `None` when `diff` needs the eighth-pel precision this crate's
1070+/// frames never carry (`allow_high_precision_mv` is always off), which is
1071+/// what [`round_to_valid_mv`] exists to avoid ever happening.
1072+fn mv_component_bits(diff: i32) -> Option<f64> {
1073+ let mag = diff.unsigned_abs() as i32;
1074+ let z = mag - 1;
1075+ if z & 1 == 0 {
1076+ return None;
1077+ }
1078+ let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
1079+ let class = mv_class_of(z);
1080+ bits += symbol_bits(&cdf::MV_CLASS, class);
1081+ let local = z - mv_class_base(class);
1082+ if class == 0 {
1083+ let bit = (local >> 3) & 1;
1084+ let fr = (local >> 1) & 3;
1085+ bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
1086+ bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
1087+ } else {
1088+ let d = local >> 3;
1089+ let fr = (local >> 1) & 3;
1090+ for i in 0..class {
1091+ bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
1092+ }
1093+ bits += symbol_bits(&cdf::MV_FR, fr as usize);
1094+ }
1095+ Some(bits)
1096+}
1097+
1098+/// What [`crate::tile::write_mv`] (private to that module) would spend
1099+/// coding `mv` as a residual against `pred`: the joint symbol naming which
1100+/// components differ, then each differing component. `None` under the same
1101+/// condition [`mv_component_bits`] returns `None`.
1102+fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
1103+ let diff = (mv.0 - pred.0, mv.1 - pred.1);
1104+ let joint = match (diff.0 != 0, diff.1 != 0) {
1105+ (false, false) => 0,
1106+ (false, true) => 1,
1107+ (true, false) => 2,
1108+ (true, true) => 3,
1109+ };
1110+ let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
1111+ for d in [diff.0, diff.1] {
1112+ if d != 0 {
1113+ bits += mv_component_bits(d)?;
1114+ }
1115+ }
1116+ Some(bits)
1117+}
1118+
1119+/// Rounds `mv` so that its residual against `pred` is one
1120+/// [`crate::tile::write_mv_component`] can actually code: each component's
1121+/// difference is either zero or has an even magnitude (the eighth-pel bit
1122+/// `allow_high_precision_mv` off always infers as one forces the coded
1123+/// magnitude odd one step further in, which comes out even here since this
1124+/// crate's motion search works in whole units of that same step). Rounding
1125+/// down keeps every coded MV — and so every `nearest_mv` a later block's
1126+/// stack votes with — built from an even displacement from `(0, 0)`, so the
1127+/// invariant holds without this function seeing the whole stack.
1128+fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
1129+ let round = |m: i32, p: i32| {
1130+ let diff = m - p;
1131+ let mag = diff.unsigned_abs() as i32;
1132+ let even = mag - mag % 2;
1133+ if even == 0 {
1134+ p
1135+ } else {
1136+ p + even * diff.signum()
1137+ }
1138+ };
1139+ (round(mv.0, pred.0), round(mv.1, pred.1))
1140+}
1141+
1142+/// Predicts one `side`-square block by motion compensation from `reference`
1143+/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
1144+#[allow(clippy::too_many_arguments)]
1145+fn mc_trial(
1146+ plane: &Plane,
1147+ x: usize,
1148+ y: usize,
1149+ side: usize,
1150+ mv: (i32, i32),
1151+ luma: bool,
1152+ reference: &[u8],
1153+ ref_width: usize,
1154+ ref_height: usize,
1155+ skip: bool,
1156+ base_q_idx: u8,
1157+ deadzone: f64,
1158+ set: TxbSet,
1159+) -> Trial {
1160+ let x_q4 = mv_to_q4(x, mv.1, luma);
1161+ let y_q4 = mv_to_q4(y, mv.0, luma);
1162+ let mut prediction = vec![0u8; side * side];
1163+ mc::predict(
1164+ reference,
1165+ ref_width,
1166+ ref_height,
1167+ x_q4,
1168+ y_q4,
1169+ side,
1170+ side,
1171+ &mut prediction,
1172+ );
1173+ plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set)
1174+}
1175+
1176+/// Codes one 32x32 block of an inter frame as whichever costs least of: each
1177+/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
1178+/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
1179+/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
1180+/// coded `skip: true`; see the corner-cut comment where they build their
1181+/// [`Trial`]s.
1182+///
1183+/// The symbol costs this ranks candidates by use fixed contexts (0) for
1184+/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
1185+/// contexts for those come from its own neighbour bookkeeping
1186+/// (`tile::Neighbours`), which is private to that module and not worth
1187+/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
1188+/// `drl_mode` contexts come straight from `stack`, which is exact, because
1189+/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
1190+/// the tile writer derives from the same grid state.
1191+#[allow(clippy::too_many_arguments)]
1192+fn search_inter_block(
1193+ luma: &mut Plane,
1194+ chroma: &mut [Plane; 2],
1195+ (x, y): (usize, usize),
1196+ search: &Search,
1197+ mode_bits: &[f64; 13],
1198+ reference: &Picture,
1199+ stack: &MvStack,
1200+) -> BlockCoeffs {
1201+ let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
1202+ let reach = Reach::of(BLOCK, x, y, luma.width, luma.height);
1203+
1204+ // skip / intra_inter symbol costs at a fixed context -- see this
1205+ // function's doc comment.
1206+ let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
1207+ let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
1208+ let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
1209+ + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
1210+ + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
1211+
1212+ struct Candidate {
1213+ cost: f64,
1214+ luma: Trial,
1215+ u: Trial,
1216+ v: Trial,
1217+ mode: u8,
1218+ skip: bool,
1219+ inter: Option<InterInfo>,
1220+ }
1221+ let mut best: Option<Candidate> = None;
1222+ let mut consider = |candidate: Candidate| {
1223+ if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
1224+ best = Some(candidate);
1225+ }
1226+ };
1227+
1228+ for &mode in search.modes {
1229+ let luma_trial = luma.trial(
1230+ At {
1231+ x,
1232+ y,
1233+ side: BLOCK,
1234+ reach,
1235+ set: luma_set,
1236+ },
1237+ mode,
1238+ search.base_q_idx,
1239+ search.deadzone,
1240+ );
1241+ let u = chroma[0].trial(
1242+ At {
1243+ x: x / 2,
1244+ y: y / 2,
1245+ side: BLOCK / 2,
1246+ reach: Reach::none(),
1247+ set: chroma_set,
1248+ },
1249+ DC_PRED,
1250+ search.base_q_idx,
1251+ search.deadzone,
1252+ );
1253+ let v = chroma[1].trial(
1254+ At {
1255+ x: x / 2,
1256+ y: y / 2,
1257+ side: BLOCK / 2,
1258+ reach: Reach::none(),
1259+ set: chroma_set,
1260+ },
1261+ DC_PRED,
1262+ search.base_q_idx,
1263+ search.deadzone,
1264+ );
1265+ let cost = luma_trial.sse
1266+ + u.sse
1267+ + v.sse
1268+ + search.lambda
1269+ * (luma_trial.bits
1270+ + u.bits
1271+ + v.bits
1272+ + mode_bits[usize::from(mode)]
1273+ + skip_bits(false)
1274+ + intra_inter_bits(false));
1275+ consider(Candidate {
1276+ cost,
1277+ luma: luma_trial,
1278+ u,
1279+ v,
1280+ mode,
1281+ skip: false,
1282+ inter: None,
1283+ });
1284+ }
1285+
1286+ let ref_luma = (&reference.y, reference.width, reference.height);
1287+ let ref_u = (&reference.u, reference.width / 2, reference.height / 2);
1288+ let ref_v = (&reference.v, reference.width / 2, reference.height / 2);
1289+ let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
1290+ + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
1291+ + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
1292+
1293+ // corner-cut: every inter candidate below codes `skip: true` -- no
1294+ // residual -- even where a coded residual would cost less. A coded
1295+ // residual on an `is_inter` block (`skip: false`) desyncs
1296+ // `sb_coeff_inter_frame_tile`'s output past what dav1d will accept
1297+ // ("Invalid data found when processing input"), isolated by a minimal
1298+ // repro (`EC_AV1_DEBUG_ONLY_SKIP` in this lane's history): an intra-only
1299+ // inter frame decodes clean, an all-skip inter frame decodes clean, but
1300+ // one `NEARESTMV` block coded with any residual breaks the stream even
1301+ // at `mv == (0, 0)`. That is inside `sb_coeff_inter_frame_tile`
1302+ // (`crate::tile`), which this lane's charter forbids editing — ceiling:
1303+ // an inter frame never codes a residual until that tile-writer defect is
1304+ // found and fixed; ping-pong candidate is `NEARESTMV`/`NEWMV` "coded"
1305+ // above.
1306+ {
1307+ let mv = stack.nearest_mv;
1308+ let luma_trial = mc_trial(
1309+ luma,
1310+ x,
1311+ y,
1312+ BLOCK,
1313+ mv,
1314+ true,
1315+ ref_luma.0,
1316+ ref_luma.1,
1317+ ref_luma.2,
1318+ true,
1319+ search.base_q_idx,
1320+ search.deadzone,
1321+ luma_set,
1322+ );
1323+ let u = mc_trial(
1324+ &chroma[0],
1325+ x / 2,
1326+ y / 2,
1327+ BLOCK / 2,
1328+ mv,
1329+ false,
1330+ ref_u.0,
1331+ ref_u.1,
1332+ ref_u.2,
1333+ true,
1334+ search.base_q_idx,
1335+ search.deadzone,
1336+ chroma_set,
1337+ );
1338+ let v = mc_trial(
1339+ &chroma[1],
1340+ x / 2,
1341+ y / 2,
1342+ BLOCK / 2,
1343+ mv,
1344+ false,
1345+ ref_v.0,
1346+ ref_v.1,
1347+ ref_v.2,
1348+ true,
1349+ search.base_q_idx,
1350+ search.deadzone,
1351+ chroma_set,
1352+ );
1353+ let cost = luma_trial.sse
1354+ + u.sse
1355+ + v.sse
1356+ + search.lambda
1357+ * (skip_bits(true) + intra_inter_bits(true) + single_ref_bits + mode_bits_inter);
1358+ consider(Candidate {
1359+ cost,
1360+ luma: luma_trial,
1361+ u,
1362+ v,
1363+ mode: DC_PRED,
1364+ skip: true,
1365+ inter: Some(InterInfo {
1366+ mode: InterMode::NearestMv,
1367+ mv,
1368+ }),
1369+ });
1370+ }
1371+
1372+ let source_block = luma.source_block(x, y, BLOCK);
1373+ let found = motion::search(
1374+ ref_luma.0,
1375+ ref_luma.1,
1376+ ref_luma.2,
1377+ &source_block,
1378+ x,
1379+ y,
1380+ BLOCK,
1381+ BLOCK,
1382+ stack.pred_mv,
1383+ search.lambda,
1384+ );
1385+ let mv = round_to_valid_mv(found.mv, stack.pred_mv);
1386+ if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) {
1387+ let luma_trial = mc_trial(
1388+ luma,
1389+ x,
1390+ y,
1391+ BLOCK,
1392+ mv,
1393+ true,
1394+ ref_luma.0,
1395+ ref_luma.1,
1396+ ref_luma.2,
1397+ true,
1398+ search.base_q_idx,
1399+ search.deadzone,
1400+ luma_set,
1401+ );
1402+ let u = mc_trial(
1403+ &chroma[0],
1404+ x / 2,
1405+ y / 2,
1406+ BLOCK / 2,
1407+ mv,
1408+ false,
1409+ ref_u.0,
1410+ ref_u.1,
1411+ ref_u.2,
1412+ true,
1413+ search.base_q_idx,
1414+ search.deadzone,
1415+ chroma_set,
1416+ );
1417+ let v = mc_trial(
1418+ &chroma[1],
1419+ x / 2,
1420+ y / 2,
1421+ BLOCK / 2,
1422+ mv,
1423+ false,
1424+ ref_v.0,
1425+ ref_v.1,
1426+ ref_v.2,
1427+ true,
1428+ search.base_q_idx,
1429+ search.deadzone,
1430+ chroma_set,
1431+ );
1432+ let drl_bits = if stack.entries.len() > 1 {
1433+ symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
1434+ } else {
1435+ 0.0
1436+ };
1437+ let cost = luma_trial.sse
1438+ + u.sse
1439+ + v.sse
1440+ + search.lambda
1441+ * (skip_bits(true)
1442+ + intra_inter_bits(true)
1443+ + single_ref_bits
1444+ + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
1445+ + drl_bits
1446+ + mv_bits);
1447+ consider(Candidate {
1448+ cost,
1449+ luma: luma_trial,
1450+ u,
1451+ v,
1452+ mode: DC_PRED,
1453+ skip: true,
1454+ inter: Some(InterInfo {
1455+ mode: InterMode::NewMv,
1456+ mv,
1457+ }),
1458+ });
1459+ }
1460+
1461+ let best = best.expect("the search offers at least the intra modes");
1462+ luma.commit(x, y, BLOCK, &best.luma);
1463+ chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
1464+ chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
1465+ BlockCoeffs {
1466+ luma: coeffs(&best.luma.levels, BLOCK),
1467+ u: coeffs(&best.u.levels, BLOCK / 2),
1468+ v: coeffs(&best.v.levels, BLOCK / 2),
1469+ mode: best.mode,
1470+ skip: best.skip,
1471+ inter: best.inter,
1472+ }
1473+}
1474+
1475+/// Encodes one picture as an inter frame predicting from `reference`'s
1476+/// reconstruction, which the caller decoded (or, for the frame right after
1477+/// the key frame, is the key frame's own reconstruction).
1478+fn encode_inter_frame(
1479+ picture: &Picture,
1480+ reference: &Picture,
1481+ base_q_idx: u8,
1482+ deadzone: f64,
1483+ order_hint: u32,
1484+) -> Result<Encoded> {
1485+ picture.check()?;
1486+ if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
1487+ return Err(Error::unsupported(
1488+ "AV1 encode",
1489+ "an inter frame is coded only for a picture that is a whole number \
1490+ of 64x64 superblocks -- the inter tile writer never splits a \
1491+ superblock's partition below that",
1492+ ));
1493+ }
1494+ if reference.width != picture.width || reference.height != picture.height {
1495+ return Err(Error::unsupported(
1496+ "AV1 encode",
1497+ "the reference picture must be the same size as the one being coded",
1498+ ));
1499+ }
1500+
1501+ // The single slot this crate's inter frames ever predict from or
1502+ // refresh (`inter_frame_headers`'s contract): every frame both reads and
1503+ // overwrites slot 0, so the frame just coded is always what the next one
1504+ // predicts against.
1505+ const LAST_SLOT: u8 = 0;
1506+ let (seq, header) = inter_frame_headers(
1507+ picture.width,
1508+ picture.height,
1509+ base_q_idx,
1510+ order_hint,
1511+ LAST_SLOT,
1512+ )?;
1513+
1514+ let mut luma = Plane {
1515+ source: &picture.y,
1516+ reconstruction: vec![128; picture.y.len()],
1517+ width: picture.width,
1518+ height: picture.height,
1519+ };
1520+ let mut chroma = [
1521+ Plane {
1522+ source: &picture.u,
1523+ reconstruction: vec![128; picture.u.len()],
1524+ width: picture.width / 2,
1525+ height: picture.height / 2,
1526+ },
1527+ Plane {
1528+ source: &picture.v,
1529+ reconstruction: vec![128; picture.v.len()],
1530+ width: picture.width / 2,
1531+ height: picture.height / 2,
1532+ },
1533+ ];
1534+
1535+ let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
1536+ let search = Search {
1537+ base_q_idx,
1538+ deadzone,
1539+ lambda: lambda_scale() * step * step,
1540+ modes: &KEY_FRAME_MODES,
1541+ };
1542+ let mode_bits_table = inter_mode_bits();
1543+
1544+ let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK);
1545+ let (sb_cols, sb_rows) = (cols / 2, rows / 2);
1546+ let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
1547+ let mut grid = MiGrid::new(mi_cols, mi_rows);
1548+ let mut blocks = vec![BlockCoeffs::default(); cols * rows];
1549+
1550+ for sb_r in 0..sb_rows {
1551+ for sb_c in 0..sb_cols {
1552+ for quadrant in 0..4 {
1553+ let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
1554+ let (x, y) = (c32 * BLOCK, r32 * BLOCK);
1555+ let (mi_row, mi_col) = (r32 * 8, c32 * 8);
1556+ let stack =
1557+ find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
1558+
1559+ let block = search_inter_block(
1560+ &mut luma,
1561+ &mut chroma,
1562+ (x, y),
1563+ &search,
1564+ &mode_bits_table,
1565+ reference,
1566+ &stack,
1567+ );
1568+
1569+ if let Some(info) = block.inter {
1570+ for dr in 0..8 {
1571+ for dc in 0..8 {
1572+ grid.set(
1573+ mi_row + dr,
1574+ mi_col + dc,
1575+ MiInfo {
1576+ is_inter: true,
1577+ ref_frame: LAST_FRAME,
1578+ mv: info.mv,
1579+ is_new_mv: matches!(info.mode, InterMode::NewMv),
1580+ },
1581+ );
1582+ }
1583+ }
1584+ }
1585+ blocks[r32 * cols + c32] = block;
1586+ }
1587+ }
1588+ }
1589+
1590+ let modes = blocks.iter().map(|b| b.mode).collect::<Vec<_>>();
1591+ let inter_block_share =
1592+ blocks.iter().filter(|b| b.inter.is_some()).count() as f64 / blocks.len() as f64;
1593+ let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?;
1594+ let mut stream = temporal_delimiter();
1595+ stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
1596+
1597+ let [u, v] = chroma;
1598+ Ok(Encoded {
1599+ stream,
1600+ modes,
1601+ inter_block_share,
900 reconstruction: Picture {1602 reconstruction: Picture {
901 width: luma.width,1603 width: luma.width,
902 height: luma.height,1604 height: luma.height,
@@ -907,10 +1609,60 @@ fn encode_key_frame_inner(
907 })1609 })
908 }1610 }
909 1611
1612+/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
1613+/// frame's temporal unit followed by one inter frame's temporal unit per
1614+/// remaining picture, all sharing the key frame's sequence header -- and
1615+/// each frame's own [`Encoded`], in coding order.
1616+#[derive(Clone, Debug)]
1617+pub struct EncodedSequence {
1618+ /// The whole stream: `frames[0].stream` (a temporal delimiter, the
1619+ /// sequence header and the key frame) followed by each later frame's
1620+ /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
1621+ /// the sequence header the key frame carried).
1622+ pub stream: Vec<u8>,
1623+ /// One entry per picture, in coding order.
1624+ pub frames: Vec<Encoded>,
1625+}
1626+
1627+/// Encodes a sequence of pictures as a key frame followed by one inter frame
1628+/// per remaining picture, each predicting from the previous frame's own
1629+/// decoded reconstruction — never from the source, which is what a decoder
1630+/// cannot see. `pictures` must be a whole number of 64x64 superblocks in
1631+/// each direction (the inter tile writer's own constraint) and non-empty.
1632+///
1633+/// # Errors
1634+/// Returns an error when `pictures` is empty, when any picture besides the
1635+/// first is not the same size as the first, or under the same conditions
1636+/// [`encode_key_frame`] and the inter frame path do.
1637+pub fn encode_sequence(
1638+ pictures: &[Picture],
1639+ base_q_idx: u8,
1640+ deadzone: f64,
1641+) -> Result<EncodedSequence> {
1642+ let Some((first, rest)) = pictures.split_first() else {
1643+ return Err(Error::unsupported(
1644+ "AV1 encode",
1645+ "a sequence needs at least one picture",
1646+ ));
1647+ };
1648+ let key = encode_key_frame(first, base_q_idx, deadzone)?;
1649+ let mut stream = key.stream.clone();
1650+ let mut reference = key.reconstruction.clone();
1651+ let mut frames = vec![key];
1652+ for (i, picture) in rest.iter().enumerate() {
1653+ let order_hint = (i + 1) as u32;
1654+ let inter = encode_inter_frame(picture, &reference, base_q_idx, deadzone, order_hint)?;
1655+ stream.extend_from_slice(&inter.stream);
1656+ reference = inter.reconstruction.clone();
1657+ frames.push(inter);
1658+ }
1659+ Ok(EncodedSequence { stream, frames })
1660+}
1661+
910 #[cfg(test)]1662 #[cfg(test)]
911 mod tests {1663 mod tests {
912 use super::*;1664 use super::*;
913- use crate::intra::{D135_PRED, D45_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};1665+ use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
914 use std::io::Write;1666 use std::io::Write;
915 use std::process::{Command, Stdio};1667 use std::process::{Command, Stdio};
916 1668
@@ -1579,4 +2331,165 @@ mod tests {
1579 psnr(&decoded.y, &picture.y)2331 psnr(&decoded.y, &picture.y)
1580 );2332 );
1581 }2333 }
2334+
2335+ /// [`test_card`], panned `shift` samples to the right (wrapping), so a
2336+ /// sequence of these is a translation a motion search can actually find
2337+ /// — the content [`test_card`] itself draws, not a fresh pattern, so an
2338+ /// inter frame's rate against the key frame's is measuring the same
2339+ /// picture moving, not two different pictures.
2340+ fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
2341+ let mut picture = Picture::grey(width, height);
2342+ for y in 0..height {
2343+ for x in 0..width {
2344+ let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
2345+ let gradient = sx * 200.0 / width as f64;
2346+ let ripple = 30.0
2347+ * (sx * std::f64::consts::PI / 23.0).sin()
2348+ * (y as f64 * std::f64::consts::PI / 37.0).cos();
2349+ let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
2350+ 40.0
2351+ } else {
2352+ 0.0
2353+ };
2354+ picture.y[y * width + x] =
2355+ (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u8;
2356+ }
2357+ }
2358+ for y in 0..height / 2 {
2359+ for x in 0..width / 2 {
2360+ let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
2361+ let i = y * width / 2 + x;
2362+ picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
2363+ picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
2364+ }
2365+ }
2366+ picture
2367+ }
2368+
2369+ /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
2370+ fn ffmpeg_decode_sequence(
2371+ stream: &[u8],
2372+ width: usize,
2373+ height: usize,
2374+ frames: usize,
2375+ ) -> Vec<Picture> {
2376+ let mut child = Command::new("ffmpeg")
2377+ .args([
2378+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
2379+ ])
2380+ .stdin(Stdio::piped())
2381+ .stdout(Stdio::piped())
2382+ .stderr(Stdio::piped())
2383+ .spawn()
2384+ .expect("ffmpeg failed to start");
2385+ child
2386+ .stdin
2387+ .take()
2388+ .expect("ffmpeg stdin")
2389+ .write_all(stream)
2390+ .expect("writing the stream to ffmpeg");
2391+ let out = child.wait_with_output().expect("ffmpeg failed to run");
2392+ assert!(
2393+ out.status.success(),
2394+ "ffmpeg refused the stream: {}",
2395+ String::from_utf8_lossy(&out.stderr)
2396+ );
2397+ let (luma, chroma) = (width * height, width * height / 4);
2398+ let frame_bytes = luma + 2 * chroma;
2399+ assert_eq!(
2400+ out.stdout.len(),
2401+ frame_bytes * frames,
2402+ "expected {frames} 4:2:0 frames, ffmpeg said: {}",
2403+ String::from_utf8_lossy(&out.stderr)
2404+ );
2405+ (0..frames)
2406+ .map(|i| {
2407+ let base = i * frame_bytes;
2408+ Picture {
2409+ width,
2410+ height,
2411+ y: out.stdout[base..base + luma].to_vec(),
2412+ u: out.stdout[base + luma..base + luma + chroma].to_vec(),
2413+ v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
2414+ }
2415+ })
2416+ .collect()
2417+ }
2418+
2419+ /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
2420+ /// makes for a key frame, extended down the reference chain: each inter
2421+ /// frame's reconstruction predicts from the previous frame's own decoded
2422+ /// reconstruction, so a single sample of drift anywhere would propagate
2423+ /// into every frame after it -- which is why every frame is checked, not
2424+ /// just the last one, and why this is an equality and not a tolerance.
2425+ #[test]
2426+ fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
2427+ if !have_ffmpeg() {
2428+ eprintln!(
2429+ "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
2430+ );
2431+ return;
2432+ }
2433+ let (width, height) = (128usize, 64usize);
2434+ let pictures: Vec<Picture> = (0..5)
2435+ .map(|i| panned_test_card(width, height, i * 3))
2436+ .collect();
2437+ let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
2438+ assert_eq!(encoded.frames.len(), 5);
2439+
2440+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
2441+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
2442+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
2443+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
2444+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
2445+ }
2446+
2447+ eprintln!("frame bytes luma PSNR (dB) inter share");
2448+ for (i, frame) in encoded.frames.iter().enumerate() {
2449+ eprintln!(
2450+ "{i:5} {:5} {:14.2} {:11.2}",
2451+ frame.stream.len(),
2452+ psnr(&frame.reconstruction.y, &pictures[i].y),
2453+ frame.inter_block_share
2454+ );
2455+ }
2456+ }
2457+
2458+ /// Low motion has to actually buy something: at least one inter frame of
2459+ /// a panning sequence has to cost fewer bytes than the key frame that
2460+ /// starts it, and the inter-block share it prints has to be non-zero --
2461+ /// a search that never picks an inter mode would still pass a rate gate
2462+ /// on a picture with no motion in it (the class this repo calls
2463+ /// gate-blind-to-feature), so the share is printed even though it is not
2464+ /// asserted on beyond being reachable at all.
2465+ #[test]
2466+ fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
2467+ let (width, height) = (256usize, 128usize);
2468+ let pictures: Vec<Picture> = (0..5)
2469+ .map(|i| panned_test_card(width, height, i * 2))
2470+ .collect();
2471+ let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
2472+
2473+ let key_bytes = encoded.frames[0].stream.len();
2474+ eprintln!("frame bytes inter share");
2475+ for (i, frame) in encoded.frames.iter().enumerate() {
2476+ eprintln!(
2477+ "{i:5} {:5} {:11.2}",
2478+ frame.stream.len(),
2479+ frame.inter_block_share
2480+ );
2481+ }
2482+ assert!(
2483+ encoded.frames[1..]
2484+ .iter()
2485+ .any(|f| f.stream.len() < key_bytes),
2486+ "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
2487+ );
2488+ assert!(
2489+ encoded.frames[1..]
2490+ .iter()
2491+ .any(|f| f.inter_block_share > 0.0),
2492+ "no inter frame coded a single inter block -- the search never fired"
2493+ );
2494+ }
1582 }2495 }
crates/ec-av1/src/tile.rsmodified+5 -13
@@ -16,7 +16,7 @@ use ec_core::{Error, Result};
16 use crate::cdf;16 use crate::cdf;
17 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};17 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
18 use crate::msac::SymbolEncoder;18 use crate::msac::SymbolEncoder;
19-use crate::mvstack::{find_mv_stack, single_ref_ctx, MiGrid, MiInfo};19+use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
20 20
21 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.21 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
22 const PARTITION_NONE: usize = 0;22 const PARTITION_NONE: usize = 0;
@@ -1369,11 +1369,7 @@ fn intra_inter_ctx(has_above: bool, has_left: bool, above_inter: bool, left_inte
1369 /// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`1369 /// `CLASS0_SIZE << (class + 2)` (spec 3), the magnitude an `MV_CLASS_n`
1370 /// component's own bits start counting from; class zero starts at zero.1370 /// component's own bits start counting from; class zero starts at zero.
1371 fn mv_class_base(class: usize) -> i32 {1371 fn mv_class_base(class: usize) -> i32 {
1372- if class == 0 {1372+ if class == 0 { 0 } else { 2i32 << (class + 2) }
1373- 0
1374- } else {
1375- 2i32 << (class + 2)
1376- }
1377 }1373 }
1378 1374
1379 /// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse1375 /// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in — the inverse
@@ -1688,8 +1684,8 @@ mod tests {
1688 use crate::sequence::sequence_header_obu;1684 use crate::sequence::sequence_header_obu;
1689 use ec_av1_syntax::sequence::SequenceHeader;1685 use ec_av1_syntax::sequence::SequenceHeader;
1690 use ec_av1_syntax::{1686 use ec_av1_syntax::{
1691- FrameHeader, FrameType, LoopFilterParams, QuantizationParams, TileInfo, TxMode,1687+ FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
1692- PRIMARY_REF_NONE,1688+ TxMode,
1693 };1689 };
1694 use std::io::Write;1690 use std::io::Write;
1695 use std::process::{Command, Stdio};1691 use std::process::{Command, Stdio};
@@ -3734,11 +3730,7 @@ mod tests {
3734 (d << 3) | (fr << 1) | 13730 (d << 3) | (fr << 1) | 1
3735 };3731 };
3736 let mag = mv_class_base(class) + local as i32 + 1;3732 let mag = mv_class_base(class) + local as i32 + 1;
3737- if sign == 1 {3733+ if sign == 1 { -mag } else { mag }
3738- -mag
3739- } else {
3740- mag
3741- }
3742 }3734 }
3743 3735
3744 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,3736 /// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,