forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/s8' into simplify/w2

Browse files at this commit

defc0b8843cf20a5c91457de3309c6dddcca465bAhmet Kaan GümüşParent: a72559cabd0111

16 changed files +5371 -5213

crates/ec-h264/src/deblock.rsmodified+505 -0
@@ -2,6 +2,8 @@
2 //! macroblock is intra, so boundary strength is 4 on macroblock edges and 32 //! macroblock is intra, so boundary strength is 4 on macroblock edges and 3
3 //! inside (8.7.2.1) — no motion-vector or reference comparisons yet.3 //! inside (8.7.2.1) — no motion-vector or reference comparisons yet.
4 4
5+use crate::dpb::{FRAME, PicPlane, Picture, SliceParams};
6+use crate::entropy::{FLAG_DECODED, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8};
5 use crate::sample::Sample;7 use crate::sample::Sample;
6 use crate::tables::{ALPHA, BETA, CHROMA_QP, TC0};8 use crate::tables::{ALPHA, BETA, CHROMA_QP, TC0};
7 9
@@ -356,3 +358,506 @@ mod tests {
356 assert!(line[3] != 60 || line[4] != 74);358 assert!(line[3] != 60 || line[4] != 74);
357 }359 }
358 }360 }
361+
362+/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
363+/// vertical edges then all horizontal edges per macroblock, then chroma.
364+// `e` and `j` are edge and segment positions inside the macroblock, used to
365+// index the plane as well as the strength arrays; iterating the arrays would
366+// hide which geometry each one names.
367+#[allow(clippy::needless_range_loop)]
368+pub(crate) fn deblock_picture<S: Sample>(pic: &mut Picture<S>) {
369+ let mb_w = pic.mb_w;
370+ let bd = pic.bd;
371+ let max = (1i32 << bd) - 1;
372+ let qp_bd = 6 * (bd as i32 - 8);
373+ let cmb_h = pic.cmb_h;
374+ let cat = pic.cat;
375+ let lcomps = if cat == 3 { 3 } else { 1 };
376+ for mb_y in 0..pic.mb_h {
377+ for mb_x in 0..mb_w {
378+ let addr = mb_y * mb_w + mb_x;
379+ if pic.mb_flags[addr] & FLAG_DECODED == 0 {
380+ continue;
381+ }
382+ let sid = pic.mb_slice[addr];
383+ let sp = pic.slices[sid as usize];
384+ if sp.disable_deblock_idc == 1 {
385+ continue;
386+ }
387+ let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0;
388+ let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid;
389+ let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1);
390+ let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w);
391+ // Deblocking QP: 0 for I_PCM macroblocks (8.7.2).
392+ let qp_of = |a: usize| -> i32 {
393+ if pic.mb_flags[a] & FLAG_PCM != 0 {
394+ 0
395+ } else {
396+ i32::from(pic.mb_qp[a])
397+ }
398+ };
399+ // 8.7: an 8x8-transform macroblock has no transform edge at luma
400+ // 4 or 12, so those internal edges are not filtered. Chroma is
401+ // unaffected for 4:2:0 (its internal edge sits on luma edge 8).
402+ let internal =
403+ |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0;
404+
405+ // Boundary strengths, per 4-sample segment of each edge (8.7.2.1).
406+ //
407+ // Both sides of an internal edge live in this macroblock, so the
408+ // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra
409+ // macroblock gives 3 everywhere, and an inter macroblock with no
410+ // luma coefficients and one motion vector over the whole 16x16
411+ // gives 0 everywhere. Only the two macroblock edges then need the
412+ // per-segment derivation.
413+ let mut bs_v = [[0u8; 4]; 4];
414+ let mut bs_h = [[0u8; 4]; 4];
415+ let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0;
416+ let internal_uniform = if cur_intra {
417+ Some(3)
418+ } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) {
419+ Some(0)
420+ } else {
421+ None
422+ };
423+ for k in 0..4 {
424+ if filter_left {
425+ bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true);
426+ }
427+ if filter_top {
428+ bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false);
429+ }
430+ }
431+ for e in 1..4 {
432+ match internal_uniform {
433+ Some(bs) => {
434+ bs_v[e] = [bs; 4];
435+ bs_h[e] = [bs; 4];
436+ }
437+ None => {
438+ for k in 0..4 {
439+ bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true);
440+ bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false);
441+ }
442+ }
443+ }
444+ }
445+
446+ // ---- luma (and Cb/Cr, coded like luma, for ChromaArrayType 3) ----
447+ for comp in 0..lcomps {
448+ let pl: &mut PicPlane<S> = match comp {
449+ 0 => &mut pic.y,
450+ 1 => &mut pic.cb,
451+ _ => &mut pic.cr,
452+ };
453+ let stride = pl.stride;
454+ let base = pl.at(mb_x * 16, mb_y * 16);
455+ let qpf = |a: usize| -> i32 {
456+ if comp == 0 {
457+ qp_of(a)
458+ } else {
459+ let s = pic.slices[pic.mb_slice[a] as usize];
460+ let off = if comp == 1 {
461+ s.cb_qp_offset
462+ } else {
463+ s.cr_qp_offset
464+ };
465+ let q = if pic.mb_flags[a] & FLAG_PCM != 0 {
466+ 0
467+ } else {
468+ i32::from(pic.mb_qp[a])
469+ };
470+ chroma_qp(q, off, qp_bd)
471+ }
472+ };
473+ let qp_q = qpf(addr);
474+ // Lossless macroblocks keep their samples (8.7.2.2).
475+ let lossless = |a: usize| {
476+ pic.bypass_enabled
477+ && pic.mb_flags[a] & FLAG_PCM == 0
478+ && i32::from(pic.mb_qp[a]) + qp_bd == 0
479+ };
480+ let (p_ll_v, q_ll) = (filter_left && lossless(addr - 1), lossless(addr));
481+ let snap_v = (p_ll_v || (filter_left && q_ll))
482+ .then(|| snap_edge(&pl.data, base, stride, true));
483+ // Vertical edges (filter across columns), left to right.
484+ for e in 0..4 {
485+ if e == 0 && !filter_left {
486+ continue;
487+ }
488+ if !internal(e) {
489+ continue;
490+ }
491+ let qp_p = if e == 0 { qpf(addr - 1) } else { qp_q };
492+ let qp_avg = (qp_p + qp_q + 1) >> 1;
493+ // Vertical edges stay scalar: a gather/scatter SIMD
494+ // variant measured slower than this loop (strided
495+ // per-lane loads dominate).
496+ for j in 0..4 {
497+ let bs = bs_v[e][j];
498+ if bs == 0 {
499+ continue;
500+ }
501+ let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
502+ if params.alpha == 0 || params.beta == 0 {
503+ continue;
504+ }
505+ for k in 0..4 {
506+ let row = j * 4 + k;
507+ filter_luma_line(
508+ &mut pl.data,
509+ max,
510+ base + row * stride + e * 4,
511+ 1,
512+ &params,
513+ );
514+ }
515+ }
516+ }
517+ if let Some(sv) = &snap_v {
518+ restore_edge(&mut pl.data, sv, base, stride, true, p_ll_v, q_ll);
519+ }
520+ let p_ll_h = filter_top && lossless(addr - mb_w);
521+ let snap_h = (p_ll_h || (filter_top && q_ll))
522+ .then(|| snap_edge(&pl.data, base, stride, false));
523+ // Horizontal edges, top to bottom.
524+ for e in 0..4 {
525+ if e == 0 && !filter_top {
526+ continue;
527+ }
528+ if !internal(e) {
529+ continue;
530+ }
531+ let qp_p = if e == 0 { qpf(addr - mb_w) } else { qp_q };
532+ let qp_avg = (qp_p + qp_q + 1) >> 1;
533+ let bs = bs_h[e];
534+ let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3];
535+ if uniform {
536+ if bs[0] == 0 {
537+ continue;
538+ }
539+ let params =
540+ edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd);
541+ if params.alpha == 0 || params.beta == 0 {
542+ continue;
543+ }
544+ // Eight rows around the edge are contiguous, so the
545+ // whole 16-sample edge filters in one pass.
546+ S::filter_luma_h_edge16(
547+ &mut pl.data,
548+ max,
549+ base + e * 4 * stride,
550+ stride,
551+ &params,
552+ );
553+ continue;
554+ }
555+ for j in 0..4 {
556+ if bs[j] == 0 {
557+ continue;
558+ }
559+ let params =
560+ edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j], bd);
561+ if params.alpha == 0 || params.beta == 0 {
562+ continue;
563+ }
564+ for k in 0..4 {
565+ filter_luma_line(
566+ &mut pl.data,
567+ max,
568+ base + e * 4 * stride + j * 4 + k,
569+ stride,
570+ &params,
571+ );
572+ }
573+ }
574+ }
575+ if let Some(sh) = &snap_h {
576+ restore_edge(&mut pl.data, sh, base, stride, false, p_ll_h, q_ll);
577+ }
578+ }
579+
580+ // ---- chroma (Cb, Cr) ----
581+ for comp in 0..if matches!(cat, 1 | 2) { 2 } else { 0 } {
582+ let (plane, off_sel): (&mut PicPlane<S>, fn(&SliceParams) -> i32) = if comp == 0 {
583+ (&mut pic.cb, |s| s.cb_qp_offset)
584+ } else {
585+ (&mut pic.cr, |s| s.cr_qp_offset)
586+ };
587+ let stride = plane.stride;
588+ let c422 = cat == 2;
589+ let base = plane.origin + (mb_y * cmb_h) * stride + mb_x * 8;
590+ // Chroma QP per side: each macroblock's luma QP mapped with
591+ // the offset of ITS OWN slice's PPS (8.7.2).
592+ let cqp = |a: usize| -> i32 {
593+ let s = pic.slices[pic.mb_slice[a] as usize];
594+ if pic.mb_flags[a] & FLAG_PCM != 0 {
595+ chroma_qp(0, off_sel(&s), qp_bd)
596+ } else {
597+ chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s), qp_bd)
598+ }
599+ };
600+ let cq_q = cqp(addr);
601+ // A chroma edge inherits the boundary strength of the luma edge
602+ // it sits on: chroma sample k maps to luma sample 2k, so a
603+ // chroma 4-sample run spans two luma 4x4 block rows.
604+ for e in 0..2 {
605+ if e == 0 && !filter_left {
606+ continue;
607+ }
608+ let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q };
609+ let qp_avg = (cq_p + cq_q + 1) >> 1;
610+ for k in 0..cmb_h {
611+ let bs = bs_v[e * 2][k >> if c422 { 2 } else { 1 }];
612+ if bs == 0 {
613+ continue;
614+ }
615+ let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
616+ if params.alpha == 0 || params.beta == 0 {
617+ continue;
618+ }
619+ filter_chroma_line(
620+ &mut plane.data,
621+ max,
622+ base + k * stride + e * 4,
623+ 1,
624+ &params,
625+ );
626+ }
627+ }
628+ // 4:2:2 chroma is as tall as luma: its horizontal 4x4 transform
629+ // edges sit at rows 0, 4, 8 and 12, each on the boundary
630+ // strength of the luma edge on the same row.
631+ for e in 0..if c422 { 4 } else { 2 } {
632+ if e == 0 && !filter_top {
633+ continue;
634+ }
635+ let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q };
636+ let qp_avg = (cq_p + cq_q + 1) >> 1;
637+ let bs = bs_h[if c422 { e } else { e * 2 }];
638+ if bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3] {
639+ if bs[0] == 0 {
640+ continue;
641+ }
642+ let params =
643+ edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd);
644+ if params.alpha == 0 || params.beta == 0 {
645+ continue;
646+ }
647+ // The four rows around the edge are contiguous, so the
648+ // whole eight-sample edge filters in one pass.
649+ S::filter_chroma_h_edge8(
650+ &mut plane.data,
651+ max,
652+ base + e * 4 * stride,
653+ stride,
654+ &params,
655+ );
656+ continue;
657+ }
658+ for k in 0..8 {
659+ let bs = bs[k / 2];
660+ if bs == 0 {
661+ continue;
662+ }
663+ let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
664+ if params.alpha == 0 || params.beta == 0 {
665+ continue;
666+ }
667+ filter_chroma_line(
668+ &mut plane.data,
669+ max,
670+ base + e * 4 * stride + k,
671+ stride,
672+ &params,
673+ );
674+ }
675+ }
676+ }
677+ }
678+ }
679+}
680+
681+/// Copy the 8 samples across a macroblock edge (4 each side) along its 16
682+/// samples, so a lossless side can be put back after the filter ran.
683+fn snap_edge<S: Sample>(data: &[S], base: usize, stride: usize, vertical: bool) -> Vec<S> {
684+ let mut v = Vec::with_capacity(128);
685+ for i in 0..16 {
686+ for d in 0..8 {
687+ v.push(if vertical {
688+ data[base + i * stride + d - 4]
689+ } else {
690+ data[base + d * stride + i - 4 * stride]
691+ });
692+ }
693+ }
694+ v
695+}
696+
697+fn restore_edge<S: Sample>(
698+ data: &mut [S],
699+ snap: &[S],
700+ base: usize,
701+ stride: usize,
702+ vertical: bool,
703+ p: bool,
704+ q: bool,
705+) {
706+ for i in 0..16 {
707+ for d in 0..8 {
708+ if (d < 4 && !p) || (d >= 4 && !q) {
709+ continue;
710+ }
711+ let idx = if vertical {
712+ base + i * stride + d - 4
713+ } else {
714+ base + d * stride + i - 4 * stride
715+ };
716+ data[idx] = snap[i * 8 + d];
717+ }
718+ }
719+}
720+
721+/// True when every 4x4 block of this macroblock predicts from the same
722+/// pictures with the same motion, so no internal edge can reach the motion
723+/// clauses of 8.7.2.1.
724+fn uniform_motion<S: Sample>(pic: &Picture<S>, mb_x: usize, mb_y: usize) -> bool {
725+ let w4 = pic.mb_w * 4;
726+ let first = mb_y * 4 * w4 + mb_x * 4;
727+ let (mv, id) = (pic.mv[first], pic.ref_id[first]);
728+ (0..4).all(|by| {
729+ let row = first + by * w4;
730+ (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id)
731+ })
732+}
733+
734+/// What clause 8.7.2.1 needs from the 4x4 block on one side of a luma edge.
735+#[derive(Clone, Copy)]
736+pub(crate) struct BsSide {
737+ /// The containing macroblock is intra: strength 4 on macroblock edges and
738+ /// 3 on internal ones, regardless of motion or levels.
739+ pub(crate) intra: bool,
740+ /// The transform block containing this sample has non-zero levels.
741+ pub(crate) coded: bool,
742+ /// MvLX of the block, `[list][component]`.
743+ pub(crate) mv: [[i16; 2]; 2],
744+ /// RefIdxLX of the block as list identities (`Picture::id`), -1 unused.
745+ pub(crate) refs: [i32; 2],
746+}
747+
748+/// Boundary strength between the 4x4 blocks on the two sides of a luma edge
749+/// (clause 8.7.2.1). `mb_edge` selects the macroblock-edge strengths 4/3.
750+pub(crate) fn bs_between(p: &BsSide, q: &BsSide, mb_edge: bool, field: bool, vertical: bool) -> u8 {
751+ if p.intra || q.intra {
752+ // A horizontal edge of a field picture is never strength 4 (8.7.2.1).
753+ return if mb_edge && (vertical || !field) {
754+ 4
755+ } else {
756+ 3
757+ };
758+ }
759+ if p.coded || q.coded {
760+ return 2;
761+ }
762+ let (pr, qr) = (p.refs, q.refs);
763+ let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0);
764+ let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0);
765+ if pn != qn {
766+ return 1;
767+ }
768+ let (pm, qm) = (p.mv, q.mv);
769+ // The vertical limit is 4 quarter frame samples: 2 in field units.
770+ let ylim = if field { 2 } else { 4 };
771+ let differs = |a: [i16; 2], b: [i16; 2]| {
772+ (i32::from(a[0]) - i32::from(b[0])).abs() >= 4
773+ || (i32::from(a[1]) - i32::from(b[1])).abs() >= ylim
774+ };
775+ if pn == 1 {
776+ let pl = usize::from(pr[0] < 0);
777+ let ql = usize::from(qr[0] < 0);
778+ if pr[pl] != qr[ql] {
779+ return 1;
780+ }
781+ return u8::from(differs(pm[pl], qm[ql]));
782+ }
783+ if pn == 0 {
784+ return 0;
785+ }
786+ // Two motion vectors each: compare the two partitions by which pictures
787+ // they reference, not by list position (NOTE 1 of 8.7.2.1).
788+ let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]);
789+ if !same_set {
790+ return 1;
791+ }
792+ if pr[0] != pr[1] {
793+ return if pr[0] == qr[0] {
794+ u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1]))
795+ } else {
796+ u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0]))
797+ };
798+ }
799+ // Both lists name the same picture: either pairing agreeing is enough.
800+ let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]);
801+ let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]);
802+ u8::from(!(straight || crossed))
803+}
804+
805+/// One side of a luma edge from picture state: the decoder path, both sides
806+/// final macroblocks. The encoder's inter trial uses this for the
807+/// already-coded neighbour and builds its candidate side itself.
808+pub(crate) fn bs_side<S: Sample>(pic: &Picture<S>, bx: usize, by: usize) -> BsSide {
809+ let w4 = pic.mb_w * 4;
810+ let mb = (by / 4) * pic.mb_w + bx / 4;
811+ BsSide {
812+ intra: pic.mb_flags[mb] & FLAG_INTER == 0,
813+ coded: bs_coded(pic, mb, bx, by),
814+ mv: pic.mv[by * w4 + bx],
815+ refs: pic.ref_id[by * w4 + bx],
816+ }
817+}
818+
819+/// "The transform block containing the sample has non-zero levels": for an
820+/// 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots
821+/// carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks).
822+fn bs_coded<S: Sample>(pic: &Picture<S>, mb: usize, bx: usize, by: usize) -> bool {
823+ let w4 = pic.mb_w * 4;
824+ if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 {
825+ return pic.nz_y[by * w4 + bx] != 0;
826+ }
827+ let (ox, oy) = (bx & !1, by & !1);
828+ pic.nz_y[oy * w4 + ox] != 0
829+ || pic.nz_y[oy * w4 + ox + 1] != 0
830+ || pic.nz_y[(oy + 1) * w4 + ox] != 0
831+ || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0
832+}
833+
834+/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1).
835+///
836+/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the
837+/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge.
838+fn boundary_strength<S: Sample>(
839+ pic: &Picture<S>,
840+ mb_x: usize,
841+ mb_y: usize,
842+ edge: usize,
843+ seg: usize,
844+ vertical: bool,
845+) -> u8 {
846+ let (qbx, qby) = if vertical {
847+ (mb_x * 4 + edge, mb_y * 4 + seg)
848+ } else {
849+ (mb_x * 4 + seg, mb_y * 4 + edge)
850+ };
851+ let (pbx, pby) = if vertical {
852+ (qbx - 1, qby)
853+ } else {
854+ (qbx, qby - 1)
855+ };
856+ bs_between(
857+ &bs_side(pic, pbx, pby),
858+ &bs_side(pic, qbx, qby),
859+ edge == 0,
860+ pic.structure != FRAME,
861+ vertical,
862+ )
863+}
crates/ec-h264/src/deblock_mbaff.rsmodified+1 -1
@@ -19,7 +19,7 @@
19 //! progressive filter stays the one the speed budget is spent on.19 //! progressive filter stays the one the speed budget is spent on.
20 20
21 use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line};21 use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line};
22-use crate::decoder::{BsSide, bs_between, bs_side};22+use crate::deblock::{BsSide, bs_between, bs_side};
23 use crate::dpb::{PicPlane, Picture, SliceParams};23 use crate::dpb::{PicPlane, Picture, SliceParams};
24 use crate::entropy::{FLAG_DECODED, FLAG_PCM, FLAG_TRANS8X8};24 use crate::entropy::{FLAG_DECODED, FLAG_PCM, FLAG_TRANS8X8};
25 use crate::sample::Sample;25 use crate::sample::Sample;
crates/ec-h264/src/decoder.rsmodified+87 -1725

Diff too large; view file

@@ -19,6 +19,7 @@
19 //! caller that wants pictures as they are decoded.19 //! caller that wants pictures as they are decoded.
20 20
21 use std::collections::VecDeque;21 use std::collections::VecDeque;
22+use std::sync::Arc;
22 23
23 use ec_core::BitReader;24 use ec_core::BitReader;
24 use ec_core::error::{Error, Result};25 use ec_core::error::{Error, Result};
@@ -29,32 +30,32 @@ use ec_h264_syntax::{
29 SliceType, Sps, WeightEntry, unescape_rbsp,30 SliceType, Sps, WeightEntry, unescape_rbsp,
30 };31 };
31 32
32-use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line};33+use crate::deblock::{chroma_qp, deblock_picture};
33 use crate::dpb::{34 use crate::dpb::{
34- BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE,35+ BLK_DIRECT, BLK_SKIP, BOTTOM, CODED_AFRM, Dpb, FRAME, Mark, NO_SLICE,
35 PicInfo, PicPlane, Picture, RefList, SliceParams, TOP,36 PicInfo, PicPlane, Picture, RefList, SliceParams, TOP,
36 };37 };
37 use crate::entropy::{38 use crate::entropy::{
38 BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM,39 BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM,
39 FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, MbaffA,40 FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, MbaffA,
40 };41 };
41-use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma};42+use crate::direct::{predict_direct, predict_direct_8x8};
43+use crate::inter::Weights;
42 use crate::mbaff::{self, MbPos};44 use crate::mbaff::{self, MbPos};
43 use crate::mv::{45 use crate::mv::{
44- B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd,46+ B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, neighbour_mvd,
45 predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,47 predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,
46 };48 };
47 use crate::pred::{49 use crate::pred::{
48- Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_8x8, add_residual_dpcm, filter_nbr8,50+ Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_dpcm, pred_chroma_8x8_halves,
49- pred_4x4, pred_8x8, pred_16x16, pred_chroma_8x8_halves, pred_chroma_8x16,51+ pred_chroma_8x16,
50 };52 };
53+use crate::residual::residual_luma_style;
51 use crate::sample::Sample;54 use crate::sample::Sample;
52 use crate::tables::BLK4_POS;55 use crate::tables::BLK4_POS;
53 use crate::transform::{56 use crate::transform::{
54 CHROMA_DC_422_RASTER, LevelScale4x4, LevelScale8x8, chroma_dc_transform_420,57 CHROMA_DC_422_RASTER, LevelScale4x4, LevelScale8x8, chroma_dc_transform_420,
55- chroma_dc_transform_422, dequant_4x4, dequant_8x8, inverse_transform_4x4,58+ chroma_dc_transform_422, dequant_4x4, inverse_transform_4x4, unfield_ac15, unzigzag_ac15,
56- inverse_transform_8x8, luma_dc_transform, unfield, unfield_8x8, unfield_ac15, unzigzag,
57- unzigzag_8x8, unzigzag_ac15,
58 };59 };
59 60
60 /// Where a 4x4 block's top-right neighbour samples come from, per61 /// Where a 4x4 block's top-right neighbour samples come from, per
@@ -105,8 +106,8 @@ pub enum OutputOrder {
105 106
106 /// The decode core, generic over the sample type of the pictures it holds.107 /// The decode core, generic over the sample type of the pictures it holds.
107 pub(crate) struct Core<S: Sample> {108 pub(crate) struct Core<S: Sample> {
108- sps_map: Vec<Option<Sps>>,109+ sps_map: Vec<Option<Arc<Sps>>>,
109- pps_map: Vec<Option<Pps>>,110+ pps_map: Vec<Option<Arc<Pps>>>,
110 rbsp: Vec<u8>,111 rbsp: Vec<u8>,
111 /// The picture being decoded, held out of the buffer pool.112 /// The picture being decoded, held out of the buffer pool.
112 cur: Picture<S>,113 cur: Picture<S>,
@@ -635,7 +636,7 @@ impl<S: Sample> Core<S> {
635 let sps = sps?;636 let sps = sps?;
636 let id = sps.id;637 let id = sps.id;
637 self.dpb.configure(&sps);638 self.dpb.configure(&sps);
638- self.sps_map[id as usize] = Some(sps);639+ self.sps_map[id as usize] = Some(Arc::new(sps));
639 self.active_pps = None;640 self.active_pps = None;
640 self.last_sps = Some(id);641 self.last_sps = Some(id);
641 Ok(NalOutcome::ParameterSet)642 Ok(NalOutcome::ParameterSet)
@@ -643,11 +644,11 @@ impl<S: Sample> Core<S> {
643 NalUnitType::Pps => {644 NalUnitType::Pps => {
644 let mut rbsp = core::mem::take(&mut self.rbsp);645 let mut rbsp = core::mem::take(&mut self.rbsp);
645 unescape_rbsp(payload, &mut rbsp);646 unescape_rbsp(payload, &mut rbsp);
646- let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref());647+ let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_deref());
647 self.rbsp = rbsp;648 self.rbsp = rbsp;
648 let pps = pps?;649 let pps = pps?;
649 let id = pps.id as usize;650 let id = pps.id as usize;
650- self.pps_map[id] = Some(pps);651+ self.pps_map[id] = Some(Arc::new(pps));
651 // A re-sent PPS may carry other scaling lists: rebuild the level scales.652 // A re-sent PPS may carry other scaling lists: rebuild the level scales.
652 self.active_pps = None;653 self.active_pps = None;
653 Ok(NalOutcome::ParameterSet)654 Ok(NalOutcome::ParameterSet)
@@ -691,7 +692,7 @@ impl<S: Sample> Core<S> {
691 let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc);692 let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc);
692 let sps_id = self.cur.sps_id as usize;693 let sps_id = self.cur.sps_id as usize;
693 let sps = self.sps_map[sps_id]694 let sps = self.sps_map[sps_id]
694- .take()695+ .clone()
695 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;696 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
696 let pic = core::mem::take(&mut self.cur);697 let pic = core::mem::take(&mut self.cur);
697 let marking = self.has_marking.then_some(&self.cur_marking);698 let marking = self.has_marking.then_some(&self.cur_marking);
@@ -702,7 +703,6 @@ impl<S: Sample> Core<S> {
702 self.dpb703 self.dpb
703 .store(pic, &sps, &self.cur_info, marking, output_ok)704 .store(pic, &sps, &self.cur_info, marking, output_ok)
704 };705 };
705- self.sps_map[sps_id] = Some(sps);
706 stored?;706 stored?;
707 if self.dpb.interlaced {707 if self.dpb.interlaced {
708 // The picture a caller asks for is the frame store, which a field708 // The picture a caller asks for is the frame store, which a field
@@ -826,14 +826,11 @@ impl<S: Sample> Core<S> {
826 copy(&pic.cr, cx_c, cy_c, cw_c, ch_c),826 copy(&pic.cr, cx_c, cy_c, cw_c, ch_c),
827 ];827 ];
828 let mut frame = VideoFrame::try_new(828 let mut frame = VideoFrame::try_new(
829- match (pic.cat, S::IS_8) {829+ S::FORMATS[match pic.cat {
830- (3, true) => PixelFormat::I444,830+ 3 => 0,
831- (3, false) => PixelFormat::I410,831+ 2 => 1,
832- (2, true) => PixelFormat::I422,832+ _ => 2,
833- (2, false) => PixelFormat::I210,833+ }],
834- (_, true) => PixelFormat::I420,
835- (_, false) => PixelFormat::I010,
836- },
837 w as u32,834 w as u32,
838 h as u32,835 h as u32,
839 planes,836 planes,
@@ -869,14 +866,13 @@ impl<S: Sample> Core<S> {
869 return Err(Error::corrupt("pic_parameter_set_id > 255"));866 return Err(Error::corrupt("pic_parameter_set_id > 255"));
870 }867 }
871 let pps = self.pps_map[pps_id as usize]868 let pps = self.pps_map[pps_id as usize]
872- .as_ref()869+ .clone()
873 .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?;870 .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?;
874 let sps = self.sps_map[pps.sps_id as usize]871 let sps = self.sps_map[pps.sps_id as usize]
875- .as_ref()872+ .clone()
876 .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?;873 .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?;
877-874+ let sh = SliceHeader::parse(rbsp, header, &sps, &pps)?;
878- check_supported::<S>(sps, pps, slice_type_code, self.wide)?;875+ check_supported::<S>(&sps, &pps, slice_type_code, self.wide)?;
879- let sh = SliceHeader::parse(rbsp, header, sps, pps)?;
880 if self.has_picture && !self.cur.complete {876 if self.has_picture && !self.cur.complete {
881 let same_picture = self.cur_key == Some(PicKey::of(&sh, header));877 let same_picture = self.cur_key == Some(PicKey::of(&sh, header));
882 // A picture starts again at macroblock 0 once macroblock 0 is878 // A picture starts again at macroblock 0 once macroblock 0 is
@@ -892,16 +888,7 @@ impl<S: Sample> Core<S> {
892 // Redundant coded slices (7.4.3) repeat primary data: ignored.888 // Redundant coded slices (7.4.3) repeat primary data: ignored.
893 return Ok(NalOutcome::Skipped);889 return Ok(NalOutcome::Skipped);
894 }890 }
895- // Borrow the parameter sets out of their slots for the duration of the891+ self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb)
896- // slice: cloning them per slice would allocate, and a decode loop that
897- // allocates per slice is the thing the whole layout is built to avoid.
898- let sps_slot = pps.sps_id as usize;
899- let sps = self.sps_map[sps_slot].take().expect("checked above");
900- let pps = self.pps_map[pps_id as usize].take().expect("checked above");
901- let outcome = self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb);
902- self.sps_map[sps_slot] = Some(sps);
903- self.pps_map[pps_id as usize] = Some(pps);
904- outcome
905 }892 }
906 893
907 #[allow(clippy::too_many_arguments)]894 #[allow(clippy::too_many_arguments)]
@@ -1560,71 +1547,71 @@ fn check_supported<S: Sample>(
1560 1547
1561 /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value.1548 /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value.
1562 #[derive(Clone, Copy)]1549 #[derive(Clone, Copy)]
1563-struct Geo {1550+pub(crate) struct Geo {
1564- src_y: usize,1551+ pub(crate) src_y: usize,
1565- dst_y: usize,1552+ pub(crate) dst_y: usize,
1566- dst_cy: usize,1553+ pub(crate) dst_cy: usize,
1567- mul: usize,1554+ pub(crate) mul: usize,
1568 }1555 }
1569 1556
1570 impl Geo {1557 impl Geo {
1571 /// Picture row of luma row `r` of the macroblock.1558 /// Picture row of luma row `r` of the macroblock.
1572 #[inline]1559 #[inline]
1573- fn y(&self, r: usize) -> usize {1560+ pub(crate) fn y(&self, r: usize) -> usize {
1574 self.dst_y + r * self.mul1561 self.dst_y + r * self.mul
1575 }1562 }
1576 1563
1577 /// Picture row of chroma row `r` of the macroblock.1564 /// Picture row of chroma row `r` of the macroblock.
1578 #[inline]1565 #[inline]
1579- fn cy(&self, r: usize) -> usize {1566+ pub(crate) fn cy(&self, r: usize) -> usize {
1580 self.dst_cy + r * self.mul1567 self.dst_cy + r * self.mul
1581 }1568 }
1582 }1569 }
1583 1570
1584 /// Mutable per-slice decode state.1571 /// Mutable per-slice decode state.
1585 pub(crate) struct SliceCtx {1572 pub(crate) struct SliceCtx {
1586- slice_id: u16,1573+ pub(crate) slice_id: u16,
1587- slice_type: SliceType,1574+ pub(crate) slice_type: SliceType,
1588- qp: i32,1575+ pub(crate) qp: i32,
1589- cb_qp_offset: i32,1576+ pub(crate) cb_qp_offset: i32,
1590- cr_qp_offset: i32,1577+ pub(crate) cr_qp_offset: i32,
1591 /// Chroma rows per macroblock: 8 (4:2:0) or 16 (4:2:2).1578 /// Chroma rows per macroblock: 8 (4:2:0) or 16 (4:2:2).
1592- cmb_h: usize,1579+ pub(crate) cmb_h: usize,
1593 /// ChromaArrayType of the picture being decoded.1580 /// ChromaArrayType of the picture being decoded.
1594- cat: u8,1581+ pub(crate) cat: u8,
1595- transform_8x8_mode: bool,1582+ pub(crate) transform_8x8_mode: bool,
1596- constrained_intra_pred: bool,1583+ pub(crate) constrained_intra_pred: bool,
1597 /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the1584 /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the
1598 /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5).1585 /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5).
1599- qp_delta_inc: u8,1586+ pub(crate) qp_delta_inc: u8,
1600 /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices.1587 /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices.
1601- lists: [RefList; 2],1588+ pub(crate) lists: [RefList; 2],
1602- num_ref_idx: [usize; 2],1589+ pub(crate) num_ref_idx: [usize; 2],
1603- direct_spatial: bool,1590+ pub(crate) direct_spatial: bool,
1604- direct_8x8_inference: bool,1591+ pub(crate) direct_8x8_inference: bool,
1605- weighted_pred: bool,1592+ pub(crate) weighted_pred: bool,
1606- weighted_bipred_idc: u8,1593+ pub(crate) weighted_bipred_idc: u8,
1607- weights: Option<PredWeightTable>,1594+ pub(crate) weights: Option<PredWeightTable>,
1608 /// `PicOrderCnt( CurrPic )`.1595 /// `PicOrderCnt( CurrPic )`.
1609- poc: i32,1596+ pub(crate) poc: i32,
1610 /// `TopFieldOrderCnt` and `BottomFieldOrderCnt` of the current picture.1597 /// `TopFieldOrderCnt` and `BottomFieldOrderCnt` of the current picture.
1611- fpoc: [i32; 2],1598+ pub(crate) fpoc: [i32; 2],
1612 /// Structure of the picture being decoded: [`FRAME`], [`TOP`] or [`BOTTOM`].1599 /// Structure of the picture being decoded: [`FRAME`], [`TOP`] or [`BOTTOM`].
1613- structure: u8,1600+ pub(crate) structure: u8,
1614 /// Parity of the macroblock being decoded when it is a field macroblock1601 /// Parity of the macroblock being decoded when it is a field macroblock
1615 /// ([`TOP`] or [`BOTTOM`]), [`FRAME`] for a frame macroblock. In a field1602 /// ([`TOP`] or [`BOTTOM`]), [`FRAME`] for a frame macroblock. In a field
1616 /// picture this is the picture's own parity.1603 /// picture this is the picture's own parity.
1617- mb_parity: u8,1604+ pub(crate) mb_parity: u8,
1618 /// Where the macroblock being decoded sits when the picture is an MBAFF1605 /// Where the macroblock being decoded sits when the picture is an MBAFF
1619 /// frame (`pos.active`); inert otherwise.1606 /// frame (`pos.active`); inert otherwise.
1620- pos: MbPos,1607+ pub(crate) pos: MbPos,
1621 }1608 }
1622 1609
1623 impl SliceCtx {1610 impl SliceCtx {
1624 /// `PicOrderCnt` of the current picture, or of the field of the current1611 /// `PicOrderCnt` of the current picture, or of the field of the current
1625 /// macroblock's parity for a field macroblock of an MBAFF frame (8.4.1.2.3, 8.4.2.3.1).1612 /// macroblock's parity for a field macroblock of an MBAFF frame (8.4.1.2.3, 8.4.2.3.1).
1626 #[inline]1613 #[inline]
1627- fn cur_poc(&self) -> i32 {1614+ pub(crate) fn cur_poc(&self) -> i32 {
1628 if self.pos.active && self.pos.field {1615 if self.pos.active && self.pos.field {
1629 self.fpoc[usize::from(self.mb_parity == BOTTOM)]1616 self.fpoc[usize::from(self.mb_parity == BOTTOM)]
1630 } else {1617 } else {
@@ -1632,14 +1619,14 @@ impl SliceCtx {
1632 }1619 }
1633 }1620 }
1634 1621
1635- fn is_b(&self) -> bool {1622+ pub(crate) fn is_b(&self) -> bool {
1636 self.slice_type == SliceType::B1623 self.slice_type == SliceType::B
1637 }1624 }
1638 1625
1639 /// The reference picture `RefPicListX[idx]` points at: a frame, or one1626 /// The reference picture `RefPicListX[idx]` points at: a frame, or one
1640 /// field of a stored frame.1627 /// field of a stored frame.
1641 #[inline(always)]1628 #[inline(always)]
1642- fn reference<'a, S: Sample>(1629+ pub(crate) fn reference<'a, S: Sample>(
1643 &self,1630 &self,
1644 refs: &'a [Picture<S>],1631 refs: &'a [Picture<S>],
1645 list: usize,1632 list: usize,
@@ -1664,7 +1651,7 @@ impl SliceCtx {
1664 1651
1665 /// [`SliceCtx::reference`] for a field macroblock of an MBAFF frame.1652 /// [`SliceCtx::reference`] for a field macroblock of an MBAFF frame.
1666 #[inline(never)]1653 #[inline(never)]
1667- fn field_mb_reference<'a, S: Sample>(1654+ pub(crate) fn field_mb_reference<'a, S: Sample>(
1668 &self,1655 &self,
1669 refs: &'a [Picture<S>],1656 refs: &'a [Picture<S>],
1670 list: usize,1657 list: usize,
@@ -1683,7 +1670,7 @@ impl SliceCtx {
1683 1670
1684 /// True while decoding a field picture or a field macroblock.1671 /// True while decoding a field picture or a field macroblock.
1685 #[inline]1672 #[inline]
1686- fn is_field(&self) -> bool {1673+ pub(crate) fn is_field(&self) -> bool {
1687 self.mb_parity != FRAME1674 self.mb_parity != FRAME
1688 }1675 }
1689 1676
@@ -1691,7 +1678,7 @@ impl SliceCtx {
1691 /// row of its first luma row (motion compensation reads fields at field1678 /// row of its first luma row (motion compensation reads fields at field
1692 /// row positions), the picture row it is written at, and the row step.1679 /// row positions), the picture row it is written at, and the row step.
1693 #[inline]1680 #[inline]
1694- fn geo(&self, mb_y: usize) -> Geo {1681+ pub(crate) fn geo(&self, mb_y: usize) -> Geo {
1695 if self.pos.active && self.pos.field {1682 if self.pos.active && self.pos.field {
1696 Geo {1683 Geo {
1697 src_y: (mb_y / 2) * 16,1684 src_y: (mb_y / 2) * 16,
@@ -1713,7 +1700,7 @@ impl SliceCtx {
1713 /// a prediction from `rp`: fields of opposite parity sit half a field line1700 /// a prediction from `rp`: fields of opposite parity sit half a field line
1714 /// apart, which is a quarter of a chroma sample.1701 /// apart, which is a quarter of a chroma sample.
1715 #[inline]1702 #[inline]
1716- fn chroma_dy<S: Sample>(&self, rp: &Picture<S>) -> i16 {1703+ pub(crate) fn chroma_dy<S: Sample>(&self, rp: &Picture<S>) -> i16 {
1717 if self.cat != 1 {1704 if self.cat != 1 {
1718 // Tables 8-9 and 8-10 apply to ChromaArrayType 1 only.1705 // Tables 8-9 and 8-10 apply to ChromaArrayType 1 only.
1719 return 0;1706 return 0;
@@ -1729,12 +1716,12 @@ impl SliceCtx {
1729 /// component of every partition resolves to [`Weights::DEFAULT`] without1716 /// component of every partition resolves to [`Weights::DEFAULT`] without
1730 /// the per-component lookup: neither weighted prediction (P) nor1717 /// the per-component lookup: neither weighted prediction (P) nor
1731 /// weighted/bi-prediction (B) is signalled.1718 /// weighted/bi-prediction (B) is signalled.
1732- fn no_weights(&self) -> bool {1719+ pub(crate) fn no_weights(&self) -> bool {
1733 self.weighted_bipred_idc == 0 && !self.weighted_pred1720 self.weighted_bipred_idc == 0 && !self.weighted_pred
1734 }1721 }
1735 1722
1736 /// Prediction weights of one component (clause 8.4.3).1723 /// Prediction weights of one component (clause 8.4.3).
1737- fn weights_for<S: Sample>(1724+ pub(crate) fn weights_for<S: Sample>(
1738 &self,1725 &self,
1739 refs: &[Picture<S>],1726 refs: &[Picture<S>],
1740 comp: usize,1727 comp: usize,
@@ -1931,7 +1918,7 @@ pub(crate) fn luma_nz_pair<S: Sample>(
1931 /// The count grid of colour component `comp` laid out like the luma one: `nz_y`,1918 /// The count grid of colour component `comp` laid out like the luma one: `nz_y`,
1932 /// or for 4:4:4 the Cb / Cr grids, which are coded like luma.1919 /// or for 4:4:4 the Cb / Cr grids, which are coded like luma.
1933 #[inline]1920 #[inline]
1934-fn nz_grid<S: Sample>(pic: &Picture<S>, comp: usize) -> &[u8] {1921+pub(crate) fn nz_grid<S: Sample>(pic: &Picture<S>, comp: usize) -> &[u8] {
1935 if comp == 0 {1922 if comp == 0 {
1936 &pic.nz_y1923 &pic.nz_y
1937 } else {1924 } else {
@@ -1940,7 +1927,7 @@ fn nz_grid<S: Sample>(pic: &Picture<S>, comp: usize) -> &[u8] {
1940 }1927 }
1941 1928
1942 #[inline]1929 #[inline]
1943-fn nz_grid_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut [u8] {1930+pub(crate) fn nz_grid_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut [u8] {
1944 if comp == 0 {1931 if comp == 0 {
1945 &mut pic.nz_y1932 &mut pic.nz_y
1946 } else {1933 } else {
@@ -1950,7 +1937,7 @@ fn nz_grid_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut [u8] {
1950 1937
1951 /// [`luma_nz_pair`] over an explicit count grid (`mb_w * 4` wide).1938 /// [`luma_nz_pair`] over an explicit count grid (`mb_w * 4` wide).
1952 #[inline]1939 #[inline]
1953-fn nz_pair_in<S: Sample>(1940+pub(crate) fn nz_pair_in<S: Sample>(
1954 pic: &Picture<S>,1941 pic: &Picture<S>,
1955 grid: &[u8],1942 grid: &[u8],
1956 n: &MbNeighbors,1943 n: &MbNeighbors,
@@ -1975,7 +1962,7 @@ fn nz_pair_in<S: Sample>(
1975 /// (9.3.3.1.1.9, ctxBlockCat 5, 9, 13): a neighbouring macroblock that did not1962 /// (9.3.3.1.1.9, ctxBlockCat 5, 9, 13): a neighbouring macroblock that did not
1976 /// use the 8x8 transform has no 8x8 block there, which counts as "not coded"1963 /// use the 8x8 transform has no 8x8 block there, which counts as "not coded"
1977 /// (I_PCM counts as coded).1964 /// (I_PCM counts as coded).
1978-fn nz_pair_8x8<S: Sample>(1965+pub(crate) fn nz_pair_8x8<S: Sample>(
1979 pic: &Picture<S>,1966 pic: &Picture<S>,
1980 comp: usize,1967 comp: usize,
1981 n: &MbNeighbors,1968 n: &MbNeighbors,
@@ -2095,13 +2082,13 @@ fn build_mb_ctx<S: Sample>(
2095 2082
2096 /// Motion data parsed for one macroblock, before prediction derivation.2083 /// Motion data parsed for one macroblock, before prediction derivation.
2097 #[derive(Clone, Copy)]2084 #[derive(Clone, Copy)]
2098-struct MbMotion {2085+pub(crate) struct MbMotion {
2099 /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock.2086 /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock.
2100- sub: [SubShape; 4],2087+ pub(crate) sub: [SubShape; 4],
2101 /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list.2088 /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list.
2102- ref_idx: [[i8; 4]; 2],2089+ pub(crate) ref_idx: [[i8; 4]; 2],
2103 /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position.2090 /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position.
2104- mvd: [[[i16; 2]; 16]; 2],2091+ pub(crate) mvd: [[[i16; 2]; 16]; 2],
2105 }2092 }
2106 2093
2107 /// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp`2094 /// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp`
@@ -2408,30 +2395,30 @@ fn fill_chroma_nz<S: Sample>(pic: &mut Picture<S>, mb_x: usize, mb_y: usize, val
2408 }2395 }
2409 2396
2410 /// Everything the shared residual path needs after prediction is decided.2397 /// Everything the shared residual path needs after prediction is decided.
2411-struct MbFinish {2398+pub(crate) struct MbFinish {
2412 /// Neighbour availability for *prediction*, which honours2399 /// Neighbour availability for *prediction*, which honours
2413 /// constrained_intra_pred_flag. The residual contexts use the plain2400 /// constrained_intra_pred_flag. The residual contexts use the plain
2414 /// availability instead — clause 9.2.1 and 9.3.3.1.1.9 only exclude an2401 /// availability instead — clause 9.2.1 and 9.3.3.1.1.9 only exclude an
2415 /// inter neighbour there when slice data partitioning is in use, and this2402 /// inter neighbour there when slice data partitioning is in use, and this
2416 /// decoder refuses partitioned slices outright.2403 /// decoder refuses partitioned slices outright.
2417- pred_nbr: MbNeighbors,2404+ pub(crate) pred_nbr: MbNeighbors,
2418- is_i16: bool,2405+ pub(crate) is_i16: bool,
2419- i16_mode: u8,2406+ pub(crate) i16_mode: u8,
2420- cbp_luma: u8,2407+ pub(crate) cbp_luma: u8,
2421- cbp_chroma: u8,2408+ pub(crate) cbp_chroma: u8,
2422- modes: [u8; 16],2409+ pub(crate) modes: [u8; 16],
2423 /// Intra8x8PredMode per 8x8 block, when `trans8x8` and `intra`.2410 /// Intra8x8PredMode per 8x8 block, when `trans8x8` and `intra`.
2424- modes8: [u8; 4],2411+ pub(crate) modes8: [u8; 4],
2425 /// transform_size_8x8_flag: the luma residual is four 8x8 transform blocks.2412 /// transform_size_8x8_flag: the luma residual is four 8x8 transform blocks.
2426- trans8x8: bool,2413+ pub(crate) trans8x8: bool,
2427- chroma_mode: u8,2414+ pub(crate) chroma_mode: u8,
2428- intra: bool,2415+ pub(crate) intra: bool,
2429- flags: u8,2416+ pub(crate) flags: u8,
2430 }2417 }
2431 2418
2432 /// The plane of colour component `comp` (0 Y, 1 Cb, 2 Cr).2419 /// The plane of colour component `comp` (0 Y, 1 Cb, 2 Cr).
2433 #[inline]2420 #[inline]
2434-fn plane_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut PicPlane<S> {2421+pub(crate) fn plane_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut PicPlane<S> {
2435 match comp {2422 match comp {
2436 0 => &mut pic.y,2423 0 => &mut pic.y,
2437 1 => &mut pic.cb,2424 1 => &mut pic.cb,
@@ -2440,7 +2427,7 @@ fn plane_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut PicPlane<S> {
2440 }2427 }
2441 2428
2442 #[inline]2429 #[inline]
2443-fn plane_ref<S: Sample>(pic: &Picture<S>, comp: usize) -> &PicPlane<S> {2430+pub(crate) fn plane_ref<S: Sample>(pic: &Picture<S>, comp: usize) -> &PicPlane<S> {
2444 match comp {2431 match comp {
2445 0 => &pic.y,2432 0 => &pic.y,
2446 1 => &pic.cb,2433 1 => &pic.cb,
@@ -2448,305 +2435,6 @@ fn plane_ref<S: Sample>(pic: &Picture<S>, comp: usize) -> &PicPlane<S> {
2448 }2435 }
2449 }2436 }
2450 2437
2451-/// `residual_luma( )` (7.3.5.3.1) of one colour component plus its
2452-/// reconstruction (8.5): the luma residual, and for ChromaArrayType 3 the Cb
2453-/// and Cr residual too, which is coded and reconstructed exactly like luma
2454-/// (against the plane of `comp`, with `qp` its QP', and `ls` / `ls8` its
2455-/// scaling lists).
2456-///
2457-/// Bitstream order equals reconstruction dependency order, so each block
2458-/// reconstructs the moment its levels are parsed. `bypass` is
2459-/// TransformBypassModeFlag: the levels are the residual (8.5.15).
2460-#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
2461-fn residual_luma_style<S: Sample>(
2462- pic: &mut Picture<S>,
2463- r: &mut Entropy<'_>,
2464- nbr: &MbNeighbors,
2465- m: &MbFinish,
2466- mb_x: usize,
2467- mb_y: usize,
2468- comp: usize,
2469- ls: &LevelScale4x4,
2470- ls8: &LevelScale8x8,
2471- qp: i32,
2472- bypass: bool,
2473- fld: bool,
2474- geo: Geo,
2475- dc_cbf: &mut u8,
2476-) -> Result<()> {
2477- let bd = pic.bd;
2478- let max = (1i32 << bd) - 1;
2479- let w4 = pic.mb_w * 4;
2480- let (bx0, by0) = (mb_x * 4, mb_y * 4);
2481- let mul = geo.mul;
2482- let cbp_luma = m.cbp_luma;
2483- let c = comp as u8;
2484- let cat3 = pic.cat == 3;
2485- let mut scan = [0i32; 16];
2486- let mut raster = [0i32; 16];
2487- let mut resid = [0i32; 16];
2488- if m.is_i16 {
2489- {
2490- let pl = plane_mut(pic, comp);
2491- let mut w = PlaneWindow {
2492- origin: pl.at(mb_x * 16, geo.y(0)),
2493- stride: pl.stride * mul,
2494- data: &mut pl.data,
2495- };
2496- pred_16x16(m.i16_mode, bd, &mut w, m.pred_nbr.b, m.pred_nbr.a);
2497- }
2498- // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
2499- let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx0, by0);
2500- let dc_tc = r.residual_block_c(&mut scan, BlockCat::LumaDc, c, na, nb)?;
2501- *dc_cbf |= u8::from(dc_tc != 0) << comp;
2502- if fld {
2503- unfield(&scan, &mut raster);
2504- } else {
2505- unzigzag(&scan, &mut raster);
2506- }
2507- if !bypass {
2508- luma_dc_transform(&mut raster, ls, qp);
2509- }
2510- let dc = raster;
2511- // Lossless horizontal / vertical prediction accumulates the residual
2512- // over the whole macroblock, so every block takes part.
2513- let dpcm = bypass && m.i16_mode < 2;
2514- let horizontal = m.i16_mode == 1;
2515- for blk in 0..16 {
2516- let (dx, dy) = BLK4_POS[blk];
2517- let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2518- let tc = if cbp_luma != 0 {
2519- let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by);
2520- r.residual_block_c(&mut scan, BlockCat::LumaAc, c, na, nb)?
2521- } else {
2522- 0
2523- };
2524- nz_grid_mut(pic, comp)[by * w4 + bx] = tc;
2525- let dc_blk = dc[dy as usize * 4 + dx as usize];
2526- if tc == 0 && dc_blk == 0 && !dpcm {
2527- continue; // prediction already in place
2528- }
2529- if tc > 0 {
2530- if fld {
2531- unfield_ac15(&scan, &mut raster);
2532- } else {
2533- unzigzag_ac15(&scan, &mut raster);
2534- }
2535- if !bypass {
2536- dequant_4x4(&mut raster, ls, qp, true);
2537- }
2538- } else {
2539- raster = [0; 16]; // DC-only block
2540- }
2541- raster[0] = dc_blk;
2542- let pl = plane_mut(pic, comp);
2543- let origin = pl.at(mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4));
2544- let stride = pl.stride * mul;
2545- if bypass {
2546- if dpcm {
2547- let first = if horizontal { dx == 0 } else { dy == 0 };
2548- add_residual_dpcm(
2549- &mut pl.data,
2550- bd,
2551- stride,
2552- origin,
2553- 4,
2554- 4,
2555- &raster,
2556- horizontal,
2557- first,
2558- );
2559- } else {
2560- add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
2561- }
2562- } else {
2563- inverse_transform_4x4(&raster, &mut resid);
2564- add_residual_4x4(&mut pl.data, bd, stride, origin, &resid);
2565- }
2566- }
2567- } else if m.trans8x8 {
2568- // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block
2569- // at a time, because an Intra_8x8 block predicts from the reconstructed
2570- // samples of the blocks before it.
2571- let mut scan8 = [0i32; 64];
2572- let mut raster8 = [0i32; 64];
2573- let mut resid8 = [0i32; 64];
2574- for blk8 in 0..4 {
2575- let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, geo.y((blk8 / 2) * 8));
2576- let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
2577- let origin = plane_ref(pic, comp).at(x, y);
2578- let stride = plane_ref(pic, comp).stride * mul;
2579- if m.intra {
2580- let n = filter_nbr8(&gather_nbr8_in(
2581- &plane_ref(pic, comp).data,
2582- &m.pred_nbr,
2583- blk8,
2584- origin,
2585- stride,
2586- ));
2587- let mut p = [S::default(); 64];
2588- pred_8x8(m.modes8[blk8], bd, &n, &mut p);
2589- let pl = plane_mut(pic, comp);
2590- for ry in 0..8 {
2591- let row = origin + ry * stride;
2592- pl.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
2593- }
2594- }
2595- if cbp_luma & (1 << blk8) == 0 {
2596- let grid = nz_grid_mut(pic, comp);
2597- for dy in 0..2 {
2598- let base = (by + dy) * w4 + bx;
2599- grid[base..base + 2].fill(0);
2600- }
2601- continue;
2602- }
2603- let tc = if r.is_cabac() {
2604- // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot
2605- // of it reports the block's own count to the neighbours
2606- // (9.3.3.1.1.9 resolves them to the 8x8 transform block). Only
2607- // ChromaArrayType 3 sends a coded_block_flag for it.
2608- let cbf = cat3.then(|| nz_pair_8x8(pic, comp, nbr, bx, by));
2609- let tc = r.residual_block_8x8(&mut scan8, c, cbf)?;
2610- let grid = nz_grid_mut(pic, comp);
2611- for dy in 0..2 {
2612- let base = (by + dy) * w4 + bx;
2613- grid[base..base + 2].fill(tc.min(16));
2614- }
2615- tc
2616- } else {
2617- // CAVLC codes the same 64 coefficients as four interleaved 4x4
2618- // blocks (7.3.5.3.1), each with its own nC neighbourhood.
2619- let mut tc = 0u8;
2620- for i4 in 0..4 {
2621- let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
2622- let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
2623- let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, sx, sy);
2624- let n = r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?;
2625- nz_grid_mut(pic, comp)[sy * w4 + sx] = n;
2626- tc += n;
2627- for i in 0..16 {
2628- scan8[4 * i + i4] = scan[i];
2629- }
2630- }
2631- tc
2632- };
2633- if tc == 0 {
2634- continue;
2635- }
2636- if fld {
2637- unfield_8x8(&scan8, &mut raster8);
2638- } else {
2639- unzigzag_8x8(&scan8, &mut raster8);
2640- }
2641- let pl = plane_mut(pic, comp);
2642- if bypass {
2643- if m.intra && m.modes8[blk8] < 2 {
2644- add_residual_dpcm(
2645- &mut pl.data,
2646- bd,
2647- stride,
2648- origin,
2649- 8,
2650- 8,
2651- &raster8,
2652- m.modes8[blk8] == 1,
2653- true,
2654- );
2655- } else {
2656- add_residual_8x8(&mut pl.data, bd, stride, origin, &raster8);
2657- }
2658- } else {
2659- dequant_8x8(&mut raster8, ls8, qp);
2660- inverse_transform_8x8(&raster8, &mut resid8);
2661- add_residual_8x8(&mut pl.data, bd, stride, origin, &resid8);
2662- }
2663- }
2664- } else {
2665- for blk in 0..16 {
2666- let (dx, dy) = BLK4_POS[blk];
2667- let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2668- let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
2669- let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by);
2670- r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?
2671- } else {
2672- 0
2673- };
2674- nz_grid_mut(pic, comp)[by * w4 + bx] = tc;
2675- let (x, y) = (mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4));
2676- let origin = plane_ref(pic, comp).at(x, y);
2677- let stride = plane_ref(pic, comp).stride * mul;
2678- if m.intra {
2679- let n =
2680- gather_nbr4_in(&plane_ref(pic, comp).data, &m.pred_nbr, blk, origin, stride);
2681- let mut p = [S::default(); 16];
2682- pred_4x4(m.modes[blk], bd, &n, &mut p);
2683- let pl = plane_mut(pic, comp);
2684- if tc == 0 {
2685- // Pure prediction: copy the 16 samples in.
2686- for ry in 0..4 {
2687- let row = origin + ry * stride;
2688- pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2689- }
2690- continue;
2691- }
2692- if fld {
2693- unfield(&scan, &mut raster);
2694- } else {
2695- unzigzag(&scan, &mut raster);
2696- }
2697- if bypass {
2698- for ry in 0..4 {
2699- let row = origin + ry * stride;
2700- pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2701- }
2702- if m.modes[blk] < 2 {
2703- add_residual_dpcm(
2704- &mut pl.data,
2705- bd,
2706- stride,
2707- origin,
2708- 4,
2709- 4,
2710- &raster,
2711- m.modes[blk] == 1,
2712- true,
2713- );
2714- } else {
2715- add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
2716- }
2717- continue;
2718- }
2719- dequant_4x4(&mut raster, ls, qp, false);
2720- inverse_transform_4x4(&raster, &mut resid);
2721- for ry in 0..4 {
2722- let row = origin + ry * stride;
2723- for rx in 0..4 {
2724- let v = p[ry * 4 + rx].to_i32() + resid[ry * 4 + rx];
2725- pl.data[row + rx] = S::clip(v, max);
2726- }
2727- }
2728- } else {
2729- if tc == 0 {
2730- continue; // motion-compensated prediction already in place
2731- }
2732- if fld {
2733- unfield(&scan, &mut raster);
2734- } else {
2735- unzigzag(&scan, &mut raster);
2736- }
2737- let pl = plane_mut(pic, comp);
2738- if bypass {
2739- add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
2740- } else {
2741- dequant_4x4(&mut raster, ls, qp, false);
2742- inverse_transform_4x4(&raster, &mut resid);
2743- add_residual_4x4(&mut pl.data, bd, stride, origin, &resid);
2744- }
2745- }
2746- }
2747- }
2748- Ok(())
2749-}
2750 2438
2751 /// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and2439 /// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and
2752 /// inter paths.2440 /// inter paths.
@@ -3347,831 +3035,6 @@ fn predict_p_skip<S: Sample>(
3347 )3035 )
3348 }3036 }
3349 3037
3350-/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock.
3351-fn predict_direct<S: Sample>(
3352- pic: &mut Picture<S>,
3353- refs: &[Picture<S>],
3354- ctx: &SliceCtx,
3355- mvc: &mut MvCtx,
3356- skip: bool,
3357-) -> Result<()> {
3358- for quad in 0..4 {
3359- direct_quadrant(pic, refs, ctx, mvc, quad, skip)?;
3360- }
3361- Ok(())
3362-}
3363-
3364-/// B_Direct_8x8 for one 8x8 sub-macroblock.
3365-fn predict_direct_8x8<S: Sample>(
3366- pic: &mut Picture<S>,
3367- refs: &[Picture<S>],
3368- ctx: &SliceCtx,
3369- mvc: &mut MvCtx,
3370- part: usize,
3371-) -> Result<()> {
3372- direct_quadrant(pic, refs, ctx, mvc, part, false)
3373-}
3374-
3375-/// One 8x8 quadrant of a direct-mode macroblock. With
3376-/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its
3377-/// outer corner 4x4 block; without it each 4x4 block is derived on its own.
3378-fn direct_quadrant<S: Sample>(
3379- pic: &mut Picture<S>,
3380- refs: &[Picture<S>],
3381- ctx: &SliceCtx,
3382- mvc: &mut MvCtx,
3383- quad: usize,
3384- skip: bool,
3385-) -> Result<()> {
3386- let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
3387- let (qx, qy) = (quad % 2 * 2, quad / 2 * 2);
3388- let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 };
3389- if ctx.direct_8x8_inference {
3390- // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own
3391- // outer corner of the macroblock.
3392- let corner = (quad % 2 * 3, quad / 2 * 3);
3393- let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?;
3394- for dy in 0..2 {
3395- for dx in 0..2 {
3396- write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags);
3397- }
3398- }
3399- S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx)
3400- } else {
3401- // Each 4x4 block derives its own motion, but they usually come out
3402- // equal: interpolation is position-invariant, so one 8x8 compensation
3403- // of the shared vector produces the same samples as four 4x4 ones and
3404- // pays the per-partition setup once instead of four times.
3405- let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4];
3406- for dy in 0..2 {
3407- for dx in 0..2 {
3408- let (px, py) = (qx + dx, qy + dy);
3409- let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?;
3410- write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags);
3411- motion[dy * 2 + dx] = (mv, ref_idx);
3412- }
3413- }
3414- if motion.iter().all(|m| *m == motion[0]) {
3415- let (mv, ref_idx) = motion[0];
3416- return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx);
3417- }
3418- for dy in 0..2 {
3419- for dx in 0..2 {
3420- let (mv, ref_idx) = motion[dy * 2 + dx];
3421- S::compensate(
3422- pic,
3423- refs,
3424- ctx,
3425- mb_x,
3426- mb_y,
3427- qx + dx,
3428- qy + dy,
3429- 1,
3430- 1,
3431- mv,
3432- ref_idx,
3433- )?;
3434- }
3435- }
3436- Ok(())
3437- }
3438-}
3439-
3440-/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture
3441-/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3).
3442-#[allow(clippy::type_complexity)]
3443-fn direct_block<S: Sample>(
3444- pic: &Picture<S>,
3445- refs: &[Picture<S>],
3446- ctx: &SliceCtx,
3447- mvc: &MvCtx,
3448- at: (usize, usize),
3449-) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> {
3450- // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or
3451- // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol —
3452- // an index into the co-located picture's own reference list, not ours.
3453- let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at);
3454- let col = ctx.reference(refs, 1, 0);
3455-
3456- if ctx.direct_spatial {
3457- // Reference indices from the macroblock's own neighbours, once.
3458- let mut ref_idx = [-1i8; 2];
3459- let mut mvp = [[0i16; 2]; 2];
3460- for list in 0..2 {
3461- let n = mvc.neighbours(pic, 0, 0, 4, list);
3462- ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx));
3463- mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0);
3464- }
3465- let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0;
3466- if zero_prediction {
3467- ref_idx = [0, 0];
3468- }
3469- // colZeroFlag (8.4.1.2.2): the co-located block sits still on a
3470- // short-term picture, referencing that picture's own list entry 0. The
3471- // index is the one belonging to the list 8.4.1.2.1 picked — reading
3472- // "either list is 0" instead lets a bi-predicted co-located block whose
3473- // list 1 index happens to be 0 zero a motion vector it must not, which
3474- // only shows on a B picture used as the co-located one.
3475- let col_short = col.is_some_and(|c| c.mark == Mark::Short);
3476- let col_zero = col_short
3477- && col_ref_id >= 0
3478- && col_ref_idx == 0
3479- && (-1..=1).contains(&col_mv[0])
3480- && (-1..=1).contains(&col_mv[1]);
3481- let mut mv = [[0i16; 2]; 2];
3482- let mut ref_id = [-1i32; 2];
3483- for list in 0..2 {
3484- if ref_idx[list] < 0 {
3485- continue;
3486- }
3487- ref_id[list] = ctx
3488- .reference(refs, list, ref_idx[list])
3489- .map(|p| p.id)
3490- .unwrap_or(-1);
3491- if zero_prediction || (ref_idx[list] == 0 && col_zero) {
3492- mv[list] = [0; 2];
3493- } else {
3494- mv[list] = mvp[list];
3495- }
3496- }
3497- return Ok((mv, ref_idx, ref_id));
3498- }
3499-
3500- // Temporal direct (8.4.1.2.3).
3501- let ref_idx0 = if col_ref_id < 0 {
3502- 0
3503- } else {
3504- map_col_to_list0(ctx, refs, col_ref_id, vscale)
3505- };
3506- let col_mv = match vscale {
3507- // 8-195 and 8-196: "/" truncates toward zero.
3508- COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2],
3509- COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)],
3510- _ => col_mv,
3511- };
3512- let pic0 = ctx.reference(refs, 0, ref_idx0);
3513- let pic1 = ctx.reference(refs, 1, 0);
3514- let ref_id = [
3515- pic0.map(|p| p.id).unwrap_or(-1),
3516- pic1.map(|p| p.id).unwrap_or(-1),
3517- ];
3518- let (Some(p0), Some(p1)) = (pic0, pic1) else {
3519- return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id));
3520- };
3521- let td = (p1.poc - p0.poc).clamp(-128, 127);
3522- if p0.mark == Mark::Long || td == 0 {
3523- return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id));
3524- }
3525- let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127);
3526- let tx = (16384 + (td / 2).abs()) / td;
3527- let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
3528- let mv0 = [
3529- ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16,
3530- ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16,
3531- ];
3532- let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]];
3533- Ok(([mv0, mv1], [ref_idx0, 0], ref_id))
3534-}
3535-
3536-/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the
3537-/// picture the co-located block referenced.
3538-fn map_col_to_list0<S: Sample>(
3539- ctx: &SliceCtx,
3540- refs: &[Picture<S>],
3541- col_ref_id: i32,
3542- vscale: u8,
3543-) -> i8 {
3544- // Picture ids step by 4: a field id is its frame's id + 1 + parity.
3545- let field_mb = ctx.pos.active && ctx.pos.field;
3546- let want = match vscale {
3547- // The field of the referenced frame with the current picture's (or
3548- // macroblock's) parity.
3549- COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity),
3550- // A field macroblock of an MBAFF frame names the field of the frame
3551- // the co-located field macroblock referenced that has its own parity.
3552- _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => {
3553- (col_ref_id & !3) + i32::from(ctx.mb_parity)
3554- }
3555- _ => col_ref_id,
3556- };
3557- let n = if field_mb {
3558- 2 * ctx.lists[0].len()
3559- } else {
3560- ctx.lists[0].len()
3561- };
3562- for i in 0..n {
3563- let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| {
3564- if vscale == COL_FLD_TO_FRM {
3565- p.id == col_ref_id & !3
3566- } else {
3567- p.id == want
3568- }
3569- });
3570- if hit {
3571- return i as i8;
3572- }
3573- }
3574- 0
3575-}
3576-
3577-/// Whether a field macroblock of an MBAFF frame whose co-located block is a
3578-/// field macroblock maps the referenced field to the field of the same parity
3579-/// as itself (true) or to that very field (false).
3580-const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false;
3581-
3582-/// `vertMvScale` of 8.4.1.2.1.
3583-const COL_ONE_TO_ONE: u8 = 0;
3584-const COL_FRM_TO_FLD: u8 = 1;
3585-const COL_FLD_TO_FRM: u8 = 2;
3586-
3587-/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame.
3588-#[inline(never)]
3589-fn colocated_mbaff<S: Sample>(
3590- ctx: &SliceCtx,
3591- refs: &[Picture<S>],
3592- mvc: &MvCtx,
3593- at: (usize, usize),
3594-) -> (i32, [i16; 2], i8, u8) {
3595- const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE);
3596- let Some((k, _)) = ctx.lists[1].get_ref(0) else {
3597- return NONE;
3598- };
3599- let Some(store) = refs.get(k) else {
3600- return NONE;
3601- };
3602- let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
3603- let w = store.mb_w.max(1);
3604- let (c, bx, by, vs) = {
3605- let field_mb = ctx.pos.field;
3606- let bot = mb_y & 1;
3607- let top = mb_y & !1;
3608- // The field of a complementary pair, or of an MBAFF frame's field
3609- // macroblock pair, a frame macroblock takes its co-located block from.
3610- let by_poc =
3611- usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs());
3612- if store.coding == CODED_FLD {
3613- let p = if field_mb { bot } else { by_poc };
3614- let Some(f) = store.fields.get(p) else {
3615- return NONE;
3616- };
3617- if field_mb {
3618- (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE)
3619- } else {
3620- // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8).
3621- let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2;
3622- (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
3623- }
3624- } else {
3625- let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0;
3626- match (field_mb, col_field) {
3627- (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE),
3628- (false, true) => {
3629- let slot = top + by_poc;
3630- let by = slot * 4 + 2 * bot + at.1 / 2;
3631- (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
3632- }
3633- (true, false) => {
3634- let slot = top + at.1 / 2;
3635- let by = slot * 4 + (2 * at.1) % 4;
3636- (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
3637- }
3638- (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE),
3639- }
3640- }
3641- };
3642- let idx = by * c.mb_w.max(1) * 4 + bx;
3643- if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
3644- let list = usize::from(c.ref_id[idx][0] < 0);
3645- (
3646- c.ref_id[idx][list],
3647- c.mv[idx][list],
3648- c.ref_idx[idx][list],
3649- vs,
3650- )
3651- } else {
3652- (-1, [0; 2], -1, vs)
3653- }
3654-}
3655-
3656-/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current
3657-/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the
3658-/// identity is -1 for an intra block.
3659-fn colocated<S: Sample>(
3660- ctx: &SliceCtx,
3661- refs: &[Picture<S>],
3662- mvc: &MvCtx,
3663- at: (usize, usize),
3664-) -> (i32, [i16; 2], i8, u8) {
3665- const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE);
3666- let Some((k, _)) = ctx.lists[1].get_ref(0) else {
3667- return NONE;
3668- };
3669- let Some(store) = refs.get(k) else {
3670- return NONE;
3671- };
3672- if ctx.pos.active {
3673- return colocated_mbaff(ctx, refs, mvc, at);
3674- }
3675- let Some(cur) = ctx.reference(refs, 1, 0) else {
3676- return NONE;
3677- };
3678- let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
3679- let w = store.mb_w.max(1);
3680- // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the
3681- // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`).
3682- let (c, bx, by, vs) = if ctx.structure != FRAME {
3683- if store.coding == CODED_FLD {
3684- (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE)
3685- } else if store.coding == CODED_AFRM {
3686- let top = 2 * mb_y;
3687- if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 {
3688- // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16.
3689- let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4;
3690- (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
3691- } else {
3692- // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag.
3693- let slot = top + usize::from(ctx.structure == BOTTOM);
3694- (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE)
3695- }
3696- } else {
3697- // mbAddrCol1 and yM = (2 * yCol) % 16.
3698- let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4;
3699- (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
3700- }
3701- } else if store.coding == CODED_FLD {
3702- let top = (store.fpoc[0] - ctx.poc).abs();
3703- let bottom = (store.fpoc[1] - ctx.poc).abs();
3704- let p = usize::from(top >= bottom);
3705- let Some(f) = store.fields.get(p) else {
3706- return NONE;
3707- };
3708- // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8).
3709- let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2;
3710- (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
3711- } else {
3712- (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE)
3713- };
3714- let idx = by * c.mb_w.max(1) * 4 + bx;
3715- if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
3716- let list = usize::from(c.ref_id[idx][0] < 0);
3717- (
3718- c.ref_id[idx][list],
3719- c.mv[idx][list],
3720- c.ref_idx[idx][list],
3721- vs,
3722- )
3723- } else {
3724- (-1, [0; 2], -1, vs)
3725- }
3726-}
3727-
3728-/// The motion vectors chroma prediction uses: the luma vectors, with the
3729-/// vertical offset of 8.4.1.4 added when a field predicts from a field of the
3730-/// opposite parity.
3731-#[inline]
3732-fn chroma_mvs<S: Sample>(
3733- ctx: &SliceCtx,
3734- refs: &[Picture<S>],
3735- ref_idx: [i8; 2],
3736- mv: [[i16; 2]; 2],
3737-) -> [[i16; 2]; 2] {
3738- let mut out = mv;
3739- if ctx.cat == 2 {
3740- // 4:2:2 chroma is full height: the vertical vector stays in quarter
3741- // samples of the chroma plane, which the eighth-sample interpolator
3742- // reads as twice the value.
3743- for l in out.iter_mut() {
3744- l[1] = l[1].wrapping_mul(2);
3745- }
3746- } else if ctx.is_field() {
3747- for l in 0..2 {
3748- if let Some(rp) = ctx.reference(refs, l, ref_idx[l]) {
3749- out[l][1] = out[l][1].wrapping_add(ctx.chroma_dy(rp));
3750- }
3751- }
3752- }
3753- out
3754-}
3755-
3756-/// The reference plane (`0` luma, `1` Cb, `2` Cr) list `list` predicts from.
3757-#[inline(always)]
3758-fn ref_plane<'a>(
3759- ctx: &SliceCtx,
3760- refs: &'a [Picture<u8>],
3761- ref_idx: [i8; 2],
3762- list: usize,
3763- comp: usize,
3764-) -> Result<RefPlane<'a>> {
3765- let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
3766- Error::corrupt("reference index names a picture the buffer does not hold")
3767- })?;
3768- let src = match comp {
3769- 0 => &rp.y,
3770- 1 => &rp.cb,
3771- _ => &rp.cr,
3772- };
3773- Ok(RefPlane {
3774- data: &src.data,
3775- stride: src.stride,
3776- origin: src.origin,
3777- width: src.width,
3778- height: src.height,
3779- pad: src.pad,
3780- })
3781-}
3782-
3783-/// Motion compensation of one partition (clause 8.4.2): interpolate each list's
3784-/// prediction, then combine them by the weighting of 8.4.2.3 and write the
3785-/// result straight into the picture, where the residual is added on top.
3786-///
3787-/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock.
3788-#[allow(clippy::too_many_arguments)]
3789-pub(crate) fn compensate8(
3790- pic: &mut Picture<u8>,
3791- refs: &[Picture<u8>],
3792- ctx: &SliceCtx,
3793- mb_x: usize,
3794- mb_y: usize,
3795- px: usize,
3796- py: usize,
3797- pw: usize,
3798- ph: usize,
3799- mv: [[i16; 2]; 2],
3800- ref_idx: [i8; 2],
3801-) -> Result<()> {
3802- let use0 = ref_idx[0] >= 0;
3803- let use1 = ref_idx[1] >= 0;
3804- if !use0 && !use1 {
3805- return Ok(());
3806- }
3807- let geo = ctx.geo(mb_y);
3808- let x0 = (mb_x * 16 + px * 4) as i32;
3809- let y0 = (geo.src_y + py * 4) as i32;
3810- let (w, h) = (pw * 4, ph * 4);
3811- // A stream carrying no weighted prediction at all resolves every
3812- // component to the identity weighting without the per-component lookup.
3813- let plain = ctx.no_weights();
3814- // ChromaArrayType 3 predicts Cb and Cr with the luma interpolation, on
3815- // their own planes and weights.
3816- let ncomp = if ctx.cat == 3 { 3 } else { 1 };
3817- for comp in 0..ncomp {
3818- let wt = if plain {
3819- Weights::DEFAULT
3820- } else {
3821- ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1)
3822- };
3823- // 8.4.2.3.1 over one list is the identity, so the interpolation of that
3824- // one list IS the prediction: it is written straight into the picture at
3825- // the picture's own pitch. Over both lists the combined prediction is the
3826- // rounded byte average of the two clipped ones, so list 0 interpolates
3827- // into the picture and list 1 averages on top of it (Put::Avg) — no
3828- // temporaries, no combining pass, no copy back.
3829- let direct = wt.is_default();
3830- let stride = plane_ref(pic, comp).stride * geo.mul;
3831- let origin = plane_ref(pic, comp).at(x0 as usize, geo.y(py * 4));
3832- // Weighted bi-prediction fuses the same way: the combining formula is
3833- // per-sample, so list 0 lands in the picture and list 1 combines on top
3834- // of it (Put::AvgW) with 8.4.2.3.2's exact integers.
3835- let weighted_put = if !direct && use0 && use1 {
3836- Some(crate::inter::Put::AvgW {
3837- w0: wt.w[0],
3838- w1: wt.w[1],
3839- shift: (wt.log_wd + 1) as u32,
3840- round: 1 << wt.log_wd,
3841- off: (wt.o[0] + wt.o[1] + 1) >> 1,
3842- })
3843- } else {
3844- None
3845- };
3846- if direct && use0 && use1 {
3847- let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?;
3848- mc_luma(
3849- &plane,
3850- x0,
3851- y0,
3852- mv[0],
3853- w,
3854- h,
3855- stride,
3856- &mut plane_mut(pic, comp).data[origin..],
3857- crate::inter::Put::Set,
3858- );
3859- let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?;
3860- mc_luma(
3861- &plane,
3862- x0,
3863- y0,
3864- mv[1],
3865- w,
3866- h,
3867- stride,
3868- &mut plane_mut(pic, comp).data[origin..],
3869- crate::inter::Put::Avg,
3870- );
3871- } else if direct {
3872- // No scratch buffer is declared on this path at all: the scratch is
3873- // zeroed on entry, and most partitions of a P slice come through here.
3874- let list = usize::from(!use0);
3875- let plane = ref_plane(ctx, refs, ref_idx, list, comp)?;
3876- mc_luma(
3877- &plane,
3878- x0,
3879- y0,
3880- mv[list],
3881- w,
3882- h,
3883- stride,
3884- &mut plane_mut(pic, comp).data[origin..],
3885- crate::inter::Put::Set,
3886- );
3887- } else if let Some(put) = weighted_put {
3888- let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?;
3889- mc_luma(
3890- &plane,
3891- x0,
3892- y0,
3893- mv[0],
3894- w,
3895- h,
3896- stride,
3897- &mut plane_mut(pic, comp).data[origin..],
3898- crate::inter::Put::Set,
3899- );
3900- let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?;
3901- mc_luma(
3902- &plane,
3903- x0,
3904- y0,
3905- mv[1],
3906- w,
3907- h,
3908- stride,
3909- &mut plane_mut(pic, comp).data[origin..],
3910- put,
3911- );
3912- } else {
3913- let mut part = [[0u8; 256]; 2];
3914- for list in 0..2 {
3915- if ref_idx[list] < 0 {
3916- continue;
3917- }
3918- let plane = ref_plane(ctx, refs, ref_idx, list, comp)?;
3919- mc_luma(
3920- &plane,
3921- x0,
3922- y0,
3923- mv[list],
3924- w,
3925- h,
3926- w,
3927- &mut part[list],
3928- crate::inter::Put::Set,
3929- );
3930- }
3931- let mut out = [0u8; 256];
3932- let (p0, p1) = part.split_at(1);
3933- combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h);
3934- for row in 0..h {
3935- let dst = origin + row * stride;
3936- plane_mut(pic, comp).data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]);
3937- }
3938- }
3939- }
3940-
3941- // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma
3942- // vector, read as eighth-sample units over the half-resolution plane.
3943- if ctx.cat == 0 || ctx.cat == 3 {
3944- return Ok(());
3945- }
3946- let cmv = chroma_mvs(ctx, refs, ref_idx, mv);
3947- let c422 = ctx.cat == 2;
3948- let (cw, ch) = (w / 2, if c422 { h } else { h / 2 });
3949- let (cx0, cy0) = (x0 / 2, if c422 { y0 } else { y0 / 2 });
3950- let crow = if c422 { py * 4 } else { py * 2 };
3951- for comp in 0..2 {
3952- let wt = if plain {
3953- Weights::DEFAULT
3954- } else {
3955- ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1)
3956- };
3957- let direct = wt.is_default();
3958- // The combining weights are per-component syntax (luma and chroma
3959- // carry their own denoms, weights and offsets), so this component's
3960- // fused mode is built from ITS OWN lookup — never the luma one.
3961- let weighted_put = if !direct && use0 && use1 {
3962- Some(crate::inter::Put::AvgW {
3963- w0: wt.w[0],
3964- w1: wt.w[1],
3965- shift: (wt.log_wd + 1) as u32,
3966- round: 1 << wt.log_wd,
3967- off: (wt.o[0] + wt.o[1] + 1) >> 1,
3968- })
3969- } else {
3970- None
3971- };
3972- let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
3973- let stride = plane_out.stride * geo.mul;
3974- let origin = plane_out.at(cx0 as usize, geo.cy(crow));
3975- if direct && use0 && use1 {
3976- let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?;
3977- mc_chroma(
3978- &plane,
3979- cx0,
3980- cy0,
3981- cmv[0],
3982- cw,
3983- ch,
3984- stride,
3985- &mut plane_out.data[origin..],
3986- crate::inter::Put::Set,
3987- );
3988- let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?;
3989- mc_chroma(
3990- &plane,
3991- cx0,
3992- cy0,
3993- cmv[1],
3994- cw,
3995- ch,
3996- stride,
3997- &mut plane_out.data[origin..],
3998- crate::inter::Put::Avg,
3999- );
4000- } else if let Some(put) = weighted_put {
4001- let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?;
4002- mc_chroma(
4003- &plane,
4004- cx0,
4005- cy0,
4006- cmv[0],
4007- cw,
4008- ch,
4009- stride,
4010- &mut plane_out.data[origin..],
4011- crate::inter::Put::Set,
4012- );
4013- let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?;
4014- mc_chroma(
4015- &plane,
4016- cx0,
4017- cy0,
4018- cmv[1],
4019- cw,
4020- ch,
4021- stride,
4022- &mut plane_out.data[origin..],
4023- put,
4024- );
4025- } else if direct {
4026- let list = usize::from(!use0);
4027- let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?;
4028- mc_chroma(
4029- &plane,
4030- cx0,
4031- cy0,
4032- cmv[list],
4033- cw,
4034- ch,
4035- stride,
4036- &mut plane_out.data[origin..],
4037- crate::inter::Put::Set,
4038- );
4039- } else {
4040- let mut cpart = [[0u8; 128]; 2];
4041- for list in 0..2 {
4042- if ref_idx[list] < 0 {
4043- continue;
4044- }
4045- let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?;
4046- mc_chroma(
4047- &plane,
4048- cx0,
4049- cy0,
4050- cmv[list],
4051- cw,
4052- ch,
4053- cw,
4054- &mut cpart[list],
4055- crate::inter::Put::Set,
4056- );
4057- }
4058- let mut cout = [0u8; 128];
4059- let (c0, c1) = cpart.split_at(1);
4060- combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch);
4061- for row in 0..ch {
4062- let dst = origin + row * stride;
4063- plane_out.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]);
4064- }
4065- }
4066- }
4067- Ok(())
4068-}
4069-
4070-/// Motion compensation of one partition over `u16` planes: the same clause
4071-/// 8.4.2 process as [`compensate8`], computed per sample from the equations.
4072-/// Weighted prediction offsets scale by `1 << (BitDepth - 8)` (8-298, 8-299).
4073-#[allow(clippy::too_many_arguments)]
4074-pub(crate) fn compensate16(
4075- pic: &mut Picture<u16>,
4076- refs: &[Picture<u16>],
4077- ctx: &SliceCtx,
4078- mb_x: usize,
4079- mb_y: usize,
4080- px: usize,
4081- py: usize,
4082- pw: usize,
4083- ph: usize,
4084- mv: [[i16; 2]; 2],
4085- ref_idx: [i8; 2],
4086-) -> Result<()> {
4087- let use0 = ref_idx[0] >= 0;
4088- let use1 = ref_idx[1] >= 0;
4089- if !use0 && !use1 {
4090- return Ok(());
4091- }
4092- let bd = pic.bd;
4093- let max = (1i32 << bd) - 1;
4094- let geo = ctx.geo(mb_y);
4095- let x0 = (mb_x * 16 + px * 4) as i32;
4096- let y0 = (geo.src_y + py * 4) as i32;
4097- let plain = ctx.no_weights();
4098- let cmv = chroma_mvs(ctx, refs, ref_idx, mv);
4099- let cat = pic.cat;
4100- let ncomp = if cat == 0 { 1 } else { 3 };
4101- for comp in 0..ncomp {
4102- let c422 = cat == 2;
4103- let (w, h, cx, cy) = if comp == 0 || cat == 3 {
4104- (pw * 4, ph * 4, x0, y0)
4105- } else if c422 {
4106- (pw * 2, ph * 4, x0 / 2, y0)
4107- } else {
4108- (pw * 2, ph * 2, x0 / 2, y0 / 2)
4109- };
4110- let mut wt = if plain {
4111- Weights::DEFAULT
4112- } else {
4113- ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1)
4114- };
4115- wt.o[0] <<= bd - 8;
4116- wt.o[1] <<= bd - 8;
4117- let mut pred = [[0i32; 256]; 2];
4118- for list in 0..2 {
4119- if ref_idx[list] < 0 {
4120- continue;
4121- }
4122- let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
4123- Error::corrupt("reference index names a picture the buffer does not hold")
4124- })?;
4125- match comp {
4126- 0 => crate::inter16::luma_pred(&rp.y, cx, cy, mv[list], w, h, max, &mut pred[list]),
4127- 1 if cat == 3 => {
4128- crate::inter16::luma_pred(&rp.cb, cx, cy, mv[list], w, h, max, &mut pred[list])
4129- }
4130- _ if cat == 3 => {
4131- crate::inter16::luma_pred(&rp.cr, cx, cy, mv[list], w, h, max, &mut pred[list])
4132- }
4133- 1 => crate::inter16::chroma_pred(&rp.cb, cx, cy, cmv[list], w, h, &mut pred[list]),
4134- _ => crate::inter16::chroma_pred(&rp.cr, cx, cy, cmv[list], w, h, &mut pred[list]),
4135- }
4136- }
4137- let plane = match comp {
4138- 0 => &mut pic.y,
4139- 1 => &mut pic.cb,
4140- _ => &mut pic.cr,
4141- };
4142- let stride = plane.stride * geo.mul;
4143- let origin = if comp == 0 || cat == 3 {
4144- plane.at(cx as usize, geo.y(py * 4))
4145- } else {
4146- plane.at(cx as usize, geo.cy(if c422 { py * 4 } else { py * 2 }))
4147- };
4148- let round1 = if wt.log_wd >= 1 {
4149- 1 << (wt.log_wd - 1)
4150- } else {
4151- 0
4152- };
4153- for row in 0..h {
4154- for col in 0..w {
4155- let i = row * w + col;
4156- let v = if use0 && use1 {
4157- // 8-301 / 8-300 (default weights reduce to the rounded mean).
4158- ((pred[0][i] * wt.w[0] + pred[1][i] * wt.w[1] + (1 << wt.log_wd))
4159- >> (wt.log_wd + 1))
4160- + ((wt.o[0] + wt.o[1] + 1) >> 1)
4161- } else {
4162- let k = usize::from(!use0);
4163- if wt.log_wd >= 1 {
4164- ((pred[k][i] * wt.w[k] + round1) >> wt.log_wd) + wt.o[k]
4165- } else {
4166- pred[k][i] * wt.w[k] + wt.o[k]
4167- }
4168- };
4169- plane.data[origin + row * stride + col] = v.clamp(0, max) as u16;
4170- }
4171- }
4172- }
4173- Ok(())
4174-}
4175 3038
4176 /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2),3039 /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2),
4177 /// including the top-right substitution rule.3040 /// including the top-right substitution rule.
@@ -4312,513 +3175,12 @@ pub(crate) fn gather_nbr8_in<S: Sample>(
4312 }3175 }
4313 }3176 }
4314 3177
4315-/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
4316-/// vertical edges then all horizontal edges per macroblock, then chroma.
4317-// `e` and `j` are edge and segment positions inside the macroblock, used to
4318-// index the plane as well as the strength arrays; iterating the arrays would
4319-// hide which geometry each one names.
4320-#[allow(clippy::needless_range_loop)]
4321-pub(crate) fn deblock_picture<S: Sample>(pic: &mut Picture<S>) {
4322- let mb_w = pic.mb_w;
4323- let bd = pic.bd;
4324- let max = (1i32 << bd) - 1;
4325- let qp_bd = 6 * (bd as i32 - 8);
4326- let cmb_h = pic.cmb_h;
4327- let cat = pic.cat;
4328- let lcomps = if cat == 3 { 3 } else { 1 };
4329- for mb_y in 0..pic.mb_h {
4330- for mb_x in 0..mb_w {
4331- let addr = mb_y * mb_w + mb_x;
4332- if pic.mb_flags[addr] & FLAG_DECODED == 0 {
4333- continue;
4334- }
4335- let sid = pic.mb_slice[addr];
4336- let sp = pic.slices[sid as usize];
4337- if sp.disable_deblock_idc == 1 {
4338- continue;
4339- }
4340- let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0;
4341- let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid;
4342- let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1);
4343- let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w);
4344- // Deblocking QP: 0 for I_PCM macroblocks (8.7.2).
4345- let qp_of = |a: usize| -> i32 {
4346- if pic.mb_flags[a] & FLAG_PCM != 0 {
4347- 0
4348- } else {
4349- i32::from(pic.mb_qp[a])
4350- }
4351- };
4352- // 8.7: an 8x8-transform macroblock has no transform edge at luma
4353- // 4 or 12, so those internal edges are not filtered. Chroma is
4354- // unaffected for 4:2:0 (its internal edge sits on luma edge 8).
4355- let internal =
4356- |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0;
4357-
4358- // Boundary strengths, per 4-sample segment of each edge (8.7.2.1).
4359- //
4360- // Both sides of an internal edge live in this macroblock, so the
4361- // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra
4362- // macroblock gives 3 everywhere, and an inter macroblock with no
4363- // luma coefficients and one motion vector over the whole 16x16
4364- // gives 0 everywhere. Only the two macroblock edges then need the
4365- // per-segment derivation.
4366- let mut bs_v = [[0u8; 4]; 4];
4367- let mut bs_h = [[0u8; 4]; 4];
4368- let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0;
4369- let internal_uniform = if cur_intra {
4370- Some(3)
4371- } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) {
4372- Some(0)
4373- } else {
4374- None
4375- };
4376- for k in 0..4 {
4377- if filter_left {
4378- bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true);
4379- }
4380- if filter_top {
4381- bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false);
4382- }
4383- }
4384- for e in 1..4 {
4385- match internal_uniform {
4386- Some(bs) => {
4387- bs_v[e] = [bs; 4];
4388- bs_h[e] = [bs; 4];
4389- }
4390- None => {
4391- for k in 0..4 {
4392- bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true);
4393- bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false);
4394- }
4395- }
4396- }
4397- }
4398-
4399- // ---- luma (and Cb/Cr, coded like luma, for ChromaArrayType 3) ----
4400- for comp in 0..lcomps {
4401- let pl: &mut PicPlane<S> = match comp {
4402- 0 => &mut pic.y,
4403- 1 => &mut pic.cb,
4404- _ => &mut pic.cr,
4405- };
4406- let stride = pl.stride;
4407- let base = pl.at(mb_x * 16, mb_y * 16);
4408- let qpf = |a: usize| -> i32 {
4409- if comp == 0 {
4410- qp_of(a)
4411- } else {
4412- let s = pic.slices[pic.mb_slice[a] as usize];
4413- let off = if comp == 1 {
4414- s.cb_qp_offset
4415- } else {
4416- s.cr_qp_offset
4417- };
4418- let q = if pic.mb_flags[a] & FLAG_PCM != 0 {
4419- 0
4420- } else {
4421- i32::from(pic.mb_qp[a])
4422- };
4423- chroma_qp(q, off, qp_bd)
4424- }
4425- };
4426- let qp_q = qpf(addr);
4427- // Lossless macroblocks keep their samples (8.7.2.2).
4428- let lossless = |a: usize| {
4429- pic.bypass_enabled
4430- && pic.mb_flags[a] & FLAG_PCM == 0
4431- && i32::from(pic.mb_qp[a]) + qp_bd == 0
4432- };
4433- let (p_ll_v, q_ll) = (filter_left && lossless(addr - 1), lossless(addr));
4434- let snap_v = (p_ll_v || (filter_left && q_ll))
4435- .then(|| snap_edge(&pl.data, base, stride, true));
4436- // Vertical edges (filter across columns), left to right.
4437- for e in 0..4 {
4438- if e == 0 && !filter_left {
4439- continue;
4440- }
4441- if !internal(e) {
4442- continue;
4443- }
4444- let qp_p = if e == 0 { qpf(addr - 1) } else { qp_q };
4445- let qp_avg = (qp_p + qp_q + 1) >> 1;
4446- // Vertical edges stay scalar: a gather/scatter SIMD
4447- // variant measured slower than this loop (strided
4448- // per-lane loads dominate).
4449- for j in 0..4 {
4450- let bs = bs_v[e][j];
4451- if bs == 0 {
4452- continue;
4453- }
4454- let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
4455- if params.alpha == 0 || params.beta == 0 {
4456- continue;
4457- }
4458- for k in 0..4 {
4459- let row = j * 4 + k;
4460- filter_luma_line(
4461- &mut pl.data,
4462- max,
4463- base + row * stride + e * 4,
4464- 1,
4465- &params,
4466- );
4467- }
4468- }
4469- }
4470- if let Some(sv) = &snap_v {
4471- restore_edge(&mut pl.data, sv, base, stride, true, p_ll_v, q_ll);
4472- }
4473- let p_ll_h = filter_top && lossless(addr - mb_w);
4474- let snap_h = (p_ll_h || (filter_top && q_ll))
4475- .then(|| snap_edge(&pl.data, base, stride, false));
4476- // Horizontal edges, top to bottom.
4477- for e in 0..4 {
4478- if e == 0 && !filter_top {
4479- continue;
4480- }
4481- if !internal(e) {
4482- continue;
4483- }
4484- let qp_p = if e == 0 { qpf(addr - mb_w) } else { qp_q };
4485- let qp_avg = (qp_p + qp_q + 1) >> 1;
4486- let bs = bs_h[e];
4487- let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3];
4488- if uniform {
4489- if bs[0] == 0 {
4490- continue;
4491- }
4492- let params =
4493- edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd);
4494- if params.alpha == 0 || params.beta == 0 {
4495- continue;
4496- }
4497- // Eight rows around the edge are contiguous, so the
4498- // whole 16-sample edge filters in one pass.
4499- S::filter_luma_h_edge16(
4500- &mut pl.data,
4501- max,
4502- base + e * 4 * stride,
4503- stride,
4504- &params,
4505- );
4506- continue;
4507- }
4508- for j in 0..4 {
4509- if bs[j] == 0 {
4510- continue;
4511- }
4512- let params =
4513- edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j], bd);
4514- if params.alpha == 0 || params.beta == 0 {
4515- continue;
4516- }
4517- for k in 0..4 {
4518- filter_luma_line(
4519- &mut pl.data,
4520- max,
4521- base + e * 4 * stride + j * 4 + k,
4522- stride,
4523- &params,
4524- );
4525- }
4526- }
4527- }
4528- if let Some(sh) = &snap_h {
4529- restore_edge(&mut pl.data, sh, base, stride, false, p_ll_h, q_ll);
4530- }
4531- }
4532-
4533- // ---- chroma (Cb, Cr) ----
4534- for comp in 0..if matches!(cat, 1 | 2) { 2 } else { 0 } {
4535- let (plane, off_sel): (&mut PicPlane<S>, fn(&SliceParams) -> i32) = if comp == 0 {
4536- (&mut pic.cb, |s| s.cb_qp_offset)
4537- } else {
4538- (&mut pic.cr, |s| s.cr_qp_offset)
4539- };
4540- let stride = plane.stride;
4541- let c422 = cat == 2;
4542- let base = plane.origin + (mb_y * cmb_h) * stride + mb_x * 8;
4543- // Chroma QP per side: each macroblock's luma QP mapped with
4544- // the offset of ITS OWN slice's PPS (8.7.2).
4545- let cqp = |a: usize| -> i32 {
4546- let s = pic.slices[pic.mb_slice[a] as usize];
4547- if pic.mb_flags[a] & FLAG_PCM != 0 {
4548- chroma_qp(0, off_sel(&s), qp_bd)
4549- } else {
4550- chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s), qp_bd)
4551- }
4552- };
4553- let cq_q = cqp(addr);
4554- // A chroma edge inherits the boundary strength of the luma edge
4555- // it sits on: chroma sample k maps to luma sample 2k, so a
4556- // chroma 4-sample run spans two luma 4x4 block rows.
4557- for e in 0..2 {
4558- if e == 0 && !filter_left {
4559- continue;
4560- }
4561- let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q };
4562- let qp_avg = (cq_p + cq_q + 1) >> 1;
4563- for k in 0..cmb_h {
4564- let bs = bs_v[e * 2][k >> if c422 { 2 } else { 1 }];
4565- if bs == 0 {
4566- continue;
4567- }
4568- let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
4569- if params.alpha == 0 || params.beta == 0 {
4570- continue;
4571- }
4572- filter_chroma_line(
4573- &mut plane.data,
4574- max,
4575- base + k * stride + e * 4,
4576- 1,
4577- &params,
4578- );
4579- }
4580- }
4581- // 4:2:2 chroma is as tall as luma: its horizontal 4x4 transform
4582- // edges sit at rows 0, 4, 8 and 12, each on the boundary
4583- // strength of the luma edge on the same row.
4584- for e in 0..if c422 { 4 } else { 2 } {
4585- if e == 0 && !filter_top {
4586- continue;
4587- }
4588- let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q };
4589- let qp_avg = (cq_p + cq_q + 1) >> 1;
4590- let bs = bs_h[if c422 { e } else { e * 2 }];
4591- if bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3] {
4592- if bs[0] == 0 {
4593- continue;
4594- }
4595- let params =
4596- edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd);
4597- if params.alpha == 0 || params.beta == 0 {
4598- continue;
4599- }
4600- // The four rows around the edge are contiguous, so the
4601- // whole eight-sample edge filters in one pass.
4602- S::filter_chroma_h_edge8(
4603- &mut plane.data,
4604- max,
4605- base + e * 4 * stride,
4606- stride,
4607- &params,
4608- );
4609- continue;
4610- }
4611- for k in 0..8 {
4612- let bs = bs[k / 2];
4613- if bs == 0 {
4614- continue;
4615- }
4616- let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
4617- if params.alpha == 0 || params.beta == 0 {
4618- continue;
4619- }
4620- filter_chroma_line(
4621- &mut plane.data,
4622- max,
4623- base + e * 4 * stride + k,
4624- stride,
4625- &params,
4626- );
4627- }
4628- }
4629- }
4630- }
4631- }
4632-}
4633-
4634-/// Copy the 8 samples across a macroblock edge (4 each side) along its 16
4635-/// samples, so a lossless side can be put back after the filter ran.
4636-fn snap_edge<S: Sample>(data: &[S], base: usize, stride: usize, vertical: bool) -> Vec<S> {
4637- let mut v = Vec::with_capacity(128);
4638- for i in 0..16 {
4639- for d in 0..8 {
4640- v.push(if vertical {
4641- data[base + i * stride + d - 4]
4642- } else {
4643- data[base + d * stride + i - 4 * stride]
4644- });
4645- }
4646- }
4647- v
4648-}
4649-
4650-fn restore_edge<S: Sample>(
4651- data: &mut [S],
4652- snap: &[S],
4653- base: usize,
4654- stride: usize,
4655- vertical: bool,
4656- p: bool,
4657- q: bool,
4658-) {
4659- for i in 0..16 {
4660- for d in 0..8 {
4661- if (d < 4 && !p) || (d >= 4 && !q) {
4662- continue;
4663- }
4664- let idx = if vertical {
4665- base + i * stride + d - 4
4666- } else {
4667- base + d * stride + i - 4 * stride
4668- };
4669- data[idx] = snap[i * 8 + d];
4670- }
4671- }
4672-}
4673-
4674-/// True when every 4x4 block of this macroblock predicts from the same
4675-/// pictures with the same motion, so no internal edge can reach the motion
4676-/// clauses of 8.7.2.1.
4677-fn uniform_motion<S: Sample>(pic: &Picture<S>, mb_x: usize, mb_y: usize) -> bool {
4678- let w4 = pic.mb_w * 4;
4679- let first = mb_y * 4 * w4 + mb_x * 4;
4680- let (mv, id) = (pic.mv[first], pic.ref_id[first]);
4681- (0..4).all(|by| {
4682- let row = first + by * w4;
4683- (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id)
4684- })
4685-}
4686-
4687-/// What clause 8.7.2.1 needs from the 4x4 block on one side of a luma edge.
4688-#[derive(Clone, Copy)]
4689-pub(crate) struct BsSide {
4690- /// The containing macroblock is intra: strength 4 on macroblock edges and
4691- /// 3 on internal ones, regardless of motion or levels.
4692- pub(crate) intra: bool,
4693- /// The transform block containing this sample has non-zero levels.
4694- pub(crate) coded: bool,
4695- /// MvLX of the block, `[list][component]`.
4696- pub(crate) mv: [[i16; 2]; 2],
4697- /// RefIdxLX of the block as list identities (`Picture::id`), -1 unused.
4698- pub(crate) refs: [i32; 2],
4699-}
4700-
4701-/// Boundary strength between the 4x4 blocks on the two sides of a luma edge
4702-/// (clause 8.7.2.1). `mb_edge` selects the macroblock-edge strengths 4/3.
4703-pub(crate) fn bs_between(p: &BsSide, q: &BsSide, mb_edge: bool, field: bool, vertical: bool) -> u8 {
4704- if p.intra || q.intra {
4705- // A horizontal edge of a field picture is never strength 4 (8.7.2.1).
4706- return if mb_edge && (vertical || !field) {
4707- 4
4708- } else {
4709- 3
4710- };
4711- }
4712- if p.coded || q.coded {
4713- return 2;
4714- }
4715- let (pr, qr) = (p.refs, q.refs);
4716- let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0);
4717- let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0);
4718- if pn != qn {
4719- return 1;
4720- }
4721- let (pm, qm) = (p.mv, q.mv);
4722- // The vertical limit is 4 quarter frame samples: 2 in field units.
4723- let ylim = if field { 2 } else { 4 };
4724- let differs = |a: [i16; 2], b: [i16; 2]| {
4725- (i32::from(a[0]) - i32::from(b[0])).abs() >= 4
4726- || (i32::from(a[1]) - i32::from(b[1])).abs() >= ylim
4727- };
4728- if pn == 1 {
4729- let pl = usize::from(pr[0] < 0);
4730- let ql = usize::from(qr[0] < 0);
4731- if pr[pl] != qr[ql] {
4732- return 1;
4733- }
4734- return u8::from(differs(pm[pl], qm[ql]));
4735- }
4736- if pn == 0 {
4737- return 0;
4738- }
4739- // Two motion vectors each: compare the two partitions by which pictures
4740- // they reference, not by list position (NOTE 1 of 8.7.2.1).
4741- let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]);
4742- if !same_set {
4743- return 1;
4744- }
4745- if pr[0] != pr[1] {
4746- return if pr[0] == qr[0] {
4747- u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1]))
4748- } else {
4749- u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0]))
4750- };
4751- }
4752- // Both lists name the same picture: either pairing agreeing is enough.
4753- let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]);
4754- let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]);
4755- u8::from(!(straight || crossed))
4756-}
4757-
4758-/// One side of a luma edge from picture state: the decoder path, both sides
4759-/// final macroblocks. The encoder's inter trial uses this for the
4760-/// already-coded neighbour and builds its candidate side itself.
4761-pub(crate) fn bs_side<S: Sample>(pic: &Picture<S>, bx: usize, by: usize) -> BsSide {
4762- let w4 = pic.mb_w * 4;
4763- let mb = (by / 4) * pic.mb_w + bx / 4;
4764- BsSide {
crates/ec-h264/src/direct.rsadded+387 -0
@@ -0,0 +1,387 @@
1+use ec_core::error::Result;
2+
3+use crate::decoder::SliceCtx;
4+use crate::dpb::{
5+ BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, FRAME, Mark, Picture,
6+};
7+use crate::mv::{MvCtx, min_positive, predict_mv, write_block};
8+use crate::sample::Sample;
9+
10+/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock.
11+pub(crate) fn predict_direct<S: Sample>(
12+ pic: &mut Picture<S>,
13+ refs: &[Picture<S>],
14+ ctx: &SliceCtx,
15+ mvc: &mut MvCtx,
16+ skip: bool,
17+) -> Result<()> {
18+ for quad in 0..4 {
19+ direct_quadrant(pic, refs, ctx, mvc, quad, skip)?;
20+ }
21+ Ok(())
22+}
23+
24+/// B_Direct_8x8 for one 8x8 sub-macroblock.
25+pub(crate) fn predict_direct_8x8<S: Sample>(
26+ pic: &mut Picture<S>,
27+ refs: &[Picture<S>],
28+ ctx: &SliceCtx,
29+ mvc: &mut MvCtx,
30+ part: usize,
31+) -> Result<()> {
32+ direct_quadrant(pic, refs, ctx, mvc, part, false)
33+}
34+
35+/// One 8x8 quadrant of a direct-mode macroblock. With
36+/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its
37+/// outer corner 4x4 block; without it each 4x4 block is derived on its own.
38+fn direct_quadrant<S: Sample>(
39+ pic: &mut Picture<S>,
40+ refs: &[Picture<S>],
41+ ctx: &SliceCtx,
42+ mvc: &mut MvCtx,
43+ quad: usize,
44+ skip: bool,
45+) -> Result<()> {
46+ let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
47+ let (qx, qy) = (quad % 2 * 2, quad / 2 * 2);
48+ let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 };
49+ if ctx.direct_8x8_inference {
50+ // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own
51+ // outer corner of the macroblock.
52+ let corner = (quad % 2 * 3, quad / 2 * 3);
53+ let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?;
54+ for dy in 0..2 {
55+ for dx in 0..2 {
56+ write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags);
57+ }
58+ }
59+ S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx)
60+ } else {
61+ // Each 4x4 block derives its own motion, but they usually come out
62+ // equal: interpolation is position-invariant, so one 8x8 compensation
63+ // of the shared vector produces the same samples as four 4x4 ones and
64+ // pays the per-partition setup once instead of four times.
65+ let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4];
66+ for dy in 0..2 {
67+ for dx in 0..2 {
68+ let (px, py) = (qx + dx, qy + dy);
69+ let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?;
70+ write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags);
71+ motion[dy * 2 + dx] = (mv, ref_idx);
72+ }
73+ }
74+ if motion.iter().all(|m| *m == motion[0]) {
75+ let (mv, ref_idx) = motion[0];
76+ return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx);
77+ }
78+ for dy in 0..2 {
79+ for dx in 0..2 {
80+ let (mv, ref_idx) = motion[dy * 2 + dx];
81+ S::compensate(
82+ pic,
83+ refs,
84+ ctx,
85+ mb_x,
86+ mb_y,
87+ qx + dx,
88+ qy + dy,
89+ 1,
90+ 1,
91+ mv,
92+ ref_idx,
93+ )?;
94+ }
95+ }
96+ Ok(())
97+ }
98+}
99+
100+/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture
101+/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3).
102+#[allow(clippy::type_complexity)]
103+fn direct_block<S: Sample>(
104+ pic: &Picture<S>,
105+ refs: &[Picture<S>],
106+ ctx: &SliceCtx,
107+ mvc: &MvCtx,
108+ at: (usize, usize),
109+) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> {
110+ // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or
111+ // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol —
112+ // an index into the co-located picture's own reference list, not ours.
113+ let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at);
114+ let col = ctx.reference(refs, 1, 0);
115+
116+ if ctx.direct_spatial {
117+ // Reference indices from the macroblock's own neighbours, once.
118+ let mut ref_idx = [-1i8; 2];
119+ let mut mvp = [[0i16; 2]; 2];
120+ for list in 0..2 {
121+ let n = mvc.neighbours(pic, 0, 0, 4, list);
122+ ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx));
123+ mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0);
124+ }
125+ let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0;
126+ if zero_prediction {
127+ ref_idx = [0, 0];
128+ }
129+ // colZeroFlag (8.4.1.2.2): the co-located block sits still on a
130+ // short-term picture, referencing that picture's own list entry 0. The
131+ // index is the one belonging to the list 8.4.1.2.1 picked — reading
132+ // "either list is 0" instead lets a bi-predicted co-located block whose
133+ // list 1 index happens to be 0 zero a motion vector it must not, which
134+ // only shows on a B picture used as the co-located one.
135+ let col_short = col.is_some_and(|c| c.mark == Mark::Short);
136+ let col_zero = col_short
137+ && col_ref_id >= 0
138+ && col_ref_idx == 0
139+ && (-1..=1).contains(&col_mv[0])
140+ && (-1..=1).contains(&col_mv[1]);
141+ let mut mv = [[0i16; 2]; 2];
142+ let mut ref_id = [-1i32; 2];
143+ for list in 0..2 {
144+ if ref_idx[list] < 0 {
145+ continue;
146+ }
147+ ref_id[list] = ctx
148+ .reference(refs, list, ref_idx[list])
149+ .map(|p| p.id)
150+ .unwrap_or(-1);
151+ if zero_prediction || (ref_idx[list] == 0 && col_zero) {
152+ mv[list] = [0; 2];
153+ } else {
154+ mv[list] = mvp[list];
155+ }
156+ }
157+ return Ok((mv, ref_idx, ref_id));
158+ }
159+
160+ // Temporal direct (8.4.1.2.3).
161+ let ref_idx0 = if col_ref_id < 0 {
162+ 0
163+ } else {
164+ map_col_to_list0(ctx, refs, col_ref_id, vscale)
165+ };
166+ let col_mv = match vscale {
167+ // 8-195 and 8-196: "/" truncates toward zero.
168+ COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2],
169+ COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)],
170+ _ => col_mv,
171+ };
172+ let pic0 = ctx.reference(refs, 0, ref_idx0);
173+ let pic1 = ctx.reference(refs, 1, 0);
174+ let ref_id = [
175+ pic0.map(|p| p.id).unwrap_or(-1),
176+ pic1.map(|p| p.id).unwrap_or(-1),
177+ ];
178+ let (Some(p0), Some(p1)) = (pic0, pic1) else {
179+ return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id));
180+ };
181+ let td = (p1.poc - p0.poc).clamp(-128, 127);
182+ if p0.mark == Mark::Long || td == 0 {
183+ return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id));
184+ }
185+ let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127);
186+ let tx = (16384 + (td / 2).abs()) / td;
187+ let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
188+ let mv0 = [
189+ ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16,
190+ ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16,
191+ ];
192+ let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]];
193+ Ok(([mv0, mv1], [ref_idx0, 0], ref_id))
194+}
195+
196+/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the
197+/// picture the co-located block referenced.
198+fn map_col_to_list0<S: Sample>(
199+ ctx: &SliceCtx,
200+ refs: &[Picture<S>],
201+ col_ref_id: i32,
202+ vscale: u8,
203+) -> i8 {
204+ // Picture ids step by 4: a field id is its frame's id + 1 + parity.
205+ let field_mb = ctx.pos.active && ctx.pos.field;
206+ let want = match vscale {
207+ // The field of the referenced frame with the current picture's (or
208+ // macroblock's) parity.
209+ COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity),
210+ // A field macroblock of an MBAFF frame names the field of the frame
211+ // the co-located field macroblock referenced that has its own parity.
212+ _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => {
213+ (col_ref_id & !3) + i32::from(ctx.mb_parity)
214+ }
215+ _ => col_ref_id,
216+ };
217+ let n = if field_mb {
218+ 2 * ctx.lists[0].len()
219+ } else {
220+ ctx.lists[0].len()
221+ };
222+ for i in 0..n {
223+ let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| {
224+ if vscale == COL_FLD_TO_FRM {
225+ p.id == col_ref_id & !3
226+ } else {
227+ p.id == want
228+ }
229+ });
230+ if hit {
231+ return i as i8;
232+ }
233+ }
234+ 0
235+}
236+
237+/// Whether a field macroblock of an MBAFF frame whose co-located block is a
238+/// field macroblock maps the referenced field to the field of the same parity
239+/// as itself (true) or to that very field (false).
240+const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false;
241+
242+/// `vertMvScale` of 8.4.1.2.1.
243+const COL_ONE_TO_ONE: u8 = 0;
244+const COL_FRM_TO_FLD: u8 = 1;
245+const COL_FLD_TO_FRM: u8 = 2;
246+
247+/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame.
248+#[inline(never)]
249+fn colocated_mbaff<S: Sample>(
250+ ctx: &SliceCtx,
251+ refs: &[Picture<S>],
252+ mvc: &MvCtx,
253+ at: (usize, usize),
254+) -> (i32, [i16; 2], i8, u8) {
255+ const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE);
256+ let Some((k, _)) = ctx.lists[1].get_ref(0) else {
257+ return NONE;
258+ };
259+ let Some(store) = refs.get(k) else {
260+ return NONE;
261+ };
262+ let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
263+ let w = store.mb_w.max(1);
264+ let (c, bx, by, vs) = {
265+ let field_mb = ctx.pos.field;
266+ let bot = mb_y & 1;
267+ let top = mb_y & !1;
268+ // The field of a complementary pair, or of an MBAFF frame's field
269+ // macroblock pair, a frame macroblock takes its co-located block from.
270+ let by_poc =
271+ usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs());
272+ if store.coding == CODED_FLD {
273+ let p = if field_mb { bot } else { by_poc };
274+ let Some(f) = store.fields.get(p) else {
275+ return NONE;
276+ };
277+ if field_mb {
278+ (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE)
279+ } else {
280+ // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8).
281+ let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2;
282+ (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
283+ }
284+ } else {
285+ let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0;
286+ match (field_mb, col_field) {
287+ (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE),
288+ (false, true) => {
289+ let slot = top + by_poc;
290+ let by = slot * 4 + 2 * bot + at.1 / 2;
291+ (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
292+ }
293+ (true, false) => {
294+ let slot = top + at.1 / 2;
295+ let by = slot * 4 + (2 * at.1) % 4;
296+ (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
297+ }
298+ (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE),
299+ }
300+ }
301+ };
302+ let idx = by * c.mb_w.max(1) * 4 + bx;
303+ if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
304+ let list = usize::from(c.ref_id[idx][0] < 0);
305+ (
306+ c.ref_id[idx][list],
307+ c.mv[idx][list],
308+ c.ref_idx[idx][list],
309+ vs,
310+ )
311+ } else {
312+ (-1, [0; 2], -1, vs)
313+ }
314+}
315+
316+/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current
317+/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the
318+/// identity is -1 for an intra block.
319+fn colocated<S: Sample>(
320+ ctx: &SliceCtx,
321+ refs: &[Picture<S>],
322+ mvc: &MvCtx,
323+ at: (usize, usize),
324+) -> (i32, [i16; 2], i8, u8) {
325+ const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE);
326+ let Some((k, _)) = ctx.lists[1].get_ref(0) else {
327+ return NONE;
328+ };
329+ let Some(store) = refs.get(k) else {
330+ return NONE;
331+ };
332+ if ctx.pos.active {
333+ return colocated_mbaff(ctx, refs, mvc, at);
334+ }
335+ let Some(cur) = ctx.reference(refs, 1, 0) else {
336+ return NONE;
337+ };
338+ let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
339+ let w = store.mb_w.max(1);
340+ // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the
341+ // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`).
342+ let (c, bx, by, vs) = if ctx.structure != FRAME {
343+ if store.coding == CODED_FLD {
344+ (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE)
345+ } else if store.coding == CODED_AFRM {
346+ let top = 2 * mb_y;
347+ if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 {
348+ // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16.
349+ let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4;
350+ (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
351+ } else {
352+ // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag.
353+ let slot = top + usize::from(ctx.structure == BOTTOM);
354+ (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE)
355+ }
356+ } else {
357+ // mbAddrCol1 and yM = (2 * yCol) % 16.
358+ let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4;
359+ (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
360+ }
361+ } else if store.coding == CODED_FLD {
362+ let top = (store.fpoc[0] - ctx.poc).abs();
363+ let bottom = (store.fpoc[1] - ctx.poc).abs();
364+ let p = usize::from(top >= bottom);
365+ let Some(f) = store.fields.get(p) else {
366+ return NONE;
367+ };
368+ // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8).
369+ let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2;
370+ (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
371+ } else {
372+ (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE)
373+ };
374+ let idx = by * c.mb_w.max(1) * 4 + bx;
375+ if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
376+ let list = usize::from(c.ref_id[idx][0] < 0);
377+ (
378+ c.ref_id[idx][list],
379+ c.mv[idx][list],
380+ c.ref_idx[idx][list],
381+ vs,
382+ )
383+ } else {
384+ (-1, [0; 2], -1, vs)
385+ }
386+}
387+
crates/ec-h264/src/enc/analysis.rsadded+141 -0
@@ -0,0 +1,141 @@
1+use super::mb;
2+use super::mb::Source;
3+
4+/// Everything one band worker needs.
5+/// Mean absolute neighbour difference of one plane, horizontal and vertical
6+/// averaged, over the `w` by `h` samples at the top left of `plane`.
7+pub(super) fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 {
8+ let (mut sum, mut n) = (0u64, 0u64);
9+ for y in 0..h {
10+ let row = &plane[y * stride..y * stride + w];
11+ for x in 1..w {
12+ sum += u64::from(row[x].abs_diff(row[x - 1]));
13+ n += 1;
14+ }
15+ if y > 0 {
16+ let prev = &plane[(y - 1) * stride..(y - 1) * stride + w];
17+ for x in 0..w {
18+ sum += u64::from(row[x].abs_diff(prev[x]));
19+ n += 1;
20+ }
21+ }
22+ }
23+ if n == 0 { 0.0 } else { sum as f64 / n as f64 }
24+}
25+
26+/// `chroma_qp_index_offset` for a source, from how textured its chroma is
27+/// relative to its luma.
28+///
29+/// A negative offset spends bits on chroma that luma would otherwise take.
30+/// That pays when the chroma planes are flat — screen capture, phone video,
31+/// anything with large constant-hue areas — because their few edges are what
32+/// the eye reads, and it loses on film, whose chroma carries as much detail as
33+/// its luma and whose luma is the better place for the same bits. The
34+/// separating statistic is the mean absolute sample gradient of the chroma
35+/// planes over that of luma, measured on the first source picture.
36+/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over
37+/// nine clips of the user's library, offset 0 against offset -2:
38+///
39+/// ```text
40+/// chroma/luma gradient 0 -> -2 (dB)
41+/// 0.013 +0.019
42+/// 0.092 +0.181
43+/// 0.094 +0.228
44+/// 0.098 +0.014
45+/// 0.118 +0.081
46+/// 0.122 +0.045
47+/// 0.128 +0.065
48+/// 0.286 +0.011
49+/// 0.911 -0.158
50+/// ```
51+///
52+/// Every clip whose chroma is flatter than its luma gains; the one film clip,
53+/// whose chroma gradient is nearly its luma's, loses. The threshold sits in
54+/// the middle of the gap the data leaves.
55+pub(super) fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 {
56+ let (w, h) = (width as usize, height as usize);
57+ let (cw, ch) = (w / 2, h / 2);
58+ let luma = mean_gradient(&src.y, src.stride, w, h);
59+ if luma <= 0.0 {
60+ return 0;
61+ }
62+ let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch)
63+ + mean_gradient(&src.v, src.c_stride, cw, ch))
64+ / 2.0;
65+ if chroma / luma < CHROMA_FLAT_RATIO {
66+ CHROMA_FLAT_QP_OFFSET
67+ } else {
68+ 0
69+ }
70+}
71+
72+/// Chroma is "flat" below this share of the luma gradient.
73+pub(super) const CHROMA_FLAT_RATIO: f64 = 0.5;
74+
75+/// The offset flat chroma is coded with.
76+pub(super) const CHROMA_FLAT_QP_OFFSET: i32 = -2;
77+
78+/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE`
79+/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as
80+/// sweep overrides. Read once per band, so they cost nothing per macroblock.
81+pub(super) fn fast_knobs() -> mb::FastKnobs {
82+ let mut k = mb::FastKnobs::default();
83+ if let Some(g) = std::env::var("EC_H264_INTRA_GATE")
84+ .ok()
85+ .and_then(|v| v.parse().ok())
86+ {
87+ k.intra_gate = g;
88+ }
89+ if let Ok(v) = std::env::var("EC_H264_SKIP_I8") {
90+ k.skip_i8 = v != "0";
91+ }
92+ if let Some(v) = std::env::var("EC_H264_ME_SUB")
93+ .ok()
94+ .and_then(|v| v.parse().ok())
95+ {
96+ k.me_sub = v;
97+ }
98+ if let Ok(v) = std::env::var("EC_H264_ME_SATD") {
99+ k.me_satd = v != "0";
100+ }
101+ if let Some(v) = std::env::var("EC_H264_INTER_TX")
102+ .ok()
103+ .and_then(|v| v.parse().ok())
104+ {
105+ k.inter_tx = v;
106+ }
107+ if let Ok(v) = std::env::var("EC_H264_LAZY_I16") {
108+ k.lazy_i16 = v != "0";
109+ }
110+ if let Some(v) = std::env::var("EC_H264_EARLY_SKIP")
111+ .ok()
112+ .and_then(|v| v.parse().ok())
113+ {
114+ k.early_skip = v;
115+ }
116+ if let Some(v) = std::env::var("EC_H264_TX8_NZ")
117+ .ok()
118+ .and_then(|v| v.parse().ok())
119+ {
120+ k.tx8_nz_limit = v;
121+ }
122+ if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") {
123+ k.p_skip_i8 = v != "0";
124+ }
125+ k
126+}
127+
128+/// Standard Lagrangian multiplier in the squared-error domain.
129+pub(crate) fn lambda_ssd(qp: i32) -> f64 {
130+ 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
131+}
132+
133+/// Lagrangian multiplier. Production uses the established byte-stable ladder;
134+/// the ablation feature can select the standard squared-error multiplier.
135+pub(super) fn lambda_for(qp: i32, standard: bool) -> f64 {
136+ if standard {
137+ lambda_ssd(qp)
138+ } else {
139+ (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
140+ }
141+}
crates/ec-h264/src/enc/mb.rsmodified+17 -3313

Diff too large; view file

@@ -12,38 +12,33 @@
12 // the arrays instead would hide which geometry each loop names.12 // the arrays instead would hide which geometry each loop names.
13 #![allow(clippy::needless_range_loop)]13 #![allow(clippy::needless_range_loop)]
14 14
15+mod inter;
16+mod intra;
17+mod me;
18+mod residual;
19+
20+use self::inter::*;
21+use self::intra::*;
22+use self::me::*;
23+use self::residual::*;
24+
15 use ec_h264_syntax::SliceType;25 use ec_h264_syntax::SliceType;
16-use wide::{i16x8, i16x16};26+use wide::{i16x16};
17 27
18-use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
19 use crate::decoder::{28 use crate::decoder::{
20- MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors,29+ mb_neighbors,
21 };30 };
22-use crate::dpb::{BLK_SKIP, Picture, Plane8};31+use crate::dpb::{Picture, Plane8};
23 use crate::entropy::{32 use crate::entropy::{
24- BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,33+ FLAG_SKIP, MbCtx, MbInfo,
25- MbCtx, MbInfo,
26 };34 };
27-use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};35+use crate::tables::{CHROMA_QP};
28-use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
29-use crate::pred::{
30- PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
31- pred_chroma_8x8,
32-};
33-use crate::tables::{BLK4_POS, CHROMA_QP};
34 use crate::transform::{36 use crate::transform::{
35- LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,37+ LevelScale4x4, LevelScale8x8, };
36- inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
37- unzigzag_ac15,
38-};
39 38
40-use super::quant::{
41- forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
42- quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc,
43-};
44 39
45 use super::{40 use super::{
46- entropy::{EncEntropy, sub_block_4x4},41+ entropy::{EncEntropy},
47 lambda_ssd,42 lambda_ssd,
48 };43 };
49 44
@@ -187,144 +182,6 @@ impl Default for Levels {
187 }182 }
188 }183 }
189 184
190-/// 4x4 Hadamard sum of absolute transformed differences between the source at
191-/// `(sx, sy)` and a 4x4 prediction.
192-// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this
193-// butterfly, bit-identical, but cycles-flat-to-worse under perf stat
194-// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions
195-// retired) -- reverted, dead end; see ledger.
196-fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 {
197- // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of
198- // them, so every intermediate fits an i16.
199- let mut d = [[0i16; 4]; 4];
200- for (y, row) in d.iter_mut().enumerate() {
201- let s = &src[(sy + y) * sstride + sx..][..4];
202- let p = &pred[y * pstride..][..4];
203- for x in 0..4 {
204- row[x] = i16::from(s[x]) - i16::from(p[x]);
205- }
206- }
207- // Vertical butterflies, lane-wise over the four columns.
208- let mut v = [[0i16; 4]; 4];
209- for x in 0..4 {
210- let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]);
211- let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
212- v[0][x] = s0 + s1;
213- v[1][x] = s0 - s1;
214- v[2][x] = s2 + s3;
215- v[3][x] = s2 - s3;
216- }
217- // Horizontal butterflies per row, then the absolute sum.
218- let mut sum = 0i32;
219- for row in &v {
220- let (a, b, c, e) = (row[0], row[1], row[2], row[3]);
221- let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
222- sum += i32::from((s0 + s1).abs())
223- + i32::from((s0 - s1).abs())
224- + i32::from((s2 + s3).abs())
225- + i32::from((s2 - s3).abs());
226- }
227- (sum + 2) >> 2
228-}
229-
230-/// SATD of a whole 16x16 luma macroblock against the prediction already in the
231-/// picture plane.
232-fn satd16(
233- src: &[u8],
234- sstride: usize,
235- sx: usize,
236- sy: usize,
237- plane: &[u8],
238- pstride: usize,
239- po: usize,
240-) -> i32 {
241- satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16)
242-}
243-
244-/// The same over a `w` x `h` partition.
245-#[allow(clippy::too_many_arguments)]
246-fn satd_block(
247- src: &[u8],
248- sstride: usize,
249- sx: usize,
250- sy: usize,
251- plane: &[u8],
252- pstride: usize,
253- po: usize,
254- w: usize,
255- h: usize,
256-) -> i32 {
257- let mut sum = 0;
258- for by in 0..h / 4 {
259- for bx in 0..w / 4 {
260- sum += satd4(
261- src,
262- sstride,
263- sx + bx * 4,
264- sy + by * 4,
265- &plane[po + by * 4 * pstride + bx * 4..],
266- pstride,
267- );
268- }
269- }
270- sum
271-}
272-
273-/// Sum of absolute differences of a `w` x `h` block against a prediction with
274-/// its own pitch. This is the motion search's inner loop and nothing else in
275-/// the encoder is called as often, so a full-width row goes through one vector.
276-#[allow(clippy::too_many_arguments)]
277-fn sad(
278- src: &[u8],
279- sstride: usize,
280- sx: usize,
281- sy: usize,
282- pred: &[u8],
283- pstride: usize,
284- w: usize,
285- h: usize,
286-) -> i32 {
287- if w == 16 {
288- let mut acc = i16x16::ZERO;
289- for y in 0..h {
290- let a = load16(src, (sy + y) * sstride + sx);
291- let b = load16(pred, y * pstride);
292- acc += (a - b).abs();
293- }
294- return acc.to_array().iter().map(|&v| i32::from(v)).sum();
295- }
296- let mut sum = 0;
297- for y in 0..h {
298- let s = &src[(sy + y) * sstride + sx..];
299- let p = &pred[y * pstride..];
300- for x in 0..w {
301- sum += (i32::from(s[x]) - i32::from(p[x])).abs();
302- }
303- }
304- sum
305-}
306-
307-/// Sum and maximum of the absolute differences between the 16x16 source block
308-/// at `(sx, sy)` and a 16-wide prediction.
309-fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) {
310- let mut acc = i16x16::ZERO;
311- let mut mx = i16x16::ZERO;
312- for y in 0..16 {
313- let a = load16(src, (sy + y) * sstride + sx);
314- let b = load16(pred, y * 16);
315- let d = (a - b).abs();
316- acc += d;
317- mx = mx.max(d);
318- }
319- let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum();
320- let max = mx
321- .to_array()
322- .iter()
323- .map(|&v| i32::from(v))
324- .max()
325- .unwrap_or(0);
326- (sum, max)
327-}
328 185
329 /// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero,186 /// Sixteen samples widened to 16-bit lanes; the tail past the slice is zero,
330 /// which only a caller reading past the plane could reach.187 /// which only a caller reading past the plane could reach.
@@ -367,21 +224,6 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] {
367 ]224 ]
368 }225 }
369 226
370-#[inline]
371-fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
372- (motion_lambda(e) * bits).round() as i32
373-}
374-
375-/// The multiplier `motion_rate` applies, for loops that price many vectors.
376-#[inline]
377-fn motion_lambda(e: &MbEnc<'_>) -> f64 {
378- if e.transform_8x8 {
379- e.lambda.sqrt()
380- } else {
381- e.lambda
382- }
383-}
384-
385 /// Everything one macroblock's coding writes into the picture, kept so that a227 /// Everything one macroblock's coding writes into the picture, kept so that a
386 /// branch can be coded, measured and undone.228 /// branch can be coded, measured and undone.
387 struct MbState {229 struct MbState {
@@ -643,3141 +485,3 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
643 }485 }
644 }486 }
645 487
646-/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against
647-/// Intra_4x4 is decided later, on real rate and real distortion (see
648-/// [`encode_intra_mb`]).
649-struct IntraCost {
650- i16_mode: u8,
651- /// SATD of the Intra_16x16 mode above: the cheap intra estimate that
652- /// `Preset::Fast` gates the full intra branch on.
653- satd: i32,
654- /// True when Intra_4x4 may be used at all for this picture and preset.
655- allow_i4: bool,
656-}
657-
658-/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a
659-/// later branch does not overwrite.
660-fn intra_pre_cost(
661- pic: &mut Picture,
662- e: &MbEnc<'_>,
663- nbr: &MbNeighbors,
664- mb_x: usize,
665- mb_y: usize,
666- modes: &[u8],
667-) -> IntraCost {
668- let (sx, sy) = (mb_x * 16, mb_y * 16);
669- let stride = pic.y.stride;
670- let origin = pic.y.at(sx, sy);
671- let mut best = (i32::MAX, 2u8);
672- for &mode in modes {
673- let ok = match mode {
674- 0 => nbr.b,
675- 1 => nbr.a,
676- 3 => nbr.a && nbr.b && nbr.d,
677- _ => true,
678- };
679- if !ok {
680- continue;
681- }
682- let mut win = PlaneWindow {
683- data: &mut pic.y.data,
684- stride,
685- origin,
686- };
687- pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
688- let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin);
689- if cost < best.0 {
690- best = (cost, mode);
691- }
692- }
693- IntraCost {
694- i16_mode: best.1,
695- satd: best.0,
696- // Intra_4x4 is tried in P pictures too, at every preset. Re-measured
697- // once the intra-versus-inter decision became a real one (BD-PSNR
698- // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures
699- // reads -1.613 dB on the film clip and -0.508 on the screen capture,
700- // where allowing it everywhere reads -0.728 and -0.500. It stays on
701- // everywhere. Under the old prediction-domain decision the screen
702- // capture preferred the restriction by a third of a dB; coding both
703- // branches for real removed that disagreement.
704- allow_i4: true,
705- }
706-}
707-
708-/// How much of a motion vector's signalling the search pays for. Half, which
709-/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264,
710-/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip
711-/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole
712-/// rate is worse than charging half on both contents, and the curve is flat
713-/// below a half and falls away above it.
714-const MV_BITS_WEIGHT: f64 = 0.5;
715-
716-/// Cap on whole-sample walk iterations per partition at `Preset::Fast`.
717-const FAST_ME_PASSES: usize = 3;
718-
719-/// The offsets the whole-sample search steps through, in units of the current
720-/// step size.
721-///
722-/// A square, not a cross. The cross this used to be could only walk along an
723-/// axis, so a diagonally moving macroblock had to be reached in two steps
724-/// through a point that was worse than both -- and a step search stops at the
725-/// first point it cannot improve on. Adding the four diagonals is worth 0.032
726-/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice
727-/// the candidates in the whole-sample stage, which is the cheap stage: it reads
728-/// the reference in place and never interpolates.
729-///
730-/// The step the walk starts from was swept with it, at 4, 8 and 16 whole
731-/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529
732-/// on the screen capture. Four is screen capture's optimum and inside film's
733-/// flat part -- a wider opening step is not a wider search here, it just lands
734-/// the walk further from the seeds, which are already the answer most of the
735-/// time.
736-const ME_PATTERN: [(i16, i16); 8] = [
737- (1, 0),
738- (-1, 0),
739- (0, 1),
740- (0, -1),
741- (1, 1),
742- (-1, -1),
743- (1, -1),
744- (-1, 1),
745-];
746-
747-/// What the search charges P_8x8 for its own signalling, against the six bits
748-/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four
749-/// sub_mb_type bins, before the four predictors' own mvd.
750-///
751-/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all
752-/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read
753-/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and
754-/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the
755-/// optimum at twelve, and quarters are worth 0.005 dB on camera content and
756-/// 0.016 on screen capture.
757-///
758-/// Re-swept once each partition was searched against its own predictor rather
759-/// than the macroblock's, because that changes what a split is worth: 6, 12
760-/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and
761-/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path.
762-const QUAD_BITS: f64 = 12.0;
763-
764-/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16,
765-/// with no sub_mb_type behind it.
766-///
767-/// Swept on the per-partition-predictor path at 3, 6 and 10 bits:
768-/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the
769-/// screen capture. Both contents want the halves charged half of what the old
770-/// whole-macroblock predictor made them look worth -- with each half searched
771-/// against its own predictor its mvd is genuinely cheaper, so the search no
772-/// longer has to be talked out of splitting.
773-const HALF_BITS: f64 = 3.0;
774-
775-/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
776-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
777-enum PShape {
778- /// P_L0_16x16.
779- Whole,
780- /// P_L0_L0_16x8: a top and a bottom half.
781- Horizontal,
782- /// P_L0_L0_8x16: a left and a right half.
783- Vertical,
784- /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
785- Quad,
786-}
787-
788-impl PShape {
789- /// mb_type of Table 7-13.
790- fn mb_type(self) -> u32 {
791- match self {
792- PShape::Whole => 0,
793- PShape::Horizontal => 1,
794- PShape::Vertical => 2,
795- PShape::Quad => 3,
796- }
797- }
798-
799- fn parts(self) -> usize {
800- match self {
801- PShape::Whole => 1,
802- PShape::Horizontal | PShape::Vertical => 2,
803- PShape::Quad => 4,
804- }
805- }
806-
807- /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
808- fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) {
809- match self {
810- PShape::Whole => ((0, 0), (16, 16)),
811- PShape::Horizontal => ((0, part * 2), (16, 8)),
812- PShape::Vertical => ((part * 2, 0), (8, 16)),
813- PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
814- }
815- }
816-
817- /// Which partition covers the 4x4 block at `(x, y)` in macroblock
818- /// coordinates, or `None` when the block is outside the macroblock.
819- fn part_of(self, x: i32, y: i32) -> Option<usize> {
820- if !(0..4).contains(&x) || !(0..4).contains(&y) {
821- return None;
822- }
823- let (x, y) = (x as usize, y as usize);
824- Some(match self {
825- PShape::Whole => 0,
826- PShape::Horizontal => y / 2,
827- PShape::Vertical => x / 2,
828- PShape::Quad => (y / 2) * 2 + x / 2,
829- })
830- }
831-
832- /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the
833- /// directional shortcuts of 8.4.1.3.
834- fn part_blocks(self) -> (usize, usize) {
835- match self {
836- PShape::Whole => (4, 4),
837- PShape::Horizontal => (4, 2),
838- PShape::Vertical => (2, 4),
839- PShape::Quad => (2, 2),
840- }
841- }
842-}
843-
844-/// How much the two chroma planes weigh against luma in the inter decision.
845-///
846-/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only
847-/// metric cannot price a term whose whole purpose is chroma: the film clip
848-/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture
849-/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside
850-/// screen capture's flat part; zero reproduces the chroma-blind decision
851-/// exactly, which is how the sweep proved the term was reaching the search.
852-///
853-/// It is worth 0.041 dB on the film clip and nothing on the screen capture --
854-/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB
855-/// per plane at every QP, and it is not because the vector was chosen without
856-/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a
857-/// half the bits it spends cost more than the chroma it buys.
858-const CHROMA_ME_WEIGHT: f64 = 0.5;
859-
860-/// How many inter candidates the macroblock decision codes before choosing,
861-/// most promising first. One is the SATD winner alone, which is what this used
862-/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV
863-/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`:
864-///
865-/// ```text
866-/// film 3840x1608 screen 2560x1440
867-/// 1 candidate -0.580 -0.474
868-/// 2 -0.521 -0.459
869-/// 3 -0.513 -0.447
870-/// 5 -0.504 -0.406
871-/// ```
872-///
873-/// monotone in the count with no turnover, so the decision is taken at the
874-/// full list. The SATD total that used to rank the shapes is a
875-/// prediction-domain estimate that never sees the residual it causes.
876-const SHAPE_RD_CANDIDATES: usize = 5;
877-
878-/// The inter decision for a P macroblock.
879-#[derive(Clone, Copy)]
880-struct InterChoice {
881- /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it;
882- /// zero where the search did not rank it.
883- satd: i32,
884- shape: PShape,
885- /// One motion vector per partition.
886- mv: [[i16; 2]; 4],
887- /// The P_Skip motion vector of 8.4.1.1.
888- skip_mv: [i16; 2],
889- /// The skip candidate is at least as good as the searched one.
890- prefer_skip: bool,
891- /// The prediction is so close to the source that the macroblock is coded
892- /// as P_Skip without costing a residual (`Preset::Fast` only).
893- force_skip: bool,
894-}
895-
896-/// Motion search plus the skip candidate.
897-fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<InterChoice> {
898- let reference = e.reference.expect("a P slice has a reference");
899- let ctx = MvCtx {
900- mb_x,
901- mb_y,
902- slice_id: e.slice_id,
903- written: 0,
904- pos: Default::default(),
905- };
906- let n = ctx.neighbours(pic, 0, 0, 4, 0);
907- let mvp = predict_mv(&n, 0, 4, 4, 0);
908- // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a
909- // zero-motion reference-0 partition.
910- let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0);
911- let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0);
912- let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0];
913- let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) {
914- [0, 0]
915- } else {
916- mvp
917- };
918-
919- let plane = RefPlane {
920- data: &reference.y.data,
921- stride: reference.y.stride,
922- origin: reference.y.origin,
923- width: reference.y.width,
924- height: reference.y.height,
925- pad: reference.y.pad,
926- };
927- let (sx, sy) = (mb_x * 16, mb_y * 16);
928- let sw = e.src.stride;
929-
930- // What the two chroma planes cost under a candidate vector, in the same
931- // SATD domain the luma search ranks in. The search itself cannot afford
932- // this -- it runs on SAD over a whole neighbourhood -- but the handful of
933- // candidates that survive to the shape decision can, and until they did,
934- // no decision in this encoder had ever looked at chroma: the vector, the
935- // shape and the skip flag were all chosen on luma alone and chroma was
936- // coded against whatever came out. Measured per plane against x264 that
937- // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we
938- // spent more bits, which is a prediction that was never asked about.
939- let cplanes = [&reference.cb, &reference.cr];
940- let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 {
941- if CHROMA_ME_WEIGHT == 0.0 {
942- return 0;
943- }
944- let mut buf = [0u8; 64];
945- let mut sum = 0;
946- for comp in 0..2 {
947- let src = cplanes[comp];
948- let rp = RefPlane {
949- data: &src.data,
950- stride: src.stride,
951- origin: src.origin,
952- width: src.width,
953- height: src.height,
954- pad: src.pad,
955- };
956- let (cw, ch) = (w / 2, h / 2);
957- mc_chroma(
958- &rp,
959- (sx + px) as i32 / 2,
960- (sy + py) as i32 / 2,
961- mv,
962- cw,
963- ch,
964- cw,
965- &mut buf,
966- crate::inter::Put::Set,
967- );
968- let plane = if comp == 0 { &e.src.u } else { &e.src.v };
969- sum += satd_block(
970- plane,
971- e.src.c_stride,
972- (sx + px) / 2,
973- (sy + py) / 2,
974- &buf,
975- cw,
976- 0,
977- cw,
978- ch,
979- );
980- }
981- (f64::from(sum) * CHROMA_ME_WEIGHT) as i32
982- };
983-
984- // Early skip: a prediction at the P_Skip vector that already sits inside
985- // the quantiser's dead zone codes nothing, so neither the search nor a
986- // residual is worth the time. Judged on luma SAD, the largest single
987- // difference and the chroma SATD, all against the quantiser step.
988- if e.preset == Preset::Fast && e.fast.early_skip > 0 {
989- let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2();
990- let k = f64::from(e.fast.early_skip) / 100.0;
991- let mut buf = [0u8; 256];
992- mc_luma(
993- &plane,
994- sx as i32,
995- sy as i32,
996- skip_mv,
997- 16,
998- 16,
999- 16,
1000- &mut buf,
1001- Put::Set,
1002- );
1003- let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf);
1004- if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0
1005- {
1006- let c = chroma_satd(0, 0, 16, 16, skip_mv);
1007- if f64::from(c) <= 64.0 * k * qstep * 4.0 {
1008- return vec![InterChoice {
1009- satd: 0,
1010- shape: PShape::Whole,
1011- mv: [skip_mv; 4],
1012- skip_mv,
1013- prefer_skip: true,
1014- force_skip: true,
1015- }];
1016- }
1017- }
1018- }
1019-
1020- let range = match e.preset {
1021- Preset::Fast => 16i16,
1022- Preset::Balanced => 48,
1023- };
1024-
1025- // One search over a `w` x `h` partition at `(px, py)` samples inside the
1026- // macroblock, seeded with the candidate vectors of its neighbourhood.
1027- let mlam = motion_lambda(e);
1028- let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| {
1029- let (x0, y0) = (sx + px, sy + py);
1030- let mut buf = [0u8; 256];
1031- // Whole-sample candidates read the reference plane in place; only the
1032- // sub-sample refinement pays for interpolation. The search runs on SAD,
1033- // which is what a search can afford; the winner is re-costed on SATD
1034- // because the intra candidates are SATD and the two scales differ.
1035- let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 {
1036- let bits = (mlam
1037- * f64::from(
1038- se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])),
1039- )
1040- * MV_BITS_WEIGHT)
1041- .round() as i32;
1042- if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
1043- let o = integer_origin(
1044- &plane,
1045- x0 as i32 + (mv[0] >> 2) as i32,
1046- y0 as i32 + (mv[1] >> 2) as i32,
1047- w,
1048- h,
1049- );
1050- return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
1051- }
1052- mc_luma(
1053- &plane,
1054- x0 as i32,
1055- y0 as i32,
1056- mv,
1057- w,
1058- h,
1059- w,
1060- &mut buf,
1061- crate::inter::Put::Set,
1062- );
1063- let d = if satd {
1064- satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
1065- } else {
1066- sad(&e.src.y, sw, x0, y0, &buf, w, w, h)
1067- };
1068- d + bits
1069- };
1070-
1071- let fast = e.preset == Preset::Fast;
1072- let mut best = ([0i16; 2], i32::MAX);
1073- for (i, &cand) in seeds.iter().enumerate() {
1074- if seeds[..i].contains(&cand) {
1075- continue;
1076- }
1077- let c = cost_of(cand, false);
1078- if c < best.1 {
1079- best = (cand, c);
1080- }
1081- }
1082- // Every partition is searched. This used to stop at a seed whose cost
1083- // was already under half a level a sample, on the reasoning that the
1084- // prediction fit and the search is the encoder's hot loop. Swept on
1085- // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is
1086- // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read
1087- // -0.586/-0.587/-0.593/-0.617 dB on the film clip and
1088- // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits
1089- // is exactly where a little more refinement is cheap.
1090- {
1091- // Fast opens at two whole samples: the seeds already carry the
1092- // neighbours' motion, so the walk only has to settle around them.
1093- let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 };
1094- let mut passes = 0;
1095- while step >= 4 {
1096- let mut improved = true;
1097- while improved {
1098- improved = false;
1099- passes += 1;
1100- if fast && passes > FAST_ME_PASSES {
1101- break;
1102- }
1103- for (dx, dy) in ME_PATTERN {
1104- let (dx, dy) = (dx * step, dy * step);
1105- let cand = [best.0[0] + dx, best.0[1] + dy];
1106- if (cand[0] - mvp[0]).abs() > range * 4
1107- || (cand[1] - mvp[1]).abs() > range * 4
1108- {
1109- continue;
1110- }
1111- let c = cost_of(cand, false);
1112- if c < best.1 {
1113- best = (cand, c);
1114- improved = true;
1115- }
1116- }
1117- }
1118- step /= 2;
1119- }
1120- // Sub-sample refinement runs on SATD, not SAD: interpolation
1121- // smooths, and a sum of absolute differences reads the smoothing
1122- // as a better match where a transform-domain cost does not. Worth
1123- // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen
1124- // capture. The whole-sample winner is re-costed in the same domain
1125- // first so the two halves of the search compare.
1126- let sub_satd = !fast || e.fast.me_satd;
1127- best.1 = cost_of(best.0, sub_satd);
1128- // Balanced iterates both sub-sample steps to convergence. Fast
1129- // looks at each ring of eight once.
1130- let rings: &[i16] = if !fast {
1131- &[2, 1]
1132- } else {
1133- match e.fast.me_sub {
1134- 0 => &[],
1135- 1 => &[2],
1136- _ => &[2, 1],
1137- }
1138- };
1139- if fast && e.fast.me_sub == 1 {
1140- // The four half-sample neighbours on the axes, then only the
1141- // diagonal the two winning axes point at.
1142- let base = best;
1143- let mut axis = [(base.0, base.1); 2];
1144- for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]]
1145- .into_iter()
1146- .enumerate()
1147- {
1148- for (dx, dy) in dirs {
1149- let cand = [base.0[0] + dx, base.0[1] + dy];
1150- let c = cost_of(cand, sub_satd);
1151- if c < axis[k].1 {
1152- axis[k] = (cand, c);
1153- }
1154- }
1155- }
1156- let both = axis[0].1 < base.1 && axis[1].1 < base.1;
1157- if both {
1158- let cand = [axis[0].0[0], axis[1].0[1]];
1159- let c = cost_of(cand, sub_satd);
1160- if c < best.1 {
1161- best = (cand, c);
1162- }
1163- }
1164- for a in axis {
1165- if a.1 < best.1 {
1166- best = a;
1167- }
1168- }
1169- }
1170- let rings: &[i16] = if fast && e.fast.me_sub == 1 {
1171- &[]
1172- } else {
1173- rings
1174- };
1175- for &step in rings {
1176- let mut improved = true;
1177- while improved {
1178- improved = false;
1179- for (dx, dy) in [
1180- (step, 0),
1181- (-step, 0),
1182- (0, step),
1183- (0, -step),
1184- (step, step),
1185- (-step, -step),
1186- (step, -step),
1187- (-step, step),
1188- ] {
1189- let cand = [best.0[0] + dx, best.0[1] + dy];
1190- let c = cost_of(cand, sub_satd);
1191- if c < best.1 {
1192- best = (cand, c);
1193- improved = !fast;
1194- }
1195- }
1196- }
1197- }
1198- }
1199- (
1200- best.0,
1201- if !fast || e.fast.me_satd {
1202- best.1
1203- } else {
1204- cost_of(best.0, true)
1205- },
1206- )
1207- };
1208-
1209- let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv];
1210- let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds);
1211- let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
1212- let skip_cost = {
1213- let mut buf = [0u8; 256];
1214- mc_luma(
1215- &plane,
1216- sx as i32,
1217- sy as i32,
1218- skip_mv,
1219- 16,
1220- 16,
1221- 16,
1222- &mut buf,
1223- Put::Set,
1224- );
1225- // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
1226- // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
1227- // and -0.741/-0.696 on the screen capture -- the two contents disagree
1228- // by less than the step between them, so this is the flat part. Six
1229- // costs 0.14 dB and twelve costs 0.42.
1230- //
1231- // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0
1232- // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/
1233- // -0.562 on screen capture, so three quarters is film's optimum and
1234- // inside screen capture's flat part.
1235- satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv)
1236- - motion_rate(e, 2.0)
1237- };
1238-
1239- let mut best = (PShape::Whole, [mv16; 4], cost16);
1240- // Every shape the search costed, kept so the macroblock decision can rank
1241- // them on coded cost instead of on this SATD total (see `encode_mb`).
1242- let mut evaluated = vec![(PShape::Whole, [mv16; 4])];
1243- // Halves, seeded with the whole-macroblock winner. The predictor used here
1244- // is the whole-macroblock one rather than each half's own: the real
1245- // predictors are derived in coding order when the choice is made, and this
1246- // only has to rank the shapes. A macroblock the 16x16 search already fits
1247- // is left alone — splitting it could only spend bits.
1248- //
1249- // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen
1250- // capture and nothing on camera content, for roughly twice the search
1251- // time. That is a Balanced trade, not a Fast one.
1252- // The threshold is a floor that real content clears everywhere: swept at
1253- // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a
1254- // thousandth of a decibel, so on these sources the halves are always
1255- // searched. It stays as a guard for content flat enough to make the two
1256- // extra searches pure cost.
1257- if e.preset == Preset::Balanced && cost16 > 16 * 16 {
1258- for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
1259- // What the shape itself costs to signal: its mb_type, plus one
1260- // sub_mb_type per quarter when it is P_8x8.
1261- let mut total = motion_rate(
1262- e,
1263- if shape == PShape::Quad {
1264- QUAD_BITS
1265- } else {
1266- HALF_BITS
1267- },
1268- );
1269- let mut mvs = [[0i16; 2]; 4];
1270- let (pw, ph) = shape.part_blocks();
1271- for part in 0..shape.parts() {
1272- let ((bx, by), (w, h)) = shape.geometry(part);
1273- // Each partition is searched against the predictor it will
1274- // actually be coded with (8.4.1.3), not against the whole
1275- // macroblock's: the partitions before it in this macroblock
1276- // are already chosen, so the neighbourhood the predictor reads
1277- // can be completed from `mvs`.
1278- let mut n = ctx.neighbours(pic, bx, by, pw, 0);
1279- let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| {
1280- if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) {
1281- *nb = crate::mv::Nb {
1282- avail: true,
1283- mv: mvs[p],
1284- ref_idx: 0,
1285- };
1286- }
1287- };
1288- inside(bx as i32 - 1, by as i32, &mut n[0]);
1289- inside(bx as i32, by as i32 - 1, &mut n[1]);
1290- let cx = bx as i32 + pw as i32;
1291- if shape.part_of(cx, by as i32 - 1).is_some() {
1292- inside(cx, by as i32 - 1, &mut n[2]);
1293- } else if !n[2].avail {
1294- inside(bx as i32 - 1, by as i32 - 1, &mut n[2]);
1295- }
1296- let part_mvp = predict_mv(&n, 0, pw, ph, part);
1297- let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]];
1298- let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds);
1299- mvs[part] = mv;
1300- total += cost + chroma_satd(bx * 4, by * 4, w, h, mv);
1301- }
1302- evaluated.push((shape, mvs));
1303- if total < best.2 {
1304- best = (shape, mvs, total);
1305- }
1306- }
1307- }
1308-
1309- // How often each shape actually wins. Behind an environment switch because
1310- // it answers a question the rate gate cannot: a partition sweep that reads
1311- // flat is either a flat knob or a path nothing enters, and only a count
1312- // tells the two apart. It found the second -- at `Preset::Fast`, which is
1313- // what the x264 comparison runs by default, no macroblock is ever split.
1314- if std::env::var_os("EC_H264_SHAPE_STATS").is_some() {
1315- static N: [std::sync::atomic::AtomicUsize; 4] = [
1316- std::sync::atomic::AtomicUsize::new(0),
1317- std::sync::atomic::AtomicUsize::new(0),
1318- std::sync::atomic::AtomicUsize::new(0),
1319- std::sync::atomic::AtomicUsize::new(0),
1320- ];
1321- let i = match best.0 {
1322- PShape::Whole => 0,
1323- PShape::Horizontal => 1,
1324- PShape::Vertical => 2,
1325- PShape::Quad => 3,
1326- };
1327- let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
1328- let tot: usize = N
1329- .iter()
1330- .map(|n| n.load(std::sync::atomic::Ordering::Relaxed))
1331- .sum();
1332- if tot.is_multiple_of(20000) {
1333- eprintln!(
1334- "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})",
1335- N[0].load(std::sync::atomic::Ordering::Relaxed),
1336- N[1].load(std::sync::atomic::Ordering::Relaxed),
1337- N[2].load(std::sync::atomic::Ordering::Relaxed),
1338- N[3].load(std::sync::atomic::Ordering::Relaxed),
1339- );
1340- }
1341- }
1342- let winner = InterChoice {
1343- satd: best.2,
1344- shape: best.0,
1345- mv: best.1,
1346- skip_mv,
1347- prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2,
1348- force_skip: false,
1349- };
1350- // The SATD winner first, then the shapes it beat, then the skip candidate
1351- // when the winner is not already it. The caller codes as many of these as
1352- // its preset allows and keeps the one with the smallest coded cost.
1353- let mut cands = vec![winner];
1354- for (shape, mv) in evaluated {
1355- if shape != winner.shape || winner.prefer_skip {
1356- cands.push(InterChoice {
1357- satd: 0,
1358- shape,
1359- mv,
1360- skip_mv,
1361- prefer_skip: false,
1362- force_skip: false,
1363- });
1364- }
1365- }
1366- if !winner.prefer_skip {
1367- cands.push(InterChoice {
1368- satd: skip_cost,
1369- shape: PShape::Whole,
1370- mv: [skip_mv; 4],
1371- skip_mv,
1372- prefer_skip: true,
1373- force_skip: false,
1374- });
1375- }
1376- cands
1377-}
1378-
1379-/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
1380-/// prediction already in the plane.
1381-#[allow(clippy::too_many_arguments)]
1382-fn code_luma_4x4(
1383- pic: &mut Picture,
1384- e: &MbEnc<'_>,
1385- w: &EncEntropy,
1386- mb_x: usize,
1387- mb_y: usize,
1388- qp: i32,
1389- intra: bool,
1390- lv: &mut Levels,
1391-) {
1392- let stride = pic.y.stride;
1393- // An inter macroblock's blocks are reconstructed only after the whole
1394- // macroblock has been quantised, because [`decimate_score`] can still take
1395- // a block away. Intra blocks reconstruct as they go: the next block in the
1396- // macroblock predicts from them.
1397- let mut pending: [Option<[i32; 16]>; 16] = [None; 16];
1398- // Per 8x8 group, what coding its blocks buys and what it costs, for the
1399- // group-level test below. A block with no levels contributes nothing to
1400- // either side: its source energy stays in the reconstruction whatever the
1401- // group decides.
1402- let mut ssd_zero = [0i64; 4];
1403- let mut ssd_coded = [0i64; 4];
1404- let mut rate = [0f64; 4];
1405- for blk in 0..16 {
1406- let (dx, dy) = BLK4_POS[blk];
1407- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1408- let origin = pic.y.at(x, y);
1409- let mut d = [0i32; 16];
1410- for ry in 0..4 {
1411- for rx in 0..4 {
1412- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1413- - i32::from(pic.y.data[origin + ry * stride + rx]);
1414- }
1415- }
1416- let source = d;
1417- forward_4x4(&mut d);
1418- let rdoq = !intra && w.is_cabac();
1419- let mut nz = if rdoq {
1420- quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk])
1421- } else {
1422- quant_4x4(&d, qp, intra, false, &mut lv.luma[blk])
1423- };
1424- if rdoq && nz != 0 {
1425- nz = rdoq_4x4(
1426- e,
1427- w,
1428- &source,
1429- &mut lv.luma[blk],
1430- qp,
1431- BlockCat::Luma4x4,
1432- false,
1433- );
1434- }
1435- lv.luma_nz[blk] = nz;
1436- if nz == 0 {
1437- continue;
1438- }
1439- let mut raster = [0i32; 16];
1440- unzigzag(&lv.luma[blk], &mut raster);
1441- dequant_4x4(&mut raster, &e.ls, qp, false);
1442- let mut resid = [0i32; 16];
1443- inverse_transform_4x4(&raster, &mut resid);
1444- // Is the block worth its bits? A block whose residual barely moves the
1445- // reconstruction is pure quantisation churn; dropping it is the cheap
1446- // half of rate-distortion optimised quantisation, and the half that
1447- // pays. Intra blocks are left alone: their reconstruction is what the
1448- // next block in the macroblock predicts from.
1449- if !rdoq
1450- && !intra
1451- && !worth_coding(
1452- &source,
1453- &resid,
1454- &lv.luma[blk],
1455- zero_block_lambda(e, qp, e.transform_8x8),
1456- )
1457- {
1458- lv.luma[blk] = [0; 16];
1459- lv.luma_nz[blk] = 0;
1460- continue;
1461- }
1462- if intra {
1463- lv.cbp_luma |= 1 << (blk >> 2);
1464- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1465- } else {
1466- for i in 0..16 {
1467- let z = i64::from(source[i]);
1468- let c = i64::from(source[i] - resid[i]);
1469- ssd_zero[blk >> 2] += z * z;
1470- ssd_coded[blk >> 2] += c * c;
1471- }
1472- rate[blk >> 2] +=
1473- match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) {
1474- // CABAC's own arithmetic cost for the levels, which is what
1475- // the group is really deciding about. It arrives in 256ths of
1476- // a bit.
1477- Some(bits) => f64::from(bits) / 256.0,
1478- None => block_bits(&lv.luma[blk]) as f64,
1479- };
1480- pending[blk] = Some(resid);
1481- }
1482- }
1483- if intra {
1484- return;
1485- }
1486- // A block that survives its own rate-distortion test can still be the last
1487- // coefficient standing in its 8x8 group, and then it is paying a
1488- // coded_block_pattern bit as well as its levels. x264 decides that with a
1489- // count of how tightly the levels cluster at the front of the scan
1490- // (`decimate`), thresholded at four per group; swept here, that count
1491- // wants opposite settings on the two contents -- monotonically off on
1492- // camera grain, monotonically harder on screen capture -- because it is a
1493- // heuristic standing in for a rate-distortion test the encoder can just
1494- // do. So do it: a group is coded only if its blocks buy more squared error
1495- // than their levels plus the pattern bit are worth, at the same lambda the
1496- // per-block test uses.
1497- // With an exact rate the lambda needs no correction factor: the group test
1498- // uses the mode decision's own lambda where the rate is CABAC's, and falls
1499- // back to the per-block test's discounted one where it is an estimate.
1500- let lambda = if w.is_cabac() {
1501- GROUP_LAMBDA * lambda_ssd(qp)
1502- } else {
1503- zero_block_lambda(e, qp, e.transform_8x8)
1504- };
1505- for g in 0..4 {
1506- if rate[g] == 0.0 {
1507- continue;
1508- }
1509- if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 {
1510- continue;
1511- }
1512- for blk in g * 4..g * 4 + 4 {
1513- lv.luma[blk] = [0; 16];
1514- lv.luma_nz[blk] = 0;
1515- pending[blk] = None;
1516- }
1517- }
1518- for blk in 0..16 {
1519- let Some(resid) = pending[blk] else { continue };
1520- let (dx, dy) = BLK4_POS[blk];
1521- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1522- let origin = pic.y.at(x, y);
1523- lv.cbp_luma |= 1 << (blk >> 2);
1524- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1525- }
1526-}
1527-
1528-/// What a group of four luma blocks pays in coded_block_pattern to be coded
1529-/// at all, in bits, on top of its own levels.
1530-///
1531-/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis --
1532-/// both make dropping a group likelier -- so only one of them is worth tuning.
1533-/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on
1534-/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture:
1535-/// the same trade the lambda makes, at a worse exchange rate. It stays at a
1536-/// plausible six.
1537-const CBP_BIT: f64 = 6.0;
1538-
1539-/// What chroma pays to take its coded_block_pattern from one to two, in bits,
1540-/// on top of the levels: the pattern bins themselves plus a coded_block_flag
1541-/// for every AC block that then has to say it is empty.
1542-///
1543-/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a
1544-/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/
1545-/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/
1546-/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The
1547-/// same sweep read on luma alone climbs all the way to +0.079 dB at 64,
1548-/// because past the turn the test is buying luma bits by throwing chroma
1549-/// away -- which is exactly the trade an all-plane metric exists to catch.
1550-const CBP_CHROMA_BIT: f64 = 16.0;
1551-
1552-/// How much of the mode-decision lambda the group test uses.
1553-///
1554-/// The 8x8 transform path was swept the same way and does not want this test
1555-/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/
1556-/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture,
1557-/// all inside its noise. One 8x8 block is a whole coded_block_pattern group,
1558-/// so its own zero test already decides what this one would, and `rdoq_8x8`
1559-/// drops it outright when the levels do not survive.
1560-///
1561-/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips:
1562-/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film
1563-/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440
1564-/// screen capture. Screen capture has an interior optimum around one -- which
1565-/// the same test on an estimated rate did not, it only ever wanted more -- and
1566-/// camera grain wants less, because a grain block that scores as noise is
1567-/// carrying signal the eye is measuring. Six tenths is the most the film clip
1568-/// takes without losing ground, and it is worth 0.06 dB on screen capture.
1569-const GROUP_LAMBDA: f64 = 0.6;
1570-
1571-/// How much of the squared-error lambda the chroma DC zero test uses.
1572-///
1573-/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`,
1574-/// with the test off against a ladder of multipliers:
1575-///
1576-/// ```text
1577-/// film screen phone handheld
1578-/// off -0.504 -0.227 -0.300 -0.886
1579-/// 0.25 -0.506 -0.227
1580-/// 0.5 -0.500 -0.220 -0.297 -0.884
1581-/// 0.75 -0.500 -0.223
1582-/// 1.0 -0.518 -0.246
1583-/// 2.0 -0.708 -0.566
1584-/// ```
1585-///
1586-/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate
1587-/// term is the whole test; above the peak it throws away chroma the picture
1588-/// needs.
1589-const CHROMA_DC_LAMBDA: f64 = 0.5;
1590-
1591-/// Squared error of coding `levels`, in the pixels the block reconstructs to.
1592-fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 {
1593- let mut raster = [0i32; 16];
1594- if skip_dc {
1595- unzigzag_ac15(levels, &mut raster);
1596- } else {
1597- unzigzag(levels, &mut raster);
1598- }
1599- dequant_4x4(&mut raster, &e.ls, qp, skip_dc);
1600- let mut resid = [0i32; 16];
1601- inverse_transform_4x4(&raster, &mut resid);
1602- let mut ssd = 0i64;
1603- for i in 0..16 {
1604- let d = i64::from(source[i] - resid[i]);
1605- ssd += d * d;
1606- }
1607- ssd
1608-}
1609-
1610-/// How much of the mode-decision lambda rate-distortion quantisation uses.
1611-///
1612-/// The bits here are the coder's own, not an estimate, so there is no
1613-/// over-estimate to correct for and the scale starts at 1. Swept over 0.5,
1614-/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a
1615-/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5
1616-/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is
1617-/// the crossing point that costs neither (-0.628 and -0.471). Table in
1618-/// `lanes/h264x264-r2.report.md`.
1619-const RDOQ_LAMBDA: f64 = 1.0;
1620-
1621-/// The dead zone rate-distortion quantisation starts from, as a divisor of the
1622-/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which
1623-/// has already thrown away the levels this search would weigh -- a search
1624-/// bounded by the heuristic it replaces measures the heuristic. This is the
1625-/// half of the change that pays: 1/6 -> 1/2 under the same search is worth
1626-/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read
1627-/// -0.647 and -0.677 dB where 1/2 reads -0.630.
1628-const RDOQ_DEAD_ZONE: i32 = 2;
1629-
1630-/// The largest level the search offers a smaller magnitude to. A big level is
1631-/// carrying real signal and never wins by shrinking; bounding the search is
1632-/// what keeps it free. Unbounded it tripled the synthetic clip's encode time
1633-/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over
1634-/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and
1635-/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture.
1636-const RDOQ_MAX_LEVEL: i32 = 2;
1637-
1638-/// The rounding the chroma AC path keeps under the search: the inter dead zone
1639-/// it already had. Luma wanted the wider 1/2 rounding once a search could take
1640-/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two
1641-/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding
1642-/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 /
1643-/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471
1644-/// with no chroma search at all. Chroma AC is sparse enough at these
1645-/// quantisers that offering more levels costs more bits than the search takes
1646-/// back; what pays is only the pruning.
1647-const RDOQ_CHROMA_DEAD_ZONE: i32 = 6;
1648-
1649-/// The rounding the 8x8 luma path keeps under the search. It answers the way
1650-/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in
1651-/// `transform_8x8` flag against flag-off, which isolates this path because the
1652-/// flag-off curve does not run through it. Film 3840x1608 / screen capture
1653-/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075,
1654-/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough
1655-/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do.
1656-const RDOQ8_DEAD_ZONE: i32 = 2;
1657-
1658-/// Rate-distortion quantisation of one inter luma block: each level is offered
1659-/// the two cheaper magnitudes below it, and takes one when the squared error it
1660-/// gives up costs less than the bits it saves.
1661-///
1662-/// The rate is the CABAC coder's own price for the whole block against the
1663-/// context state as it stands, so dropping a level is priced with the
1664-/// significance map that follows from it — which is where most of the saving
1665-/// is. Intra blocks stay out: their reconstruction is what the next block in
1666-/// the macroblock predicts from, so a level changed here would move a
1667-/// prediction the decision cannot see.
1668-#[allow(clippy::too_many_arguments)]
1669-fn rdoq_4x4(
1670- e: &MbEnc<'_>,
1671- w: &EncEntropy,
1672- source: &[i32; 16],
1673- levels: &mut [i32; 16],
1674- qp: i32,
1675- cat: BlockCat,
1676- skip_dc: bool,
1677-) -> u8 {
1678- let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
1679- return levels.iter().filter(|&&l| l != 0).count() as u8;
1680- };
1681- let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
1682- let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
1683- // Highest scanning position first: dropping the last significant level is
1684- // what shortens the significance map, so it is tried while the levels
1685- // above it are still gone.
1686- for pos in (0..cat.max_num_coeff()).rev() {
1687- let level = levels[pos];
1688- if level == 0 {
1689- continue;
1690- }
1691- let mag = level.abs();
1692- if mag > RDOQ_MAX_LEVEL {
1693- continue;
1694- }
1695- let mut tried = mag;
1696- for candidate in [mag - 1, 0] {
1697- if candidate == tried {
1698- continue;
1699- }
1700- tried = candidate;
1701- let keep = levels[pos];
1702- levels[pos] = candidate * level.signum();
1703- let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
1704- unreachable!("CAVLC returned early");
1705- };
1706- let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
1707- if trial < cost {
1708- cost = trial;
1709- } else {
1710- levels[pos] = keep;
1711- }
1712- }
1713- }
1714- // And the block as a whole: zeroing it drops the coded_block_pattern bit as
1715- // well as every level, which no single-coefficient step can see. This is
1716- // the same decision `worth_coding` makes for the paths without an exact
1717- // rate, made here with one.
1718- let zero_bits = w
1719- .residual_block_cost(&[0; 16], cat, Some(1), Some(1))
1720- .expect("CABAC");
1721- let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
1722- if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost {
1723- *levels = [0; 16];
1724- return 0;
1725- }
1726- levels.iter().filter(|&&l| l != 0).count() as u8
1727-}
1728-
1729-/// How much of the mode-decision lambda the zero-block test uses.
1730-///
1731-/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
1732-/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier
1733-/// brings the rate term back to the coder actually in force. Measured over
1734-/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only
1735-/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate)
1736-/// without costing camera content.
1737-const ZERO_BLOCK_LAMBDA: f64 = 0.4;
1738-
1739-fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 {
1740- if transform_8x8 {
1741- e.lambda
1742- } else {
1743- ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
1744- }
1745-}
1746-
1747-/// The rate-distortion test behind the per-block zero decision: coding the
1748-/// block has to buy more squared error than its bits are worth.
1749-fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
1750- let mut ssd_zero = 0i64;
1751- let mut ssd_coded = 0i64;
1752- for i in 0..source.len() {
1753- let z = i64::from(source[i]);
1754- let c = i64::from(source[i] - resid[i]);
1755- ssd_zero += z * z;
1756- ssd_coded += c * c;
1757- }
1758- ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
1759-}
1760-
1761-/// Predict and code the luma of an Intra_16x16 macroblock.
1762-#[allow(clippy::too_many_arguments)]
1763-fn code_i16_luma(
1764- pic: &mut Picture,
1765- e: &MbEnc<'_>,
1766- mb_x: usize,
1767- mb_y: usize,
1768- qp: i32,
1769- mode: u8,
1770- nbr: &MbNeighbors,
1771- lv: &mut Levels,
1772-) {
1773- let w4 = pic.mb_w * 4;
1774- for dy in 0..4 {
1775- let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
1776- pic.i4_modes[base..base + 4].fill(2);
1777- }
1778- let stride = pic.y.stride;
1779- let origin = pic.y.at(mb_x * 16, mb_y * 16);
1780- let mut win = PlaneWindow {
1781- data: &mut pic.y.data,
1782- stride,
1783- origin,
1784- };
1785- pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
1786- code_luma_i16(pic, e, mb_x, mb_y, qp, lv);
1787-}
1788-
1789-/// The Intra_16x16 luma path (8.5.10 in reverse then forward again).
1790-fn code_luma_i16(
1791- pic: &mut Picture,
1792- e: &MbEnc<'_>,
1793- mb_x: usize,
1794- mb_y: usize,
1795- qp: i32,
1796- lv: &mut Levels,
1797-) {
1798- let stride = pic.y.stride;
1799- let mut dc = [0i32; 16];
1800- let mut ac = [[0i32; 16]; 16];
1801- for blk in 0..16 {
1802- let (dx, dy) = BLK4_POS[blk];
1803- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1804- let origin = pic.y.at(x, y);
1805- let mut d = [0i32; 16];
1806- for ry in 0..4 {
1807- for rx in 0..4 {
1808- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
1809- - i32::from(pic.y.data[origin + ry * stride + rx]);
1810- }
1811- }
1812- forward_4x4(&mut d);
1813- dc[dy as usize * 4 + dx as usize] = d[0];
1814- let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]);
1815- lv.luma_nz[blk] = nz;
1816- ac[blk] = lv.luma[blk];
1817- if nz > 0 {
1818- lv.cbp_luma = 15;
1819- }
1820- }
1821- if lv.cbp_luma == 0 {
1822- for blk in 0..16 {
1823- lv.luma[blk] = [0; 16];
1824- lv.luma_nz[blk] = 0;
1825- }
1826- }
1827- forward_hadamard_4x4(&mut dc);
1828- quant_luma_dc(&dc, qp, &mut lv.dc);
1829-
1830- // Reconstruct exactly as the decoder does: DC through 8.5.10, then each
1831- // block's AC with the DC substituted at raster position 0.
1832- let mut raster = [0i32; 16];
1833- unzigzag(&lv.dc, &mut raster);
1834- luma_dc_transform(&mut raster, &e.ls, qp);
1835- let dc_recon = raster;
1836- for blk in 0..16 {
1837- let (dx, dy) = BLK4_POS[blk];
1838- let dc_blk = dc_recon[dy as usize * 4 + dx as usize];
1839- let tc = lv.luma_nz[blk];
1840- if tc == 0 && dc_blk == 0 {
1841- continue;
1842- }
1843- let mut raster = [0i32; 16];
1844- if tc > 0 {
1845- unzigzag_ac15(&ac[blk], &mut raster);
1846- dequant_4x4(&mut raster, &e.ls, qp, true);
1847- }
1848- raster[0] = dc_blk;
1849- let mut resid = [0i32; 16];
1850- inverse_transform_4x4(&raster, &mut resid);
1851- let origin = pic
1852- .y
1853- .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1854- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
1855- }
1856-}
1857-
1858-/// Chroma residual for both components (8.5.11 + the AC path).
1859-#[allow(clippy::too_many_arguments)]
1860-fn code_chroma(
1861- pic: &mut Picture,
1862- e: &MbEnc<'_>,
1863- w: &EncEntropy,
1864- mb_x: usize,
1865- mb_y: usize,
1866- qp_y: i32,
1867- intra: bool,
1868- lv: &mut Levels,
1869-) {
1870- let qp_c = chroma_qp(qp_y, e.cqo);
1871- let mut dc_lists = [[0i32; 4]; 2];
1872- let mut ac = [[[0i32; 16]; 4]; 2];
1873- let mut srcs = [[[0i32; 16]; 4]; 2];
1874- let mut any_ac = false;
1875- for comp in 0..2 {
1876- let (plane, src) = if comp == 0 {
1877- (&pic.cb, &e.src.u)
1878- } else {
1879- (&pic.cr, &e.src.v)
1880- };
1881- let stride = plane.stride;
1882- for blk in 0..4 {
1883- let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
1884- let origin = plane.at(x, y);
1885- let mut d = [0i32; 16];
1886- for ry in 0..4 {
1887- for rx in 0..4 {
1888- d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx])
1889- - i32::from(plane.data[origin + ry * stride + rx]);
1890- }
1891- }
1892- let source = d;
1893- srcs[comp][blk] = d;
1894- forward_4x4(&mut d);
1895- dc_lists[comp][blk] = d[0];
1896- let rdoq = !intra && w.is_cabac();
1897- let mut nz = if rdoq {
1898- quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk])
1899- } else {
1900- quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk])
1901- };
1902- if rdoq && nz > 0 {
1903- nz = rdoq_4x4(
1904- e,
1905- w,
1906- &source,
1907- &mut ac[comp][blk],
1908- qp_c,
1909- BlockCat::ChromaAc,
1910- true,
1911- );
1912- } else if nz > 0 {
1913- // The same zero decision as luma, against the AC part alone:
1914- // the DC of this block travels through the 2x2 Hadamard and is
1915- // decided with the other three.
1916- let mut raster = [0i32; 16];
1917- unzigzag_ac15(&ac[comp][blk], &mut raster);
1918- dequant_4x4(&mut raster, &e.ls, qp_c, true);
1919- let mut resid = [0i32; 16];
1920- inverse_transform_4x4(&raster, &mut resid);
1921- if !worth_coding(
1922- &source,
1923- &resid,
1924- &ac[comp][blk],
1925- zero_block_lambda(e, qp_c, e.transform_8x8),
1926- ) {
1927- ac[comp][blk] = [0; 16];
1928- nz = 0;
1929- }
1930- }
1931- lv.chroma_nz[comp][blk] = nz;
1932- if nz > 0 {
1933- any_ac = true;
1934- }
1935- }
1936- }
1937- // The chroma pattern is one decision for all eight AC blocks: a single
1938- // surviving block takes coded_block_pattern from one to two, and every
1939- // other block then has to code a coded_block_flag to say it is empty. So
1940- // the same group test luma runs over four blocks runs here over all eight,
1941- // against the same lambda.
1942- if any_ac {
1943- let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64);
1944- for comp in 0..2 {
1945- for blk in 0..4 {
1946- let source = &srcs[comp][blk];
1947- let mut resid = [0i32; 16];
1948- if lv.chroma_nz[comp][blk] > 0 {
1949- let mut raster = [0i32; 16];
1950- unzigzag_ac15(&ac[comp][blk], &mut raster);
1951- dequant_4x4(&mut raster, &e.ls, qp_c, true);
1952- inverse_transform_4x4(&raster, &mut resid);
1953- rate += match w.residual_block_cost(
1954- &ac[comp][blk],
1955- BlockCat::ChromaAc,
1956- Some(1),
1957- Some(1),
1958- ) {
1959- Some(bits) => f64::from(bits) / 256.0,
1960- None => block_bits(&ac[comp][blk]) as f64,
1961- };
1962- }
1963- for i in 0..16 {
1964- let z = i64::from(source[i]);
1965- let c = i64::from(source[i] - resid[i]);
1966- ssd_zero += z * z;
1967- ssd_coded += c * c;
1968- }
1969- }
1970- }
1971- let lambda = if w.is_cabac() {
1972- GROUP_LAMBDA * lambda_ssd(qp_c)
1973- } else {
1974- zero_block_lambda(e, qp_c, false)
1975- };
1976- if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 {
1977- ac = [[[0; 16]; 4]; 2];
1978- lv.chroma_nz = [[0; 4]; 2];
1979- any_ac = false;
1980- }
1981- }
1982- // The chroma DC block had no zero test at all: whatever the quantiser
1983- // produced was coded. Its four coefficients spread over all 64 samples of
1984- // the component, and with only DC in the block the inverse transform gives
1985- // every sample the same (dc + 32) >> 6, so the squared error zeroing costs
1986- // is exact in one pass over the AC residual that is already reconstructed
1987- // here.
1988- let mut any_dc = false;
1989- for comp in 0..2 {
1990- forward_hadamard_2x2(&mut dc_lists[comp]);
1991- let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]);
1992- if nz > 0 {
1993- let mut dc = [
1994- lv.chroma_dc[comp][0],
1995- lv.chroma_dc[comp][1],
1996- lv.chroma_dc[comp][2],
1997- lv.chroma_dc[comp][3],
1998- ];
1999- chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
2000- let mut delta = 0i64;
2001- for blk in 0..4 {
2002- let mut resid = [0i32; 16];
2003- if any_ac && lv.chroma_nz[comp][blk] > 0 {
2004- let mut raster = [0i32; 16];
2005- unzigzag_ac15(&ac[comp][blk], &mut raster);
2006- dequant_4x4(&mut raster, &e.ls, qp_c, true);
2007- inverse_transform_4x4(&raster, &mut resid);
2008- }
2009- let c = i64::from((dc[blk] + 32) >> 6);
2010- let err: i64 = (0..16)
2011- .map(|i| i64::from(srcs[comp][blk][i] - resid[i]))
2012- .sum();
2013- delta += 16 * c * c - 2 * c * err;
2014- }
2015- let rate = match w.residual_block_cost(
2016- &lv.chroma_dc[comp],
2017- BlockCat::ChromaDc(comp as u8),
2018- Some(1),
2019- Some(1),
2020- ) {
2021- Some(bits) => f64::from(bits) / 256.0,
2022- None => block_bits(&lv.chroma_dc[comp]) as f64,
2023- };
2024- if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 {
2025- lv.chroma_dc[comp] = [0; 16];
2026- nz = 0;
2027- }
2028- }
2029- if nz > 0 {
2030- any_dc = true;
2031- }
2032- }
2033- lv.cbp_chroma = if any_ac {
2034- 2
2035- } else if any_dc {
2036- 1
2037- } else {
2038- 0
2039- };
2040- if lv.cbp_chroma < 2 {
2041- lv.chroma_nz = [[0; 4]; 2];
2042- } else {
2043- lv.chroma = ac;
2044- }
2045- if lv.cbp_chroma == 0 {
2046- return;
2047- }
2048- for comp in 0..2 {
2049- let mut dc = [
2050- lv.chroma_dc[comp][0],
2051- lv.chroma_dc[comp][1],
2052- lv.chroma_dc[comp][2],
2053- lv.chroma_dc[comp][3],
2054- ];
2055- chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
2056- let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
2057- let stride = plane.stride;
2058- for blk in 0..4 {
2059- let tc = lv.chroma_nz[comp][blk];
2060- if tc == 0 && dc[blk] == 0 {
2061- continue;
2062- }
2063- let mut raster = [0i32; 16];
2064- if tc > 0 {
2065- unzigzag_ac15(&lv.chroma[comp][blk], &mut raster);
2066- dequant_4x4(&mut raster, &e.ls, qp_c, true);
2067- }
2068- raster[0] = dc[blk];
2069- let mut resid = [0i32; 16];
2070- inverse_transform_4x4(&raster, &mut resid);
2071- let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
2072- add_residual_4x4(&mut plane.data, 8, stride, origin, &resid);
2073- }
2074- }
2075-}
2076-
2077-/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction
2078-/// mode against the *reconstructed* neighbours and reconstruct it immediately,
2079-/// because the next block predicts from it. Returns the chosen modes and the
2080-/// modes they were predicted to be.
2081-/// How many SATD survivors the Intra_4x4 mode decision re-costs with real
2082-/// quantisation before choosing.
2083-const I4_RD_CANDIDATES: usize = 3;
2084-
2085-fn code_intra_4x4(
2086- pic: &mut Picture,
2087- e: &MbEnc<'_>,
2088- mb_x: usize,
2089- mb_y: usize,
2090- qp: i32,
2091- nbr: &MbNeighbors,
2092- lv: &mut Levels,
2093-) -> ([u8; 16], [u8; 16]) {
2094- let w4 = pic.mb_w * 4;
2095- let (bx0, by0) = (mb_x * 4, mb_y * 4);
2096- let mut modes = [2u8; 16];
2097- let mut pred_modes = [2u8; 16];
2098- for blk in 0..16 {
2099- let (dx, dy) = BLK4_POS[blk];
2100- let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2101- let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
2102- let left_avail = if dx == 0 { nbr.a } else { true };
2103- let top_avail = if dy == 0 { nbr.b } else { true };
2104- let predicted = if left_avail && top_avail {
2105- pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
2106- } else {
2107- 2
2108- };
2109- pred_modes[blk] = predicted;
2110- let n = gather_nbr4(pic, nbr, blk, x, y);
2111- let have_tl = match (dx, dy) {
2112- (0, 0) => nbr.d,
2113- (0, _) => nbr.a,
2114- (_, 0) => nbr.b,
2115- _ => true,
2116- };
2117- let allowed = modes_allowed(n.have_top, n.have_left, have_tl);
2118- let mut best = (i32::MAX, predicted.min(2));
2119- let mut p = [0u8; 16];
2120- let mut ranked = [(i32::MAX, 2u8); 9];
2121- for mode in 0..9u8 {
2122- if !allowed[mode as usize] {
2123- continue;
2124- }
2125- pred_4x4(mode, 8, &n, &mut p);
2126- let bits = if mode == predicted { 1 } else { 4 };
2127- let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
2128- ranked[mode as usize] = (c, mode);
2129- if c < best.0 {
2130- best = (c, mode);
2131- }
2132- }
2133- let mut mode = best.1;
2134- // SATD ranks the modes; the survivors are re-costed with the
2135- // quantisation actually in force, because a mode that predicts a
2136- // little worse can quantise to far fewer levels. Measured against
2137- // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440
2138- // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB
2139- // at GOP 10, for 3-4% encode time. Three survivors is where it
2140- // saturates -- all nine landed within 0.002 dB of three, for 7% more
2141- // encode time.
2142- {
2143- ranked.sort_unstable();
2144- let keep = I4_RD_CANDIDATES;
2145- // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the
2146- // full rate term this search loses 0.065 dB instead of gaining,
2147- // and it loses more the more candidates it sees.
2148- let lambda = ZERO_BLOCK_LAMBDA
2149- * if e.transform_8x8 {
2150- e.lambda
2151- } else {
2152- lambda_ssd(qp)
2153- };
2154- let mut best_rd = f64::MAX;
2155- for &(c, cand) in ranked.iter().take(keep) {
2156- if c == i32::MAX {
2157- break;
2158- }
2159- pred_4x4(cand, 8, &n, &mut p);
2160- let mut d = [0i32; 16];
2161- for ry in 0..4 {
2162- for rx in 0..4 {
2163- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2164- - i32::from(p[ry * 4 + rx]);
2165- }
2166- }
2167- let src = d;
2168- forward_4x4(&mut d);
2169- let mut levels = [0i32; 16];
2170- let nz = quant_4x4(&d, qp, true, false, &mut levels);
2171- let mut resid = [0i32; 16];
2172- if nz > 0 {
2173- let mut raster = [0i32; 16];
2174- unzigzag(&levels, &mut raster);
2175- dequant_4x4(&mut raster, &e.ls, qp, false);
2176- inverse_transform_4x4(&raster, &mut resid);
2177- }
2178- let mut ssd = 0i64;
2179- for i in 0..16 {
2180- let err = i64::from(src[i] - resid[i]);
2181- ssd += err * err;
2182- }
2183- let mode_bits = if cand == predicted { 1 } else { 4 };
2184- let bits = block_bits(&levels) + mode_bits;
2185- let cost = ssd as f64 + lambda * bits as f64;
2186- if cost < best_rd {
2187- best_rd = cost;
2188- mode = cand;
2189- }
2190- }
2191- }
2192- modes[blk] = mode;
2193- pic.i4_modes[by * w4 + bx] = mode;
2194- // Prediction into the plane, then residual and reconstruction.
2195- pred_4x4(mode, 8, &n, &mut p);
2196- let stride = pic.y.stride;
2197- let origin = pic.y.at(x, y);
2198- for ry in 0..4 {
2199- let row = origin + ry * stride;
2200- pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2201- }
2202- let mut d = [0i32; 16];
2203- for ry in 0..4 {
2204- for rx in 0..4 {
2205- d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2206- - i32::from(p[ry * 4 + rx]);
2207- }
2208- }
2209- forward_4x4(&mut d);
2210- let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]);
2211- lv.luma_nz[blk] = nz;
2212- if nz > 0 {
2213- lv.cbp_luma |= 1 << (blk >> 2);
2214- let mut raster = [0i32; 16];
2215- unzigzag(&lv.luma[blk], &mut raster);
2216- dequant_4x4(&mut raster, &e.ls, qp, false);
2217- let mut resid = [0i32; 16];
2218- inverse_transform_4x4(&raster, &mut resid);
2219- add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
2220- }
2221- }
2222- (modes, pred_modes)
2223-}
2224-
2225-/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read
2226-/// from the 4x4 slots every size writes its mode into.
2227-fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 {
2228- let w4 = pic.mb_w * 4;
2229- let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true };
2230- let top_avail = if blk8 < 2 { nbr.b } else { true };
2231- if left_avail && top_avail {
2232- pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
2233- } else {
2234- 2
2235- }
2236-}
2237-
2238-/// Residual of one 8x8 luma block against the prediction already in the
2239-/// plane: forward transform, quantise, and — when anything survives —
2240-/// reconstruct with the decoder's own inverse. Returns the non-zero count.
2241-#[allow(clippy::too_many_arguments)]
2242-fn code_block_8x8(
2243- pic: &mut Picture,
2244- e: &MbEnc<'_>,
2245- w: &EncEntropy,
2246- x: usize,
2247- y: usize,
2248- qp: i32,
2249- intra: bool,
2250- out: &mut [i32; 64],
2251-) -> u8 {
2252- let stride = pic.y.stride;
2253- let origin = pic.y.at(x, y);
2254- let mut d = [0i32; 64];
2255- for ry in 0..8 {
2256- for rx in 0..8 {
2257- d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
2258- - i32::from(pic.y.data[origin + ry * stride + rx]);
2259- }
2260- }
2261- let rdoq = !intra && w.is_cabac();
2262- let fwd = forward_8x8(&d);
2263- let mut nz = if rdoq {
2264- quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out)
2265- } else {
2266- quant_8x8(&fwd, &e.ls8, qp, intra, out)
2267- };
2268- if nz == 0 {
2269- return 0;
2270- }
2271- if rdoq {
2272- nz = rdoq_8x8(e, w, &d, out, qp);
2273- if nz == 0 {
2274- return 0;
2275- }
2276- }
2277- let mut raster = [0i32; 64];
2278- unzigzag_8x8(out, &mut raster);
2279- dequant_8x8(&mut raster, &e.ls8, qp);
2280- let mut resid = [0i32; 64];
2281- inverse_transform_8x8(&raster, &mut resid);
2282- if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8))
2283- {
2284- *out = [0; 64];
2285- return 0;
2286- }
2287- add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid);
2288- nz
2289-}
2290-
2291-/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
2292-/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
2293-/// samples, and every 4x4 mode slot of a block carries its mode.
2294-#[allow(clippy::too_many_arguments)]
2295-fn code_intra_8x8(
2296- pic: &mut Picture,
2297- e: &MbEnc<'_>,
2298- w: &EncEntropy,
2299- mb_x: usize,
2300- mb_y: usize,
2301- qp: i32,
2302- nbr: &MbNeighbors,
2303- lv: &mut Levels,
2304-) -> ([u8; 4], [u8; 4]) {
2305- let w4 = pic.mb_w * 4;
2306- let mut modes = [2u8; 4];
2307- let mut pred_modes = [2u8; 4];
2308- lv.trans8 = true;
2309- for blk8 in 0..4 {
2310- let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2);
2311- let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
2312- let predicted = predicted_mode8(pic, nbr, bx, by, blk8);
2313- pred_modes[blk8] = predicted;
2314- let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y));
2315- let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl);
2316- let mut p = [0u8; 64];
2317- {
2318- let (mode, coded, recon) =
2319- i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p);
2320- let stride = pic.y.stride;
2321- let origin = pic.y.at(x, y);
2322- for ry in 0..8 {
2323- let row = origin + ry * stride;
2324- pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]);
2325- }
2326- lv.luma8[blk8] = coded.0;
2327- if coded.1 {
2328- lv.cbp_luma |= 1 << blk8;
2329- }
2330- modes[blk8] = mode;
2331- for dy in 0..2 {
2332- let base = (by + dy) * w4 + bx;
2333- pic.i4_modes[base..base + 2].fill(mode);
2334- }
2335- }
2336- }
2337- (modes, pred_modes)
2338-}
2339-
2340-/// The inter residual under the 8x8 transform, prediction already in the
2341-/// plane: the sibling of [`code_luma_4x4`].
2342-fn code_luma_8x8(
2343- pic: &mut Picture,
2344- e: &MbEnc<'_>,
2345- w: &EncEntropy,
2346- mb_x: usize,
2347- mb_y: usize,
2348- qp: i32,
2349- lv: &mut Levels,
2350-) {
2351- lv.trans8 = true;
2352- for blk8 in 0..4 {
2353- let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
2354- if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
2355- lv.cbp_luma |= 1 << blk8;
2356- }
2357- }
2358-}
2359-
2360-/// Squared error of coding `levels` as an 8x8 block, in its pixels.
2361-fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 {
2362- let mut raster = [0i32; 64];
2363- unzigzag_8x8(levels, &mut raster);
2364- dequant_8x8(&mut raster, &e.ls8, qp);
2365- let mut resid = [0i32; 64];
2366- inverse_transform_8x8(&raster, &mut resid);
2367- let mut ssd = 0i64;
2368- for k in 0..64 {
2369- let d = i64::from(source[k]) - i64::from(resid[k]);
2370- ssd += d * d;
2371- }
2372- ssd
2373-}
2374-
2375-/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the
2376-/// CABAC coder's own price, with the 8x8 block's own contexts.
2377-fn rdoq_8x8(
2378- e: &MbEnc<'_>,
2379- w: &EncEntropy,
2380- source: &[i32; 64],
2381- levels: &mut [i32; 64],
2382- qp: i32,
2383-) -> u8 {
2384- let Some(bits) = w.residual_block_8x8_cost(levels) else {
2385- return levels.iter().filter(|&&l| l != 0).count() as u8;
2386- };
2387- let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
2388- let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
2389- for pos in (0..64).rev() {
2390- let level = levels[pos];
2391- if level == 0 {
2392- continue;
2393- }
2394- let mag = level.abs();
2395- if mag > RDOQ_MAX_LEVEL {
2396- continue;
2397- }
2398- let mut tried = mag;
2399- for candidate in [mag - 1, 0] {
2400- if candidate == tried {
2401- continue;
2402- }
2403- tried = candidate;
2404- let keep = levels[pos];
2405- levels[pos] = candidate * level.signum();
2406- let bits = w
2407- .residual_block_8x8_cost(levels)
2408- .expect("CAVLC returned early");
2409- let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
2410- if trial < cost {
2411- cost = trial;
2412- } else {
2413- levels[pos] = keep;
2414- break;
2415- }
2416- }
2417- }
2418- // The whole block against nothing, on the same exact price.
2419- let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
2420- if ssd_zero as f64 <= cost {
2421- *levels = [0; 64];
2422- return 0;
crates/ec-h264/src/enc/mb/inter.rsadded+346 -0
@@ -0,0 +1,346 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+
4+use crate::decoder::{
5+ MbNeighbors, };
6+use crate::dpb::{BLK_SKIP, Picture};
7+use crate::entropy::{
8+ FLAG_DECODED, FLAG_INTER, FLAG_SKIP, };
9+use crate::inter::{Put, RefPlane, mc_chroma, mc_luma};
10+use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_mvd};
11+
12+
13+use crate::enc::{
14+ entropy::{EncEntropy},
15+ lambda_ssd,
16+};
17+use super::*;
18+
19+#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
20+pub(super) fn inter_mb_bits(
21+ pic: &Picture,
22+ e: &MbEnc<'_>,
23+ w: &EncEntropy,
24+ mb_addr: usize,
25+ nbr: &MbNeighbors,
26+ shape: PShape,
27+ mvd: &[[i16; 2]; 4],
28+ inc: &[[usize; 2]; 4],
29+ lv: &Levels,
30+) -> i64 {
31+ entropy_bits(w, |cw| {
32+ cw.begin_mb(&e.mb_ctx);
33+ cw.coded_mb(true, e.skip_inc);
34+ cw.set_intra(false);
35+ cw.mb_type(true, shape.mb_type());
36+ if shape == PShape::Quad {
37+ for _ in 0..4 {
38+ cw.sub_mb_type_p(0); // P_L0_8x8
39+ }
40+ }
41+ for part in 0..shape.parts() {
42+ for comp in 0..2 {
43+ cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
44+ }
45+ }
46+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
47+ if lv.cbp_luma != 0 && e.transform_8x8 {
48+ cw.transform_size_8x8_flag(lv.trans8);
49+ }
50+ if lv.cbp_luma != 0 || lv.cbp_chroma != 0 {
51+ cw.mb_qp_delta(e.target_qp - e.qp);
52+ let mb_x = mb_addr % pic.mb_w;
53+ let mb_y = mb_addr / pic.mb_w;
54+ write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false);
55+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
56+ }
57+ })
58+}
59+
60+/// Motion-compensate one partition into the picture planes.
61+pub(super) fn compensate_part(
62+ pic: &mut Picture,
63+ reference: &Picture,
64+ mb_x: usize,
65+ mb_y: usize,
66+ (bx, by): (usize, usize),
67+ (w, h): (usize, usize),
68+ mv: [i16; 2],
69+) {
70+ let (x0, y0) = ((mb_x * 16 + bx * 4) as i32, (mb_y * 16 + by * 4) as i32);
71+ let plane = RefPlane {
72+ data: &reference.y.data,
73+ stride: reference.y.stride,
74+ origin: reference.y.origin,
75+ width: reference.y.width,
76+ height: reference.y.height,
77+ pad: reference.y.pad,
78+ };
79+ let stride = pic.y.stride;
80+ let origin = pic.y.at(mb_x * 16 + bx * 4, mb_y * 16 + by * 4);
81+ mc_luma(
82+ &plane,
83+ x0,
84+ y0,
85+ mv,
86+ w,
87+ h,
88+ stride,
89+ &mut pic.y.data[origin..],
90+ Put::Set,
91+ );
92+ for comp in 0..2 {
93+ let src = if comp == 0 {
94+ &reference.cb
95+ } else {
96+ &reference.cr
97+ };
98+ let plane = RefPlane {
99+ data: &src.data,
100+ stride: src.stride,
101+ origin: src.origin,
102+ width: src.width,
103+ height: src.height,
104+ pad: src.pad,
105+ };
106+ let dst = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
107+ let stride = dst.stride;
108+ let origin = dst.at(mb_x * 8 + bx * 2, mb_y * 8 + by * 2);
109+ mc_chroma(
110+ &plane,
111+ x0 / 2,
112+ y0 / 2,
113+ mv,
114+ w / 2,
115+ h / 2,
116+ stride,
117+ &mut dst.data[origin..],
118+ Put::Set,
119+ );
120+ }
121+}
122+
123+/// Code a P macroblock: skip, one 16x16 partition, two halves or four
124+/// quarters.
125+pub(super) fn encode_inter_mb(
126+ pic: &mut Picture,
127+ e: &mut MbEnc<'_>,
128+ w: &mut EncEntropy,
129+ mb_addr: usize,
130+ nbr: MbNeighbors,
131+ choice: InterChoice,
132+) {
133+ let mb_x = mb_addr % pic.mb_w;
134+ let mb_y = mb_addr / pic.mb_w;
135+ let reference = e.reference.expect("a P macroblock has a reference");
136+ let ref_id = reference.id;
137+ let qp = e.target_qp;
138+ let shape = if choice.prefer_skip {
139+ PShape::Whole
140+ } else {
141+ choice.shape
142+ };
143+
144+ // Motion vectors, their predictors and the reconstruction, partition by
145+ // partition and in coding order: a partition's predictor reads the motion
146+ // of the partitions before it (8.4.1.3), so the order is not free.
147+ let mut ctx = MvCtx {
148+ mb_x,
149+ mb_y,
150+ slice_id: e.slice_id,
151+ written: 0,
152+ pos: Default::default(),
153+ };
154+ let (part_w, part_h) = shape.part_blocks();
155+ let mut mvd = [[0i16; 2]; 4];
156+ let mut inc = [[0usize; 2]; 4];
157+ for part in 0..shape.parts() {
158+ let ((bx, by), (pw, ph)) = shape.geometry(part);
159+ let mv = if choice.prefer_skip {
160+ choice.skip_mv
161+ } else {
162+ choice.mv[part]
163+ };
164+ let n = ctx.neighbours(pic, bx, by, part_w, 0);
165+ let mvp = predict_mv(&n, 0, part_w, part_h, part);
166+ // ctxIdxInc from the neighbouring partitions' absolute mvd
167+ // (9.3.3.1.1.7), read before this partition writes its own.
168+ let (gx, gy) = ((mb_x * 4 + bx) as i32, (mb_y * 4 + by) as i32);
169+ for comp in 0..2 {
170+ let sum = neighbour_mvd(pic, &ctx, gx - 1, gy, 0)[comp]
171+ + neighbour_mvd(pic, &ctx, gx, gy - 1, 0)[comp];
172+ inc[part][comp] = if sum > 32 {
173+ 2
174+ } else if sum > 2 {
175+ 1
176+ } else {
177+ 0
178+ };
179+ }
180+ mvd[part] = [mv[0] - mvp[0], mv[1] - mvp[1]];
181+ compensate_part(pic, reference, mb_x, mb_y, (bx, by), (pw, ph), mv);
182+ for py in by..by + ph / 4 {
183+ for px in bx..bx + pw / 4 {
184+ write_block(
185+ pic,
186+ &mut ctx,
187+ px,
188+ py,
189+ [mv, [0, 0]],
190+ [0, -1],
191+ [ref_id, -1],
192+ 0,
193+ );
194+ write_mvd(pic, mb_x, mb_y, px, py, 0, mvd[part]);
195+ }
196+ }
197+ }
198+
199+ // Skipping is only *available* on the P_Skip vector of a whole macroblock,
200+ // and only worth taking when the residual it drops is worth less than the
201+ // bits it saves: on static content a macroblock whose residual is pure
202+ // quantisation churn costs bits every picture and improves nothing.
203+ let may_skip = choice.prefer_skip;
204+ let (lv, skip) = if choice.force_skip {
205+ (Levels::default(), true)
206+ } else {
207+ let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y));
208+ let mut chroma_lv = Levels::default();
209+ code_chroma(pic, e, w, mb_x, mb_y, qp, false, &mut chroma_lv);
210+ let mut lv = chroma_lv.clone();
211+ let tx_mode = if e.preset == Preset::Fast {
212+ e.fast.inter_tx
213+ } else {
214+ 0
215+ };
216+ if e.transform_8x8 && tx_mode == 1 {
217+ code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv);
218+ } else if e.transform_8x8 && tx_mode != 2 {
219+ // Both transform sizes on the same prediction; the cheaper
220+ // rate-distortion cost is coded.
221+ let mut pred = [0u8; 256];
222+ save_luma(pic, mb_x, mb_y, &mut pred);
223+ let mut lv4 = chroma_lv.clone();
224+ code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv4);
225+ // At Fast the 8x8 trial is only worth its time when the 4x4 coding
226+ // left a few levels in a smooth residual: an empty one cannot be
227+ // beaten and a dense one rarely is.
228+ let nz4: u32 = lv4.luma_nz.iter().map(|&n| u32::from(n)).sum();
229+ if tx_mode == 3 && (lv4.cbp_luma == 0 || nz4 > e.fast.tx8_nz_limit) {
230+ lv = lv4;
231+ } else {
232+ let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
233+ let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;
234+ let mut recon4 = [0u8; 256];
235+ save_luma(pic, mb_x, mb_y, &mut recon4);
236+ restore_luma(pic, mb_x, mb_y, &pred);
237+ let mut lv8 = chroma_lv;
238+ code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8);
239+ let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
240+ let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64;
241+ if cost8 < cost4 {
242+ lv = lv8;
243+ } else {
244+ lv = lv4;
245+ restore_luma(pic, mb_x, mb_y, &recon4);
246+ }
247+ }
248+ } else {
249+ code_luma_4x4(pic, e, w, mb_x, mb_y, qp, false, &mut lv);
250+ }
251+ let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
252+ let skip = match ssd_skip {
253+ None => false,
254+ Some(_) if empty => true,
255+ Some(ssd_skip) => {
256+ let coded = if e.transform_8x8 {
257+ let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv);
258+ ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
259+ } else {
260+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64
261+ };
262+ if ssd_skip as f64 <= coded {
263+ // Put the prediction back: the residual has been added to it.
264+ compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv);
265+ true
266+ } else {
267+ false
268+ }
269+ }
270+ };
271+ (lv, skip)
272+ };
273+
274+ let w4 = pic.mb_w * 4;
275+ if skip {
276+ for py in 0..4 {
277+ for px in 0..4 {
278+ let idx = (mb_y * 4 + py) * w4 + mb_x * 4 + px;
279+ pic.blk[idx] = BLK_SKIP;
280+ pic.mvd_abs[idx] = [0; 4];
281+ }
282+ }
283+ for dy in 0..4 {
284+ let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
285+ pic.nz_y[base..base + 4].fill(0);
286+ pic.i4_modes[base..base + 4].fill(2);
287+ }
288+ for comp in 0..2 {
289+ for dy in 0..2 {
290+ let base = (mb_y * 2 + dy) * pic.mb_w * 2 + mb_x * 2;
291+ pic.nz_c[comp][base..base + 2].fill(0);
292+ }
293+ }
294+ pic.mb_qp[mb_addr] = e.qp as i8;
295+ pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_INTER | FLAG_SKIP;
296+ pic.mb_cbp[mb_addr] = 0;
297+ pic.mb_dc_cbf[mb_addr] = 0;
298+ pic.mb_slice[mb_addr] = e.slice_id;
299+ pic.decoded_mbs += 1;
300+ e.qp_delta_inc = 0;
301+ w.skipped_mb(e.skip_inc);
302+ return;
303+ }
304+ for dy in 0..4 {
305+ let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
306+ pic.i4_modes[base..base + 4].fill(2);
307+ }
308+
309+ // ---- syntax ----
310+ w.begin_mb(&e.mb_ctx);
311+ w.coded_mb(true, e.skip_inc);
312+ w.set_intra(false);
313+ w.mb_type(true, shape.mb_type());
314+ if shape == PShape::Quad {
315+ for _ in 0..4 {
316+ w.sub_mb_type_p(0); // P_L0_8x8
317+ }
318+ }
319+ // num_ref_idx_l0_active is 1, so ref_idx_l0 is not coded.
320+ for part in 0..shape.parts() {
321+ for comp in 0..2 {
322+ w.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
323+ }
324+ }
325+ w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
326+ // Every shape this encoder emits is 8x8-aligned, so the decoder reads the
327+ // flag whenever luma is coded.
328+ if lv.cbp_luma != 0 && e.transform_8x8 {
329+ w.transform_size_8x8_flag(lv.trans8);
330+ }
331+ finish_mb(
332+ pic,
333+ e,
334+ w,
335+ mb_addr,
336+ &nbr,
337+ &lv,
338+ MbRecord {
339+ intra: false,
340+ is_i16: false,
341+ chroma_mode: 0,
342+ qp,
343+ },
344+ );
345+}
346+
crates/ec-h264/src/enc/mb/intra.rsadded+800 -0
@@ -0,0 +1,800 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+use ec_h264_syntax::SliceType;
4+
5+use crate::decoder::{
6+ MbNeighbors, gather_nbr4, gather_nbr8, };
7+use crate::dpb::{Picture};
8+use crate::entropy::{
9+ BlockCat, };
10+use crate::mv::{write_intra_mb};
11+use crate::pred::{
12+ PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
13+ pred_chroma_8x8,
14+};
15+use crate::tables::{BLK4_POS};
16+use crate::transform::{
17+ dequant_4x4, dequant_8x8,
18+ inverse_transform_4x4, inverse_transform_8x8, unzigzag, unzigzag_8x8,
19+ };
20+
21+use crate::enc::quant::{
22+ forward_4x4, forward_8x8, quant_4x4,
23+ quant_8x8, quant_8x8_offset, };
24+
25+use crate::enc::{
26+ entropy::{EncEntropy},
27+ lambda_ssd,
28+};
29+use super::*;
30+
31+/// The Intra_16x16 mode this macroblock would use. Intra_16x16 against
32+/// Intra_4x4 is decided later, on real rate and real distortion (see
33+/// [`encode_intra_mb`]).
34+pub(super) struct IntraCost {
35+ pub(super) i16_mode: u8,
36+ /// SATD of the Intra_16x16 mode above: the cheap intra estimate that
37+ /// `Preset::Fast` gates the full intra branch on.
38+ pub(super) satd: i32,
39+ /// True when Intra_4x4 may be used at all for this picture and preset.
40+ pub(super) allow_i4: bool,
41+}
42+
43+/// Best Intra_16x16 mode by SATD, leaving nothing behind in the plane that a
44+/// later branch does not overwrite.
45+pub(super) fn intra_pre_cost(
46+ pic: &mut Picture,
47+ e: &MbEnc<'_>,
48+ nbr: &MbNeighbors,
49+ mb_x: usize,
50+ mb_y: usize,
51+ modes: &[u8],
52+) -> IntraCost {
53+ let (sx, sy) = (mb_x * 16, mb_y * 16);
54+ let stride = pic.y.stride;
55+ let origin = pic.y.at(sx, sy);
56+ let mut best = (i32::MAX, 2u8);
57+ for &mode in modes {
58+ let ok = match mode {
59+ 0 => nbr.b,
60+ 1 => nbr.a,
61+ 3 => nbr.a && nbr.b && nbr.d,
62+ _ => true,
63+ };
64+ if !ok {
65+ continue;
66+ }
67+ let mut win = PlaneWindow {
68+ data: &mut pic.y.data,
69+ stride,
70+ origin,
71+ };
72+ pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
73+ let cost = satd16(&e.src.y, e.src.stride, sx, sy, &pic.y.data, stride, origin);
74+ if cost < best.0 {
75+ best = (cost, mode);
76+ }
77+ }
78+ IntraCost {
79+ i16_mode: best.1,
80+ satd: best.0,
81+ // Intra_4x4 is tried in P pictures too, at every preset. Re-measured
82+ // once the intra-versus-inter decision became a real one (BD-PSNR
83+ // against x264, GOP 10, QP 22/26/30/34): restricting it to I pictures
84+ // reads -1.613 dB on the film clip and -0.508 on the screen capture,
85+ // where allowing it everywhere reads -0.728 and -0.500. It stays on
86+ // everywhere. Under the old prediction-domain decision the screen
87+ // capture preferred the restriction by a third of a dB; coding both
88+ // branches for real removed that disagreement.
89+ allow_i4: true,
90+ }
91+}
92+
93+/// Code the luma of an Intra_4x4 macroblock: per block, choose the prediction
94+/// mode against the *reconstructed* neighbours and reconstruct it immediately,
95+/// because the next block predicts from it. Returns the chosen modes and the
96+/// modes they were predicted to be.
97+/// How many SATD survivors the Intra_4x4 mode decision re-costs with real
98+/// quantisation before choosing.
99+pub(super) const I4_RD_CANDIDATES: usize = 3;
100+
101+pub(super) fn code_intra_4x4(
102+ pic: &mut Picture,
103+ e: &MbEnc<'_>,
104+ mb_x: usize,
105+ mb_y: usize,
106+ qp: i32,
107+ nbr: &MbNeighbors,
108+ lv: &mut Levels,
109+) -> ([u8; 16], [u8; 16]) {
110+ let w4 = pic.mb_w * 4;
111+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
112+ let mut modes = [2u8; 16];
113+ let mut pred_modes = [2u8; 16];
114+ for blk in 0..16 {
115+ let (dx, dy) = BLK4_POS[blk];
116+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
117+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
118+ let left_avail = if dx == 0 { nbr.a } else { true };
119+ let top_avail = if dy == 0 { nbr.b } else { true };
120+ let predicted = if left_avail && top_avail {
121+ pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
122+ } else {
123+ 2
124+ };
125+ pred_modes[blk] = predicted;
126+ let n = gather_nbr4(pic, nbr, blk, x, y);
127+ let have_tl = match (dx, dy) {
128+ (0, 0) => nbr.d,
129+ (0, _) => nbr.a,
130+ (_, 0) => nbr.b,
131+ _ => true,
132+ };
133+ let allowed = modes_allowed(n.have_top, n.have_left, have_tl);
134+ let mut best = (i32::MAX, predicted.min(2));
135+ let mut p = [0u8; 16];
136+ let mut ranked = [(i32::MAX, 2u8); 9];
137+ for mode in 0..9u8 {
138+ if !allowed[mode as usize] {
139+ continue;
140+ }
141+ pred_4x4(mode, 8, &n, &mut p);
142+ let bits = if mode == predicted { 1 } else { 4 };
143+ let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
144+ ranked[mode as usize] = (c, mode);
145+ if c < best.0 {
146+ best = (c, mode);
147+ }
148+ }
149+ let mut mode = best.1;
150+ // SATD ranks the modes; the survivors are re-costed with the
151+ // quantisation actually in force, because a mode that predicts a
152+ // little worse can quantise to far fewer levels. Measured against
153+ // x264 with `bd_psnr_vs_x264` on a 3840x1608 film clip and a 2560x1440
154+ // screen capture: +0.129 and +0.088 dB all-intra, +0.062 and +0.043 dB
155+ // at GOP 10, for 3-4% encode time. Three survivors is where it
156+ // saturates -- all nine landed within 0.002 dB of three, for 7% more
157+ // encode time.
158+ {
159+ ranked.sort_unstable();
160+ let keep = I4_RD_CANDIDATES;
161+ // The same over-count [`ZERO_BLOCK_LAMBDA`] corrects for: with the
162+ // full rate term this search loses 0.065 dB instead of gaining,
163+ // and it loses more the more candidates it sees.
164+ let lambda = ZERO_BLOCK_LAMBDA
165+ * if e.transform_8x8 {
166+ e.lambda
167+ } else {
168+ lambda_ssd(qp)
169+ };
170+ let mut best_rd = f64::MAX;
171+ for &(c, cand) in ranked.iter().take(keep) {
172+ if c == i32::MAX {
173+ break;
174+ }
175+ pred_4x4(cand, 8, &n, &mut p);
176+ let mut d = [0i32; 16];
177+ for ry in 0..4 {
178+ for rx in 0..4 {
179+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
180+ - i32::from(p[ry * 4 + rx]);
181+ }
182+ }
183+ let src = d;
184+ forward_4x4(&mut d);
185+ let mut levels = [0i32; 16];
186+ let nz = quant_4x4(&d, qp, true, false, &mut levels);
187+ let mut resid = [0i32; 16];
188+ if nz > 0 {
189+ let mut raster = [0i32; 16];
190+ unzigzag(&levels, &mut raster);
191+ dequant_4x4(&mut raster, &e.ls, qp, false);
192+ inverse_transform_4x4(&raster, &mut resid);
193+ }
194+ let mut ssd = 0i64;
195+ for i in 0..16 {
196+ let err = i64::from(src[i] - resid[i]);
197+ ssd += err * err;
198+ }
199+ let mode_bits = if cand == predicted { 1 } else { 4 };
200+ let bits = block_bits(&levels) + mode_bits;
201+ let cost = ssd as f64 + lambda * bits as f64;
202+ if cost < best_rd {
203+ best_rd = cost;
204+ mode = cand;
205+ }
206+ }
207+ }
208+ modes[blk] = mode;
209+ pic.i4_modes[by * w4 + bx] = mode;
210+ // Prediction into the plane, then residual and reconstruction.
211+ pred_4x4(mode, 8, &n, &mut p);
212+ let stride = pic.y.stride;
213+ let origin = pic.y.at(x, y);
214+ for ry in 0..4 {
215+ let row = origin + ry * stride;
216+ pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
217+ }
218+ let mut d = [0i32; 16];
219+ for ry in 0..4 {
220+ for rx in 0..4 {
221+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
222+ - i32::from(p[ry * 4 + rx]);
223+ }
224+ }
225+ forward_4x4(&mut d);
226+ let nz = quant_4x4(&d, qp, true, false, &mut lv.luma[blk]);
227+ lv.luma_nz[blk] = nz;
228+ if nz > 0 {
229+ lv.cbp_luma |= 1 << (blk >> 2);
230+ let mut raster = [0i32; 16];
231+ unzigzag(&lv.luma[blk], &mut raster);
232+ dequant_4x4(&mut raster, &e.ls, qp, false);
233+ let mut resid = [0i32; 16];
234+ inverse_transform_4x4(&raster, &mut resid);
235+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
236+ }
237+ }
238+ (modes, pred_modes)
239+}
240+
241+/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read
242+/// from the 4x4 slots every size writes its mode into.
243+pub(super) fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 {
244+ let w4 = pic.mb_w * 4;
245+ let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true };
246+ let top_avail = if blk8 < 2 { nbr.b } else { true };
247+ if left_avail && top_avail {
248+ pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx])
249+ } else {
250+ 2
251+ }
252+}
253+
254+/// Residual of one 8x8 luma block against the prediction already in the
255+/// plane: forward transform, quantise, and — when anything survives —
256+/// reconstruct with the decoder's own inverse. Returns the non-zero count.
257+#[allow(clippy::too_many_arguments)]
258+pub(super) fn code_block_8x8(
259+ pic: &mut Picture,
260+ e: &MbEnc<'_>,
261+ w: &EncEntropy,
262+ x: usize,
263+ y: usize,
264+ qp: i32,
265+ intra: bool,
266+ out: &mut [i32; 64],
267+) -> u8 {
268+ let stride = pic.y.stride;
269+ let origin = pic.y.at(x, y);
270+ let mut d = [0i32; 64];
271+ for ry in 0..8 {
272+ for rx in 0..8 {
273+ d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
274+ - i32::from(pic.y.data[origin + ry * stride + rx]);
275+ }
276+ }
277+ let rdoq = !intra && w.is_cabac();
278+ let fwd = forward_8x8(&d);
279+ let mut nz = if rdoq {
280+ quant_8x8_offset(&fwd, &e.ls8, qp, RDOQ8_DEAD_ZONE, out)
281+ } else {
282+ quant_8x8(&fwd, &e.ls8, qp, intra, out)
283+ };
284+ if nz == 0 {
285+ return 0;
286+ }
287+ if rdoq {
288+ nz = rdoq_8x8(e, w, &d, out, qp);
289+ if nz == 0 {
290+ return 0;
291+ }
292+ }
293+ let mut raster = [0i32; 64];
294+ unzigzag_8x8(out, &mut raster);
295+ dequant_8x8(&mut raster, &e.ls8, qp);
296+ let mut resid = [0i32; 64];
297+ inverse_transform_8x8(&raster, &mut resid);
298+ if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8))
299+ {
300+ *out = [0; 64];
301+ return 0;
302+ }
303+ add_residual_8x8(&mut pic.y.data, 8, stride, origin, &resid);
304+ nz
305+}
306+
307+/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of
308+/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference
309+/// samples, and every 4x4 mode slot of a block carries its mode.
310+#[allow(clippy::too_many_arguments)]
311+pub(super) fn code_intra_8x8(
312+ pic: &mut Picture,
313+ e: &MbEnc<'_>,
314+ w: &EncEntropy,
315+ mb_x: usize,
316+ mb_y: usize,
317+ qp: i32,
318+ nbr: &MbNeighbors,
319+ lv: &mut Levels,
320+) -> ([u8; 4], [u8; 4]) {
321+ let w4 = pic.mb_w * 4;
322+ let mut modes = [2u8; 4];
323+ let mut pred_modes = [2u8; 4];
324+ lv.trans8 = true;
325+ for blk8 in 0..4 {
326+ let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2);
327+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
328+ let predicted = predicted_mode8(pic, nbr, bx, by, blk8);
329+ pred_modes[blk8] = predicted;
330+ let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y));
331+ let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl);
332+ let mut p = [0u8; 64];
333+ {
334+ let (mode, coded, recon) =
335+ i8_mode_by_rd(pic, e, w, x, y, qp, &n, &allowed, predicted, &mut p);
336+ let stride = pic.y.stride;
337+ let origin = pic.y.at(x, y);
338+ for ry in 0..8 {
339+ let row = origin + ry * stride;
340+ pic.y.data[row..row + 8].copy_from_slice(&recon[ry * 8..ry * 8 + 8]);
341+ }
342+ lv.luma8[blk8] = coded.0;
343+ if coded.1 {
344+ lv.cbp_luma |= 1 << blk8;
345+ }
346+ modes[blk8] = mode;
347+ for dy in 0..2 {
348+ let base = (by + dy) * w4 + bx;
349+ pic.i4_modes[base..base + 2].fill(mode);
350+ }
351+ }
352+ }
353+ (modes, pred_modes)
354+}
355+
356+#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
357+pub(super) fn intra_mb_bits(
358+ pic: &Picture,
359+ e: &MbEnc<'_>,
360+ w: &EncEntropy,
361+ mb_addr: usize,
362+ nbr: &MbNeighbors,
363+ lv: &Levels,
364+ i4: Option<(&[u8], &[u8])>,
365+ i16_mode: u8,
366+ chroma_mode: u8,
367+) -> i64 {
368+ let use_i4 = i4.is_some();
369+ let p_slice = e.slice_type == SliceType::P;
370+ let offset = if p_slice { 5 } else { 0 };
371+ let intra_type = if use_i4 {
372+ 0
373+ } else {
374+ 1 + u32::from(i16_mode)
375+ + 4 * u32::from(lv.cbp_chroma)
376+ + if lv.cbp_luma != 0 { 12 } else { 0 }
377+ };
378+ entropy_bits(w, |cw| {
379+ cw.begin_mb(&e.mb_ctx);
380+ cw.coded_mb(p_slice, e.skip_inc);
381+ cw.set_intra(true);
382+ cw.mb_type(p_slice, intra_type + offset);
383+ if let Some((modes, pred)) = i4 {
384+ if e.transform_8x8 {
385+ cw.transform_size_8x8_flag(lv.trans8);
386+ }
387+ for blk in 0..modes.len() {
388+ let rem = if modes[blk] == pred[blk] {
389+ None
390+ } else if modes[blk] > pred[blk] {
391+ Some(modes[blk] - 1)
392+ } else {
393+ Some(modes[blk])
394+ };
395+ cw.intra4x4_pred_mode(rem);
396+ }
397+ }
398+ cw.intra_chroma_pred_mode(chroma_mode);
399+ if use_i4 {
400+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
401+ }
402+ let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4;
403+ if coded {
404+ cw.mb_qp_delta(e.target_qp - e.qp);
405+ }
406+ let mb_x = mb_addr % pic.mb_w;
407+ let mb_y = mb_addr / pic.mb_w;
408+ write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4);
409+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
410+ })
411+}
412+
413+/// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real
414+/// rate and real distortion.
415+///
416+/// A SATD estimate of the 4x4 form has to predict from the source samples
417+/// inside the macroblock — the reconstruction it would predict from does not
418+/// exist until the mode is chosen — and on flat or text-heavy pictures that
419+/// estimate misjudges which form wins. Coding both and measuring is worth
420+/// more than it costs: it is 1.1 dB on screen capture at matched bitrate.
421+pub(super) fn encode_intra_mb(
422+ pic: &mut Picture,
423+ e: &mut MbEnc<'_>,
424+ w: &mut EncEntropy,
425+ mb_addr: usize,
426+ nbr: MbNeighbors,
427+ cost: IntraCost,
428+) {
429+ let mb_x = mb_addr % pic.mb_w;
430+ let mb_y = mb_addr / pic.mb_w;
431+ let w4 = pic.mb_w * 4;
432+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
433+ let qp = e.target_qp;
434+ write_intra_mb(pic, mb_x, mb_y);
435+ let mut lv: Levels;
436+ let mut modes = [2u8; 16];
437+ let mut pred_modes = [2u8; 16];
438+ let mut modes8 = [2u8; 4];
439+ let mut pred_modes8 = [2u8; 4];
440+ let mut use_i4 = false;
441+ let mut chroma_lv = Levels::default();
442+ let chroma_mode = choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv);
443+ let mut use_i8 = false;
444+
445+ if cost.allow_i4 {
446+ let mut lv4 = chroma_lv.clone();
447+ let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4);
448+ let cost4 = if e.transform_8x8 {
449+ let bits = intra_mb_bits(
450+ pic,
451+ e,
452+ w,
453+ mb_addr,
454+ &nbr,
455+ &lv4,
456+ Some((&m4, &p4)),
457+ cost.i16_mode,
458+ chroma_mode,
459+ );
460+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64
461+ + e.lambda * bits as f64
462+ } else {
463+ ssd_luma(pic, e, mb_x, mb_y) as f64
464+ + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64
465+ };
466+ let mut recon4 = [0u8; 256];
467+ save_luma(pic, mb_x, mb_y, &mut recon4);
468+ let mut modes4 = [2u8; 16];
469+ for blk in 0..16 {
470+ let (dx, dy) = BLK4_POS[blk];
471+ modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize];
472+ }
473+
474+ // Intra_8x8 on the same terms, when the PPS allows it.
475+ let mut lv8 = chroma_lv.clone();
476+ let mut recon8 = [0u8; 256];
477+ let skip8 = e.preset == Preset::Fast
478+ && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P));
479+ let cost8 = if e.transform_8x8 && !skip8 {
480+ let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8);
481+ modes8 = m8;
482+ pred_modes8 = p8;
483+ save_luma(pic, mb_x, mb_y, &mut recon8);
484+ let bits = intra_mb_bits(
485+ pic,
486+ e,
487+ w,
488+ mb_addr,
489+ &nbr,
490+ &lv8,
491+ Some((&m8, &p8)),
492+ cost.i16_mode,
493+ chroma_mode,
494+ );
495+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true, intra_bs) as f64
496+ + e.lambda * bits as f64
497+ } else {
498+ f64::INFINITY
499+ };
500+
501+ let mut lv16 = chroma_lv;
502+ code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16);
503+ let cost16 = if e.transform_8x8 {
504+ let bits = intra_mb_bits(
505+ pic,
506+ e,
507+ w,
508+ mb_addr,
509+ &nbr,
510+ &lv16,
511+ None,
512+ cost.i16_mode,
513+ chroma_mode,
514+ );
515+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64
516+ + e.lambda * bits as f64
517+ } else {
518+ ssd_luma(pic, e, mb_x, mb_y) as f64
519+ + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64
520+ };
521+
522+ if cost8 <= cost4 && cost8 <= cost16 {
523+ use_i4 = true;
524+ use_i8 = true;
525+ restore_luma(pic, mb_x, mb_y, &recon8);
526+ for blk8 in 0..4 {
527+ for dy in 0..2 {
528+ let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2;
529+ pic.i4_modes[base..base + 2].fill(modes8[blk8]);
530+ }
531+ }
532+ lv = lv8;
533+ } else if cost4 <= cost16 {
534+ use_i4 = true;
535+ restore_luma(pic, mb_x, mb_y, &recon4);
536+ for blk in 0..16 {
537+ let (dx, dy) = BLK4_POS[blk];
538+ pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize] = modes4[blk];
539+ }
540+ lv = lv4;
541+ modes = m4;
542+ pred_modes = p4;
543+ } else {
544+ lv = lv16;
545+ }
546+ } else {
547+ lv = chroma_lv;
548+ code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv);
549+ }
550+
551+ // ---- syntax ----
552+ w.begin_mb(&e.mb_ctx);
553+ w.coded_mb(e.slice_type == SliceType::P, e.skip_inc);
554+ w.set_intra(true);
555+ let intra_type = if use_i4 {
556+ 0
557+ } else {
558+ 1 + u32::from(cost.i16_mode)
559+ + 4 * u32::from(lv.cbp_chroma)
560+ + if lv.cbp_luma != 0 { 12 } else { 0 }
561+ };
562+ let p_slice = e.slice_type == SliceType::P;
563+ let offset = if p_slice { 5 } else { 0 };
564+ w.mb_type(p_slice, intra_type + offset);
565+ if use_i4 {
566+ if e.transform_8x8 {
567+ w.transform_size_8x8_flag(use_i8);
568+ }
569+ // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4
570+ // elements' binarisation and contexts (9.3.2.2, Table 9-34).
571+ let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 {
572+ (&modes8, &pred_modes8)
573+ } else {
574+ (&modes, &pred_modes)
575+ };
576+ for blk in 0..modes.len() {
577+ let rem = if modes[blk] == pred_modes[blk] {
578+ None
579+ } else if modes[blk] > pred_modes[blk] {
580+ Some(modes[blk] - 1)
581+ } else {
582+ Some(modes[blk])
583+ };
584+ w.intra4x4_pred_mode(rem);
585+ }
586+ }
587+ w.intra_chroma_pred_mode(chroma_mode);
588+ if use_i4 {
589+ w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
590+ }
591+ finish_mb(
592+ pic,
593+ e,
594+ w,
595+ mb_addr,
596+ &nbr,
597+ &lv,
598+ MbRecord {
599+ intra: true,
600+ is_i16: !use_i4,
601+ chroma_mode,
602+ qp,
603+ },
604+ );
605+}
606+
607+/// Chroma prediction mode by rate-distortion: every available mode is coded
608+/// through the real chroma path and scored on reconstructed SSD plus the bits
609+/// its levels and its own name actually cost. The SATD-plus-mode-bits chooser
610+/// this replaced picked the mode before the quantiser had a say, which reads
611+/// as a chroma deficit at matched luma: measured with `bd_psnr_vs_x264`
612+/// against x264 `-preset medium`, BD-PSNR-YUV, GOP 10, 24 pictures:
613+///
614+/// | clip | SATD | RD |
615+/// |---|---|---|
616+/// | 3840x1608 film | -0.500 dB | -0.443 dB |
617+/// | 2560x1440 screen capture | -0.220 dB | -0.146 dB |
618+/// | 2560x1440 screen capture, second scene | -0.571 dB | -0.538 dB |
619+/// | 1080p phone clip | -1.122 dB | -1.084 dB |
620+/// | 720p web clip | -0.606 dB | -0.572 dB |
621+///
622+/// Luma is unmoved (film -0.065 -> -0.070 dB) and the encode time does not
623+/// change measurably: only intra macroblocks pay, and only four trials of the
624+/// chroma path each.
625+#[allow(clippy::too_many_arguments)]
626+pub(super) fn choose_chroma_mode_rd(
627+ pic: &mut Picture,
628+ e: &MbEnc<'_>,
629+ w: &EncEntropy,
630+ nbr: &MbNeighbors,
631+ mb_x: usize,
632+ mb_y: usize,
633+ qp: i32,
634+ out: &mut Levels,
635+) -> u8 {
636+ let qp_c = chroma_qp(qp, e.cqo);
637+ let lambda = lambda_ssd(qp_c);
638+ let mut best: Option<(f64, u8, Levels, [[u8; 64]; 2])> = None;
639+ for mode in [0u8, 1, 2, 3] {
640+ let ok = match mode {
641+ 1 => nbr.a,
642+ 2 => nbr.b,
643+ 3 => nbr.a && nbr.b && nbr.d,
644+ _ => true,
645+ };
646+ if !ok {
647+ continue;
648+ }
649+ for comp in 0..2 {
650+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
651+ let stride = plane.stride;
652+ let origin = plane.at(mb_x * 8, mb_y * 8);
653+ let mut win = PlaneWindow {
654+ data: &mut plane.data,
655+ stride,
656+ origin,
657+ };
658+ pred_chroma_8x8(mode, 8, &mut win, nbr.b, nbr.a);
659+ }
660+ let mut lv = Levels::default();
661+ code_chroma(pic, e, w, mb_x, mb_y, qp, true, &mut lv);
662+ let mut ssd = 0i64;
663+ let mut recon = [[0u8; 64]; 2];
664+ for comp in 0..2 {
665+ let (plane, src) = if comp == 0 {
666+ (&pic.cb, &e.src.u)
667+ } else {
668+ (&pic.cr, &e.src.v)
669+ };
670+ let origin = plane.at(mb_x * 8, mb_y * 8);
671+ for ry in 0..8 {
672+ for rx in 0..8 {
673+ let r = plane.data[origin + ry * plane.stride + rx];
674+ recon[comp][ry * 8 + rx] = r;
675+ let d = i64::from(src[(mb_y * 8 + ry) * e.src.c_stride + mb_x * 8 + rx])
676+ - i64::from(r);
677+ ssd += d * d;
678+ }
679+ }
680+ }
681+ let mut bits = match mode {
682+ 0 => 1.0,
683+ 3 => 5.0,
684+ _ => 3.0,
685+ };
686+ for comp in 0..2 {
687+ bits += match w.residual_block_cost(
688+ &lv.chroma_dc[comp],
689+ BlockCat::ChromaDc(comp as u8),
690+ Some(1),
691+ Some(1),
692+ ) {
693+ Some(b) => f64::from(b) / 256.0,
694+ None => block_bits(&lv.chroma_dc[comp]) as f64,
695+ };
696+ for blk in 0..4 {
697+ bits += match w.residual_block_cost(
698+ &lv.chroma[comp][blk],
699+ BlockCat::ChromaAc,
700+ Some(1),
701+ Some(1),
702+ ) {
703+ Some(b) => f64::from(b) / 256.0,
704+ None => block_bits(&lv.chroma[comp][blk]) as f64,
705+ };
706+ }
707+ }
708+ let cost = ssd as f64 + lambda * bits;
709+ if best.as_ref().is_none_or(|b| cost < b.0) {
710+ best = Some((cost, mode, lv, recon));
711+ }
712+ }
713+ let (_, mode, lv, recon) = best.expect("chroma DC prediction is always available");
714+ for comp in 0..2 {
715+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
716+ let stride = plane.stride;
717+ let origin = plane.at(mb_x * 8, mb_y * 8);
718+ for ry in 0..8 {
719+ for rx in 0..8 {
720+ plane.data[origin + ry * stride + rx] = recon[comp][ry * 8 + rx];
721+ }
722+ }
723+ }
724+ *out = lv;
725+ mode
726+}
727+
728+/// The mode decision of [`code_intra_8x8`]: for every allowed mode, predict,
729+/// code the 8x8 residual at the real QP and score `SSD + lambda * bits`, then
730+/// keep the cheapest. The SATD chooser this replaced scored the prediction
731+/// residual before the quantiser had a say, so it optimised a proxy.
732+///
733+/// Returns the winning mode, its coded levels with whether the block has any,
734+/// and the reconstructed 8x8 to write back. Measured on BD-PSNR against x264
735+/// with the 8x8 transform on, GOP 10, 24 consecutive pictures, luma / YUV:
736+/// • 3840x1608 film: +0.475 / -0.068 -> +0.512 / -0.035
737+/// • 1138x640 web: +0.040 / -0.031 -> +0.076 / +0.003
738+/// • 854x480 web: +0.070 / +0.047 -> +0.132 / +0.108
739+/// • 2560x1440 screen: -0.206 / -0.199 -> -0.215 / -0.207
740+/// Three clips of four gain; the screen capture loses 0.008 dB. Encode time
741+/// moves from 12 s to 13 s on the 854x480 clip.
742+#[allow(clippy::too_many_arguments)]
743+pub(super) fn i8_mode_by_rd(
744+ pic: &mut Picture,
745+ e: &MbEnc<'_>,
746+ w: &EncEntropy,
747+ x: usize,
748+ y: usize,
749+ qp: i32,
750+ n: &crate::pred::Nbr8,
751+ allowed: &[bool; 9],
752+ predicted: u8,
753+ p: &mut [u8; 64],
754+) -> (u8, ([i32; 64], bool), [u8; 64]) {
755+ let lambda = lambda_ssd(qp);
756+ let stride = pic.y.stride;
757+ let origin = pic.y.at(x, y);
758+ type Best = Option<(f64, u8, [i32; 64], bool, [u8; 64])>;
759+ let mut best: Best = None;
760+ for mode in 0..9u8 {
761+ if !allowed[mode as usize] {
762+ continue;
763+ }
764+ pred_8x8(mode, 8, n, p);
765+ for ry in 0..8 {
766+ let row = origin + ry * stride;
767+ pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
768+ }
769+ let mut levels = [0i32; 64];
770+ let nz = code_block_8x8(pic, e, w, x, y, qp, true, &mut levels);
771+ let mut ssd = 0i64;
772+ let mut recon = [0u8; 64];
773+ for ry in 0..8 {
774+ let row = origin + ry * stride;
775+ for rx in 0..8 {
776+ let r = pic.y.data[row + rx];
777+ recon[ry * 8 + rx] = r;
778+ let d = i64::from(e.src.y[(y + ry) * e.src.stride + x + rx]) - i64::from(r);
779+ ssd += d * d;
780+ }
781+ }
782+ let mut bits = if mode == predicted { 1.0 } else { 4.0 };
783+ if nz > 0 {
784+ // `Luma8x8` has no coded_block_flag of its own — the CBP carries it
785+ // — so it needs the 8x8 cost path, not the cbf-indexed one.
786+ bits += match w.residual_block_8x8_cost(&levels) {
787+ Some(b) => f64::from(b) / 256.0,
788+ None => block_bits(&levels) as f64,
789+ };
790+ }
791+ let cost = ssd as f64 + lambda * bits;
792+ if best.as_ref().is_none_or(|b| cost < b.0) {
793+ best = Some((cost, mode, levels, nz > 0, recon));
794+ }
795+ }
796+ let (_, mode, levels, coded, recon) =
797+ best.expect("Intra_8x8 always has at least the DC mode available");
798+ (mode, (levels, coded), recon)
799+}
800+
crates/ec-h264/src/enc/mb/me.rsadded+836 -0
@@ -0,0 +1,836 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+use wide::{i16x16};
4+
5+use crate::dpb::{Picture};
6+use crate::inter::{Put, RefPlane, integer_origin, mc_chroma, mc_luma};
7+use crate::mv::{MvCtx, predict_mv};
8+
9+
10+use super::*;
11+
12+/// 4x4 Hadamard sum of absolute transformed differences between the source at
13+/// `(sx, sy)` and a 4x4 prediction.
14+// Tried (lane-h264perf r2): a transpose-based i32x4 vectorization of this
15+// butterfly, bit-identical, but cycles-flat-to-worse under perf stat
16+// (22.958B -> 23.042B cycles over 10 reps despite fewer instructions
17+// retired) -- reverted, dead end; see ledger.
18+pub(super) fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 {
19+ // Differences are at most 255 in magnitude and the 2-D Hadamard sums 16 of
20+ // them, so every intermediate fits an i16.
21+ let mut d = [[0i16; 4]; 4];
22+ for (y, row) in d.iter_mut().enumerate() {
23+ let s = &src[(sy + y) * sstride + sx..][..4];
24+ let p = &pred[y * pstride..][..4];
25+ for x in 0..4 {
26+ row[x] = i16::from(s[x]) - i16::from(p[x]);
27+ }
28+ }
29+ // Vertical butterflies, lane-wise over the four columns.
30+ let mut v = [[0i16; 4]; 4];
31+ for x in 0..4 {
32+ let (a, b, c, e) = (d[0][x], d[1][x], d[2][x], d[3][x]);
33+ let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
34+ v[0][x] = s0 + s1;
35+ v[1][x] = s0 - s1;
36+ v[2][x] = s2 + s3;
37+ v[3][x] = s2 - s3;
38+ }
39+ // Horizontal butterflies per row, then the absolute sum.
40+ let mut sum = 0i32;
41+ for row in &v {
42+ let (a, b, c, e) = (row[0], row[1], row[2], row[3]);
43+ let (s0, s1, s2, s3) = (a + b, c + e, a - b, c - e);
44+ sum += i32::from((s0 + s1).abs())
45+ + i32::from((s0 - s1).abs())
46+ + i32::from((s2 + s3).abs())
47+ + i32::from((s2 - s3).abs());
48+ }
49+ (sum + 2) >> 2
50+}
51+
52+/// SATD of a whole 16x16 luma macroblock against the prediction already in the
53+/// picture plane.
54+pub(super) fn satd16(
55+ src: &[u8],
56+ sstride: usize,
57+ sx: usize,
58+ sy: usize,
59+ plane: &[u8],
60+ pstride: usize,
61+ po: usize,
62+) -> i32 {
63+ satd_block(src, sstride, sx, sy, plane, pstride, po, 16, 16)
64+}
65+
66+/// The same over a `w` x `h` partition.
67+#[allow(clippy::too_many_arguments)]
68+pub(super) fn satd_block(
69+ src: &[u8],
70+ sstride: usize,
71+ sx: usize,
72+ sy: usize,
73+ plane: &[u8],
74+ pstride: usize,
75+ po: usize,
76+ w: usize,
77+ h: usize,
78+) -> i32 {
79+ let mut sum = 0;
80+ for by in 0..h / 4 {
81+ for bx in 0..w / 4 {
82+ sum += satd4(
83+ src,
84+ sstride,
85+ sx + bx * 4,
86+ sy + by * 4,
87+ &plane[po + by * 4 * pstride + bx * 4..],
88+ pstride,
89+ );
90+ }
91+ }
92+ sum
93+}
94+
95+/// Sum of absolute differences of a `w` x `h` block against a prediction with
96+/// its own pitch. This is the motion search's inner loop and nothing else in
97+/// the encoder is called as often, so a full-width row goes through one vector.
98+#[allow(clippy::too_many_arguments)]
99+pub(super) fn sad(
100+ src: &[u8],
101+ sstride: usize,
102+ sx: usize,
103+ sy: usize,
104+ pred: &[u8],
105+ pstride: usize,
106+ w: usize,
107+ h: usize,
108+) -> i32 {
109+ if w == 16 {
110+ let mut acc = i16x16::ZERO;
111+ for y in 0..h {
112+ let a = load16(src, (sy + y) * sstride + sx);
113+ let b = load16(pred, y * pstride);
114+ acc += (a - b).abs();
115+ }
116+ return acc.to_array().iter().map(|&v| i32::from(v)).sum();
117+ }
118+ let mut sum = 0;
119+ for y in 0..h {
120+ let s = &src[(sy + y) * sstride + sx..];
121+ let p = &pred[y * pstride..];
122+ for x in 0..w {
123+ sum += (i32::from(s[x]) - i32::from(p[x])).abs();
124+ }
125+ }
126+ sum
127+}
128+
129+/// Sum and maximum of the absolute differences between the 16x16 source block
130+/// at `(sx, sy)` and a 16-wide prediction.
131+pub(super) fn sad_max16(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8]) -> (i32, i32) {
132+ let mut acc = i16x16::ZERO;
133+ let mut mx = i16x16::ZERO;
134+ for y in 0..16 {
135+ let a = load16(src, (sy + y) * sstride + sx);
136+ let b = load16(pred, y * 16);
137+ let d = (a - b).abs();
138+ acc += d;
139+ mx = mx.max(d);
140+ }
141+ let sum = acc.to_array().iter().map(|&v| i32::from(v)).sum();
142+ let max = mx
143+ .to_array()
144+ .iter()
145+ .map(|&v| i32::from(v))
146+ .max()
147+ .unwrap_or(0);
148+ (sum, max)
149+}
150+
151+#[inline]
152+pub(super) fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
153+ (motion_lambda(e) * bits).round() as i32
154+}
155+
156+/// The multiplier `motion_rate` applies, for loops that price many vectors.
157+#[inline]
158+pub(super) fn motion_lambda(e: &MbEnc<'_>) -> f64 {
159+ if e.transform_8x8 {
160+ e.lambda.sqrt()
161+ } else {
162+ e.lambda
163+ }
164+}
165+
166+/// How much of a motion vector's signalling the search pays for. Half, which
167+/// is not the true rate: swept on consecutive pictures (BD-PSNR against x264,
168+/// GOP 10), 0.25/0.5/1.0/2.0 read -1.074/-1.043/-1.225/-1.618 on the film clip
169+/// and -0.676/-0.661/-0.795/-1.201 on the screen capture. Charging the whole
170+/// rate is worse than charging half on both contents, and the curve is flat
171+/// below a half and falls away above it.
172+pub(super) const MV_BITS_WEIGHT: f64 = 0.5;
173+
174+/// Cap on whole-sample walk iterations per partition at `Preset::Fast`.
175+pub(super) const FAST_ME_PASSES: usize = 3;
176+
177+/// The offsets the whole-sample search steps through, in units of the current
178+/// step size.
179+///
180+/// A square, not a cross. The cross this used to be could only walk along an
181+/// axis, so a diagonally moving macroblock had to be reached in two steps
182+/// through a point that was worse than both -- and a step search stops at the
183+/// first point it cannot improve on. Adding the four diagonals is worth 0.032
184+/// dB BD-PSNR-YUV on the film clip and 0.041 on the screen capture for twice
185+/// the candidates in the whole-sample stage, which is the cheap stage: it reads
186+/// the reference in place and never interpolates.
187+///
188+/// The step the walk starts from was swept with it, at 4, 8 and 16 whole
189+/// samples: -0.580/-0.580/-0.593 dB on the film clip and -0.474/-0.493/-0.529
190+/// on the screen capture. Four is screen capture's optimum and inside film's
191+/// flat part -- a wider opening step is not a wider search here, it just lands
192+/// the walk further from the seeds, which are already the answer most of the
193+/// time.
194+pub(super) const ME_PATTERN: [(i16, i16); 8] = [
195+ (1, 0),
196+ (-1, 0),
197+ (0, 1),
198+ (0, -1),
199+ (1, 1),
200+ (-1, -1),
201+ (1, -1),
202+ (-1, 1),
203+];
204+
205+/// What the search charges P_8x8 for its own signalling, against the six bits
206+/// a 16x8 or 8x16 is charged: an mb_type that is one bin longer plus four
207+/// sub_mb_type bins, before the four predictors' own mvd.
208+///
209+/// Swept at `Preset::Balanced` -- the only preset that searches shapes at all
210+/// -- on consecutive pictures against x264. Off, 6, 12 and 20 bits read
211+/// -0.382/-0.379/-0.377/-0.378 dB BD-PSNR on the film clip and
212+/// -0.369/-0.364/-0.353/-0.356 on the screen capture: both contents put the
213+/// optimum at twelve, and quarters are worth 0.005 dB on camera content and
214+/// 0.016 on screen capture.
215+///
216+/// Re-swept once each partition was searched against its own predictor rather
217+/// than the macroblock's, because that changes what a split is worth: 6, 12
218+/// and 20 read -0.342/-0.343/-0.346 dB on the film clip and
219+/// -0.322/-0.314/-0.324 on the screen capture. Twelve survives the new path.
220+pub(super) const QUAD_BITS: f64 = 12.0;
221+
222+/// The same charge for a 16x8 or 8x16: one extra mb_type bin over P_16x16,
223+/// with no sub_mb_type behind it.
224+///
225+/// Swept on the per-partition-predictor path at 3, 6 and 10 bits:
226+/// -0.329/-0.343/-0.358 dB on the film clip and -0.310/-0.314/-0.326 on the
227+/// screen capture. Both contents want the halves charged half of what the old
228+/// whole-macroblock predictor made them look worth -- with each half searched
229+/// against its own predictor its mvd is genuinely cheaper, so the search no
230+/// longer has to be talked out of splitting.
231+pub(super) const HALF_BITS: f64 = 3.0;
232+
233+/// How a P macroblock is partitioned, in the mb_type numbering of Table 7-13.
234+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
235+pub(super) enum PShape {
236+ /// P_L0_16x16.
237+ Whole,
238+ /// P_L0_L0_16x8: a top and a bottom half.
239+ Horizontal,
240+ /// P_L0_L0_8x16: a left and a right half.
241+ Vertical,
242+ /// P_8x8 with four P_L0_8x8 sub-partitions: a quarter each.
243+ Quad,
244+}
245+
246+impl PShape {
247+ /// mb_type of Table 7-13.
248+ pub(super) fn mb_type(self) -> u32 {
249+ match self {
250+ PShape::Whole => 0,
251+ PShape::Horizontal => 1,
252+ PShape::Vertical => 2,
253+ PShape::Quad => 3,
254+ }
255+ }
256+
257+ pub(super) fn parts(self) -> usize {
258+ match self {
259+ PShape::Whole => 1,
260+ PShape::Horizontal | PShape::Vertical => 2,
261+ PShape::Quad => 4,
262+ }
263+ }
264+
265+ /// Partition `part`'s origin in 4x4 blocks and its size in luma samples.
266+ pub(super) fn geometry(self, part: usize) -> ((usize, usize), (usize, usize)) {
267+ match self {
268+ PShape::Whole => ((0, 0), (16, 16)),
269+ PShape::Horizontal => ((0, part * 2), (16, 8)),
270+ PShape::Vertical => ((part * 2, 0), (8, 16)),
271+ PShape::Quad => (((part % 2) * 2, (part / 2) * 2), (8, 8)),
272+ }
273+ }
274+
275+ /// Which partition covers the 4x4 block at `(x, y)` in macroblock
276+ /// coordinates, or `None` when the block is outside the macroblock.
277+ pub(super) fn part_of(self, x: i32, y: i32) -> Option<usize> {
278+ if !(0..4).contains(&x) || !(0..4).contains(&y) {
279+ return None;
280+ }
281+ let (x, y) = (x as usize, y as usize);
282+ Some(match self {
283+ PShape::Whole => 0,
284+ PShape::Horizontal => y / 2,
285+ PShape::Vertical => x / 2,
286+ PShape::Quad => (y / 2) * 2 + x / 2,
287+ })
288+ }
289+
290+ /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks, which select the
291+ /// directional shortcuts of 8.4.1.3.
292+ pub(super) fn part_blocks(self) -> (usize, usize) {
293+ match self {
294+ PShape::Whole => (4, 4),
295+ PShape::Horizontal => (4, 2),
296+ PShape::Vertical => (2, 4),
297+ PShape::Quad => (2, 2),
298+ }
299+ }
300+}
301+
302+/// How much the two chroma planes weigh against luma in the inter decision.
303+///
304+/// Swept at 0, 0.25, 0.5, 1 and 2, read on BD-PSNR-YUV because a luma-only
305+/// metric cannot price a term whose whole purpose is chroma: the film clip
306+/// reads -0.653/-0.622/-0.612/-0.615/-0.626 dB and the screen capture
307+/// -0.517/-0.521/-0.515/-0.521/-0.546. A half is film's optimum and inside
308+/// screen capture's flat part; zero reproduces the chroma-blind decision
309+/// exactly, which is how the sweep proved the term was reaching the search.
310+///
311+/// It is worth 0.041 dB on the film clip and nothing on the screen capture --
312+/// small enough to name what it rules out. Our chroma trails x264 by 0.5-0.9 dB
313+/// per plane at every QP, and it is not because the vector was chosen without
314+/// looking: weighting chroma up lifts chroma PSNR monotonically, and past a
315+/// half the bits it spends cost more than the chroma it buys.
316+pub(super) const CHROMA_ME_WEIGHT: f64 = 0.5;
317+
318+/// How many inter candidates the macroblock decision codes before choosing,
319+/// most promising first. One is the SATD winner alone, which is what this used
320+/// to do; five is every shape the search costed plus P_Skip. BD-PSNR-YUV
321+/// against x264 at GOP 10 over QP 22/26/30/34, at `Preset::Balanced`:
322+///
323+/// ```text
324+/// film 3840x1608 screen 2560x1440
325+/// 1 candidate -0.580 -0.474
326+/// 2 -0.521 -0.459
327+/// 3 -0.513 -0.447
328+/// 5 -0.504 -0.406
329+/// ```
330+///
331+/// monotone in the count with no turnover, so the decision is taken at the
332+/// full list. The SATD total that used to rank the shapes is a
333+/// prediction-domain estimate that never sees the residual it causes.
334+pub(super) const SHAPE_RD_CANDIDATES: usize = 5;
335+
336+/// The inter decision for a P macroblock.
337+#[derive(Clone, Copy)]
338+pub(super) struct InterChoice {
339+ /// The candidate's SATD cost (luma plus chroma) as the shape search ranked it;
340+ /// zero where the search did not rank it.
341+ pub(super) satd: i32,
342+ pub(super) shape: PShape,
343+ /// One motion vector per partition.
344+ pub(super) mv: [[i16; 2]; 4],
345+ /// The P_Skip motion vector of 8.4.1.1.
346+ pub(super) skip_mv: [i16; 2],
347+ /// The skip candidate is at least as good as the searched one.
348+ pub(super) prefer_skip: bool,
349+ /// The prediction is so close to the source that the macroblock is coded
350+ /// as P_Skip without costing a residual (`Preset::Fast` only).
351+ pub(super) force_skip: bool,
352+}
353+
354+/// Motion search plus the skip candidate.
355+pub(super) fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<InterChoice> {
356+ let reference = e.reference.expect("a P slice has a reference");
357+ let ctx = MvCtx {
358+ mb_x,
359+ mb_y,
360+ slice_id: e.slice_id,
361+ written: 0,
362+ pos: Default::default(),
363+ };
364+ let n = ctx.neighbours(pic, 0, 0, 4, 0);
365+ let mvp = predict_mv(&n, 0, 4, 4, 0);
366+ // P_Skip (8.4.1.1): zero when either neighbour is missing or is itself a
367+ // zero-motion reference-0 partition.
368+ let a = ctx.at(pic, mb_x as i32 * 4 - 1, mb_y as i32 * 4, 0);
369+ let b = ctx.at(pic, mb_x as i32 * 4, mb_y as i32 * 4 - 1, 0);
370+ let zero = |nb: &crate::mv::Nb| nb.ref_idx == 0 && nb.mv == [0, 0];
371+ let skip_mv = if !a.avail || !b.avail || zero(&a) || zero(&b) {
372+ [0, 0]
373+ } else {
374+ mvp
375+ };
376+
377+ let plane = RefPlane {
378+ data: &reference.y.data,
379+ stride: reference.y.stride,
380+ origin: reference.y.origin,
381+ width: reference.y.width,
382+ height: reference.y.height,
383+ pad: reference.y.pad,
384+ };
385+ let (sx, sy) = (mb_x * 16, mb_y * 16);
386+ let sw = e.src.stride;
387+
388+ // What the two chroma planes cost under a candidate vector, in the same
389+ // SATD domain the luma search ranks in. The search itself cannot afford
390+ // this -- it runs on SAD over a whole neighbourhood -- but the handful of
391+ // candidates that survive to the shape decision can, and until they did,
392+ // no decision in this encoder had ever looked at chroma: the vector, the
393+ // shape and the skip flag were all chosen on luma alone and chroma was
394+ // coded against whatever came out. Measured per plane against x264 that
395+ // showed up as a uniform 0.5-0.9 dB chroma deficit at every QP while we
396+ // spent more bits, which is a prediction that was never asked about.
397+ let cplanes = [&reference.cb, &reference.cr];
398+ let chroma_satd = |px: usize, py: usize, w: usize, h: usize, mv: [i16; 2]| -> i32 {
399+ if CHROMA_ME_WEIGHT == 0.0 {
400+ return 0;
401+ }
402+ let mut buf = [0u8; 64];
403+ let mut sum = 0;
404+ for comp in 0..2 {
405+ let src = cplanes[comp];
406+ let rp = RefPlane {
407+ data: &src.data,
408+ stride: src.stride,
409+ origin: src.origin,
410+ width: src.width,
411+ height: src.height,
412+ pad: src.pad,
413+ };
414+ let (cw, ch) = (w / 2, h / 2);
415+ mc_chroma(
416+ &rp,
417+ (sx + px) as i32 / 2,
418+ (sy + py) as i32 / 2,
419+ mv,
420+ cw,
421+ ch,
422+ cw,
423+ &mut buf,
424+ crate::inter::Put::Set,
425+ );
426+ let plane = if comp == 0 { &e.src.u } else { &e.src.v };
427+ sum += satd_block(
428+ plane,
429+ e.src.c_stride,
430+ (sx + px) / 2,
431+ (sy + py) / 2,
432+ &buf,
433+ cw,
434+ 0,
435+ cw,
436+ ch,
437+ );
438+ }
439+ (f64::from(sum) * CHROMA_ME_WEIGHT) as i32
440+ };
441+
442+ // Early skip: a prediction at the P_Skip vector that already sits inside
443+ // the quantiser's dead zone codes nothing, so neither the search nor a
444+ // residual is worth the time. Judged on luma SAD, the largest single
445+ // difference and the chroma SATD, all against the quantiser step.
446+ if e.preset == Preset::Fast && e.fast.early_skip > 0 {
447+ let qstep = ((f64::from(e.qp) - 4.0) / 6.0).exp2();
448+ let k = f64::from(e.fast.early_skip) / 100.0;
449+ let mut buf = [0u8; 256];
450+ mc_luma(
451+ &plane,
452+ sx as i32,
453+ sy as i32,
454+ skip_mv,
455+ 16,
456+ 16,
457+ 16,
458+ &mut buf,
459+ Put::Set,
460+ );
461+ let (sad_luma, max_luma) = sad_max16(&e.src.y, sw, sx, sy, &buf);
462+ if f64::from(sad_luma) <= 256.0 * k * qstep && f64::from(max_luma) <= 4.0 * k * qstep + 2.0
463+ {
464+ let c = chroma_satd(0, 0, 16, 16, skip_mv);
465+ if f64::from(c) <= 64.0 * k * qstep * 4.0 {
466+ return vec![InterChoice {
467+ satd: 0,
468+ shape: PShape::Whole,
469+ mv: [skip_mv; 4],
470+ skip_mv,
471+ prefer_skip: true,
472+ force_skip: true,
473+ }];
474+ }
475+ }
476+ }
477+
478+ let range = match e.preset {
479+ Preset::Fast => 16i16,
480+ Preset::Balanced => 48,
481+ };
482+
483+ // One search over a `w` x `h` partition at `(px, py)` samples inside the
484+ // macroblock, seeded with the candidate vectors of its neighbourhood.
485+ let mlam = motion_lambda(e);
486+ let search = |px: usize, py: usize, w: usize, h: usize, mvp: [i16; 2], seeds: &[[i16; 2]]| {
487+ let (x0, y0) = (sx + px, sy + py);
488+ let mut buf = [0u8; 256];
489+ // Whole-sample candidates read the reference plane in place; only the
490+ // sub-sample refinement pays for interpolation. The search runs on SAD,
491+ // which is what a search can afford; the winner is re-costed on SATD
492+ // because the intra candidates are SATD and the two scales differ.
493+ let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 {
494+ let bits = (mlam
495+ * f64::from(
496+ se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])),
497+ )
498+ * MV_BITS_WEIGHT)
499+ .round() as i32;
500+ if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
501+ let o = integer_origin(
502+ &plane,
503+ x0 as i32 + (mv[0] >> 2) as i32,
504+ y0 as i32 + (mv[1] >> 2) as i32,
505+ w,
506+ h,
507+ );
508+ return sad(&e.src.y, sw, x0, y0, &plane.data[o..], plane.stride, w, h) + bits;
509+ }
510+ mc_luma(
511+ &plane,
512+ x0 as i32,
513+ y0 as i32,
514+ mv,
515+ w,
516+ h,
517+ w,
518+ &mut buf,
519+ crate::inter::Put::Set,
520+ );
521+ let d = if satd {
522+ satd_block(&e.src.y, sw, x0, y0, &buf, w, 0, w, h)
523+ } else {
524+ sad(&e.src.y, sw, x0, y0, &buf, w, w, h)
525+ };
526+ d + bits
527+ };
528+
529+ let fast = e.preset == Preset::Fast;
530+ let mut best = ([0i16; 2], i32::MAX);
531+ for (i, &cand) in seeds.iter().enumerate() {
532+ if seeds[..i].contains(&cand) {
533+ continue;
534+ }
535+ let c = cost_of(cand, false);
536+ if c < best.1 {
537+ best = (cand, c);
538+ }
539+ }
540+ // Every partition is searched. This used to stop at a seed whose cost
541+ // was already under half a level a sample, on the reasoning that the
542+ // prediction fit and the search is the encoder's hot loop. Swept on
543+ // consecutive pictures (BD-PSNR against x264, GOP 10) the threshold is
544+ // monotonically harmful: 0/0.25/0.5/1.0 levels a sample read
545+ // -0.586/-0.587/-0.593/-0.617 dB on the film clip and
546+ // -0.466/-0.470/-0.468/-0.476 on the screen capture. A seed that fits
547+ // is exactly where a little more refinement is cheap.
548+ {
549+ // Fast opens at two whole samples: the seeds already carry the
550+ // neighbours' motion, so the walk only has to settle around them.
551+ let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 };
552+ let mut passes = 0;
553+ while step >= 4 {
554+ let mut improved = true;
555+ while improved {
556+ improved = false;
557+ passes += 1;
558+ if fast && passes > FAST_ME_PASSES {
559+ break;
560+ }
561+ for (dx, dy) in ME_PATTERN {
562+ let (dx, dy) = (dx * step, dy * step);
563+ let cand = [best.0[0] + dx, best.0[1] + dy];
564+ if (cand[0] - mvp[0]).abs() > range * 4
565+ || (cand[1] - mvp[1]).abs() > range * 4
566+ {
567+ continue;
568+ }
569+ let c = cost_of(cand, false);
570+ if c < best.1 {
571+ best = (cand, c);
572+ improved = true;
573+ }
574+ }
575+ }
576+ step /= 2;
577+ }
578+ // Sub-sample refinement runs on SATD, not SAD: interpolation
579+ // smooths, and a sum of absolute differences reads the smoothing
580+ // as a better match where a transform-domain cost does not. Worth
581+ // 0.06 dB BD-PSNR on the film clip and 0.04 dB on the screen
582+ // capture. The whole-sample winner is re-costed in the same domain
583+ // first so the two halves of the search compare.
584+ let sub_satd = !fast || e.fast.me_satd;
585+ best.1 = cost_of(best.0, sub_satd);
586+ // Balanced iterates both sub-sample steps to convergence. Fast
587+ // looks at each ring of eight once.
588+ let rings: &[i16] = if !fast {
589+ &[2, 1]
590+ } else {
591+ match e.fast.me_sub {
592+ 0 => &[],
593+ 1 => &[2],
594+ _ => &[2, 1],
595+ }
596+ };
597+ if fast && e.fast.me_sub == 1 {
598+ // The four half-sample neighbours on the axes, then only the
599+ // diagonal the two winning axes point at.
600+ let base = best;
601+ let mut axis = [(base.0, base.1); 2];
602+ for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]]
603+ .into_iter()
604+ .enumerate()
605+ {
606+ for (dx, dy) in dirs {
607+ let cand = [base.0[0] + dx, base.0[1] + dy];
608+ let c = cost_of(cand, sub_satd);
609+ if c < axis[k].1 {
610+ axis[k] = (cand, c);
611+ }
612+ }
613+ }
614+ let both = axis[0].1 < base.1 && axis[1].1 < base.1;
615+ if both {
616+ let cand = [axis[0].0[0], axis[1].0[1]];
617+ let c = cost_of(cand, sub_satd);
618+ if c < best.1 {
619+ best = (cand, c);
620+ }
621+ }
622+ for a in axis {
623+ if a.1 < best.1 {
624+ best = a;
625+ }
626+ }
627+ }
628+ let rings: &[i16] = if fast && e.fast.me_sub == 1 {
629+ &[]
630+ } else {
631+ rings
632+ };
633+ for &step in rings {
634+ let mut improved = true;
635+ while improved {
636+ improved = false;
637+ for (dx, dy) in [
638+ (step, 0),
639+ (-step, 0),
640+ (0, step),
641+ (0, -step),
642+ (step, step),
643+ (-step, -step),
644+ (step, -step),
645+ (-step, step),
646+ ] {
647+ let cand = [best.0[0] + dx, best.0[1] + dy];
648+ let c = cost_of(cand, sub_satd);
649+ if c < best.1 {
650+ best = (cand, c);
651+ improved = !fast;
652+ }
653+ }
654+ }
655+ }
656+ }
657+ (
658+ best.0,
659+ if !fast || e.fast.me_satd {
660+ best.1
661+ } else {
662+ cost_of(best.0, true)
663+ },
664+ )
665+ };
666+
667+ let seeds = [mvp, skip_mv, [0, 0], n[0].mv, n[1].mv, n[2].mv];
668+ let (mv16, cost16) = search(0, 0, 16, 16, mvp, &seeds);
669+ let cost16 = cost16 + chroma_satd(0, 0, 16, 16, mv16);
670+ let skip_cost = {
671+ let mut buf = [0u8; 256];
672+ mc_luma(
673+ &plane,
674+ sx as i32,
675+ sy as i32,
676+ skip_mv,
677+ 16,
678+ 16,
679+ 16,
680+ &mut buf,
681+ Put::Set,
682+ );
683+ // P_Skip's rebate is the signalling it genuinely saves. Re-measured on
684+ // consecutive pictures: 0 and 2 read -1.102/-1.154 dB on the film clip
685+ // and -0.741/-0.696 on the screen capture -- the two contents disagree
686+ // by less than the step between them, so this is the flat part. Six
687+ // costs 0.14 dB and twelve costs 0.42.
688+ //
689+ // The Intra_4x4 discount above was swept with it: 0.65/0.75/0.85/1.0
690+ // read -1.216/-1.154/-1.182/-1.373 on film and -0.970/-0.696/-0.591/
691+ // -0.562 on screen capture, so three quarters is film's optimum and
692+ // inside screen capture's flat part.
693+ satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) + chroma_satd(0, 0, 16, 16, skip_mv)
694+ - motion_rate(e, 2.0)
695+ };
696+
697+ let mut best = (PShape::Whole, [mv16; 4], cost16);
698+ // Every shape the search costed, kept so the macroblock decision can rank
699+ // them on coded cost instead of on this SATD total (see `encode_mb`).
700+ let mut evaluated = vec![(PShape::Whole, [mv16; 4])];
701+ // Halves, seeded with the whole-macroblock winner. The predictor used here
702+ // is the whole-macroblock one rather than each half's own: the real
703+ // predictors are derived in coding order when the choice is made, and this
704+ // only has to rank the shapes. A macroblock the 16x16 search already fits
705+ // is left alone — splitting it could only spend bits.
706+ //
707+ // Measured: two more searches per macroblock buy 0.1-0.2 dB on screen
708+ // capture and nothing on camera content, for roughly twice the search
709+ // time. That is a Balanced trade, not a Fast one.
710+ // The threshold is a floor that real content clears everywhere: swept at
711+ // 0, 0.5, 1 and 2 levels a sample it moves neither clip's BD-PSNR by a
712+ // thousandth of a decibel, so on these sources the halves are always
713+ // searched. It stays as a guard for content flat enough to make the two
714+ // extra searches pure cost.
715+ if e.preset == Preset::Balanced && cost16 > 16 * 16 {
716+ for shape in [PShape::Horizontal, PShape::Vertical, PShape::Quad] {
717+ // What the shape itself costs to signal: its mb_type, plus one
718+ // sub_mb_type per quarter when it is P_8x8.
719+ let mut total = motion_rate(
720+ e,
721+ if shape == PShape::Quad {
722+ QUAD_BITS
723+ } else {
724+ HALF_BITS
725+ },
726+ );
727+ let mut mvs = [[0i16; 2]; 4];
728+ let (pw, ph) = shape.part_blocks();
729+ for part in 0..shape.parts() {
730+ let ((bx, by), (w, h)) = shape.geometry(part);
731+ // Each partition is searched against the predictor it will
732+ // actually be coded with (8.4.1.3), not against the whole
733+ // macroblock's: the partitions before it in this macroblock
734+ // are already chosen, so the neighbourhood the predictor reads
735+ // can be completed from `mvs`.
736+ let mut n = ctx.neighbours(pic, bx, by, pw, 0);
737+ let inside = |x: i32, y: i32, nb: &mut crate::mv::Nb| {
738+ if let Some(p) = shape.part_of(x, y).filter(|&p| p < part) {
739+ *nb = crate::mv::Nb {
740+ avail: true,
741+ mv: mvs[p],
742+ ref_idx: 0,
743+ };
744+ }
745+ };
746+ inside(bx as i32 - 1, by as i32, &mut n[0]);
747+ inside(bx as i32, by as i32 - 1, &mut n[1]);
748+ let cx = bx as i32 + pw as i32;
749+ if shape.part_of(cx, by as i32 - 1).is_some() {
750+ inside(cx, by as i32 - 1, &mut n[2]);
751+ } else if !n[2].avail {
752+ inside(bx as i32 - 1, by as i32 - 1, &mut n[2]);
753+ }
754+ let part_mvp = predict_mv(&n, 0, pw, ph, part);
755+ let seeds = [mv16, part_mvp, mvp, skip_mv, [0, 0]];
756+ let (mv, cost) = search(bx * 4, by * 4, w, h, part_mvp, &seeds);
757+ mvs[part] = mv;
758+ total += cost + chroma_satd(bx * 4, by * 4, w, h, mv);
759+ }
760+ evaluated.push((shape, mvs));
761+ if total < best.2 {
762+ best = (shape, mvs, total);
763+ }
764+ }
765+ }
766+
767+ // How often each shape actually wins. Behind an environment switch because
768+ // it answers a question the rate gate cannot: a partition sweep that reads
769+ // flat is either a flat knob or a path nothing enters, and only a count
770+ // tells the two apart. It found the second -- at `Preset::Fast`, which is
771+ // what the x264 comparison runs by default, no macroblock is ever split.
772+ if std::env::var_os("EC_H264_SHAPE_STATS").is_some() {
773+ static N: [std::sync::atomic::AtomicUsize; 4] = [
774+ std::sync::atomic::AtomicUsize::new(0),
775+ std::sync::atomic::AtomicUsize::new(0),
776+ std::sync::atomic::AtomicUsize::new(0),
777+ std::sync::atomic::AtomicUsize::new(0),
778+ ];
779+ let i = match best.0 {
780+ PShape::Whole => 0,
781+ PShape::Horizontal => 1,
782+ PShape::Vertical => 2,
783+ PShape::Quad => 3,
784+ };
785+ let v = N[i].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
786+ let tot: usize = N
787+ .iter()
788+ .map(|n| n.load(std::sync::atomic::Ordering::Relaxed))
789+ .sum();
790+ if tot.is_multiple_of(20000) {
791+ eprintln!(
792+ "SHAPES whole={} horiz={} vert={} quad={} (last {i} -> {v})",
793+ N[0].load(std::sync::atomic::Ordering::Relaxed),
794+ N[1].load(std::sync::atomic::Ordering::Relaxed),
795+ N[2].load(std::sync::atomic::Ordering::Relaxed),
796+ N[3].load(std::sync::atomic::Ordering::Relaxed),
797+ );
798+ }
799+ }
800+ let winner = InterChoice {
801+ satd: best.2,
802+ shape: best.0,
803+ mv: best.1,
804+ skip_mv,
805+ prefer_skip: best.0 == PShape::Whole && skip_cost <= best.2,
806+ force_skip: false,
807+ };
808+ // The SATD winner first, then the shapes it beat, then the skip candidate
809+ // when the winner is not already it. The caller codes as many of these as
810+ // its preset allows and keeps the one with the smallest coded cost.
811+ let mut cands = vec![winner];
812+ for (shape, mv) in evaluated {
813+ if shape != winner.shape || winner.prefer_skip {
814+ cands.push(InterChoice {
815+ satd: 0,
816+ shape,
817+ mv,
818+ skip_mv,
819+ prefer_skip: false,
820+ force_skip: false,
821+ });
822+ }
823+ }
824+ if !winner.prefer_skip {
825+ cands.push(InterChoice {
826+ satd: skip_cost,
827+ shape: PShape::Whole,
828+ mv: [skip_mv; 4],
829+ skip_mv,
830+ prefer_skip: true,
831+ force_skip: false,
832+ });
833+ }
834+ cands
835+}
836+
crates/ec-h264/src/enc/mb/residual.rsadded+1403 -0
@@ -0,0 +1,1403 @@
1+#![allow(clippy::needless_range_loop)]
2+
3+use wide::{i16x8};
4+
5+use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
6+use crate::decoder::{
7+ MbNeighbors, chroma_nz_pair, luma_nz_pair, };
8+use crate::dpb::{Picture};
9+use crate::entropy::{
10+ BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_TRANS8X8,
11+ };
12+use crate::pred::{
13+ PlaneWindow, add_residual_4x4, pred_16x16,
14+ };
15+use crate::tables::{BLK4_POS};
16+use crate::transform::{
17+ chroma_dc_transform_420, dequant_4x4, dequant_8x8,
18+ inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
19+ unzigzag_ac15,
20+};
21+
22+use crate::enc::quant::{
23+ forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4,
24+ quant_4x4_offset, quant_chroma_dc, quant_luma_dc,
25+};
26+
27+use crate::enc::{
28+ entropy::{EncEntropy, sub_block_4x4},
29+ lambda_ssd,
30+};
31+use super::*;
32+
33+/// Quantise and reconstruct the luma residual of a non-Intra_16x16 macroblock,
34+/// prediction already in the plane.
35+#[allow(clippy::too_many_arguments)]
36+pub(super) fn code_luma_4x4(
37+ pic: &mut Picture,
38+ e: &MbEnc<'_>,
39+ w: &EncEntropy,
40+ mb_x: usize,
41+ mb_y: usize,
42+ qp: i32,
43+ intra: bool,
44+ lv: &mut Levels,
45+) {
46+ let stride = pic.y.stride;
47+ // An inter macroblock's blocks are reconstructed only after the whole
48+ // macroblock has been quantised, because [`decimate_score`] can still take
49+ // a block away. Intra blocks reconstruct as they go: the next block in the
50+ // macroblock predicts from them.
51+ let mut pending: [Option<[i32; 16]>; 16] = [None; 16];
52+ // Per 8x8 group, what coding its blocks buys and what it costs, for the
53+ // group-level test below. A block with no levels contributes nothing to
54+ // either side: its source energy stays in the reconstruction whatever the
55+ // group decides.
56+ let mut ssd_zero = [0i64; 4];
57+ let mut ssd_coded = [0i64; 4];
58+ let mut rate = [0f64; 4];
59+ for blk in 0..16 {
60+ let (dx, dy) = BLK4_POS[blk];
61+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
62+ let origin = pic.y.at(x, y);
63+ let mut d = [0i32; 16];
64+ for ry in 0..4 {
65+ for rx in 0..4 {
66+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
67+ - i32::from(pic.y.data[origin + ry * stride + rx]);
68+ }
69+ }
70+ let source = d;
71+ forward_4x4(&mut d);
72+ let rdoq = !intra && w.is_cabac();
73+ let mut nz = if rdoq {
74+ quant_4x4_offset(&d, qp, RDOQ_DEAD_ZONE, false, &mut lv.luma[blk])
75+ } else {
76+ quant_4x4(&d, qp, intra, false, &mut lv.luma[blk])
77+ };
78+ if rdoq && nz != 0 {
79+ nz = rdoq_4x4(
80+ e,
81+ w,
82+ &source,
83+ &mut lv.luma[blk],
84+ qp,
85+ BlockCat::Luma4x4,
86+ false,
87+ );
88+ }
89+ lv.luma_nz[blk] = nz;
90+ if nz == 0 {
91+ continue;
92+ }
93+ let mut raster = [0i32; 16];
94+ unzigzag(&lv.luma[blk], &mut raster);
95+ dequant_4x4(&mut raster, &e.ls, qp, false);
96+ let mut resid = [0i32; 16];
97+ inverse_transform_4x4(&raster, &mut resid);
98+ // Is the block worth its bits? A block whose residual barely moves the
99+ // reconstruction is pure quantisation churn; dropping it is the cheap
100+ // half of rate-distortion optimised quantisation, and the half that
101+ // pays. Intra blocks are left alone: their reconstruction is what the
102+ // next block in the macroblock predicts from.
103+ if !rdoq
104+ && !intra
105+ && !worth_coding(
106+ &source,
107+ &resid,
108+ &lv.luma[blk],
109+ zero_block_lambda(e, qp, e.transform_8x8),
110+ )
111+ {
112+ lv.luma[blk] = [0; 16];
113+ lv.luma_nz[blk] = 0;
114+ continue;
115+ }
116+ if intra {
117+ lv.cbp_luma |= 1 << (blk >> 2);
118+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
119+ } else {
120+ for i in 0..16 {
121+ let z = i64::from(source[i]);
122+ let c = i64::from(source[i] - resid[i]);
123+ ssd_zero[blk >> 2] += z * z;
124+ ssd_coded[blk >> 2] += c * c;
125+ }
126+ rate[blk >> 2] +=
127+ match w.residual_block_cost(&lv.luma[blk], BlockCat::Luma4x4, Some(1), Some(1)) {
128+ // CABAC's own arithmetic cost for the levels, which is what
129+ // the group is really deciding about. It arrives in 256ths of
130+ // a bit.
131+ Some(bits) => f64::from(bits) / 256.0,
132+ None => block_bits(&lv.luma[blk]) as f64,
133+ };
134+ pending[blk] = Some(resid);
135+ }
136+ }
137+ if intra {
138+ return;
139+ }
140+ // A block that survives its own rate-distortion test can still be the last
141+ // coefficient standing in its 8x8 group, and then it is paying a
142+ // coded_block_pattern bit as well as its levels. x264 decides that with a
143+ // count of how tightly the levels cluster at the front of the scan
144+ // (`decimate`), thresholded at four per group; swept here, that count
145+ // wants opposite settings on the two contents -- monotonically off on
146+ // camera grain, monotonically harder on screen capture -- because it is a
147+ // heuristic standing in for a rate-distortion test the encoder can just
148+ // do. So do it: a group is coded only if its blocks buy more squared error
149+ // than their levels plus the pattern bit are worth, at the same lambda the
150+ // per-block test uses.
151+ // With an exact rate the lambda needs no correction factor: the group test
152+ // uses the mode decision's own lambda where the rate is CABAC's, and falls
153+ // back to the per-block test's discounted one where it is an estimate.
154+ let lambda = if w.is_cabac() {
155+ GROUP_LAMBDA * lambda_ssd(qp)
156+ } else {
157+ zero_block_lambda(e, qp, e.transform_8x8)
158+ };
159+ for g in 0..4 {
160+ if rate[g] == 0.0 {
161+ continue;
162+ }
163+ if ssd_coded[g] as f64 + lambda * (rate[g] + CBP_BIT) < ssd_zero[g] as f64 {
164+ continue;
165+ }
166+ for blk in g * 4..g * 4 + 4 {
167+ lv.luma[blk] = [0; 16];
168+ lv.luma_nz[blk] = 0;
169+ pending[blk] = None;
170+ }
171+ }
172+ for blk in 0..16 {
173+ let Some(resid) = pending[blk] else { continue };
174+ let (dx, dy) = BLK4_POS[blk];
175+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
176+ let origin = pic.y.at(x, y);
177+ lv.cbp_luma |= 1 << (blk >> 2);
178+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
179+ }
180+}
181+
182+/// What a group of four luma blocks pays in coded_block_pattern to be coded
183+/// at all, in bits, on top of its own levels.
184+///
185+/// This charge and [`GROUP_LAMBDA`] move the group test along the same axis --
186+/// both make dropping a group likelier -- so only one of them is worth tuning.
187+/// Swept at 0, 6, 12 and 24 bits it reads -0.317/-0.335/-0.379/-0.472 dB on
188+/// the film clip against -0.295/-0.212/-0.191/-0.185 on the screen capture:
189+/// the same trade the lambda makes, at a worse exchange rate. It stays at a
190+/// plausible six.
191+pub(super) const CBP_BIT: f64 = 6.0;
192+
193+/// What chroma pays to take its coded_block_pattern from one to two, in bits,
194+/// on top of the levels: the pattern bins themselves plus a coded_block_flag
195+/// for every AC block that then has to say it is empty.
196+///
197+/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a
198+/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/
199+/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/
200+/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The
201+/// same sweep read on luma alone climbs all the way to +0.079 dB at 64,
202+/// because past the turn the test is buying luma bits by throwing chroma
203+/// away -- which is exactly the trade an all-plane metric exists to catch.
204+pub(super) const CBP_CHROMA_BIT: f64 = 16.0;
205+
206+/// How much of the mode-decision lambda the group test uses.
207+///
208+/// The 8x8 transform path was swept the same way and does not want this test
209+/// at all: at 0, 0.3 and 0.6 the `transform_8x8` gate reads +0.620/+0.624/
210+/// +0.608 dB on the film clip and +0.007/+0.007/+0.009 on the screen capture,
211+/// all inside its noise. One 8x8 block is a whole coded_block_pattern group,
212+/// so its own zero test already decides what this one would, and `rdoq_8x8`
213+/// drops it outright when the levels do not survive.
214+///
215+/// Swept at 0.25, 0.5, 0.6, 0.75, 0.9, 1.0 and 2.0 on both real clips:
216+/// -0.315/-0.314/-0.321/-0.335/-0.354/-0.372/-0.575 dB on the 3840x1608 film
217+/// clip and -0.297/-0.267/-0.252/-0.212/-0.202/-0.193/-0.277 on the 2560x1440
218+/// screen capture. Screen capture has an interior optimum around one -- which
219+/// the same test on an estimated rate did not, it only ever wanted more -- and
220+/// camera grain wants less, because a grain block that scores as noise is
221+/// carrying signal the eye is measuring. Six tenths is the most the film clip
222+/// takes without losing ground, and it is worth 0.06 dB on screen capture.
223+pub(super) const GROUP_LAMBDA: f64 = 0.6;
224+
225+/// How much of the squared-error lambda the chroma DC zero test uses.
226+///
227+/// BD-PSNR-YUV against x264 at GOP 10 over QP 22/26/30/34, `Preset::Balanced`,
228+/// with the test off against a ladder of multipliers:
229+///
230+/// ```text
231+/// film screen phone handheld
232+/// off -0.504 -0.227 -0.300 -0.886
233+/// 0.25 -0.506 -0.227
234+/// 0.5 -0.500 -0.220 -0.297 -0.884
235+/// 0.75 -0.500 -0.223
236+/// 1.0 -0.518 -0.246
237+/// 2.0 -0.708 -0.566
238+/// ```
239+///
240+/// Zeroing on squared error alone (a multiplier of 0) never fires, so the rate
241+/// term is the whole test; above the peak it throws away chroma the picture
242+/// needs.
243+pub(super) const CHROMA_DC_LAMBDA: f64 = 0.5;
244+
245+/// Squared error of coding `levels`, in the pixels the block reconstructs to.
246+pub(super) fn block_ssd(e: &MbEnc<'_>, source: &[i32; 16], levels: &[i32; 16], qp: i32, skip_dc: bool) -> i64 {
247+ let mut raster = [0i32; 16];
248+ if skip_dc {
249+ unzigzag_ac15(levels, &mut raster);
250+ } else {
251+ unzigzag(levels, &mut raster);
252+ }
253+ dequant_4x4(&mut raster, &e.ls, qp, skip_dc);
254+ let mut resid = [0i32; 16];
255+ inverse_transform_4x4(&raster, &mut resid);
256+ let mut ssd = 0i64;
257+ for i in 0..16 {
258+ let d = i64::from(source[i] - resid[i]);
259+ ssd += d * d;
260+ }
261+ ssd
262+}
263+
264+/// How much of the mode-decision lambda rate-distortion quantisation uses.
265+///
266+/// The bits here are the coder's own, not an estimate, so there is no
267+/// over-estimate to correct for and the scale starts at 1. Swept over 0.5,
268+/// 1.0, 1.25, 1.5 and 2.0 against x264 on a 3840x1608 film clip and a
269+/// 2560x1440 screen capture: the two disagree, film reading -0.607 dB at 0.5
270+/// and -0.680 at 1.5 while screen capture reads -0.620 and -0.444, and 1.0 is
271+/// the crossing point that costs neither (-0.628 and -0.471). Table in
272+/// `lanes/h264x264-r2.report.md`.
273+pub(super) const RDOQ_LAMBDA: f64 = 1.0;
274+
275+/// The dead zone rate-distortion quantisation starts from, as a divisor of the
276+/// quantiser step: 2 is round-to-nearest. The plain inter path uses 6, which
277+/// has already thrown away the levels this search would weigh -- a search
278+/// bounded by the heuristic it replaces measures the heuristic. This is the
279+/// half of the change that pays: 1/6 -> 1/2 under the same search is worth
280+/// 0.102 dB on the film clip and 0.301 on the synthetic gate. 1/3 and 1/4 read
281+/// -0.647 and -0.677 dB where 1/2 reads -0.630.
282+pub(super) const RDOQ_DEAD_ZONE: i32 = 2;
283+
284+/// The largest level the search offers a smaller magnitude to. A big level is
285+/// carrying real signal and never wins by shrinking; bounding the search is
286+/// what keeps it free. Unbounded it tripled the synthetic clip's encode time
287+/// (1.08 s -> 3.53 s) for the same BD-PSNR; at 2 the run is 1.09 s. Swept over
288+/// 1, 2 and 3: -4.062/-0.623/-0.496, -4.073/-0.628/-0.471 and
289+/// -4.065/-0.629/-0.477 dB on synthetic, film and screen capture.
290+pub(super) const RDOQ_MAX_LEVEL: i32 = 2;
291+
292+/// The rounding the chroma AC path keeps under the search: the inter dead zone
293+/// it already had. Luma wanted the wider 1/2 rounding once a search could take
294+/// levels back down (`RDOQ_DEAD_ZONE`); chroma does not. Measured on the two
295+/// clips at the settled luma constants, BD-PSNR against x264: 1/2 rounding
296+/// -0.653 film / -0.482 screen capture, 1/4 -0.623 / -0.472, 1/3 -0.644 /
297+/// -0.481, and the 1/6 kept here -0.593 / -0.468 -- against -0.628 / -0.471
298+/// with no chroma search at all. Chroma AC is sparse enough at these
299+/// quantisers that offering more levels costs more bits than the search takes
300+/// back; what pays is only the pruning.
301+pub(super) const RDOQ_CHROMA_DEAD_ZONE: i32 = 6;
302+
303+/// The rounding the 8x8 luma path keeps under the search. It answers the way
304+/// 4x4 luma did, not the way chroma did: measured as BD-PSNR of the opt-in
305+/// `transform_8x8` flag against flag-off, which isolates this path because the
306+/// flag-off curve does not run through it. Film 3840x1608 / screen capture
307+/// 2560x1440, no search +0.535 / +0.042, 1/6 +0.551 / --, 1/3 +0.605 / +0.075,
308+/// and the 1/2 kept here +0.619 / +0.067. The 8x8 blocks carry enough
309+/// coefficients for the extra levels to pay for themselves, as 4x4 luma's do.
310+pub(super) const RDOQ8_DEAD_ZONE: i32 = 2;
311+
312+/// Rate-distortion quantisation of one inter luma block: each level is offered
313+/// the two cheaper magnitudes below it, and takes one when the squared error it
314+/// gives up costs less than the bits it saves.
315+///
316+/// The rate is the CABAC coder's own price for the whole block against the
317+/// context state as it stands, so dropping a level is priced with the
318+/// significance map that follows from it — which is where most of the saving
319+/// is. Intra blocks stay out: their reconstruction is what the next block in
320+/// the macroblock predicts from, so a level changed here would move a
321+/// prediction the decision cannot see.
322+#[allow(clippy::too_many_arguments)]
323+pub(super) fn rdoq_4x4(
324+ e: &MbEnc<'_>,
325+ w: &EncEntropy,
326+ source: &[i32; 16],
327+ levels: &mut [i32; 16],
328+ qp: i32,
329+ cat: BlockCat,
330+ skip_dc: bool,
331+) -> u8 {
332+ let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
333+ return levels.iter().filter(|&&l| l != 0).count() as u8;
334+ };
335+ let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
336+ let mut cost = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
337+ // Highest scanning position first: dropping the last significant level is
338+ // what shortens the significance map, so it is tried while the levels
339+ // above it are still gone.
340+ for pos in (0..cat.max_num_coeff()).rev() {
341+ let level = levels[pos];
342+ if level == 0 {
343+ continue;
344+ }
345+ let mag = level.abs();
346+ if mag > RDOQ_MAX_LEVEL {
347+ continue;
348+ }
349+ let mut tried = mag;
350+ for candidate in [mag - 1, 0] {
351+ if candidate == tried {
352+ continue;
353+ }
354+ tried = candidate;
355+ let keep = levels[pos];
356+ levels[pos] = candidate * level.signum();
357+ let Some(bits) = w.residual_block_cost(levels, cat, Some(1), Some(1)) else {
358+ unreachable!("CAVLC returned early");
359+ };
360+ let trial = block_ssd(e, source, levels, qp, skip_dc) as f64 + lambda * f64::from(bits);
361+ if trial < cost {
362+ cost = trial;
363+ } else {
364+ levels[pos] = keep;
365+ }
366+ }
367+ }
368+ // And the block as a whole: zeroing it drops the coded_block_pattern bit as
369+ // well as every level, which no single-coefficient step can see. This is
370+ // the same decision `worth_coding` makes for the paths without an exact
371+ // rate, made here with one.
372+ let zero_bits = w
373+ .residual_block_cost(&[0; 16], cat, Some(1), Some(1))
374+ .expect("CABAC");
375+ let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
376+ if ssd_zero as f64 + lambda * f64::from(zero_bits) <= cost {
377+ *levels = [0; 16];
378+ return 0;
379+ }
380+ levels.iter().filter(|&&l| l != 0).count() as u8
381+}
382+
383+/// How much of the mode-decision lambda the zero-block test uses.
384+///
385+/// [`block_bits`] counts a level at its exp-Golomb-ish width, which is what
386+/// CAVLC spends and an over-estimate of what CABAC spends; the multiplier
387+/// brings the rate term back to the coder actually in force. Measured over
388+/// 0.0, 0.4 and 1.0 on 1080p camera and screen-capture clips: 0.4 is the only
389+/// one that gains on screen content (+0.13 to +0.39 dB at matched bitrate)
390+/// without costing camera content.
391+pub(super) const ZERO_BLOCK_LAMBDA: f64 = 0.4;
392+
393+pub(super) fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 {
394+ if transform_8x8 {
395+ e.lambda
396+ } else {
397+ ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
398+ }
399+}
400+
401+/// The rate-distortion test behind the per-block zero decision: coding the
402+/// block has to buy more squared error than its bits are worth.
403+pub(super) fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
404+ let mut ssd_zero = 0i64;
405+ let mut ssd_coded = 0i64;
406+ for i in 0..source.len() {
407+ let z = i64::from(source[i]);
408+ let c = i64::from(source[i] - resid[i]);
409+ ssd_zero += z * z;
410+ ssd_coded += c * c;
411+ }
412+ ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
413+}
414+
415+/// Predict and code the luma of an Intra_16x16 macroblock.
416+#[allow(clippy::too_many_arguments)]
417+pub(super) fn code_i16_luma(
418+ pic: &mut Picture,
419+ e: &MbEnc<'_>,
420+ mb_x: usize,
421+ mb_y: usize,
422+ qp: i32,
423+ mode: u8,
424+ nbr: &MbNeighbors,
425+ lv: &mut Levels,
426+) {
427+ let w4 = pic.mb_w * 4;
428+ for dy in 0..4 {
429+ let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
430+ pic.i4_modes[base..base + 4].fill(2);
431+ }
432+ let stride = pic.y.stride;
433+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
434+ let mut win = PlaneWindow {
435+ data: &mut pic.y.data,
436+ stride,
437+ origin,
438+ };
439+ pred_16x16(mode, 8, &mut win, nbr.b, nbr.a);
440+ code_luma_i16(pic, e, mb_x, mb_y, qp, lv);
441+}
442+
443+/// The Intra_16x16 luma path (8.5.10 in reverse then forward again).
444+pub(super) fn code_luma_i16(
445+ pic: &mut Picture,
446+ e: &MbEnc<'_>,
447+ mb_x: usize,
448+ mb_y: usize,
449+ qp: i32,
450+ lv: &mut Levels,
451+) {
452+ let stride = pic.y.stride;
453+ let mut dc = [0i32; 16];
454+ let mut ac = [[0i32; 16]; 16];
455+ for blk in 0..16 {
456+ let (dx, dy) = BLK4_POS[blk];
457+ let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
458+ let origin = pic.y.at(x, y);
459+ let mut d = [0i32; 16];
460+ for ry in 0..4 {
461+ for rx in 0..4 {
462+ d[ry * 4 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx])
463+ - i32::from(pic.y.data[origin + ry * stride + rx]);
464+ }
465+ }
466+ forward_4x4(&mut d);
467+ dc[dy as usize * 4 + dx as usize] = d[0];
468+ let nz = quant_4x4(&d, qp, true, true, &mut lv.luma[blk]);
469+ lv.luma_nz[blk] = nz;
470+ ac[blk] = lv.luma[blk];
471+ if nz > 0 {
472+ lv.cbp_luma = 15;
473+ }
474+ }
475+ if lv.cbp_luma == 0 {
476+ for blk in 0..16 {
477+ lv.luma[blk] = [0; 16];
478+ lv.luma_nz[blk] = 0;
479+ }
480+ }
481+ forward_hadamard_4x4(&mut dc);
482+ quant_luma_dc(&dc, qp, &mut lv.dc);
483+
484+ // Reconstruct exactly as the decoder does: DC through 8.5.10, then each
485+ // block's AC with the DC substituted at raster position 0.
486+ let mut raster = [0i32; 16];
487+ unzigzag(&lv.dc, &mut raster);
488+ luma_dc_transform(&mut raster, &e.ls, qp);
489+ let dc_recon = raster;
490+ for blk in 0..16 {
491+ let (dx, dy) = BLK4_POS[blk];
492+ let dc_blk = dc_recon[dy as usize * 4 + dx as usize];
493+ let tc = lv.luma_nz[blk];
494+ if tc == 0 && dc_blk == 0 {
495+ continue;
496+ }
497+ let mut raster = [0i32; 16];
498+ if tc > 0 {
499+ unzigzag_ac15(&ac[blk], &mut raster);
500+ dequant_4x4(&mut raster, &e.ls, qp, true);
501+ }
502+ raster[0] = dc_blk;
503+ let mut resid = [0i32; 16];
504+ inverse_transform_4x4(&raster, &mut resid);
505+ let origin = pic
506+ .y
507+ .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
508+ add_residual_4x4(&mut pic.y.data, 8, stride, origin, &resid);
509+ }
510+}
511+
512+/// Chroma residual for both components (8.5.11 + the AC path).
513+#[allow(clippy::too_many_arguments)]
514+pub(super) fn code_chroma(
515+ pic: &mut Picture,
516+ e: &MbEnc<'_>,
517+ w: &EncEntropy,
518+ mb_x: usize,
519+ mb_y: usize,
520+ qp_y: i32,
521+ intra: bool,
522+ lv: &mut Levels,
523+) {
524+ let qp_c = chroma_qp(qp_y, e.cqo);
525+ let mut dc_lists = [[0i32; 4]; 2];
526+ let mut ac = [[[0i32; 16]; 4]; 2];
527+ let mut srcs = [[[0i32; 16]; 4]; 2];
528+ let mut any_ac = false;
529+ for comp in 0..2 {
530+ let (plane, src) = if comp == 0 {
531+ (&pic.cb, &e.src.u)
532+ } else {
533+ (&pic.cr, &e.src.v)
534+ };
535+ let stride = plane.stride;
536+ for blk in 0..4 {
537+ let (x, y) = (mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
538+ let origin = plane.at(x, y);
539+ let mut d = [0i32; 16];
540+ for ry in 0..4 {
541+ for rx in 0..4 {
542+ d[ry * 4 + rx] = i32::from(src[(y + ry) * e.src.c_stride + x + rx])
543+ - i32::from(plane.data[origin + ry * stride + rx]);
544+ }
545+ }
546+ let source = d;
547+ srcs[comp][blk] = d;
548+ forward_4x4(&mut d);
549+ dc_lists[comp][blk] = d[0];
550+ let rdoq = !intra && w.is_cabac();
551+ let mut nz = if rdoq {
552+ quant_4x4_offset(&d, qp_c, RDOQ_CHROMA_DEAD_ZONE, true, &mut ac[comp][blk])
553+ } else {
554+ quant_4x4(&d, qp_c, intra, true, &mut ac[comp][blk])
555+ };
556+ if rdoq && nz > 0 {
557+ nz = rdoq_4x4(
558+ e,
559+ w,
560+ &source,
561+ &mut ac[comp][blk],
562+ qp_c,
563+ BlockCat::ChromaAc,
564+ true,
565+ );
566+ } else if nz > 0 {
567+ // The same zero decision as luma, against the AC part alone:
568+ // the DC of this block travels through the 2x2 Hadamard and is
569+ // decided with the other three.
570+ let mut raster = [0i32; 16];
571+ unzigzag_ac15(&ac[comp][blk], &mut raster);
572+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
573+ let mut resid = [0i32; 16];
574+ inverse_transform_4x4(&raster, &mut resid);
575+ if !worth_coding(
576+ &source,
577+ &resid,
578+ &ac[comp][blk],
579+ zero_block_lambda(e, qp_c, e.transform_8x8),
580+ ) {
581+ ac[comp][blk] = [0; 16];
582+ nz = 0;
583+ }
584+ }
585+ lv.chroma_nz[comp][blk] = nz;
586+ if nz > 0 {
587+ any_ac = true;
588+ }
589+ }
590+ }
591+ // The chroma pattern is one decision for all eight AC blocks: a single
592+ // surviving block takes coded_block_pattern from one to two, and every
593+ // other block then has to code a coded_block_flag to say it is empty. So
594+ // the same group test luma runs over four blocks runs here over all eight,
595+ // against the same lambda.
596+ if any_ac {
597+ let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64);
598+ for comp in 0..2 {
599+ for blk in 0..4 {
600+ let source = &srcs[comp][blk];
601+ let mut resid = [0i32; 16];
602+ if lv.chroma_nz[comp][blk] > 0 {
603+ let mut raster = [0i32; 16];
604+ unzigzag_ac15(&ac[comp][blk], &mut raster);
605+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
606+ inverse_transform_4x4(&raster, &mut resid);
607+ rate += match w.residual_block_cost(
608+ &ac[comp][blk],
609+ BlockCat::ChromaAc,
610+ Some(1),
611+ Some(1),
612+ ) {
613+ Some(bits) => f64::from(bits) / 256.0,
614+ None => block_bits(&ac[comp][blk]) as f64,
615+ };
616+ }
617+ for i in 0..16 {
618+ let z = i64::from(source[i]);
619+ let c = i64::from(source[i] - resid[i]);
620+ ssd_zero += z * z;
621+ ssd_coded += c * c;
622+ }
623+ }
624+ }
625+ let lambda = if w.is_cabac() {
626+ GROUP_LAMBDA * lambda_ssd(qp_c)
627+ } else {
628+ zero_block_lambda(e, qp_c, false)
629+ };
630+ if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 {
631+ ac = [[[0; 16]; 4]; 2];
632+ lv.chroma_nz = [[0; 4]; 2];
633+ any_ac = false;
634+ }
635+ }
636+ // The chroma DC block had no zero test at all: whatever the quantiser
637+ // produced was coded. Its four coefficients spread over all 64 samples of
638+ // the component, and with only DC in the block the inverse transform gives
639+ // every sample the same (dc + 32) >> 6, so the squared error zeroing costs
640+ // is exact in one pass over the AC residual that is already reconstructed
641+ // here.
642+ let mut any_dc = false;
643+ for comp in 0..2 {
644+ forward_hadamard_2x2(&mut dc_lists[comp]);
645+ let mut nz = quant_chroma_dc(&dc_lists[comp], qp_c, intra, &mut lv.chroma_dc[comp]);
646+ if nz > 0 {
647+ let mut dc = [
648+ lv.chroma_dc[comp][0],
649+ lv.chroma_dc[comp][1],
650+ lv.chroma_dc[comp][2],
651+ lv.chroma_dc[comp][3],
652+ ];
653+ chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
654+ let mut delta = 0i64;
655+ for blk in 0..4 {
656+ let mut resid = [0i32; 16];
657+ if any_ac && lv.chroma_nz[comp][blk] > 0 {
658+ let mut raster = [0i32; 16];
659+ unzigzag_ac15(&ac[comp][blk], &mut raster);
660+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
661+ inverse_transform_4x4(&raster, &mut resid);
662+ }
663+ let c = i64::from((dc[blk] + 32) >> 6);
664+ let err: i64 = (0..16)
665+ .map(|i| i64::from(srcs[comp][blk][i] - resid[i]))
666+ .sum();
667+ delta += 16 * c * c - 2 * c * err;
668+ }
669+ let rate = match w.residual_block_cost(
670+ &lv.chroma_dc[comp],
671+ BlockCat::ChromaDc(comp as u8),
672+ Some(1),
673+ Some(1),
674+ ) {
675+ Some(bits) => f64::from(bits) / 256.0,
676+ None => block_bits(&lv.chroma_dc[comp]) as f64,
677+ };
678+ if delta as f64 + CHROMA_DC_LAMBDA * lambda_ssd(qp_c) * rate >= 0.0 {
679+ lv.chroma_dc[comp] = [0; 16];
680+ nz = 0;
681+ }
682+ }
683+ if nz > 0 {
684+ any_dc = true;
685+ }
686+ }
687+ lv.cbp_chroma = if any_ac {
688+ 2
689+ } else if any_dc {
690+ 1
691+ } else {
692+ 0
693+ };
694+ if lv.cbp_chroma < 2 {
695+ lv.chroma_nz = [[0; 4]; 2];
696+ } else {
697+ lv.chroma = ac;
698+ }
699+ if lv.cbp_chroma == 0 {
700+ return;
701+ }
702+ for comp in 0..2 {
703+ let mut dc = [
704+ lv.chroma_dc[comp][0],
705+ lv.chroma_dc[comp][1],
706+ lv.chroma_dc[comp][2],
707+ lv.chroma_dc[comp][3],
708+ ];
709+ chroma_dc_transform_420(&mut dc, &e.ls, qp_c);
710+ let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
711+ let stride = plane.stride;
712+ for blk in 0..4 {
713+ let tc = lv.chroma_nz[comp][blk];
714+ if tc == 0 && dc[blk] == 0 {
715+ continue;
716+ }
717+ let mut raster = [0i32; 16];
718+ if tc > 0 {
719+ unzigzag_ac15(&lv.chroma[comp][blk], &mut raster);
720+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
721+ }
722+ raster[0] = dc[blk];
723+ let mut resid = [0i32; 16];
724+ inverse_transform_4x4(&raster, &mut resid);
725+ let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
726+ add_residual_4x4(&mut plane.data, 8, stride, origin, &resid);
727+ }
728+ }
729+}
730+
731+/// The inter residual under the 8x8 transform, prediction already in the
732+/// plane: the sibling of [`code_luma_4x4`].
733+pub(super) fn code_luma_8x8(
734+ pic: &mut Picture,
735+ e: &MbEnc<'_>,
736+ w: &EncEntropy,
737+ mb_x: usize,
738+ mb_y: usize,
739+ qp: i32,
740+ lv: &mut Levels,
741+) {
742+ lv.trans8 = true;
743+ for blk8 in 0..4 {
744+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8);
745+ if code_block_8x8(pic, e, w, x, y, qp, false, &mut lv.luma8[blk8]) > 0 {
746+ lv.cbp_luma |= 1 << blk8;
747+ }
748+ }
749+}
750+
751+/// Squared error of coding `levels` as an 8x8 block, in its pixels.
752+pub(super) fn block_ssd_8x8(e: &MbEnc<'_>, source: &[i32; 64], levels: &[i32; 64], qp: i32) -> i64 {
753+ let mut raster = [0i32; 64];
754+ unzigzag_8x8(levels, &mut raster);
755+ dequant_8x8(&mut raster, &e.ls8, qp);
756+ let mut resid = [0i32; 64];
757+ inverse_transform_8x8(&raster, &mut resid);
758+ let mut ssd = 0i64;
759+ for k in 0..64 {
760+ let d = i64::from(source[k]) - i64::from(resid[k]);
761+ ssd += d * d;
762+ }
763+ ssd
764+}
765+
766+/// [`rdoq_4x4`] for the 8x8 transform: the same walk down the scan against the
767+/// CABAC coder's own price, with the 8x8 block's own contexts.
768+pub(super) fn rdoq_8x8(
769+ e: &MbEnc<'_>,
770+ w: &EncEntropy,
771+ source: &[i32; 64],
772+ levels: &mut [i32; 64],
773+ qp: i32,
774+) -> u8 {
775+ let Some(bits) = w.residual_block_8x8_cost(levels) else {
776+ return levels.iter().filter(|&&l| l != 0).count() as u8;
777+ };
778+ let lambda = RDOQ_LAMBDA * lambda_ssd(qp) / 256.0;
779+ let mut cost = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
780+ for pos in (0..64).rev() {
781+ let level = levels[pos];
782+ if level == 0 {
783+ continue;
784+ }
785+ let mag = level.abs();
786+ if mag > RDOQ_MAX_LEVEL {
787+ continue;
788+ }
789+ let mut tried = mag;
790+ for candidate in [mag - 1, 0] {
791+ if candidate == tried {
792+ continue;
793+ }
794+ tried = candidate;
795+ let keep = levels[pos];
796+ levels[pos] = candidate * level.signum();
797+ let bits = w
798+ .residual_block_8x8_cost(levels)
799+ .expect("CAVLC returned early");
800+ let trial = block_ssd_8x8(e, source, levels, qp) as f64 + lambda * f64::from(bits);
801+ if trial < cost {
802+ cost = trial;
803+ } else {
804+ levels[pos] = keep;
805+ break;
806+ }
807+ }
808+ }
809+ // The whole block against nothing, on the same exact price.
810+ let ssd_zero: i64 = source.iter().map(|&c| i64::from(c) * i64::from(c)).sum();
811+ if ssd_zero as f64 <= cost {
812+ *levels = [0; 64];
813+ return 0;
814+ }
815+ levels.iter().filter(|&&l| l != 0).count() as u8
816+}
817+
818+/// Squared error of the luma macroblock against the source.
819+pub(super) fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
820+ let stride = pic.y.stride;
821+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
822+ let mut sum = 0i64;
823+ for row in 0..16 {
824+ let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
825+ for x in 0..16 {
826+ let d = i64::from(e.src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]);
827+ sum += d * d;
828+ }
829+ }
830+ sum
831+}
832+
833+/// Copy the luma macroblock out of the plane, and back in.
834+pub(super) fn save_luma(pic: &Picture, mb_x: usize, mb_y: usize, out: &mut [u8; 256]) {
835+ let stride = pic.y.stride;
836+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
837+ for row in 0..16 {
838+ out[row * 16..row * 16 + 16].copy_from_slice(&pic.y.data[origin + row * stride..][..16]);
839+ }
840+}
841+
842+pub(super) fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) {
843+ let stride = pic.y.stride;
844+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
845+ for row in 0..16 {
846+ pic.y.data[origin + row * stride..][..16].copy_from_slice(&src[row * 16..row * 16 + 16]);
847+ }
848+}
849+
850+pub(super) fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
851+ let mut bits = estimate_luma_bits(lv);
852+ match i4 {
853+ Some((modes, pred)) => {
854+ bits += 6;
855+ for blk in 0..modes.len() {
856+ bits += if modes[blk] == pred[blk] { 1 } else { 4 };
857+ }
858+ }
859+ None => bits += 8,
860+ }
861+ bits
862+}
863+
864+pub(super) fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 {
865+ let mut probe = w.probe_copy();
866+ let before = probe.bit_len();
867+ write(&mut probe);
868+ (probe.bit_len() - before) as i64
869+}
870+
871+pub(super) fn cost_luma_nz_pair(
872+ pic: &Picture,
873+ nbr: &MbNeighbors,
874+ local: &[u8; 16],
875+ bx0: usize,
876+ by0: usize,
877+ bx: usize,
878+ by: usize,
879+) -> (Option<u8>, Option<u8>) {
880+ let w4 = pic.mb_w * 4;
881+ let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true };
882+ let top_avail = if by.is_multiple_of(4) { nbr.b } else { true };
883+ let left = (left_avail && bx > 0).then(|| {
884+ if bx > bx0 {
885+ local[(by - by0) * 4 + (bx - bx0 - 1)]
886+ } else {
887+ pic.nz_y[by * w4 + bx - 1]
888+ }
889+ });
890+ let top = (top_avail && by > 0).then(|| {
891+ if by > by0 {
892+ local[(by - by0 - 1) * 4 + (bx - bx0)]
893+ } else {
894+ pic.nz_y[(by - 1) * w4 + bx]
895+ }
896+ });
897+ (left, top)
898+}
899+
900+pub(super) fn write_luma_for_cost(
901+ pic: &Picture,
902+ nbr: &MbNeighbors,
903+ w: &mut EncEntropy,
904+ mb_x: usize,
905+ mb_y: usize,
906+ lv: &Levels,
907+ is_i16: bool,
908+) {
909+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
910+ let mut nz = [0u8; 16];
911+ if is_i16 {
912+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0);
913+ nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
914+ }
915+ if lv.trans8 {
916+ for blk8 in 0..4 {
917+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
918+ if lv.cbp_luma & (1 << blk8) == 0 {
919+ continue;
920+ }
921+ if w.is_cabac() {
922+ let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
923+ for dy in 0..2 {
924+ let base = (by - by0 + dy) * 4 + bx - bx0;
925+ nz[base..base + 2].fill(tc.min(16));
926+ }
927+ } else {
928+ for i4 in 0..4 {
929+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
930+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
931+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy);
932+ let sub = sub_block_4x4(&lv.luma8[blk8], i4);
933+ nz[(sy - by0) * 4 + (sx - bx0)] =
934+ w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
935+ }
936+ }
937+ }
938+ return;
939+ }
940+ for blk in 0..16 {
941+ let (dx, dy) = BLK4_POS[blk];
942+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
943+ let group = 1 << (blk >> 2);
944+ let coded_block = if is_i16 {
945+ lv.cbp_luma != 0
946+ } else {
947+ lv.cbp_luma & group != 0
948+ };
949+ if coded_block {
950+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by);
951+ let (levels, cat) = if is_i16 {
952+ (&lv.luma[blk][..15], BlockCat::LumaAc)
953+ } else {
954+ (&lv.luma[blk][..16], BlockCat::Luma4x4)
955+ };
956+ nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb);
957+ }
958+ }
959+}
960+
961+#[allow(clippy::too_many_arguments)] // the encoder cost model takes its per-MB state explicitly
962+pub(super) fn cost_chroma_nz_pair(
963+ pic: &Picture,
964+ nbr: &MbNeighbors,
965+ local: &[[u8; 4]; 2],
966+ comp: usize,
967+ cx0: usize,
968+ cy0: usize,
969+ cx: usize,
970+ cy: usize,
971+) -> (Option<u8>, Option<u8>) {
972+ let w2 = pic.mb_w * 2;
973+ let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true };
974+ let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true };
975+ let left = (left_avail && cx > 0).then(|| {
976+ if cx > cx0 {
977+ local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)]
978+ } else {
979+ pic.nz_c[comp][cy * w2 + cx - 1]
980+ }
981+ });
982+ let top = (top_avail && cy > 0).then(|| {
983+ if cy > cy0 {
984+ local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)]
985+ } else {
986+ pic.nz_c[comp][(cy - 1) * w2 + cx]
987+ }
988+ });
989+ (left, top)
990+}
991+
992+pub(super) fn write_chroma_for_cost(
993+ pic: &Picture,
994+ nbr: &MbNeighbors,
995+ w: &mut EncEntropy,
996+ mb_x: usize,
997+ mb_y: usize,
998+ lv: &Levels,
999+) {
1000+ if lv.cbp_chroma != 0 {
1001+ for comp in 0..2 {
1002+ w.residual_block(
1003+ &lv.chroma_dc[comp][..4],
1004+ BlockCat::ChromaDc(comp as u8),
1005+ None,
1006+ None,
1007+ );
1008+ }
1009+ }
1010+ if lv.cbp_chroma != 2 {
1011+ return;
1012+ }
1013+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1014+ let mut nz = [[0u8; 4]; 2];
1015+ for comp in 0..2 {
1016+ for blk in 0..4 {
1017+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1018+ let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy);
1019+ nz[comp][blk] =
1020+ w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb);
1021+ }
1022+ }
1023+}
1024+
1025+/// Eight samples widened to 16-bit lanes; the tail past the slice is zero,
1026+/// which only a caller reading past the plane could reach.
1027+#[inline]
1028+pub(super) fn load8(data: &[u8], at: usize) -> i16x8 {
1029+ let mut a = [0i16; 8];
1030+ if let Some(row) = data.get(at..at + 8) {
1031+ for (o, &b) in a.iter_mut().zip(row) {
1032+ *o = i16::from(b);
1033+ }
1034+ }
1035+ i16x8::from(a)
1036+}
1037+
1038+/// Squared error of the whole macroblock against the source, luma and chroma:
1039+/// the distortion term of the skip decision.
1040+///
1041+/// Each row's 16 (luma) or 8 (chroma) per-pixel differences fit in `i16`
1042+/// (range `-255..=255`), and `dot` widens the pairwise products to `i32`
1043+/// before summing, so this is the exact same integer value as scalar
1044+/// `i64::from(d) * i64::from(d)` per pixel, just batched a row at a time and
1045+/// summed into the `i64` accumulator in a different (still overflow-free,
1046+/// so exact) order.
1047+pub(super) fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 {
1048+ let mut sum = 0i64;
1049+ let stride = pic.y.stride;
1050+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
1051+ for row in 0..16 {
1052+ let s = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
1053+ let d = load16(&e.src.y, s) - load16(&pic.y.data, origin + row * stride);
1054+ sum += d
1055+ .dot(d)
1056+ .to_array()
1057+ .iter()
1058+ .map(|&v| i64::from(v))
1059+ .sum::<i64>();
1060+ }
1061+ for comp in 0..2 {
1062+ let (plane, src) = if comp == 0 {
1063+ (&pic.cb, &e.src.u)
1064+ } else {
1065+ (&pic.cr, &e.src.v)
1066+ };
1067+ let stride = plane.stride;
1068+ let origin = plane.at(mb_x * 8, mb_y * 8);
1069+ for row in 0..8 {
1070+ let s = (mb_y * 8 + row) * e.src.c_stride + mb_x * 8;
1071+ let d = load8(src, s) - load8(&plane.data, origin + row * stride);
1072+ sum += d
1073+ .dot(d)
1074+ .to_array()
1075+ .iter()
1076+ .map(|&v| i64::from(v))
1077+ .sum::<i64>();
1078+ }
1079+ }
1080+ sum
1081+}
1082+
1083+/// [`ssd_mb`] with the luma half measured after the loop filter this
1084+/// macroblock's reconstruction will get. `bs(edge, seg, vertical)` is the
1085+/// boundary strength of one 4-sample edge segment — edge 0 the macroblock
1086+/// edge, edges 1..3 the internal edges at offsets 4/8/12 — as the decoder
1087+/// will derive it, so an intra candidate passes its forced 4/3 and an inter
1088+/// candidate its own coded/motion strengths. A transform-8x8 macroblock has
1089+/// no transform edge at luma offsets 4 and 12, so those stay unfiltered,
1090+/// exactly as the decoder's `internal` gate decides it. Neighbours share
1091+/// this slice's qp with the zero offsets the encoder writes, so every edge
1092+/// is parameterised by the trial qp alone. The right and bottom edges
1093+/// belong to macroblocks coded later and cannot be known here; the aprons
1094+/// are the pre-filter neighbour samples, which is everything that exists at
1095+/// decision time. The chroma half is left pre-filter: chroma never takes
1096+/// the 8x8 transform, so it cannot separate the candidates.
1097+///
1098+/// The 8x8-vs-4x4 trials are judged by this and not by [`ssd_mb`] because the
1099+/// two candidates meet different edge sets under the same loop filter: a
1100+/// pre-filter SSD prices the 4x4 candidate as if its extra filtered edges
1101+/// cost nothing.
1102+pub(super) fn ssd_mb_deblocked(
1103+ pic: &Picture,
1104+ e: &MbEnc<'_>,
1105+ mb_x: usize,
1106+ mb_y: usize,
1107+ nbr: &MbNeighbors,
1108+ trans8: bool,
1109+ bs: impl Fn(usize, usize, bool) -> u8,
1110+) -> i64 {
1111+ // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4
1112+ // edge reads p3 and rewrites p2 on its far side.
1113+ const A: usize = 4;
1114+ const S: usize = A + 16;
1115+ let mut scratch = [0u8; S * S];
1116+ let stride = pic.y.stride;
1117+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
1118+ for row in 0..16 {
1119+ let src = origin + row * stride;
1120+ let dst = (A + row) * S + A;
1121+ scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
1122+ }
1123+ if nbr.a {
1124+ for row in 0..16 {
1125+ let src = origin + row * stride - A;
1126+ let dst = (A + row) * S;
1127+ scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]);
1128+ }
1129+ }
1130+ if nbr.b {
1131+ for row in 0..A {
1132+ let src = origin - (A - row) * stride;
1133+ let dst = row * S + A;
1134+ scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
1135+ }
1136+ }
1137+ // Vertical edges left to right, then horizontal top to bottom, the order
1138+ // of 8.7.1: each edge filters what the earlier edges left behind. Each
1139+ // 4-sample segment carries its own strength, as in the decoder.
1140+ let qp = e.target_qp;
1141+ for edge in 0..4 {
1142+ let x = edge * 4;
1143+ if (edge == 0 && !nbr.a) || (trans8 && x != 0 && x != 8) {
1144+ continue;
1145+ }
1146+ for seg in 0..4 {
1147+ let s = bs(edge, seg, true);
1148+ if s == 0 {
1149+ continue;
1150+ }
1151+ let ep = edge_params(qp, 0, 0, s, 8);
1152+ for row in seg * 4..seg * 4 + 4 {
1153+ filter_luma_line(&mut scratch, 255, (A + row) * S + A + x, 1, &ep);
1154+ }
1155+ }
1156+ }
1157+ for edge in 0..4 {
1158+ let y = edge * 4;
1159+ if (edge == 0 && !nbr.b) || (trans8 && y != 0 && y != 8) {
1160+ continue;
1161+ }
1162+ let seg_bs = [
1163+ bs(edge, 0, false),
1164+ bs(edge, 1, false),
1165+ bs(edge, 2, false),
1166+ bs(edge, 3, false),
1167+ ];
1168+ if seg_bs[0] == seg_bs[1] && seg_bs[1] == seg_bs[2] && seg_bs[2] == seg_bs[3] {
1169+ if seg_bs[0] != 0 {
1170+ let ep = edge_params(qp, 0, 0, seg_bs[0], 8);
1171+ filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &ep);
1172+ }
1173+ continue;
1174+ }
1175+ for seg in 0..4 {
1176+ if seg_bs[seg] == 0 {
1177+ continue;
1178+ }
1179+ let ep = edge_params(qp, 0, 0, seg_bs[seg], 8);
1180+ for col in seg * 4..seg * 4 + 4 {
1181+ filter_luma_line(&mut scratch, 255, (A + y) * S + A + col, S, &ep);
1182+ }
1183+ }
1184+ }
1185+ let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y);
1186+ for row in 0..16 {
1187+ let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
1188+ for x in 0..16 {
1189+ let d = i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
1190+ sum += d * d;
1191+ }
1192+ }
1193+ sum
1194+}
1195+
1196+/// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its
1197+/// macroblock edges, 3 on the internal luma edges.
1198+pub(super) fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 {
1199+ if edge == 0 { 4 } else { 3 }
1200+}
1201+
1202+/// Rough bit cost of a macroblock's luma residual.
1203+pub(super) fn estimate_luma_bits(lv: &Levels) -> i64 {
1204+ let mut bits = 0;
1205+ if lv.trans8 {
1206+ for blk8 in 0..4 {
1207+ if lv.cbp_luma & (1 << blk8) != 0 {
1208+ // A level's position costs two more bits in a 64-coefficient
1209+ // significance map than in a 16-coefficient one; measured
1210+ // against the coded size on the text clip, without this the
1211+ // estimate undercharges Intra_8x8 by ~44 bits a macroblock.
1212+ let b = &lv.luma8[blk8];
1213+ bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64;
1214+ }
1215+ }
1216+ return bits;
1217+ }
1218+ for blk in 0..16 {
1219+ if lv.cbp_luma & (1 << (blk >> 2)) != 0 {
1220+ bits += block_bits(&lv.luma[blk]);
1221+ }
1222+ }
1223+ if lv.cbp_luma == 15 {
1224+ // Intra_16x16 also carries the DC block.
1225+ bits += block_bits(&lv.dc);
1226+ }
1227+ bits
1228+}
1229+
1230+/// Bits one residual block costs, to the accuracy a mode decision needs.
1231+pub(super) fn block_bits(b: &[i32]) -> i64 {
1232+ let mut n = 0i64;
1233+ for &l in b {
1234+ if l != 0 {
1235+ n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
1236+ }
1237+ }
1238+ if n > 0 { n + 6 } else { 2 }
1239+}
1240+
1241+/// Rough bit cost of a macroblock's residual, for the skip decision: a level
1242+/// costs its magnitude's exp-Golomb-ish width, a coded block its token.
1243+pub(super) fn estimate_bits(lv: &Levels) -> i64 {
1244+ let mut bits = 10 + estimate_luma_bits(lv);
1245+ if lv.cbp_chroma != 0 {
1246+ for comp in 0..2 {
1247+ bits += block_bits(&lv.chroma_dc[comp][..4]);
1248+ if lv.cbp_chroma == 2 {
1249+ for blk in 0..4 {
1250+ bits += block_bits(&lv.chroma[comp][blk][..15]);
1251+ }
1252+ }
1253+ }
1254+ }
1255+ bits
1256+}
1257+
1258+/// What the residual writer needs to know about the macroblock it closes.
1259+pub(super) struct MbRecord {
1260+ pub(super) intra: bool,
1261+ pub(super) is_i16: bool,
1262+ pub(super) chroma_mode: u8,
1263+ /// The QP the residual was quantised at.
1264+ pub(super) qp: i32,
1265+}
1266+
1267+/// mb_qp_delta, the residual blocks and the per-macroblock metadata: the
1268+/// writing half of [`crate::decoder::finish_macroblock`].
1269+pub(super) fn finish_mb(
1270+ pic: &mut Picture,
1271+ e: &mut MbEnc<'_>,
1272+ w: &mut EncEntropy,
1273+ mb_addr: usize,
1274+ nbr: &MbNeighbors,
1275+ lv: &Levels,
1276+ m: MbRecord,
1277+) {
1278+ let mb_x = mb_addr % pic.mb_w;
1279+ let mb_y = mb_addr / pic.mb_w;
1280+ let w4 = pic.mb_w * 4;
1281+ let w2 = pic.mb_w * 2;
1282+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
1283+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1284+
1285+ let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || m.is_i16;
1286+ let qp_y = if coded {
1287+ let delta = m.qp - e.qp;
1288+ w.mb_qp_delta(delta);
1289+ e.qp_delta_inc = u8::from(delta != 0);
1290+ e.qp = m.qp;
1291+ m.qp
1292+ } else {
1293+ // No residual: the QP prediction chain is untouched (7.4.5), and the
1294+ // deblocking filter uses the chain value.
1295+ e.qp_delta_inc = 0;
1296+ e.qp
1297+ };
1298+ pic.mb_qp[mb_addr] = qp_y as i8;
1299+ pic.mb_flags[mb_addr] = FLAG_DECODED
1300+ | if m.is_i16 { FLAG_I16 } else { 0 }
1301+ | if m.intra { 0 } else { FLAG_INTER }
1302+ // The flag only reaches the stream when the decoder reads it (7.3.5).
1303+ | if lv.trans8 && (m.intra || lv.cbp_luma != 0) {
1304+ FLAG_TRANS8X8
1305+ } else {
1306+ 0
1307+ }
1308+ | if m.intra && m.chroma_mode != 0 {
1309+ FLAG_CHROMA_PRED
1310+ } else {
1311+ 0
1312+ };
1313+ pic.mb_cbp[mb_addr] = lv.cbp_luma | (lv.cbp_chroma << 4);
1314+ pic.mb_slice[mb_addr] = e.slice_id;
1315+ pic.decoded_mbs += 1;
1316+
1317+ let mut dc_cbf = 0u8;
1318+ // Luma DC (Intra_16x16 only), then the luma blocks in Z-order.
1319+ if m.is_i16 {
1320+ let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0);
1321+ let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
1322+ dc_cbf |= u8::from(tc != 0);
1323+ }
1324+ if lv.trans8 {
1325+ // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports
1326+ // its count in every 4x4 slot; CAVLC codes four interleaved 4x4
1327+ // blocks, each with its own nC and count.
1328+ for blk8 in 0..4 {
1329+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
1330+ if lv.cbp_luma & (1 << blk8) == 0 {
1331+ for dy in 0..2 {
1332+ let base = (by + dy) * w4 + bx;
1333+ pic.nz_y[base..base + 2].fill(0);
1334+ }
1335+ } else if w.is_cabac() {
1336+ let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
1337+ for dy in 0..2 {
1338+ let base = (by + dy) * w4 + bx;
1339+ pic.nz_y[base..base + 2].fill(tc.min(16));
1340+ }
1341+ } else {
1342+ for i4 in 0..4 {
1343+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
1344+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
1345+ let (na, nb) = luma_nz_pair(pic, nbr, sx, sy);
1346+ let sub = sub_block_4x4(&lv.luma8[blk8], i4);
1347+ pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
1348+ }
1349+ }
1350+ }
1351+ }
1352+ for blk in 0..16 {
1353+ if lv.trans8 {
1354+ break;
1355+ }
1356+ let (dx, dy) = BLK4_POS[blk];
1357+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
1358+ let group = 1 << (blk >> 2);
1359+ let coded_block = if m.is_i16 {
1360+ lv.cbp_luma != 0
1361+ } else {
1362+ lv.cbp_luma & group != 0
1363+ };
1364+ let tc = if coded_block {
1365+ let (na, nb) = luma_nz_pair(pic, nbr, bx, by);
1366+ let (levels, cat) = if m.is_i16 {
1367+ (&lv.luma[blk][..15], BlockCat::LumaAc)
1368+ } else {
1369+ (&lv.luma[blk][..16], BlockCat::Luma4x4)
1370+ };
1371+ w.residual_block(levels, cat, na, nb)
1372+ } else {
1373+ 0
1374+ };
1375+ pic.nz_y[by * w4 + bx] = tc;
1376+ }
1377+ // Chroma DC then chroma AC, in bitstream order.
1378+ if lv.cbp_chroma != 0 {
1379+ for comp in 0..2 {
1380+ let tc = w.residual_block(
1381+ &lv.chroma_dc[comp][..4],
1382+ BlockCat::ChromaDc(comp as u8),
1383+ None,
1384+ None,
1385+ );
1386+ dc_cbf |= u8::from(tc != 0) << (1 + comp);
1387+ }
1388+ }
1389+ for comp in 0..2 {
1390+ for blk in 0..4 {
1391+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1392+ let tc = if lv.cbp_chroma == 2 {
1393+ let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy);
1394+ w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb)
1395+ } else {
1396+ 0
1397+ };
1398+ pic.nz_c[comp][cy * w2 + cx] = tc;
1399+ }
1400+ }
1401+ pic.mb_dc_cbf[mb_addr] = dc_cbf;
1402+}
1403+
crates/ec-h264/src/enc/mod.rsmodified+55 -163
@@ -20,6 +20,7 @@
20 //! once over the whole picture, across slice boundaries exactly as a decoder20 //! once over the whole picture, across slice boundaries exactly as a decoder
21 //! runs it. No `unsafe`, no shared mutable state at all.21 //! runs it. No `unsafe`, no shared mutable state at all.
22 22
23+mod analysis;
23 mod cabac_enc;24 mod cabac_enc;
24 mod entropy;25 mod entropy;
25 mod headers;26 mod headers;
@@ -34,13 +35,14 @@ use ec_core::error::{Error, Result};
34 use ec_h264_syntax::nal::{NalUnitType, escape_rbsp};35 use ec_h264_syntax::nal::{NalUnitType, escape_rbsp};
35 use ec_h264_syntax::{SliceType, Sps};36 use ec_h264_syntax::{SliceType, Sps};
36 37
37-use crate::decoder::deblock_picture;38+use crate::deblock::deblock_picture;
38 use crate::dpb::{Picture, SliceParams as DeblockParams};39 use crate::dpb::{Picture, SliceParams as DeblockParams};
39 use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};40 use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
40 use crate::transform::{LevelScale4x4, LevelScale8x8};41 use crate::transform::{LevelScale4x4, LevelScale8x8};
41 42
42 use entropy::EncEntropy;43 use entropy::EncEntropy;
43 use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};44 use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
45+use analysis::{chroma_qp_offset_for_source, fast_knobs, lambda_for, lambda_ssd};
44 use mb::{MbEnc, Source, encode_mb};46 use mb::{MbEnc, Source, encode_mb};
45 use pool::BandPool;47 use pool::BandPool;
46 use rc::RateControl;48 use rc::RateControl;
@@ -304,7 +306,6 @@ impl Encoder {
304 pub fn encode(&mut self, frame: &PictureView<'_>) -> Result<EncodedPicture> {306 pub fn encode(&mut self, frame: &PictureView<'_>) -> Result<EncodedPicture> {
305 self.encode_with(frame, false)307 self.encode_with(frame, false)
306 }308 }
307-
308 /// [`Encoder::encode`], coding the picture as an IDR when `force_keyframe`309 /// [`Encoder::encode`], coding the picture as an IDR when `force_keyframe`
309 /// is set; the GOP restarts from it.310 /// is set; the GOP restarts from it.
310 pub fn encode_with(311 pub fn encode_with(
@@ -312,6 +313,12 @@ impl Encoder {
312 frame: &PictureView<'_>,313 frame: &PictureView<'_>,
313 force_keyframe: bool,314 force_keyframe: bool,
314 ) -> Result<EncodedPicture> {315 ) -> Result<EncodedPicture> {
316+ let step = self.begin_frame(frame, force_keyframe)?;
317+ let outputs = self.code_bands(&step);
318+ Ok(self.finish_frame(step, outputs))
319+ }
320+
321+ fn begin_frame(&mut self, frame: &PictureView<'_>, force_keyframe: bool) -> Result<FrameStep> {
315 if frame.width != self.cfg.width || frame.height != self.cfg.height {322 if frame.width != self.cfg.width || frame.height != self.cfg.height {
316 return Err(Error::corrupt("frame size differs from the encoder's"));323 return Err(Error::corrupt("frame size differs from the encoder's"));
317 }324 }
@@ -333,13 +340,23 @@ impl Encoder {
333 self.frame_num = 0;340 self.frame_num = 0;
334 }341 }
335 let slice_type = if idr { SliceType::I } else { SliceType::P };342 let slice_type = if idr { SliceType::I } else { SliceType::P };
336-
337 let mb_w = self.sps.mb_width as usize;343 let mb_w = self.sps.mb_width as usize;
338 let mb_h = self.sps.mb_height as usize;344 let mb_h = self.sps.mb_height as usize;
339 let bands = split_bands(mb_h, self.threads);345 let bands = split_bands(mb_h, self.threads);
340 let picture_id = self.next_id;346 let picture_id = self.next_id;
341 self.next_id = self.next_id.wrapping_add(1);347 self.next_id = self.next_id.wrapping_add(1);
348+ Ok(FrameStep {
349+ idr,
350+ qp,
351+ slice_type,
352+ mb_w,
353+ mb_h,
354+ bands,
355+ picture_id,
356+ })
357+ }
342 358
359+ fn code_bands(&mut self, step: &FrameStep) -> Vec<Vec<u8>> {
343 // Per-band coding. Every worker owns its picture and its bitstream;360 // Per-band coding. Every worker owns its picture and its bitstream;
344 // the frame's shared inputs (source, reference, parameters) travel in361 // the frame's shared inputs (source, reference, parameters) travel in
345 // one `Arc`, and come back to the encoder once every band has answered.362 // one `Arc`, and come back to the encoder once every band has answered.
@@ -348,20 +365,20 @@ impl Encoder {
348 cfg: self.cfg.clone(),365 cfg: self.cfg.clone(),
349 rc: self.rc.clone(),366 rc: self.rc.clone(),
350 src: std::mem::take(&mut self.src),367 src: std::mem::take(&mut self.src),
351- reference: (!idr).then(|| std::mem::take(&mut self.reference)),368+ reference: (!step.idr).then(|| std::mem::take(&mut self.reference)),
352- bands: bands.clone(),369+ bands: step.bands.clone(),
353- slice_type,370+ slice_type: step.slice_type,
354 frame_num: self.frame_num,371 frame_num: self.frame_num,
355- idr,372+ idr: step.idr,
356 idr_pic_id: self.idr_pic_id,373 idr_pic_id: self.idr_pic_id,
357- qp,374+ qp: step.qp,
358- target: self.rc.frame_target(idr),375+ target: self.rc.frame_target(step.idr),
359- total_mbs: (mb_w * mb_h) as f64,376+ total_mbs: (step.mb_w * step.mb_h) as f64,
360 cqo: self.cqo,377 cqo: self.cqo,
361- mb_w,378+ mb_w: step.mb_w,
362 });379 });
363 380
364- let mut answers = Vec::with_capacity(bands.len());381+ let mut answers = Vec::with_capacity(step.bands.len());
365 if self.threads == 1 {382 if self.threads == 1 {
366 // One band: coded on this thread, with no workers.383 // One band: coded on this thread, with no workers.
367 let pic = std::mem::take(&mut self.workers[0]);384 let pic = std::mem::take(&mut self.workers[0]);
@@ -369,7 +386,7 @@ impl Encoder {
369 pic,386 pic,
370 shared: Arc::clone(&shared),387 shared: Arc::clone(&shared),
371 band: 0,388 band: 0,
372- picture_id,389+ picture_id: step.picture_id,
373 }));390 }));
374 } else {391 } else {
375 let threads = self.threads;392 let threads = self.threads;
@@ -383,15 +400,15 @@ impl Encoder {
383 pic: std::mem::take(worker),400 pic: std::mem::take(worker),
384 shared: Arc::clone(&shared),401 shared: Arc::clone(&shared),
385 band,402 band,
386- picture_id,403+ picture_id: step.picture_id,
387 },404 },
388 );405 );
389 }406 }
390- for band in 0..bands.len() {407+ for band in 0..step.bands.len() {
391 answers.push(pool.collect(band));408 answers.push(pool.collect(band));
392 }409 }
393 }410 }
394- let mut outputs: Vec<Vec<u8>> = Vec::with_capacity(bands.len());411+ let mut outputs: Vec<Vec<u8>> = Vec::with_capacity(step.bands.len());
395 for (band, answer) in answers.into_iter().enumerate() {412 for (band, answer) in answers.into_iter().enumerate() {
396 outputs.push(answer.rbsp);413 outputs.push(answer.rbsp);
397 self.workers[band] = answer.pic;414 self.workers[band] = answer.pic;
@@ -404,13 +421,16 @@ impl Encoder {
404 if let Some(reference) = shared.reference {421 if let Some(reference) = shared.reference {
405 self.reference = reference;422 self.reference = reference;
406 }423 }
424+ outputs
425+ }
407 426
427+ fn finish_frame(&mut self, step: FrameStep, outputs: Vec<Vec<u8>>) -> EncodedPicture {
408 // Stitch the bands into worker 0's picture, then filter the whole428 // Stitch the bands into worker 0's picture, then filter the whole
409 // picture the way a decoder does.429 // picture the way a decoder does.
410 let (first, rest) = self.workers.split_at_mut(1);430 let (first, rest) = self.workers.split_at_mut(1);
411 let master = &mut first[0];431 let master = &mut first[0];
412 master.slices.clear();432 master.slices.clear();
413- for _ in 0..bands.len() {433+ for _ in 0..step.bands.len() {
414 master.slices.push(DeblockParams {434 master.slices.push(DeblockParams {
415 disable_deblock_idc: 0,435 disable_deblock_idc: 0,
416 alpha_offset: 0,436 alpha_offset: 0,
@@ -419,7 +439,7 @@ impl Encoder {
419 cr_qp_offset: self.cqo,439 cr_qp_offset: self.cqo,
420 });440 });
421 }441 }
422- for (band, worker) in bands.iter().skip(1).zip(rest.iter()) {442+ for (band, worker) in step.bands.iter().skip(1).zip(rest.iter()) {
423 merge_band(master, worker, *band);443 merge_band(master, worker, *band);
424 }444 }
425 for &f in &master.mb_flags {445 for &f in &master.mb_flags {
@@ -439,11 +459,11 @@ impl Encoder {
439 459
440 // Assemble the access unit.460 // Assemble the access unit.
441 let mut au = Vec::with_capacity(outputs.iter().map(Vec::len).sum::<usize>() + 64);461 let mut au = Vec::with_capacity(outputs.iter().map(Vec::len).sum::<usize>() + 64);
442- if idr {462+ if step.idr {
443 au.extend_from_slice(&self.sps_nal);463 au.extend_from_slice(&self.sps_nal);
444 au.extend_from_slice(&self.pps_nal);464 au.extend_from_slice(&self.pps_nal);
445 }465 }
446- let unit = if idr {466+ let unit = if step.idr {
447 NalUnitType::SliceIdr467 NalUnitType::SliceIdr
448 } else {468 } else {
449 NalUnitType::Slice469 NalUnitType::Slice
@@ -453,17 +473,17 @@ impl Encoder {
453 }473 }
454 474
455 let bits = au.len() as u64 * 8;475 let bits = au.len() as u64 * 8;
456- self.rc.update(idr, qp, bits);476+ self.rc.update(step.idr, step.qp, bits);
457 self.frames += 1;477 self.frames += 1;
458 self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM);478 self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM);
459- if idr {479+ if step.idr {
460 self.idr_pic_id ^= 1;480 self.idr_pic_id ^= 1;
461 }481 }
462- Ok(EncodedPicture {482+ EncodedPicture {
463 au,483 au,
464- key_frame: idr,484+ key_frame: step.idr,
465- qp,485+ qp: step.qp,
466- })486+ }
467 }487 }
468 488
469 /// Copy the caller's planes into whole-macroblock buffers, replicating the489 /// Copy the caller's planes into whole-macroblock buffers, replicating the
@@ -512,80 +532,16 @@ impl Encoder {
512 }532 }
513 }533 }
514 534
515-/// Everything one band worker needs.535+struct FrameStep {
516-/// Mean absolute neighbour difference of one plane, horizontal and vertical536+ idr: bool,
517-/// averaged, over the `w` by `h` samples at the top left of `plane`.537+ qp: i32,
518-fn mean_gradient(plane: &[u8], stride: usize, w: usize, h: usize) -> f64 {538+ slice_type: SliceType,
519- let (mut sum, mut n) = (0u64, 0u64);539+ mb_w: usize,
520- for y in 0..h {540+ mb_h: usize,
521- let row = &plane[y * stride..y * stride + w];541+ bands: Vec<(usize, usize)>,
522- for x in 1..w {542+ picture_id: i32,
523- sum += u64::from(row[x].abs_diff(row[x - 1]));
524- n += 1;
525- }
526- if y > 0 {
527- let prev = &plane[(y - 1) * stride..(y - 1) * stride + w];
528- for x in 0..w {
529- sum += u64::from(row[x].abs_diff(prev[x]));
530- n += 1;
531- }
532- }
533- }
534- if n == 0 { 0.0 } else { sum as f64 / n as f64 }
535-}
536-
537-/// `chroma_qp_index_offset` for a source, from how textured its chroma is
538-/// relative to its luma.
539-///
540-/// A negative offset spends bits on chroma that luma would otherwise take.
541-/// That pays when the chroma planes are flat — screen capture, phone video,
542-/// anything with large constant-hue areas — because their few edges are what
543-/// the eye reads, and it loses on film, whose chroma carries as much detail as
544-/// its luma and whose luma is the better place for the same bits. The
545-/// separating statistic is the mean absolute sample gradient of the chroma
546-/// planes over that of luma, measured on the first source picture.
547-/// BD-PSNR-YUV against x264, GOP 10, QP 22/26/30/34, `Preset::Balanced`, over
548-/// nine clips of the user's library, offset 0 against offset -2:
549-///
550-/// ```text
551-/// chroma/luma gradient 0 -> -2 (dB)
552-/// 0.013 +0.019
553-/// 0.092 +0.181
554-/// 0.094 +0.228
555-/// 0.098 +0.014
556-/// 0.118 +0.081
557-/// 0.122 +0.045
558-/// 0.128 +0.065
559-/// 0.286 +0.011
560-/// 0.911 -0.158
561-/// ```
562-///
563-/// Every clip whose chroma is flatter than its luma gains; the one film clip,
564-/// whose chroma gradient is nearly its luma's, loses. The threshold sits in
565-/// the middle of the gap the data leaves.
566-fn chroma_qp_offset_for_source(src: &Source, width: u32, height: u32) -> i32 {
567- let (w, h) = (width as usize, height as usize);
568- let (cw, ch) = (w / 2, h / 2);
569- let luma = mean_gradient(&src.y, src.stride, w, h);
570- if luma <= 0.0 {
571- return 0;
572- }
573- let chroma = (mean_gradient(&src.u, src.c_stride, cw, ch)
574- + mean_gradient(&src.v, src.c_stride, cw, ch))
575- / 2.0;
576- if chroma / luma < CHROMA_FLAT_RATIO {
577- CHROMA_FLAT_QP_OFFSET
578- } else {
579- 0
580- }
581 }543 }
582 544
583-/// Chroma is "flat" below this share of the luma gradient.
584-const CHROMA_FLAT_RATIO: f64 = 0.5;
585-
586-/// The offset flat chroma is coded with.
587-const CHROMA_FLAT_QP_OFFSET: i32 = -2;
588-
589 /// What every band of one picture reads. The workers share it through an `Arc`.545 /// What every band of one picture reads. The workers share it through an `Arc`.
590 struct FrameShared {546 struct FrameShared {
591 sps: Sps,547 sps: Sps,
@@ -740,71 +696,6 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
740 w.finish(job.slice_type == SliceType::P)696 w.finish(job.slice_type == SliceType::P)
741 }697 }
742 698
743-/// The Fast-preset speed settings: the defaults, with `EC_H264_INTRA_GATE`
744-/// (a number) and `EC_H264_SKIP_I8` (any value but 0 skips Intra_8x8) as
745-/// sweep overrides. Read once per band, so they cost nothing per macroblock.
746-fn fast_knobs() -> mb::FastKnobs {
747- let mut k = mb::FastKnobs::default();
748- if let Some(g) = std::env::var("EC_H264_INTRA_GATE")
749- .ok()
750- .and_then(|v| v.parse().ok())
751- {
752- k.intra_gate = g;
753- }
754- if let Ok(v) = std::env::var("EC_H264_SKIP_I8") {
755- k.skip_i8 = v != "0";
756- }
757- if let Some(v) = std::env::var("EC_H264_ME_SUB")
758- .ok()
759- .and_then(|v| v.parse().ok())
760- {
761- k.me_sub = v;
762- }
763- if let Ok(v) = std::env::var("EC_H264_ME_SATD") {
764- k.me_satd = v != "0";
765- }
766- if let Some(v) = std::env::var("EC_H264_INTER_TX")
767- .ok()
768- .and_then(|v| v.parse().ok())
769- {
770- k.inter_tx = v;
771- }
772- if let Ok(v) = std::env::var("EC_H264_LAZY_I16") {
773- k.lazy_i16 = v != "0";
774- }
775- if let Some(v) = std::env::var("EC_H264_EARLY_SKIP")
776- .ok()
777- .and_then(|v| v.parse().ok())
778- {
779- k.early_skip = v;
780- }
781- if let Some(v) = std::env::var("EC_H264_TX8_NZ")
782- .ok()
783- .and_then(|v| v.parse().ok())
784- {
785- k.tx8_nz_limit = v;
786- }
787- if let Ok(v) = std::env::var("EC_H264_P_SKIP_I8") {
788- k.p_skip_i8 = v != "0";
789- }
790- k
791-}
792-
793-/// Standard Lagrangian multiplier in the squared-error domain.
794-pub(crate) fn lambda_ssd(qp: i32) -> f64 {
795- 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
796-}
797-
798-/// Lagrangian multiplier. Production uses the established byte-stable ladder;
799-/// the ablation feature can select the standard squared-error multiplier.
800-fn lambda_for(qp: i32, standard: bool) -> f64 {
801- if standard {
802- lambda_ssd(qp)
803- } else {
804- (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
805- }
806-}
807-
808 /// Split `mb_h` macroblock rows into at most `n` contiguous bands.699 /// Split `mb_h` macroblock rows into at most `n` contiguous bands.
809 fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> {700 fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> {
810 let n = n.clamp(1, mb_h);701 let n = n.clamp(1, mb_h);
@@ -927,6 +818,7 @@ fn rational_timing(fps: f64) -> (u32, u32) {
927 #[cfg(test)]818 #[cfg(test)]
928 mod tests {819 mod tests {
929 use super::*;820 use super::*;
821+ use super::analysis::CHROMA_FLAT_QP_OFFSET;
930 822
931 #[test]823 #[test]
932 fn bands_cover_every_row_once() {824 fn bands_cover_every_row_once() {
crates/ec-h264/src/lib.rsmodified+3 -0
@@ -43,6 +43,7 @@ mod cavlc;
43 mod codec;43 mod codec;
44 mod deblock;44 mod deblock;
45 mod deblock_mbaff;45 mod deblock_mbaff;
46+mod direct;
46 mod decoder;47 mod decoder;
47 mod dpb;48 mod dpb;
48 mod enc;49 mod enc;
@@ -51,8 +52,10 @@ mod fmo;
51 mod inter;52 mod inter;
52 mod inter16;53 mod inter16;
53 mod mbaff;54 mod mbaff;
55+mod mc;
54 mod mv;56 mod mv;
55 mod pred;57 mod pred;
58+mod residual;
56 mod sample;59 mod sample;
57 mod tables;60 mod tables;
58 mod transform;61 mod transform;
crates/ec-h264/src/mc.rsadded+455 -0
@@ -0,0 +1,455 @@
1+use ec_core::error::{Error, Result};
2+
3+use crate::decoder::{SliceCtx, plane_mut, plane_ref};
4+use crate::dpb::Picture;
5+use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma};
6+use crate::sample::Sample;
7+
8+
9+/// The motion vectors chroma prediction uses: the luma vectors, with the
10+/// vertical offset of 8.4.1.4 added when a field predicts from a field of the
11+/// opposite parity.
12+#[inline]
13+fn chroma_mvs<S: Sample>(
14+ ctx: &SliceCtx,
15+ refs: &[Picture<S>],
16+ ref_idx: [i8; 2],
17+ mv: [[i16; 2]; 2],
18+) -> [[i16; 2]; 2] {
19+ let mut out = mv;
20+ if ctx.cat == 2 {
21+ // 4:2:2 chroma is full height: the vertical vector stays in quarter
22+ // samples of the chroma plane, which the eighth-sample interpolator
23+ // reads as twice the value.
24+ for l in out.iter_mut() {
25+ l[1] = l[1].wrapping_mul(2);
26+ }
27+ } else if ctx.is_field() {
28+ for l in 0..2 {
29+ if let Some(rp) = ctx.reference(refs, l, ref_idx[l]) {
30+ out[l][1] = out[l][1].wrapping_add(ctx.chroma_dy(rp));
31+ }
32+ }
33+ }
34+ out
35+}
36+
37+/// The reference plane (`0` luma, `1` Cb, `2` Cr) list `list` predicts from.
38+#[inline(always)]
39+fn ref_plane<'a>(
40+ ctx: &SliceCtx,
41+ refs: &'a [Picture<u8>],
42+ ref_idx: [i8; 2],
43+ list: usize,
44+ comp: usize,
45+) -> Result<RefPlane<'a>> {
46+ let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
47+ Error::corrupt("reference index names a picture the buffer does not hold")
48+ })?;
49+ let src = match comp {
50+ 0 => &rp.y,
51+ 1 => &rp.cb,
52+ _ => &rp.cr,
53+ };
54+ Ok(RefPlane {
55+ data: &src.data,
56+ stride: src.stride,
57+ origin: src.origin,
58+ width: src.width,
59+ height: src.height,
60+ pad: src.pad,
61+ })
62+}
63+
64+/// Motion compensation of one partition (clause 8.4.2): interpolate each list's
65+/// prediction, then combine them by the weighting of 8.4.2.3 and write the
66+/// result straight into the picture, where the residual is added on top.
67+///
68+/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock.
69+#[allow(clippy::too_many_arguments)]
70+pub(crate) fn compensate8(
71+ pic: &mut Picture<u8>,
72+ refs: &[Picture<u8>],
73+ ctx: &SliceCtx,
74+ mb_x: usize,
75+ mb_y: usize,
76+ px: usize,
77+ py: usize,
78+ pw: usize,
79+ ph: usize,
80+ mv: [[i16; 2]; 2],
81+ ref_idx: [i8; 2],
82+) -> Result<()> {
83+ let use0 = ref_idx[0] >= 0;
84+ let use1 = ref_idx[1] >= 0;
85+ if !use0 && !use1 {
86+ return Ok(());
87+ }
88+ let geo = ctx.geo(mb_y);
89+ let x0 = (mb_x * 16 + px * 4) as i32;
90+ let y0 = (geo.src_y + py * 4) as i32;
91+ let (w, h) = (pw * 4, ph * 4);
92+ // A stream carrying no weighted prediction at all resolves every
93+ // component to the identity weighting without the per-component lookup.
94+ let plain = ctx.no_weights();
95+ // ChromaArrayType 3 predicts Cb and Cr with the luma interpolation, on
96+ // their own planes and weights.
97+ let ncomp = if ctx.cat == 3 { 3 } else { 1 };
98+ for comp in 0..ncomp {
99+ let wt = if plain {
100+ Weights::DEFAULT
101+ } else {
102+ ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1)
103+ };
104+ // 8.4.2.3.1 over one list is the identity, so the interpolation of that
105+ // one list IS the prediction: it is written straight into the picture at
106+ // the picture's own pitch. Over both lists the combined prediction is the
107+ // rounded byte average of the two clipped ones, so list 0 interpolates
108+ // into the picture and list 1 averages on top of it (Put::Avg) — no
109+ // temporaries, no combining pass, no copy back.
110+ let direct = wt.is_default();
111+ let stride = plane_ref(pic, comp).stride * geo.mul;
112+ let origin = plane_ref(pic, comp).at(x0 as usize, geo.y(py * 4));
113+ // Weighted bi-prediction fuses the same way: the combining formula is
114+ // per-sample, so list 0 lands in the picture and list 1 combines on top
115+ // of it (Put::AvgW) with 8.4.2.3.2's exact integers.
116+ let weighted_put = if !direct && use0 && use1 {
117+ Some(crate::inter::Put::AvgW {
118+ w0: wt.w[0],
119+ w1: wt.w[1],
120+ shift: (wt.log_wd + 1) as u32,
121+ round: 1 << wt.log_wd,
122+ off: (wt.o[0] + wt.o[1] + 1) >> 1,
123+ })
124+ } else {
125+ None
126+ };
127+ if direct && use0 && use1 {
128+ let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?;
129+ mc_luma(
130+ &plane,
131+ x0,
132+ y0,
133+ mv[0],
134+ w,
135+ h,
136+ stride,
137+ &mut plane_mut(pic, comp).data[origin..],
138+ crate::inter::Put::Set,
139+ );
140+ let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?;
141+ mc_luma(
142+ &plane,
143+ x0,
144+ y0,
145+ mv[1],
146+ w,
147+ h,
148+ stride,
149+ &mut plane_mut(pic, comp).data[origin..],
150+ crate::inter::Put::Avg,
151+ );
152+ } else if direct {
153+ // No scratch buffer is declared on this path at all: the scratch is
154+ // zeroed on entry, and most partitions of a P slice come through here.
155+ let list = usize::from(!use0);
156+ let plane = ref_plane(ctx, refs, ref_idx, list, comp)?;
157+ mc_luma(
158+ &plane,
159+ x0,
160+ y0,
161+ mv[list],
162+ w,
163+ h,
164+ stride,
165+ &mut plane_mut(pic, comp).data[origin..],
166+ crate::inter::Put::Set,
167+ );
168+ } else if let Some(put) = weighted_put {
169+ let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?;
170+ mc_luma(
171+ &plane,
172+ x0,
173+ y0,
174+ mv[0],
175+ w,
176+ h,
177+ stride,
178+ &mut plane_mut(pic, comp).data[origin..],
179+ crate::inter::Put::Set,
180+ );
181+ let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?;
182+ mc_luma(
183+ &plane,
184+ x0,
185+ y0,
186+ mv[1],
187+ w,
188+ h,
189+ stride,
190+ &mut plane_mut(pic, comp).data[origin..],
191+ put,
192+ );
193+ } else {
194+ let mut part = [[0u8; 256]; 2];
195+ for list in 0..2 {
196+ if ref_idx[list] < 0 {
197+ continue;
198+ }
199+ let plane = ref_plane(ctx, refs, ref_idx, list, comp)?;
200+ mc_luma(
201+ &plane,
202+ x0,
203+ y0,
204+ mv[list],
205+ w,
206+ h,
207+ w,
208+ &mut part[list],
209+ crate::inter::Put::Set,
210+ );
211+ }
212+ let mut out = [0u8; 256];
213+ let (p0, p1) = part.split_at(1);
214+ combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h);
215+ for row in 0..h {
216+ let dst = origin + row * stride;
217+ plane_mut(pic, comp).data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]);
218+ }
219+ }
220+ }
221+
222+ // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma
223+ // vector, read as eighth-sample units over the half-resolution plane.
224+ if ctx.cat == 0 || ctx.cat == 3 {
225+ return Ok(());
226+ }
227+ let cmv = chroma_mvs(ctx, refs, ref_idx, mv);
228+ let c422 = ctx.cat == 2;
229+ let (cw, ch) = (w / 2, if c422 { h } else { h / 2 });
230+ let (cx0, cy0) = (x0 / 2, if c422 { y0 } else { y0 / 2 });
231+ let crow = if c422 { py * 4 } else { py * 2 };
232+ for comp in 0..2 {
233+ let wt = if plain {
234+ Weights::DEFAULT
235+ } else {
236+ ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1)
237+ };
238+ let direct = wt.is_default();
239+ // The combining weights are per-component syntax (luma and chroma
240+ // carry their own denoms, weights and offsets), so this component's
241+ // fused mode is built from ITS OWN lookup — never the luma one.
242+ let weighted_put = if !direct && use0 && use1 {
243+ Some(crate::inter::Put::AvgW {
244+ w0: wt.w[0],
245+ w1: wt.w[1],
246+ shift: (wt.log_wd + 1) as u32,
247+ round: 1 << wt.log_wd,
248+ off: (wt.o[0] + wt.o[1] + 1) >> 1,
249+ })
250+ } else {
251+ None
252+ };
253+ let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
254+ let stride = plane_out.stride * geo.mul;
255+ let origin = plane_out.at(cx0 as usize, geo.cy(crow));
256+ if direct && use0 && use1 {
257+ let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?;
258+ mc_chroma(
259+ &plane,
260+ cx0,
261+ cy0,
262+ cmv[0],
263+ cw,
264+ ch,
265+ stride,
266+ &mut plane_out.data[origin..],
267+ crate::inter::Put::Set,
268+ );
269+ let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?;
270+ mc_chroma(
271+ &plane,
272+ cx0,
273+ cy0,
274+ cmv[1],
275+ cw,
276+ ch,
277+ stride,
278+ &mut plane_out.data[origin..],
279+ crate::inter::Put::Avg,
280+ );
281+ } else if let Some(put) = weighted_put {
282+ let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?;
283+ mc_chroma(
284+ &plane,
285+ cx0,
286+ cy0,
287+ cmv[0],
288+ cw,
289+ ch,
290+ stride,
291+ &mut plane_out.data[origin..],
292+ crate::inter::Put::Set,
293+ );
294+ let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?;
295+ mc_chroma(
296+ &plane,
297+ cx0,
298+ cy0,
299+ cmv[1],
300+ cw,
301+ ch,
302+ stride,
303+ &mut plane_out.data[origin..],
304+ put,
305+ );
306+ } else if direct {
307+ let list = usize::from(!use0);
308+ let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?;
309+ mc_chroma(
310+ &plane,
311+ cx0,
312+ cy0,
313+ cmv[list],
314+ cw,
315+ ch,
316+ stride,
317+ &mut plane_out.data[origin..],
318+ crate::inter::Put::Set,
319+ );
320+ } else {
321+ let mut cpart = [[0u8; 128]; 2];
322+ for list in 0..2 {
323+ if ref_idx[list] < 0 {
324+ continue;
325+ }
326+ let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?;
327+ mc_chroma(
328+ &plane,
329+ cx0,
330+ cy0,
331+ cmv[list],
332+ cw,
333+ ch,
334+ cw,
335+ &mut cpart[list],
336+ crate::inter::Put::Set,
337+ );
338+ }
339+ let mut cout = [0u8; 128];
340+ let (c0, c1) = cpart.split_at(1);
341+ combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch);
342+ for row in 0..ch {
343+ let dst = origin + row * stride;
344+ plane_out.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]);
345+ }
346+ }
347+ }
348+ Ok(())
349+}
350+
351+/// Motion compensation of one partition over `u16` planes: the same clause
352+/// 8.4.2 process as [`compensate8`], computed per sample from the equations.
353+/// Weighted prediction offsets scale by `1 << (BitDepth - 8)` (8-298, 8-299).
354+#[allow(clippy::too_many_arguments)]
355+pub(crate) fn compensate16(
356+ pic: &mut Picture<u16>,
357+ refs: &[Picture<u16>],
358+ ctx: &SliceCtx,
359+ mb_x: usize,
360+ mb_y: usize,
361+ px: usize,
362+ py: usize,
363+ pw: usize,
364+ ph: usize,
365+ mv: [[i16; 2]; 2],
366+ ref_idx: [i8; 2],
367+) -> Result<()> {
368+ let use0 = ref_idx[0] >= 0;
369+ let use1 = ref_idx[1] >= 0;
370+ if !use0 && !use1 {
371+ return Ok(());
372+ }
373+ let bd = pic.bd;
374+ let max = (1i32 << bd) - 1;
375+ let geo = ctx.geo(mb_y);
376+ let x0 = (mb_x * 16 + px * 4) as i32;
377+ let y0 = (geo.src_y + py * 4) as i32;
378+ let plain = ctx.no_weights();
379+ let cmv = chroma_mvs(ctx, refs, ref_idx, mv);
380+ let cat = pic.cat;
381+ let ncomp = if cat == 0 { 1 } else { 3 };
382+ for comp in 0..ncomp {
383+ let c422 = cat == 2;
384+ let (w, h, cx, cy) = if comp == 0 || cat == 3 {
385+ (pw * 4, ph * 4, x0, y0)
386+ } else if c422 {
387+ (pw * 2, ph * 4, x0 / 2, y0)
388+ } else {
389+ (pw * 2, ph * 2, x0 / 2, y0 / 2)
390+ };
391+ let mut wt = if plain {
392+ Weights::DEFAULT
393+ } else {
394+ ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1)
395+ };
396+ wt.o[0] <<= bd - 8;
397+ wt.o[1] <<= bd - 8;
398+ let mut pred = [[0i32; 256]; 2];
399+ for list in 0..2 {
400+ if ref_idx[list] < 0 {
401+ continue;
402+ }
403+ let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
404+ Error::corrupt("reference index names a picture the buffer does not hold")
405+ })?;
406+ match comp {
407+ 0 => crate::inter16::luma_pred(&rp.y, cx, cy, mv[list], w, h, max, &mut pred[list]),
408+ 1 if cat == 3 => {
409+ crate::inter16::luma_pred(&rp.cb, cx, cy, mv[list], w, h, max, &mut pred[list])
410+ }
411+ _ if cat == 3 => {
412+ crate::inter16::luma_pred(&rp.cr, cx, cy, mv[list], w, h, max, &mut pred[list])
413+ }
414+ 1 => crate::inter16::chroma_pred(&rp.cb, cx, cy, cmv[list], w, h, &mut pred[list]),
415+ _ => crate::inter16::chroma_pred(&rp.cr, cx, cy, cmv[list], w, h, &mut pred[list]),
416+ }
417+ }
418+ let plane = match comp {
419+ 0 => &mut pic.y,
420+ 1 => &mut pic.cb,
421+ _ => &mut pic.cr,
422+ };
423+ let stride = plane.stride * geo.mul;
424+ let origin = if comp == 0 || cat == 3 {
425+ plane.at(cx as usize, geo.y(py * 4))
426+ } else {
427+ plane.at(cx as usize, geo.cy(if c422 { py * 4 } else { py * 2 }))
428+ };
429+ let round1 = if wt.log_wd >= 1 {
430+ 1 << (wt.log_wd - 1)
431+ } else {
432+ 0
433+ };
434+ for row in 0..h {
435+ for col in 0..w {
436+ let i = row * w + col;
437+ let v = if use0 && use1 {
438+ // 8-301 / 8-300 (default weights reduce to the rounded mean).
439+ ((pred[0][i] * wt.w[0] + pred[1][i] * wt.w[1] + (1 << wt.log_wd))
440+ >> (wt.log_wd + 1))
441+ + ((wt.o[0] + wt.o[1] + 1) >> 1)
442+ } else {
443+ let k = usize::from(!use0);
444+ if wt.log_wd >= 1 {
445+ ((pred[k][i] * wt.w[k] + round1) >> wt.log_wd) + wt.o[k]
446+ } else {
447+ pred[k][i] * wt.w[k] + wt.o[k]
448+ }
449+ };
450+ plane.data[origin + row * stride + col] = v.clamp(0, max) as u16;
451+ }
452+ }
453+ }
454+ Ok(())
455+}
crates/ec-h264/src/residual.rsadded+320 -0
@@ -0,0 +1,320 @@
1+use ec_core::error::Result;
2+
3+use crate::decoder::{
4+ Geo, MbFinish, MbNeighbors, gather_nbr4_in, gather_nbr8_in, nz_grid, nz_grid_mut, nz_pair_8x8,
5+ nz_pair_in,
6+ plane_mut, plane_ref,
7+};
8+use crate::dpb::Picture;
9+use crate::entropy::{BlockCat, Entropy};
10+use crate::pred::{
11+ PlaneWindow, add_residual_4x4, add_residual_8x8, add_residual_dpcm, filter_nbr8, pred_16x16,
12+ pred_4x4, pred_8x8,
13+};
14+use crate::sample::Sample;
15+use crate::tables::BLK4_POS;
16+use crate::transform::{
17+ LevelScale4x4, LevelScale8x8, dequant_4x4, dequant_8x8, inverse_transform_4x4,
18+ inverse_transform_8x8, unfield, unfield_8x8, unfield_ac15, unzigzag, unzigzag_8x8,
19+ luma_dc_transform, unzigzag_ac15,
20+};
21+
22+/// `residual_luma( )` (7.3.5.3.1) of one colour component plus its
23+/// reconstruction (8.5): the luma residual, and for ChromaArrayType 3 the Cb
24+/// and Cr residual too, which is coded and reconstructed exactly like luma
25+/// (against the plane of `comp`, with `qp` its QP', and `ls` / `ls8` its
26+/// scaling lists).
27+///
28+/// Bitstream order equals reconstruction dependency order, so each block
29+/// reconstructs the moment its levels are parsed. `bypass` is
30+/// TransformBypassModeFlag: the levels are the residual (8.5.15).
31+#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
32+pub(crate) fn residual_luma_style<S: Sample>(
33+ pic: &mut Picture<S>,
34+ r: &mut Entropy<'_>,
35+ nbr: &MbNeighbors,
36+ m: &MbFinish,
37+ mb_x: usize,
38+ mb_y: usize,
39+ comp: usize,
40+ ls: &LevelScale4x4,
41+ ls8: &LevelScale8x8,
42+ qp: i32,
43+ bypass: bool,
44+ fld: bool,
45+ geo: Geo,
46+ dc_cbf: &mut u8,
47+) -> Result<()> {
48+ let bd = pic.bd;
49+ let max = (1i32 << bd) - 1;
50+ let w4 = pic.mb_w * 4;
51+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
52+ let mul = geo.mul;
53+ let cbp_luma = m.cbp_luma;
54+ let c = comp as u8;
55+ let cat3 = pic.cat == 3;
56+ let mut scan = [0i32; 16];
57+ let mut raster = [0i32; 16];
58+ let mut resid = [0i32; 16];
59+ if m.is_i16 {
60+ {
61+ let pl = plane_mut(pic, comp);
62+ let mut w = PlaneWindow {
63+ origin: pl.at(mb_x * 16, geo.y(0)),
64+ stride: pl.stride * mul,
65+ data: &mut pl.data,
66+ };
67+ pred_16x16(m.i16_mode, bd, &mut w, m.pred_nbr.b, m.pred_nbr.a);
68+ }
69+ // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
70+ let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx0, by0);
71+ let dc_tc = r.residual_block_c(&mut scan, BlockCat::LumaDc, c, na, nb)?;
72+ *dc_cbf |= u8::from(dc_tc != 0) << comp;
73+ if fld {
74+ unfield(&scan, &mut raster);
75+ } else {
76+ unzigzag(&scan, &mut raster);
77+ }
78+ if !bypass {
79+ luma_dc_transform(&mut raster, ls, qp);
80+ }
81+ let dc = raster;
82+ // Lossless horizontal / vertical prediction accumulates the residual
83+ // over the whole macroblock, so every block takes part.
84+ let dpcm = bypass && m.i16_mode < 2;
85+ let horizontal = m.i16_mode == 1;
86+ for blk in 0..16 {
87+ let (dx, dy) = BLK4_POS[blk];
88+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
89+ let tc = if cbp_luma != 0 {
90+ let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by);
91+ r.residual_block_c(&mut scan, BlockCat::LumaAc, c, na, nb)?
92+ } else {
93+ 0
94+ };
95+ nz_grid_mut(pic, comp)[by * w4 + bx] = tc;
96+ let dc_blk = dc[dy as usize * 4 + dx as usize];
97+ if tc == 0 && dc_blk == 0 && !dpcm {
98+ continue; // prediction already in place
99+ }
100+ if tc > 0 {
101+ if fld {
102+ unfield_ac15(&scan, &mut raster);
103+ } else {
104+ unzigzag_ac15(&scan, &mut raster);
105+ }
106+ if !bypass {
107+ dequant_4x4(&mut raster, ls, qp, true);
108+ }
109+ } else {
110+ raster = [0; 16]; // DC-only block
111+ }
112+ raster[0] = dc_blk;
113+ let pl = plane_mut(pic, comp);
114+ let origin = pl.at(mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4));
115+ let stride = pl.stride * mul;
116+ if bypass {
117+ if dpcm {
118+ let first = if horizontal { dx == 0 } else { dy == 0 };
119+ add_residual_dpcm(
120+ &mut pl.data,
121+ bd,
122+ stride,
123+ origin,
124+ 4,
125+ 4,
126+ &raster,
127+ horizontal,
128+ first,
129+ );
130+ } else {
131+ add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
132+ }
133+ } else {
134+ inverse_transform_4x4(&raster, &mut resid);
135+ add_residual_4x4(&mut pl.data, bd, stride, origin, &resid);
136+ }
137+ }
138+ } else if m.trans8x8 {
139+ // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block
140+ // at a time, because an Intra_8x8 block predicts from the reconstructed
141+ // samples of the blocks before it.
142+ let mut scan8 = [0i32; 64];
143+ let mut raster8 = [0i32; 64];
144+ let mut resid8 = [0i32; 64];
145+ for blk8 in 0..4 {
146+ let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, geo.y((blk8 / 2) * 8));
147+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
148+ let origin = plane_ref(pic, comp).at(x, y);
149+ let stride = plane_ref(pic, comp).stride * mul;
150+ if m.intra {
151+ let n = filter_nbr8(&gather_nbr8_in(
152+ &plane_ref(pic, comp).data,
153+ &m.pred_nbr,
154+ blk8,
155+ origin,
156+ stride,
157+ ));
158+ let mut p = [S::default(); 64];
159+ pred_8x8(m.modes8[blk8], bd, &n, &mut p);
160+ let pl = plane_mut(pic, comp);
161+ for ry in 0..8 {
162+ let row = origin + ry * stride;
163+ pl.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
164+ }
165+ }
166+ if cbp_luma & (1 << blk8) == 0 {
167+ let grid = nz_grid_mut(pic, comp);
168+ for dy in 0..2 {
169+ let base = (by + dy) * w4 + bx;
170+ grid[base..base + 2].fill(0);
171+ }
172+ continue;
173+ }
174+ let tc = if r.is_cabac() {
175+ // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot
176+ // of it reports the block's own count to the neighbours
177+ // (9.3.3.1.1.9 resolves them to the 8x8 transform block). Only
178+ // ChromaArrayType 3 sends a coded_block_flag for it.
179+ let cbf = cat3.then(|| nz_pair_8x8(pic, comp, nbr, bx, by));
180+ let tc = r.residual_block_8x8(&mut scan8, c, cbf)?;
181+ let grid = nz_grid_mut(pic, comp);
182+ for dy in 0..2 {
183+ let base = (by + dy) * w4 + bx;
184+ grid[base..base + 2].fill(tc.min(16));
185+ }
186+ tc
187+ } else {
188+ // CAVLC codes the same 64 coefficients as four interleaved 4x4
189+ // blocks (7.3.5.3.1), each with its own nC neighbourhood.
190+ let mut tc = 0u8;
191+ for i4 in 0..4 {
192+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
193+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
194+ let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, sx, sy);
195+ let n = r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?;
196+ nz_grid_mut(pic, comp)[sy * w4 + sx] = n;
197+ tc += n;
198+ for i in 0..16 {
199+ scan8[4 * i + i4] = scan[i];
200+ }
201+ }
202+ tc
203+ };
204+ if tc == 0 {
205+ continue;
206+ }
207+ if fld {
208+ unfield_8x8(&scan8, &mut raster8);
209+ } else {
210+ unzigzag_8x8(&scan8, &mut raster8);
211+ }
212+ let pl = plane_mut(pic, comp);
213+ if bypass {
214+ if m.intra && m.modes8[blk8] < 2 {
215+ add_residual_dpcm(
216+ &mut pl.data,
217+ bd,
218+ stride,
219+ origin,
220+ 8,
221+ 8,
222+ &raster8,
223+ m.modes8[blk8] == 1,
224+ true,
225+ );
226+ } else {
227+ add_residual_8x8(&mut pl.data, bd, stride, origin, &raster8);
228+ }
229+ } else {
230+ dequant_8x8(&mut raster8, ls8, qp);
231+ inverse_transform_8x8(&raster8, &mut resid8);
232+ add_residual_8x8(&mut pl.data, bd, stride, origin, &resid8);
233+ }
234+ }
235+ } else {
236+ for blk in 0..16 {
237+ let (dx, dy) = BLK4_POS[blk];
238+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
239+ let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
240+ let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by);
241+ r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?
242+ } else {
243+ 0
244+ };
245+ nz_grid_mut(pic, comp)[by * w4 + bx] = tc;
246+ let (x, y) = (mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4));
247+ let origin = plane_ref(pic, comp).at(x, y);
248+ let stride = plane_ref(pic, comp).stride * mul;
249+ if m.intra {
250+ let n =
251+ gather_nbr4_in(&plane_ref(pic, comp).data, &m.pred_nbr, blk, origin, stride);
252+ let mut p = [S::default(); 16];
253+ pred_4x4(m.modes[blk], bd, &n, &mut p);
254+ let pl = plane_mut(pic, comp);
255+ if tc == 0 {
256+ // Pure prediction: copy the 16 samples in.
257+ for ry in 0..4 {
258+ let row = origin + ry * stride;
259+ pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
260+ }
261+ continue;
262+ }
263+ if fld {
264+ unfield(&scan, &mut raster);
265+ } else {
266+ unzigzag(&scan, &mut raster);
267+ }
268+ if bypass {
269+ for ry in 0..4 {
270+ let row = origin + ry * stride;
271+ pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
272+ }
273+ if m.modes[blk] < 2 {
274+ add_residual_dpcm(
275+ &mut pl.data,
276+ bd,
277+ stride,
278+ origin,
279+ 4,
280+ 4,
281+ &raster,
282+ m.modes[blk] == 1,
283+ true,
284+ );
285+ } else {
286+ add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
287+ }
288+ continue;
289+ }
290+ dequant_4x4(&mut raster, ls, qp, false);
291+ inverse_transform_4x4(&raster, &mut resid);
292+ for ry in 0..4 {
293+ let row = origin + ry * stride;
294+ for rx in 0..4 {
295+ let v = p[ry * 4 + rx].to_i32() + resid[ry * 4 + rx];
296+ pl.data[row + rx] = S::clip(v, max);
297+ }
298+ }
299+ } else {
300+ if tc == 0 {
301+ continue; // motion-compensated prediction already in place
302+ }
303+ if fld {
304+ unfield(&scan, &mut raster);
305+ } else {
306+ unzigzag(&scan, &mut raster);
307+ }
308+ let pl = plane_mut(pic, comp);
309+ if bypass {
310+ add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
311+ } else {
312+ dequant_4x4(&mut raster, ls, qp, false);
313+ inverse_transform_4x4(&raster, &mut resid);
314+ add_residual_4x4(&mut pl.data, bd, stride, origin, &resid);
315+ }
316+ }
317+ }
318+ }
319+ Ok(())
320+}
crates/ec-h264/src/sample.rsmodified+6 -1
@@ -6,9 +6,11 @@
6 use crate::deblock::{6 use crate::deblock::{
7 EdgeParams, filter_chroma_h_edge8, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,7 EdgeParams, filter_chroma_h_edge8, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,
8 };8 };
9-use crate::decoder::{SliceCtx, compensate8, compensate16};9+use crate::decoder::SliceCtx;
10+use crate::mc::{compensate8, compensate16};
10 use crate::dpb::Picture;11 use crate::dpb::Picture;
11 use ec_core::error::Result;12 use ec_core::error::Result;
13+use ec_core::frame::PixelFormat;
12 14
13 /// A picture sample.15 /// A picture sample.
14 pub(crate) trait Sample:16 pub(crate) trait Sample:
@@ -16,6 +18,7 @@ pub(crate) trait Sample:
16 {18 {
17 /// True for the 8-bit instantiation.19 /// True for the 8-bit instantiation.
18 const IS_8: bool;20 const IS_8: bool;
21+ const FORMATS: [PixelFormat; 3];
19 /// Bytes per sample in an output frame.22 /// Bytes per sample in an output frame.
20 const BYTES: usize;23 const BYTES: usize;
21 /// Append `src` to an output plane, little-endian, shifted left by `shift`.24 /// Append `src` to an output plane, little-endian, shifted left by `shift`.
@@ -73,6 +76,7 @@ pub(crate) trait Sample:
73 76
74 impl Sample for u8 {77 impl Sample for u8 {
75 const IS_8: bool = true;78 const IS_8: bool = true;
79+ const FORMATS: [PixelFormat; 3] = [PixelFormat::I444, PixelFormat::I422, PixelFormat::I420];
76 const BYTES: usize = 1;80 const BYTES: usize = 1;
77 #[inline]81 #[inline]
78 fn extend_bytes(out: &mut Vec<u8>, src: &[u8], _shift: u32) {82 fn extend_bytes(out: &mut Vec<u8>, src: &[u8], _shift: u32) {
@@ -130,6 +134,7 @@ impl Sample for u8 {
130 134
131 impl Sample for u16 {135 impl Sample for u16 {
132 const IS_8: bool = false;136 const IS_8: bool = false;
137+ const FORMATS: [PixelFormat; 3] = [PixelFormat::I410, PixelFormat::I210, PixelFormat::I010];
133 const BYTES: usize = 2;138 const BYTES: usize = 2;
134 #[inline]139 #[inline]
135 fn extend_bytes(out: &mut Vec<u8>, src: &[u16], shift: u32) {140 fn extend_bytes(out: &mut Vec<u8>, src: &[u16], shift: u32) {
crates/ec-h264/src/transform.rsmodified+9 -10
@@ -118,15 +118,18 @@ pub fn dequant_8x8(block: &mut [i32; 64], ls: &LevelScale8x8, qp: i32) {
118 /// 8x8 zig-zag (Table 8-14).118 /// 8x8 zig-zag (Table 8-14).
119 #[inline]119 #[inline]
120 pub fn unzigzag_8x8(scan: &[i32; 64], out: &mut [i32; 64]) {120 pub fn unzigzag_8x8(scan: &[i32; 64], out: &mut [i32; 64]) {
121- for (s, &raster) in ZIGZAG_8X8.iter().enumerate() {121+ unscan(&ZIGZAG_8X8, scan, out);
122- out[raster as usize] = scan[s];
123- }
124 }122 }
125 123
126 /// The same with the 8x8 field scan (Table 8-14), for field macroblocks.124 /// The same with the 8x8 field scan (Table 8-14), for field macroblocks.
127 #[inline]125 #[inline]
128 pub fn unfield_8x8(scan: &[i32; 64], out: &mut [i32; 64]) {126 pub fn unfield_8x8(scan: &[i32; 64], out: &mut [i32; 64]) {
129- for (s, &raster) in FIELD_8X8.iter().enumerate() {127+ unscan(&FIELD_8X8, scan, out);
128+}
129+
130+#[inline]
131+pub fn unscan<const N: usize>(order: &[u8], scan: &[i32; N], out: &mut [i32; N]) {
132+ for (s, &raster) in order.iter().enumerate() {
130 out[raster as usize] = scan[s];133 out[raster as usize] = scan[s];
131 }134 }
132 }135 }
@@ -197,17 +200,13 @@ pub fn inverse_transform_8x8(d: &[i32; 64], r: &mut [i32; 64]) {
197 /// Place scan-order coefficients into raster order using the 4x4 zig-zag.200 /// Place scan-order coefficients into raster order using the 4x4 zig-zag.
198 #[inline]201 #[inline]
199 pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) {202 pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) {
200- for (s, &raster) in ZIGZAG_4X4.iter().enumerate() {203+ unscan(&ZIGZAG_4X4, scan, out);
201- out[raster as usize] = scan[s];
202- }
203 }204 }
204 205
205 /// The same with the 4x4 field scan (Table 8-13), for field macroblocks.206 /// The same with the 4x4 field scan (Table 8-13), for field macroblocks.
206 #[inline]207 #[inline]
207 pub fn unfield(scan: &[i32; 16], out: &mut [i32; 16]) {208 pub fn unfield(scan: &[i32; 16], out: &mut [i32; 16]) {
208- for (s, &raster) in FIELD_4X4.iter().enumerate() {209+ unscan(&FIELD_4X4, scan, out);
209- out[raster as usize] = scan[s];
210- }
211 }210 }
212 211
213 /// Field-scan counterpart of [`unzigzag_ac15`].212 /// Field-scan counterpart of [`unzigzag_ac15`].