using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace Febe.Core.Codecs.H265; /// /// Inter prediction (§8.5.3): reference picture lists (§8.3.4), merge mode and AMVP with their spatial and temporal /// candidates, fractional sample interpolation and weighted sample prediction. /// public sealed partial class H265Decoder { /// fL of table 8-11 (luma, quarter samples 1 to 3), taps at −3 to +4. private static readonly sbyte[] s_lumaFilter = [ 0, 0, 0, 64, 0, 0, 0, 0, -1, 4, -10, 58, 17, -5, 1, 0, -1, 4, -11, 40, 40, -11, 4, -1, 0, 1, -5, 17, 58, -10, 4, -1, ]; /// fC of table 8-12 (chroma, eighth samples 1 to 7), taps at −1 to +2. private static readonly sbyte[] s_chromaFilter = [ 0, 64, 0, 0, -2, 58, 10, -2, -4, 54, 16, -2, -6, 46, 28, -4, -4, 36, 36, -4, -4, 28, 46, -6, -2, 16, 54, -4, -2, 10, 58, -2, ]; /// l0CandIdx and l1CandIdx of table 8-7 (combined bi-predictive merging candidates). private static readonly byte[] s_combinedL0 = [0, 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3]; private static readonly byte[] s_combinedL1 = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2]; /// predSamplesL0 and predSamplesL1 of the block being predicted, at 14-bit precision. private readonly short[] predL0 = new short[64 * 64]; private readonly short[] predL1 = new short[64 * 64]; /// The reference samples a block needs, padded at the picture edges (8-228, 8-229). private readonly ushort[] refBlock = new ushort[(64 + 7) * (64 + 7)]; /// The horizontal pass of a block filtered in both directions. private readonly short[] filterTemp = new short[(64 + 7) * 64]; /// RefPicList0 and RefPicList1 of a P or B slice (§8.3.4), its collocated picture and NoBackwardPredFlag. private void BuildReferencePictureLists(SliceHeader h) { var total = refStCurrBefore.Count + refStCurrAfter.Count + refLtCurr.Count; if (total == 0 || total != h.NumPicTotalCurr) { throw new H265Exception("Insieme di riferimento che non corrisponde alla slice."); } Span temp = stackalloc int[Math.Max(16, total)]; var lists = h.Type == SliceType.B ? 2 : 1; h.NoBackwardPred = true; for (var list = 0; list < lists; list++) { // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; RefPicListTemp1 swaps the first two; both repeat // until they hold Max(num_ref_idx_active, NumPicTotalCurr) entries. An entry is its index in that order. var active = h.NumRefIdxActive[list]; var length = Math.Max(active, total); if (temp.Length < length) { temp = new int[length]; } int before = refStCurrBefore.Count, after = refStCurrAfter.Count; var r = 0; while (r < length) { for (var i = 0; i < (list == 0 ? before : after) && r < length; i++) { temp[r++] = list == 0 ? i : before + i; } for (var i = 0; i < (list == 0 ? after : before) && r < length; i++) { temp[r++] = list == 0 ? before + i : i; } for (var i = 0; i < refLtCurr.Count && r < length; i++) { temp[r++] = before + after + i; } } for (var i = 0; i < active; i++) { var entry = temp[h.ListModification[list] ? h.ListEntry[list][i] : i]; var longTerm = entry >= before + after; var (picture, refPoc) = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after]; h.RefPicList[list][i] = picture; h.RefPoc[list][i] = refPoc; h.RefIsLongTerm[list][i] = longTerm; h.NoBackwardPred &= refPoc <= cur!.Poc; } } h.ColPic = null; if (h.TemporalMvpEnabled) { var list = h.Type == SliceType.B && !h.CollocatedFromL0 ? 1 : 0; if (h.CollocatedRefIdx >= h.NumRefIdxActive[list]) { throw new H265Exception("Immagine co-locata fuori dalla lista."); } h.ColPic = h.RefPicList[list][h.CollocatedRefIdx]; } } /// /// The prediction block availability (§6.4.2) of the neighbour (xN, yN) of a prediction block of the current coding /// unit, false also when the neighbour is intra. /// private bool NeighbourAvailable(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int xN, int yN) { var size = 1 << cuLog2; bool available; if (xN >= cuX && yN >= cuY && xN < cuX + size && yN < cuY + size) { // In the same coding block: everything decoded before, except partition 2 seen from partition 1 of NxN. available = !((nPbW << 1) == size && (nPbH << 1) == size && partIdx == 1 && cuY + nPbH <= yN && cuX + nPbW > xN); } else { available = Available(xPb, yPb, xN, yN); } return available && predMode[Grid(xN, yN)] != ModeIntra; } /// The motion of a merged prediction unit (§8.5.3.2.2 to §8.5.3.2.5). private MvField MergeMotion(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int mergeIdx) { var originalSize = nPbW + nPbH; var level = pps.Log2ParallelMergeLevel; if (level > 2 && cuLog2 == 3) { // singleMCLFlag: every prediction unit of an 8×8 coding unit shares the list of the 2N×2N one. xPb = cuX; yPb = cuY; nPbW = nPbH = 8; partIdx = 0; } var motion = cur!.Motion; Span list = stackalloc MvField[5]; var count = 0; // Spatial candidates (§8.5.3.2.3), in the order A1, B1, B0, A0, B2. int xA1 = xPb - 1, yA1 = yPb + nPbH - 1; var availableA1 = !SameMergeRegion(xPb, yPb, xA1, yA1, level) && !(partIdx == 1 && cuPartMode is PartNx2N or PartnLx2N or PartnRx2N) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA1, yA1); var a1 = availableA1 ? motion[Grid(xA1, yA1)] : default; if (availableA1) { list[count++] = a1; } int xB1 = xPb + nPbW - 1, yB1 = yPb - 1; var availableB1 = !SameMergeRegion(xPb, yPb, xB1, yB1, level) && !(partIdx == 1 && cuPartMode is Part2NxN or Part2NxnU or Part2NxnD) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB1, yB1); var b1 = availableB1 ? motion[Grid(xB1, yB1)] : default; var flagB1 = availableB1 && !(availableA1 && a1.SameAs(b1)); if (flagB1) { list[count++] = b1; } if (mergeIdx < count) { return Restricted(list[mergeIdx], originalSize); } int xB0 = xPb + nPbW, yB0 = yPb - 1; var availableB0 = !SameMergeRegion(xPb, yPb, xB0, yB0, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB0, yB0); var flagB0 = false; if (availableB0) { var b0 = motion[Grid(xB0, yB0)]; flagB0 = !(availableB1 && b1.SameAs(b0)); if (flagB0) { list[count++] = b0; } } int xA0 = xPb - 1, yA0 = yPb + nPbH; var availableA0 = !SameMergeRegion(xPb, yPb, xA0, yA0, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA0); var flagA0 = false; if (availableA0) { var a0 = motion[Grid(xA0, yA0)]; flagA0 = !(availableA1 && a1.SameAs(a0)); if (flagA0) { list[count++] = a0; } } if (count < 4) { // B2 only when one of the four others is missing. int xB2 = xPb - 1, yB2 = yPb - 1; if (!SameMergeRegion(xPb, yPb, xB2, yB2, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB2, yB2)) { var b2 = motion[Grid(xB2, yB2)]; if (!(availableA1 && a1.SameAs(b2)) && !(availableB1 && b1.SameAs(b2))) { list[count++] = b2; } } } if (mergeIdx < count) { return Restricted(list[mergeIdx], originalSize); } // The temporal candidate (§8.5.3.2.8), reference index 0 in each list. if (slice.TemporalMvpEnabled) { var candidate = MvField.Intra; if (TemporalMotionVector(xPb, yPb, nPbW, nPbH, 0, 0, out var x0, out var y0)) { candidate.Ref0 = 0; candidate.X0 = x0; candidate.Y0 = y0; } if (slice.Type == SliceType.B && TemporalMotionVector(xPb, yPb, nPbW, nPbH, 1, 0, out var x1, out var y1)) { candidate.Ref1 = 0; candidate.X1 = x1; candidate.Y1 = y1; } if (candidate.Ref0 >= 0 || candidate.Ref1 >= 0) { list[count++] = candidate; } } if (mergeIdx < count) { return Restricted(list[mergeIdx], originalSize); } var max = slice.MaxNumMergeCand; // Combined bi-predictive candidates (§8.5.3.2.4). if (slice.Type == SliceType.B && count > 1 && count < max) { var original = count; for (var combIdx = 0; combIdx < original * (original - 1) && count < max; combIdx++) { var l0 = list[s_combinedL0[combIdx]]; var l1 = list[s_combinedL1[combIdx]]; if (l0.Ref0 >= 0 && l1.Ref1 >= 0 && (!ReferenceEquals(slice.RefPicList[0][l0.Ref0], slice.RefPicList[1][l1.Ref1]) || l0.X0 != l1.X1 || l0.Y0 != l1.Y1)) { list[count++] = new MvField { Ref0 = l0.Ref0, X0 = l0.X0, Y0 = l0.Y0, Ref1 = l1.Ref1, X1 = l1.X1, Y1 = l1.Y1 }; } } } if (mergeIdx < count) { return Restricted(list[mergeIdx], originalSize); } // Zero candidates (§8.5.3.2.5). var numRefIdx = slice.Type == SliceType.P ? slice.NumRefIdxActive[0] : Math.Min(slice.NumRefIdxActive[0], slice.NumRefIdxActive[1]); var zeroIdx = mergeIdx - count; var refIdx = (sbyte)(zeroIdx < numRefIdx ? zeroIdx : 0); var zero = new MvField { Ref0 = refIdx, Ref1 = slice.Type == SliceType.B ? refIdx : (sbyte)-1 }; return Restricted(zero, originalSize); } private static bool SameMergeRegion(int xPb, int yPb, int xN, int yN, int level) => xPb >> level == xN >> level && yPb >> level == yN >> level; /// 8×4 and 4×8 prediction units are never bi-predicted (8-118): list 1 is dropped. private static MvField Restricted(MvField motion, int originalSize) { if (originalSize == 12 && motion.Ref0 >= 0 && motion.Ref1 >= 0) { motion.Ref1 = -1; motion.X1 = motion.Y1 = 0; } return motion; } /// mvpLX of AMVP (§8.5.3.2.6, §8.5.3.2.7) for list and a reference index. private (int X, int Y) PredictedMotionVector(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int x, int refIdx, int mvpFlag) { var motion = cur!.Motion; var target = slice.RefPicList[x][refIdx]; var targetLongTerm = slice.RefIsLongTerm[x][refIdx]; var targetPoc = slice.RefPoc[x][refIdx]; var poc = cur.Poc; // A: A0 then A1. int xA0 = xPb - 1, yA0 = yPb + nPbH, yA1 = yPb + nPbH - 1; var availableA0 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA0); var availableA1 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA1); var isScaled = availableA0 || availableA1; var flagA = false; int ax = 0, ay = 0; for (var k = 0; k < 2 && !flagA; k++) { if (k == 0 ? availableA0 : availableA1) { flagA = SameReference(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, out ax, out ay); } } for (var k = 0; k < 2 && !flagA; k++) { if (k == 0 ? availableA0 : availableA1) { flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, targetPoc, targetLongTerm, poc, out ax, out ay); } } // B: B0, B1 then B2. int xB0 = xPb + nPbW, xB1 = xPb + nPbW - 1, xB2 = xPb - 1, yB = yPb - 1; var availableB0 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB0, yB); var availableB1 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB1, yB); var availableB2 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB2, yB); var flagB = false; int bx = 0, by = 0; for (var k = 0; k < 3 && !flagB; k++) { if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2) { flagB = SameReference(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, out bx, out by); } } if (!isScaled) { if (flagB) { flagA = true; ax = bx; ay = by; } flagB = false; for (var k = 0; k < 3 && !flagB; k++) { if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2) { flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, targetPoc, targetLongTerm, poc, out bx, out by); } } } // mvpListLX (8-182): A, B unless equal to A, then the temporal candidate, then zeros. Span candidates = stackalloc int[4]; var count = 0; if (flagA) { candidates[0] = ax; candidates[1] = ay; count = 1; } if (flagB && !(flagA && ax == bx && ay == by)) { candidates[count * 2] = bx; candidates[(count * 2) + 1] = by; count++; } if (count < 2 && mvpFlag >= count && slice.TemporalMvpEnabled && TemporalMotionVector(xPb, yPb, nPbW, nPbH, x, refIdx, out var cx, out var cy)) { candidates[count * 2] = cx; candidates[(count * 2) + 1] = cy; count++; } return mvpFlag < count ? (candidates[mvpFlag * 2], candidates[(mvpFlag * 2) + 1]) : (0, 0); } /// The first conditions of §8.5.3.2.7: the neighbour refers to the same picture, in list X or in list Y. private bool SameReference(in MvField n, int x, Picture target, out int mx, out int my) { if (x == 0) { if (n.Ref0 >= 0 && ReferenceEquals(slice.RefPicList[0][n.Ref0], target)) { (mx, my) = (n.X0, n.Y0); return true; } if (n.Ref1 >= 0 && ReferenceEquals(slice.RefPicList[1][n.Ref1], target)) { (mx, my) = (n.X1, n.Y1); return true; } } else { if (n.Ref1 >= 0 && ReferenceEquals(slice.RefPicList[1][n.Ref1], target)) { (mx, my) = (n.X1, n.Y1); return true; } if (n.Ref0 >= 0 && ReferenceEquals(slice.RefPicList[0][n.Ref0], target)) { (mx, my) = (n.X0, n.Y0); return true; } } mx = my = 0; return false; } /// /// The second conditions of §8.5.3.2.7: a neighbour whose reference is long-term exactly when the target is, its /// vector scaled by the POC distances when both are short-term. /// private bool ScaledCandidate(in MvField n, int x, int targetPoc, bool targetLongTerm, int poc, out int mx, out int my) { for (var pass = 0; pass < 2; pass++) { var list = pass == 0 ? x : 1 - x; var refIdx = list == 0 ? n.Ref0 : n.Ref1; if (refIdx < 0 || slice.RefIsLongTerm[list][refIdx] != targetLongTerm) { continue; } mx = list == 0 ? n.X0 : n.X1; my = list == 0 ? n.Y0 : n.Y1; if (!targetLongTerm) { var td = Math.Clamp(poc - slice.RefPoc[list][refIdx], -128, 127); var tb = Math.Clamp(poc - targetPoc, -128, 127); if (td != 0) { mx = ScaleMv(mx, td, tb); my = ScaleMv(my, td, tb); } } return true; } mx = my = 0; return false; } /// The scaling of a motion vector by POC distances (8-179 to 8-181, 8-205 to 8-207). private static int ScaleMv(int mv, int td, int tb) { var tx = (16384 + (Math.Abs(td) >> 1)) / td; var distScaleFactor = Math.Clamp(((tb * tx) + 32) >> 6, -4096, 4095); var product = distScaleFactor * mv; return Math.Clamp(Math.Sign(product) * ((Math.Abs(product) + 127) >> 8), -32768, 32767); } /// /// The temporal luma motion vector prediction (§8.5.3.2.8): the collocated block at the bottom right of the /// prediction block (inside the same CTB row) or else at its centre, on the 16×16 grid of the collocated picture. /// private bool TemporalMotionVector(int xPb, int yPb, int nPbW, int nPbH, int x, int refIdx, out short mx, out short my) { var col = slice.ColPic; if (col is null || !col.Fits(sps)) { mx = my = 0; return false; } int xBr = xPb + nPbW, yBr = yPb + nPbH; if (yPb >> sps.Log2CtbSize == yBr >> sps.Log2CtbSize && yBr < sps.Height && xBr < sps.Width && CollocatedMotionVector(col, (xBr >> 4) << 4, (yBr >> 4) << 4, x, refIdx, out mx, out my)) { return true; } int xCtr = xPb + (nPbW >> 1), yCtr = yPb + (nPbH >> 1); return CollocatedMotionVector(col, (xCtr >> 4) << 4, (yCtr >> 4) << 4, x, refIdx, out mx, out my); } /// The collocated motion vectors (§8.5.3.2.9). private bool CollocatedMotionVector(Picture col, int xCol, int yCol, int x, int refIdx, out short mx, out short my) { mx = my = 0; var n = col.Motion[Grid(xCol, yCol)]; if (n.Ref0 < 0 && n.Ref1 < 0) { return false; } int listCol = n.Ref0 < 0 ? 1 : n.Ref1 < 0 ? 0 : slice.NoBackwardPred ? x : slice.CollocatedFromL0 ? 1 : 0; var refIdxCol = listCol == 0 ? n.Ref0 : n.Ref1; var ctb = ((yCol >> col.Sps.Log2CtbSize) * col.Sps.WidthInCtbs) + (xCol >> col.Sps.Log2CtbSize); if (ctb >= col.CtbSlice.Length || col.CtbSlice[ctb] < 0 || col.CtbSlice[ctb] >= col.Slices.Count) { return false; } var colSlice = col.Slices[col.CtbSlice[ctb]]; var longTerm = slice.RefIsLongTerm[x][refIdx]; if (colSlice.RefIsLongTerm[listCol][refIdxCol] != longTerm) { return false; } int vx = listCol == 0 ? n.X0 : n.X1, vy = listCol == 0 ? n.Y0 : n.Y1; var colPocDiff = col.Poc - colSlice.RefPoc[listCol][refIdxCol]; var currPocDiff = cur!.Poc - slice.RefPoc[x][refIdx]; if (!longTerm && colPocDiff != currPocDiff && colPocDiff != 0) { var td = Math.Clamp(colPocDiff, -128, 127); var tb = Math.Clamp(currPocDiff, -128, 127); vx = ScaleMv(vx, td, tb); vy = ScaleMv(vy, td, tb); } mx = (short)vx; my = (short)vy; return true; } /// The decoding process for inter sample prediction (§8.5.3.3) of one prediction block, written into the picture. private void PredictInter(int xPb, int yPb, int width, int height, in MvField motion) { var weighted = slice.Type == SliceType.P ? pps.WeightedPred : pps.WeightedBipred; var picture = cur!; var components = sps.ChromaArrayType == 0 ? 1 : 3; for (var c = 0; c < components; c++) { int x0 = xPb, y0 = yPb, w = width, h = height; int mx0 = motion.X0, my0 = motion.Y0, mx1 = motion.X1, my1 = motion.Y1; if (c > 0) { // Chroma vectors in eighths of a chroma sample (8-228, 8-229): mvCLX = mvLX * 2 / SubWidthC (SubHeightC). int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY; x0 >>= sx; y0 >>= sy; w >>= sx; h >>= sy; mx0 <<= 1 - sx; mx1 <<= 1 - sx; my0 <<= 1 - sy; my1 <<= 1 - sy; } var bitDepth = c == 0 ? sps.BitDepthY : sps.BitDepthC; if (motion.Ref0 >= 0) { Interpolate(slice.RefPicList[0][motion.Ref0], c, x0, y0, w, h, mx0, my0, bitDepth, predL0); } if (motion.Ref1 >= 0) { Interpolate(slice.RefPicList[1][motion.Ref1], c, x0, y0, w, h, mx1, my1, bitDepth, predL1); } var plane = picture.Planes[c]; var stride = picture.Stride(c); if (weighted) { ExplicitWeights(plane, stride, x0, y0, w, h, c, motion, bitDepth); } else { DefaultWeights(plane, stride, x0, y0, w, h, motion, bitDepth); } } } /// The default weighted sample prediction (§8.5.3.3.4.2): a rounded shift, or the rounded mean of both lists. private void DefaultWeights(ushort[] plane, int stride, int x0, int y0, int w, int h, in MvField motion, int bitDepth) { var max = (1 << bitDepth) - 1; if (motion.Ref0 >= 0 && motion.Ref1 >= 0) { var shift = 15 - bitDepth; var offset = 1 << (shift - 1); for (var y = 0; y < h; y++) { var row = plane.AsSpan(((y0 + y) * stride) + x0, w); var a = predL0.AsSpan(y * w, w); var b = predL1.AsSpan(y * w, w); for (var x = 0; x < row.Length; x++) { row[x] = (ushort)Math.Clamp((a[x] + b[x] + offset) >> shift, 0, max); } } } else { var source = motion.Ref0 >= 0 ? predL0 : predL1; var shift = 14 - bitDepth; var offset = shift > 0 ? 1 << (shift - 1) : 0; for (var y = 0; y < h; y++) { var row = plane.AsSpan(((y0 + y) * stride) + x0, w); var a = source.AsSpan(y * w, w); for (var x = 0; x < row.Length; x++) { row[x] = (ushort)Math.Clamp((a[x] + offset) >> shift, 0, max); } } } } /// The explicit weighted sample prediction (§8.5.3.3.4.3) with the weights and offsets of the slice header. private void ExplicitWeights(ushort[] plane, int stride, int x0, int y0, int w, int h, int c, in MvField motion, int bitDepth) { var max = (1 << bitDepth) - 1; var shift1 = 14 - bitDepth; var log2Wd = (c == 0 ? slice.LumaLog2WeightDenom : slice.ChromaLog2WeightDenom) + shift1; int w0 = 0, o0 = 0, w1 = 0, o1 = 0; if (motion.Ref0 >= 0) { w0 = c == 0 ? slice.LumaWeight[0][motion.Ref0] : slice.ChromaWeight[0][(motion.Ref0 * 2) + c - 1]; o0 = c == 0 ? slice.LumaOffset[0][motion.Ref0] : slice.ChromaOffset[0][(motion.Ref0 * 2) + c - 1]; } if (motion.Ref1 >= 0) { w1 = c == 0 ? slice.LumaWeight[1][motion.Ref1] : slice.ChromaWeight[1][(motion.Ref1 * 2) + c - 1]; o1 = c == 0 ? slice.LumaOffset[1][motion.Ref1] : slice.ChromaOffset[1][(motion.Ref1 * 2) + c - 1]; } if (motion.Ref0 >= 0 && motion.Ref1 >= 0) { var round = (o0 + o1 + 1) << log2Wd; var shift = log2Wd + 1; for (var y = 0; y < h; y++) { var row = plane.AsSpan(((y0 + y) * stride) + x0, w); var a = predL0.AsSpan(y * w, w); var b = predL1.AsSpan(y * w, w); for (var x = 0; x < row.Length; x++) { row[x] = (ushort)Math.Clamp(((a[x] * w0) + (b[x] * w1) + round) >> shift, 0, max); } } return; } var source = motion.Ref0 >= 0 ? predL0 : predL1; var weight = motion.Ref0 >= 0 ? w0 : w1; var add = motion.Ref0 >= 0 ? o0 : o1; for (var y = 0; y < h; y++) { var row = plane.AsSpan(((y0 + y) * stride) + x0, w); var a = source.AsSpan(y * w, w); if (log2Wd >= 1) { var rounding = 1 << (log2Wd - 1); for (var x = 0; x < row.Length; x++) { row[x] = (ushort)Math.Clamp((((a[x] * weight) + rounding) >> log2Wd) + add, 0, max); } } else { for (var x = 0; x < row.Length; x++) { row[x] = (ushort)Math.Clamp((a[x] * weight) + add, 0, max); } } } } /// /// The fractional sample interpolation (§8.5.3.3.3) of one component of a block from a reference picture, at 14-bit /// precision: 8 taps for luma in quarter samples, 4 taps for chroma in eighth samples. /// private void Interpolate(Picture reference, int c, int x0, int y0, int w, int h, int mvX, int mvY, int bitDepth, short[] output) { var luma = c == 0; var taps = luma ? 8 : 4; var before = luma ? 3 : 1; var fracBits = luma ? 2 : 3; var fracX = mvX & ((1 << fracBits) - 1); var fracY = mvY & ((1 << fracBits) - 1); var xInt = x0 + (mvX >> fracBits); var yInt = y0 + (mvY >> fracBits); var plane = reference.Planes[c]; var planeWidth = luma ? reference.Width : reference.ChromaWidth; var planeHeight = luma ? reference.Height : reference.ChromaHeight; // The reference samples, from (xInt − before, yInt − before): straight from the picture when they are all in it, // otherwise copied with the coordinates clamped to the picture. int left = xInt - before, top = yInt - before, rw = w + taps - 1, rh = h + taps - 1; ushort[] source; int origin, stride; if (left >= 0 && top >= 0 && left + rw <= planeWidth && top + rh <= planeHeight) { source = plane; stride = planeWidth; origin = (top * stride) + left; } else { source = refBlock; stride = rw; origin = 0; // The columns inside the picture are copied, those outside repeat the edge sample. var inStart = Math.Clamp(-left, 0, rw); var inEnd = Math.Clamp(planeWidth - left, inStart, rw); for (var y = 0; y < rh; y++) { var sourceRow = plane.AsSpan(Math.Clamp(top + y, 0, planeHeight - 1) * planeWidth, planeWidth); var row = refBlock.AsSpan(y * rw, rw); if (inEnd > inStart) { sourceRow.Slice(left + inStart, inEnd - inStart).CopyTo(row[inStart..]); } row[..inStart].Fill(sourceRow[0]); row[inEnd..].Fill(sourceRow[^1]); } } var shift1 = bitDepth - 8; var shift3 = 14 - bitDepth; var filters = luma ? s_lumaFilter : s_chromaFilter; if (fracX == 0 && fracY == 0) { for (var y = 0; y < h; y++) { var row = source.AsSpan(origin + ((y + before) * stride) + before, w); var o = output.AsSpan(y * w, w); var x = 0; if (Vector128.IsHardwareAccelerated) { for (; x + 8 <= w; x += 8) { (Vector128.Create(row.Slice(x, 8)).AsInt16() << shift3).CopyTo(o.Slice(x, 8)); } } for (; x < w; x++) { o[x] = (short)(row[x] << shift3); } } return; } if (fracY == 0) { var f = filters.AsSpan(fracX * taps, taps); for (var y = 0; y < h; y++) { FilterRow(source, origin + ((y + before) * stride), 1, f, w, shift1, output.AsSpan(y * w, w)); } return; } if (fracX == 0) { var f = filters.AsSpan(fracY * taps, taps); for (var y = 0; y < h; y++) { FilterRow(source, origin + (y * stride) + before, stride, f, w, shift1, output.AsSpan(y * w, w)); } return; } // Both: the horizontal pass on every row the vertical one needs, then the vertical pass with a shift of 6. var fx = filters.AsSpan(fracX * taps, taps); for (var y = 0; y < rh; y++) { FilterRow(source, origin + (y * stride), 1, fx, w, shift1, filterTemp.AsSpan(y * w, w)); } var fy = filters.AsSpan(fracY * taps, taps); for (var y = 0; y < h; y++) { FilterColumn(filterTemp, y * w, w, fy, w, output.AsSpan(y * w, w)); } } /// /// One row of a filter over samples, apart (1 horizontally, the stride vertically): 8 outputs /// at a time in vectors where the processor has them, the rest one by one. /// private static void FilterRow(ushort[] source, int start, int step, ReadOnlySpan f, int w, int shift, Span output) { var x = 0; var taps = f.Length; var src = source.AsSpan(start); if (src.Length < w + ((taps - 1) * step) || output.Length < w) { throw new ArgumentOutOfRangeException(nameof(source)); } if (Vector128.IsHardwareAccelerated && w >= 8) { ref var s0 = ref MemoryMarshal.GetReference(src); ref var o0 = ref MemoryMarshal.GetReference(output); var st = (nuint)step; if (shift == 0) { // 8-bit samples: every product and every partial sum fits in 16 bits (at most 88 × 255). Vector128 c0 = Vector128.Create((short)f[0]), c1 = Vector128.Create((short)f[1]); Vector128 c2 = Vector128.Create((short)f[2]), c3 = Vector128.Create((short)f[3]); if (taps == 8) { Vector128 c4 = Vector128.Create((short)f[4]), c5 = Vector128.Create((short)f[5]); Vector128 c6 = Vector128.Create((short)f[6]), c7 = Vector128.Create((short)f[7]); for (; x + 8 <= w; x += 8) { var at = (nuint)x; var sum = (Vector128.LoadUnsafe(ref s0, at).AsInt16() * c0) + (Vector128.LoadUnsafe(ref s0, at + st).AsInt16() * c1) + (Vector128.LoadUnsafe(ref s0, at + (2 * st)).AsInt16() * c2) + (Vector128.LoadUnsafe(ref s0, at + (3 * st)).AsInt16() * c3) + (Vector128.LoadUnsafe(ref s0, at + (4 * st)).AsInt16() * c4) + (Vector128.LoadUnsafe(ref s0, at + (5 * st)).AsInt16() * c5) + (Vector128.LoadUnsafe(ref s0, at + (6 * st)).AsInt16() * c6) + (Vector128.LoadUnsafe(ref s0, at + (7 * st)).AsInt16() * c7); sum.StoreUnsafe(ref o0, at); } } else { for (; x + 8 <= w; x += 8) { var at = (nuint)x; var sum = (Vector128.LoadUnsafe(ref s0, at).AsInt16() * c0) + (Vector128.LoadUnsafe(ref s0, at + st).AsInt16() * c1) + (Vector128.LoadUnsafe(ref s0, at + (2 * st)).AsInt16() * c2) + (Vector128.LoadUnsafe(ref s0, at + (3 * st)).AsInt16() * c3); sum.StoreUnsafe(ref o0, at); } } } else { for (; x + 8 <= w; x += 8) { var at = (nuint)x; Vector128 lo = Vector128.Zero, hi = Vector128.Zero; for (var k = 0; k < taps; k++) { var (a, b) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + ((nuint)k * st))); var c = Vector128.Create((int)f[k]); lo += a.AsInt32() * c; hi += b.AsInt32() * c; } Vector128.Narrow(lo >> shift, hi >> shift).StoreUnsafe(ref o0, at); } } } if (taps == 8) { int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3], f4 = f[4], f5 = f[5], f6 = f[6], f7 = f[7]; for (; x < w; x++) { var sum = (f0 * src[x]) + (f1 * src[x + step]) + (f2 * src[x + (2 * step)]) + (f3 * src[x + (3 * step)]) + (f4 * src[x + (4 * step)]) + (f5 * src[x + (5 * step)]) + (f6 * src[x + (6 * step)]) + (f7 * src[x + (7 * step)]); output[x] = (short)(sum >> shift); } } else { int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3]; for (; x < w; x++) { var sum = (f0 * src[x]) + (f1 * src[x + step]) + (f2 * src[x + (2 * step)]) + (f3 * src[x + (3 * step)]); output[x] = (short)(sum >> shift); } } } /// The vertical pass over the 14-bit rows of the horizontal one (8-236, 8-246), shifted by 6. private static void FilterColumn(short[] source, int start, int stride, ReadOnlySpan f, int w, Span output) { var x = 0; var taps = f.Length; var src = source.AsSpan(start); if (src.Length < w + ((taps - 1) * stride) || output.Length < w) { throw new ArgumentOutOfRangeException(nameof(source)); } if (Vector128.IsHardwareAccelerated && w >= 8) { ref var s0 = ref MemoryMarshal.GetReference(src); ref var o0 = ref MemoryMarshal.GetReference(output); var st = (nuint)stride; Vector128 c0 = Vector128.Create((int)f[0]), c1 = Vector128.Create((int)f[1]); Vector128 c2 = Vector128.Create((int)f[2]), c3 = Vector128.Create((int)f[3]); if (taps == 8) { Vector128 c4 = Vector128.Create((int)f[4]), c5 = Vector128.Create((int)f[5]); Vector128 c6 = Vector128.Create((int)f[6]), c7 = Vector128.Create((int)f[7]); for (; x + 8 <= w; x += 8) { var at = (nuint)x; var (a0, b0) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at)); var (a1, b1) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + st)); var (a2, b2) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (2 * st))); var (a3, b3) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (3 * st))); var (a4, b4) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (4 * st))); var (a5, b5) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (5 * st))); var (a6, b6) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (6 * st))); var (a7, b7) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (7 * st))); var lo = (a0 * c0) + (a1 * c1) + (a2 * c2) + (a3 * c3) + (a4 * c4) + (a5 * c5) + (a6 * c6) + (a7 * c7); var hi = (b0 * c0) + (b1 * c1) + (b2 * c2) + (b3 * c3) + (b4 * c4) + (b5 * c5) + (b6 * c6) + (b7 * c7); Vector128.Narrow(lo >> 6, hi >> 6).StoreUnsafe(ref o0, at); } } else { for (; x + 8 <= w; x += 8) { var at = (nuint)x; var (a0, b0) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at)); var (a1, b1) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + st)); var (a2, b2) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (2 * st))); var (a3, b3) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (3 * st))); var lo = (a0 * c0) + (a1 * c1) + (a2 * c2) + (a3 * c3); var hi = (b0 * c0) + (b1 * c1) + (b2 * c2) + (b3 * c3); Vector128.Narrow(lo >> 6, hi >> 6).StoreUnsafe(ref o0, at); } } } if (taps == 8) { int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3], f4 = f[4], f5 = f[5], f6 = f[6], f7 = f[7]; for (; x < w; x++) { var sum = (f0 * src[x]) + (f1 * src[x + stride]) + (f2 * src[x + (2 * stride)]) + (f3 * src[x + (3 * stride)]) + (f4 * src[x + (4 * stride)]) + (f5 * src[x + (5 * stride)]) + (f6 * src[x + (6 * stride)]) + (f7 * src[x + (7 * stride)]); output[x] = (short)(sum >> 6); } } else { int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3]; for (; x < w; x++) { var sum = (f0 * src[x]) + (f1 * src[x + stride]) + (f2 * src[x + (2 * stride)]) + (f3 * src[x + (3 * stride)]); output[x] = (short)(sum >> 6); } } } }