namespace Febe.Core.Codecs.H264; public sealed partial class H264Decoder { private int weightMode; private int[] implicitW0 = []; /// /// The neighbouring 4×4 luma block covering (, ) relative to the current /// macroblock (§6.4.12): 0 not available, 1 in another macroblock, 2 in the current one (its availability then /// depends on the decoding order, ). /// private int Neighbor(int xN, int yN, out int n, out int blk) { blk = (((yN & 15) >> 2) * 4) + ((xN & 15) >> 2); n = -1; if (yN < 0) { if (xN < 0) { if (!availD) { return 0; } n = mb - widthInMbs - 1; } else if (xN < 16) { if (!availB) { return 0; } n = mb - widthInMbs; } else { if (!availC) { return 0; } n = mb - widthInMbs + 1; } return 1; } if (yN >= 16) { return 0; } if (xN < 0) { if (!availA) { return 0; } n = mb - 1; return 1; } if (xN >= 16) { return 0; } n = mb; return 2; } private (bool Available, int RefIdx, int X, int Y) MotionNeighbor(int list, int xN, int yN) { var where = Neighbor(xN, yN, out var n, out var blk); if (where == 0 || (where == 2 && !blkDone[blk])) { return (false, -1, 0, 0); } var picture = cur!; var refIdx = picture.RefIdx[(((list * mbCount) + n) * 4) + B8OfRaster(blk)]; if (refIdx < 0 || picture.MbIntra[n]) { return (true, -1, 0, 0); } var i = ((((list * mbCount) + n) * 16) + blk) * 2; return (true, refIdx, picture.Mv[i], picture.Mv[i + 1]); } /// /// Luma motion vector prediction (§8.4.1.3). : 0 none, 1/2 the upper/lower 16×8 /// partition, 3/4 the left/right 8×16 partition. /// private (int X, int Y) Mvp(int list, int refIdx, int px, int py, int w, int directional) { var a = MotionNeighbor(list, px - 1, py); var b = MotionNeighbor(list, px, py - 1); var c = MotionNeighbor(list, px + w, py - 1); if (!c.Available) { c = MotionNeighbor(list, px - 1, py - 1); } switch (directional) { case 1 when b.RefIdx == refIdx: return (b.X, b.Y); case 2 when a.RefIdx == refIdx: return (a.X, a.Y); case 3 when a.RefIdx == refIdx: return (a.X, a.Y); case 4 when c.RefIdx == refIdx: return (c.X, c.Y); } if (!b.Available && !c.Available && a.Available) { b = a; c = a; } var matches = (a.RefIdx == refIdx ? 1 : 0) + (b.RefIdx == refIdx ? 1 : 0) + (c.RefIdx == refIdx ? 1 : 0); if (matches == 1) { return a.RefIdx == refIdx ? (a.X, a.Y) : b.RefIdx == refIdx ? (b.X, b.Y) : (c.X, c.Y); } return (Median(a.X, b.X, c.X), Median(a.Y, b.Y, c.Y)); } private static int Median(int a, int b, int c) => Math.Max(Math.Min(a, b), Math.Min(Math.Max(a, b), c)); private void DeriveMv(int list, int px, int py, int w, int h, int directional) { var picture = cur!; var b8 = ((py >> 3) * 2) + (px >> 3); var refIdx = picture.RefIdx[(((list * mbCount) + mb) * 4) + b8]; var (x, y) = Mvp(list, refIdx, px, py, w, directional); var blk = ((py >> 2) * 4) + (px >> 2); x += mvdValue[((list * 16) + blk) * 2]; y += mvdValue[(((list * 16) + blk) * 2) + 1]; FillMv(list, px, py, w, h, x, y); } private void FillMv(int list, int px, int py, int w, int h, int x, int y) { var mv = cur!.Mv; for (var by = py; by < py + h; by += 4) { for (var bx = px; bx < px + w; bx += 4) { var i = ((((list * mbCount) + mb) * 16) + ((by >> 2) * 4) + (bx >> 2)) * 2; mv[i] = (short)x; mv[i + 1] = (short)y; } } } private void PredictPSkip() { for (var b8 = 0; b8 < 4; b8++) { SetRefIdx(0, b8, 0); } var a = MotionNeighbor(0, -1, 0); var b = MotionNeighbor(0, 0, -1); int x = 0, y = 0; if (a.Available && b.Available && !(a.RefIdx == 0 && a.X == 0 && a.Y == 0) && !(b.RefIdx == 0 && b.X == 0 && b.Y == 0)) { (x, y) = Mvp(0, 0, 0, 0, 16, 0); } FillMv(0, 0, 0, 16, 16, x, y); MarkDone(0, 0, 16, 16); } private static int MinPositive(int a, int b) => a >= 0 && b >= 0 ? Math.Min(a, b) : Math.Max(a, b); /// Direct prediction (§8.4.1.2) of the sub-macroblocks to − 1. private void PredictDirect(int first, int end) { var picture = cur!; var col = Reference(1, 0); var inference = sps.Direct8x8Inference; int ref0 = -1, ref1 = -1; int mvp0x = 0, mvp0y = 0, mvp1x = 0, mvp1y = 0; var directZero = false; if (sh.DirectSpatialMvPred) { for (var list = 0; list < 2; list++) { var a = MotionNeighbor(list, -1, 0); var b = MotionNeighbor(list, 0, -1); var c = MotionNeighbor(list, 16, -1); if (!c.Available) { c = MotionNeighbor(list, -1, -1); } var r = MinPositive(a.RefIdx, MinPositive(b.RefIdx, c.RefIdx)); if (list == 0) { ref0 = r; } else { ref1 = r; } } if (ref0 < 0 && ref1 < 0) { ref0 = ref1 = 0; directZero = true; } else { if (ref0 >= 0) { (mvp0x, mvp0y) = Mvp(0, ref0, 0, 0, 16, 0); } if (ref1 >= 0) { (mvp1x, mvp1y) = Mvp(1, ref1, 0, 0, 16, 0); } } } for (var sub = first; sub < end; sub++) { for (var k = 0; k < 4; k++) { var blk = ((((sub >> 1) * 2) + (k >> 1)) * 4) + ((sub & 1) * 2) + (k & 1); var colBlk = inference ? sub switch { 0 => 0, 1 => 3, 2 => 12, _ => 15 } : blk; int colX = 0, colY = 0, colRef = -1; Picture? colRefPic = null; if (!col.MbIntra[mb]) { var colB8 = B8OfRaster(colBlk); var list = col.RefIdx[(mb * 4) + colB8] >= 0 ? 0 : 1; colRef = col.RefIdx[(((list * mbCount) + mb) * 4) + colB8]; colRefPic = col.RefPic[(((list * mbCount) + mb) * 4) + colB8]; var i = ((((list * mbCount) + mb) * 16) + colBlk) * 2; colX = col.Mv[i]; colY = col.Mv[i + 1]; } int r0, r1, m0x, m0y, m1x, m1y; if (sh.DirectSpatialMvPred) { var colZero = !col.LongTerm && colRef == 0 && colX is >= -1 and <= 1 && colY is >= -1 and <= 1; r0 = ref0; r1 = ref1; if (directZero || (r0 == 0 && colZero)) { (m0x, m0y) = (0, 0); } else { (m0x, m0y) = (mvp0x, mvp0y); } if (directZero || (r1 == 0 && colZero)) { (m1x, m1y) = (0, 0); } else { (m1x, m1y) = (mvp1x, mvp1y); } } else { r0 = colRef < 0 ? 0 : MapColToList0(colRefPic); r1 = 0; var pic0 = Reference(0, r0); var td = Math.Clamp(col.Poc - pic0.Poc, -128, 127); if (pic0.LongTerm || td == 0) { (m0x, m0y) = (colX, colY); (m1x, m1y) = (0, 0); } else { var tb = Math.Clamp(picture.Poc - pic0.Poc, -128, 127); var tx = (16384 + Math.Abs(td / 2)) / td; var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023); m0x = ((scale * colX) + 128) >> 8; m0y = ((scale * colY) + 128) >> 8; m1x = m0x - colX; m1y = m0y - colY; } } if (k == 0) { SetDirectRef(0, sub, r0); SetDirectRef(1, sub, r1); } var mv = picture.Mv; var i0 = (((0 * mbCount) + mb) * 16) + blk; var i1 = (((1 * mbCount) + mb) * 16) + blk; mv[i0 * 2] = (short)(r0 >= 0 ? m0x : 0); mv[(i0 * 2) + 1] = (short)(r0 >= 0 ? m0y : 0); mv[i1 * 2] = (short)(r1 >= 0 ? m1x : 0); mv[(i1 * 2) + 1] = (short)(r1 >= 0 ? m1y : 0); blkDone[blk] = true; } } } private void SetDirectRef(int list, int b8, int refIdx) { var index = (((list * mbCount) + mb) * 4) + b8; var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; if (refIdx < 0 || refIdx >= active) { cur!.RefIdx[index] = -1; cur.RefPic[index] = null; return; } cur!.RefIdx[index] = (sbyte)refIdx; cur.RefPic[index] = Reference(list, refIdx); } private int MapColToList0(Picture? picture) { var list = refList[0]; for (var i = 0; i < list.Length; i++) { if (ReferenceEquals(list[i], picture)) { return i; } } return 0; } /// A reference picture of the slice; a substitute when the stream refers to a missing one. private Picture Reference(int list, int refIdx) { var l = refList[list]; if ((uint)refIdx < (uint)l.Length && l[refIdx] is { } p) { return p; } foreach (var q in l) { if (q is not null) { return q; } } foreach (var q in dpb) { if (q.IsReference && !ReferenceEquals(q, cur)) { return q; } } // Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged. throw new H264Exception("Slice P o B senza immagini di riferimento."); } private void PrepareWeights() { weightMode = sh.Type == SliceType.P ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0; if (weightMode != 2) { return; } int n0 = sh.NumRefIdxActiveL0, n1 = sh.NumRefIdxActiveL1; if (implicitW0.Length < n0 * n1) { implicitW0 = new int[Math.Max(n0 * n1, 1)]; } var poc = cur!.Poc; for (var i = 0; i < n0; i++) { for (var j = 0; j < n1; j++) { var p0 = Reference(0, i); var p1 = Reference(1, j); var w0 = 32; var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127); if (td != 0 && !p0.LongTerm && !p1.LongTerm) { var tb = Math.Clamp(poc - p0.Poc, -128, 127); var tx = (16384 + Math.Abs(td / 2)) / td; var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023); if ((scale >> 2) is >= -64 and <= 128) { w0 = 64 - (scale >> 2); } } implicitW0[(i * n1) + j] = w0; } } } private void MotionCompensateDirect(int first, int end) { for (var sub = first; sub < end; sub++) { int ox = (sub & 1) * 8, oy = (sub >> 1) * 8; if (sps.Direct8x8Inference) { MotionCompensate(ox, oy, 8, 8); } else { for (var k = 0; k < 4; k++) { MotionCompensate(ox + ((k & 1) * 4), oy + ((k >> 1) * 4), 4, 4); } } } } /// Inter prediction of one partition with its motion (§8.4.2), written into the current picture. private void MotionCompensate(int px, int py, int w, int h) { var picture = cur!; var b8 = ((py >> 3) * 2) + (px >> 3); var blk = ((py >> 2) * 4) + (px >> 2); int r0 = picture.RefIdx[(mb * 4) + b8]; int r1 = picture.RefIdx[((mbCount + mb) * 4) + b8]; var i0 = ((mb * 16) + blk) * 2; var i1 = (((mbCount + mb) * 16) + blk) * 2; var x = (mbX * 16) + px; var y = (mbY * 16) + py; Span a = stackalloc byte[256]; Span b = stackalloc byte[256]; var size = w * h; var pa = a[..size]; var pb = b[..size]; Picture? p0 = r0 >= 0 ? Reference(0, r0) : null; Picture? p1 = r1 >= 0 ? Reference(1, r1) : null; if (p0 is null && p1 is null) { p0 = Reference(0, 0); r0 = 0; } int mv0x = picture.Mv[i0], mv0y = picture.Mv[i0 + 1], mv1x = picture.Mv[i1], mv1y = picture.Mv[i1 + 1]; // Luma. if (p0 is not null) { InterPrediction.Luma(p0, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa); } if (p1 is not null) { InterPrediction.Luma(p1, (x * 4) + mv1x, (y * 4) + mv1y, w, h, p0 is null ? pa : pb); } Combine(pa, pb, p0 is not null, p1 is not null, r0, r1, 0); var stride = picture.Width; for (var row = 0; row < h; row++) { pa.Slice(row * w, w).CopyTo(picture.Y.AsSpan(((y + row) * stride) + x, w)); } // Chroma. int cw = w / 2, ch = h / 2, cstride = stride / 2, cheight = picture.Height / 2; var csize = cw * ch; var ca = a[..csize]; var cb = b[..csize]; for (var comp = 1; comp <= 2; comp++) { if (p0 is not null) { InterPrediction.Chroma(comp == 1 ? p0.Cb : p0.Cr, cstride, cheight, (x * 4) + mv0x, (y * 4) + mv0y, cw, ch, ca); } if (p1 is not null) { InterPrediction.Chroma(comp == 1 ? p1.Cb : p1.Cr, cstride, cheight, (x * 4) + mv1x, (y * 4) + mv1y, cw, ch, p0 is null ? ca : cb); } Combine(ca, cb, p0 is not null, p1 is not null, r0, r1, comp); var plane = comp == 1 ? picture.Cb : picture.Cr; for (var row = 0; row < ch; row++) { ca.Slice(row * cw, cw).CopyTo(plane.AsSpan((((y / 2) + row) * cstride) + (x / 2), cw)); } } } private void Combine(Span a, ReadOnlySpan b, bool use0, bool use1, int r0, int r1, int comp) { if (use0 && use1) { if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets) { var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; InterPrediction.WeightTwo(a, b, logWd, weights[0][(r0 * 3) + comp], weights[1][(r1 * 3) + comp], offsets[0][(r0 * 3) + comp], offsets[1][(r1 * 3) + comp]); } else if (weightMode == 2) { var w0 = implicitW0[(r0 * sh.NumRefIdxActiveL1) + r1]; InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0); } else { InterPrediction.Average(a, b); } return; } if (weightMode == 1 && sh.Weights is { } w && sh.Offsets is { } o) { var list = use0 ? 0 : 1; var r = use0 ? r0 : r1; var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp]); } } }