using static Febe.Core.Codecs.H264.Samples; namespace Febe.Core.Codecs.H264; public sealed partial class H264Decoder { /// The luma-like plane the deblocking filter is working on: Y, or one colour plane coded separately. private byte[] deblockLuma = []; /// /// Deblocking filter (§8.7) of the picture just decoded, macroblock by macroblock in address order: a frame, one /// field (its rows only, as a picture of its own), or an MBAFF frame (pairs, top then bottom macroblock). Colour planes /// coded separately are filtered one by one, each as a monochrome picture with its own macroblock data. /// private void Deblock(Picture picture) { var any = false; foreach (var filter in sliceFilters) { any |= filter.Disable != 1; } if (!any) { return; } if (!separatePlanes) { DeblockPlane(picture, picture.Y); return; } for (var k = 0; k < 3; k++) { SelectColourPlane(k); picture.SelectPlane(k); DeblockPlane(picture, picture.Plane(k)); } SelectColourPlane(0); picture.SelectPlane(0); } private void DeblockPlane(Picture picture, byte[] luma) { deblockLuma = luma; if (wide) { DeblockPicture(picture); } else { DeblockPicture(picture); } } private void DeblockPicture(Picture picture) where T : unmanaged { if (curStructure != 0) { DeblockRows(picture, 2, curStructure - 1); } else if (activeSps!.MbAdaptiveFrameField) { DeblockPairs(picture); } else { DeblockRows(picture, 1, 0); } } /// A frame ( 1) or the field of ( 2). private void DeblockRows(Picture picture, int rowStep, int parity) where T : unmanaged { var w = widthInMbs; int width = picture.Width, cwidth = picture.ChromaWidth; int stride = width * rowStep, cstride = cwidth * rowStep; Span bs = stackalloc byte[4]; var rows = heightInMbs / rowStep; for (var row = 0; row < rows; row++) { for (var mx = 0; mx < w; mx++) { var m = (((row * rowStep) + parity) * w) + mx; var s = mbSlice[m]; if (s < 0) { continue; } var (disable, alphaOffset, betaOffset) = sliceFilters[s]; if (disable == 1) { continue; } var lumaOrigin = (((row * 16 * rowStep) + parity) * width) + (mx * 16); var chromaOrigin = (((row * mbHeightC * rowStep) + parity) * cwidth) + (mx * mbWidthC); if (mx > 0 && mbSlice[m - 1] >= 0 && (disable != 2 || mbSlice[m - 1] == s)) { MbEdge(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); var up = m - (rowStep * w); if (row > 0 && mbSlice[up] >= 0 && (disable != 2 || mbSlice[up] == s)) { MbEdge(picture, up, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } } } /// /// An MBAFF frame. Between a frame and a field pair the left edge is filtered row by row, each row against the /// macroblock that holds it; the top edge of a frame macroblock under a field pair twice, once per field (§8.7.1). /// private void DeblockPairs(Picture picture) where T : unmanaged { var w = widthInMbs; int width = picture.Width, cwidth = picture.ChromaWidth; Span bs = stackalloc byte[4]; Span rowBs = stackalloc byte[16]; Span rowMb = stackalloc int[16]; var field = picture.MbField; for (var pairY = 0; pairY < heightInMbs / 2; pairY++) { for (var mx = 0; mx < w; mx++) { for (var bottom = 0; bottom < 2; bottom++) { var m = (((2 * pairY) + bottom) * w) + mx; var s = mbSlice[m]; if (s < 0) { continue; } var (disable, alphaOffset, betaOffset) = sliceFilters[s]; if (disable == 1) { continue; } var isField = field[m]; int lumaOrigin, stride, chromaOrigin, cstride; if (isField) { lumaOrigin = (((pairY * 32) + bottom) * width) + (mx * 16); chromaOrigin = (((pairY * 2 * mbHeightC) + bottom) * cwidth) + (mx * mbWidthC); stride = 2 * width; cstride = 2 * cwidth; } else { lumaOrigin = ((((2 * pairY) + bottom) * 16) * width) + (mx * 16); chromaOrigin = ((((2 * pairY) + bottom) * mbHeightC) * cwidth) + (mx * mbWidthC); stride = width; cstride = cwidth; } // Left edge. var leftTop = (2 * pairY * w) + mx - 1; if (mx > 0 && mbSlice[leftTop] >= 0 && (disable != 2 || mbSlice[leftTop] == s)) { var leftField = field[leftTop]; if (leftField == isField) { MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } else { MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb); } } InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); // Top edge. if (!isField && bottom == 1) { MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } else if (pairY > 0) { var aboveTop = (((2 * pairY) - 2) * w) + mx; if (mbSlice[aboveTop] >= 0 && (disable != 2 || mbSlice[aboveTop] == s)) { if (!isField && field[aboveTop]) { // A frame macroblock under a field pair: each field of its top rows against that field. for (var j = 0; j < 2; j++) { MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs); } } else { var pm = isField && bottom == 0 && field[aboveTop] ? aboveTop : aboveTop + w; MbEdge(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } } } InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); } } } } /// /// The left edge of an MBAFF macroblock whose left pair is of the other kind (frame and field): bS and qP row by /// row, from the macroblock holding each row of the left pair. A chroma row takes the bS of a luma row: in 4:2:0 the /// mapping of §8.7.2.1, in 4:2:2 and 4:4:4 (as many chroma rows as luma rows) the row itself. /// private void MixedLeftEdge( Picture picture, int m, int leftTop, bool isField, bool bottom, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span rowBs, Span rowMb) where T : unmanaged { var w = widthInMbs; var leftField = picture.MbField[leftTop]; for (var r = 0; r < 16; r++) { var pm = LeftOfPair(leftTop, w, leftField, isField, bottom, r, 16, out var yM); rowMb[r] = pm; rowBs[r] = (byte)BoundaryStrength(picture, pm, (((yM & 15) >> 2) * 4) + 3, m, (r >> 2) * 4, true, true); } var luma = Plane(deblockLuma); for (var r = 0; r < 16; r++) { if (rowBs[r] == 0) { continue; } if (Thresholds(mbQp[rowMb[r]], mbQp[m], alphaOffset, betaOffset, bitDepthY, out var alpha, out var beta, out var indexA)) { FilterLuma(luma, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA, bitDepthY - 8, maxY); } } if (chromaArrayType == 0) { return; } var cb = Plane(picture.Cb); var cr = Plane(picture.Cr); for (var k = 0; k < mbHeightC; k++) { var lumaRow = mbHeightC == 16 ? k : isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1); var strength = rowBs[lumaRow]; if (strength == 0) { continue; } var pm = rowMb[lumaRow]; for (var c = 0; c < 2; c++) { if (!Thresholds(mbQpC[(pm * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, out var alpha, out var beta, out var indexA)) { continue; } var plane = c == 0 ? cb : cr; if (chromaArrayType == 3) { FilterLuma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC); } else { FilterChroma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC); } } } } /// A macroblock edge between (left or above) and , luma and chroma. private void MbEdge( Picture picture, int pm, int qm, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span bs) where T : unmanaged { for (var i = 0; i < 4; i++) { int qb = vertical ? i * 4 : i, pb = vertical ? (i * 4) + 3 : 12 + i; bs[i] = (byte)BoundaryStrength(picture, pm, pb, qm, qb, true, vertical); } if ((bs[0] | bs[1] | bs[2] | bs[3]) == 0) { return; } int along = vertical ? stride : 1, across = vertical ? 1 : stride; Edge(Plane(deblockLuma), lumaOrigin, along, across, bs, 16, mbQp[pm], mbQp[qm], alphaOffset, betaOffset, bitDepthY, chromaStyle: false); if (chromaArrayType == 0) { return; } int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride; var count = vertical ? mbHeightC : mbWidthC; for (var c = 0; c < 2; c++) { Edge(Plane(c == 0 ? picture.Cb : picture.Cr), chromaOrigin, calong, cacross, bs, count, mbQpC[(pm * 2) + c], mbQpC[(qm * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3); } } /// /// The internal edges of macroblock in one direction: luma 4, 8, 12 (only 8 with the 8×8 /// transform); chroma at the same luma positions where they fall on a 4×4 chroma block edge — 4 for 4:2:0, the /// rows 4, 8 and 12 of 4:2:2 (whatever the transform of luma), all the luma edges in 4:4:4. /// private void InnerEdges( Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span bs) where T : unmanaged { var t8 = mbT8[m]; int along = vertical ? stride : 1, across = vertical ? 1 : stride; int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride; var chromaSize = vertical ? mbWidthC : mbHeightC; var count = vertical ? mbHeightC : mbWidthC; for (var edge = 1; edge < 4; edge++) { var lumaEdge = !t8 || (edge & 1) == 0; var chromaEdge = chromaArrayType switch { 0 => false, 3 => lumaEdge, _ => chromaSize == 16 || edge == 2, }; if (!lumaEdge && !chromaEdge) { continue; } for (var i = 0; i < 4; i++) { var qb = vertical ? (i * 4) + edge : (edge * 4) + i; bs[i] = (byte)BoundaryStrength(picture, m, qb - (vertical ? 1 : 4), m, qb, false, vertical); } if ((bs[0] | bs[1] | bs[2] | bs[3]) == 0) { continue; } if (lumaEdge) { var offset = edge * 4 * (vertical ? 1 : stride); Edge(Plane(deblockLuma), lumaOrigin + offset, along, across, bs, 16, mbQp[m], mbQp[m], alphaOffset, betaOffset, bitDepthY, chromaStyle: false); } if (chromaEdge) { var position = edge * chromaSize / 4; var coffset = position * (vertical ? 1 : cstride); for (var c = 0; c < 2; c++) { Edge(Plane(c == 0 ? picture.Cb : picture.Cr), chromaOrigin + coffset, calong, cacross, bs, count, mbQpC[(m * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3); } } } } /// /// α, β and indexA of an edge (§8.7.2.2) from the qP of its two sides, scaled to the bit depth (equations 8-466, /// 8-467); false when the edge is not filtered. /// private static bool Thresholds(int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, out int alpha, out int beta, out int indexA) { var qpav = (qpP + qpQ + 1) >> 1; indexA = Math.Clamp(qpav + alphaOffset, 0, 51); alpha = H264Tables.Alpha[indexA] << (bitDepth - 8); beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)] << (bitDepth - 8); return alpha != 0 && beta != 0; } /// /// The samples along one edge (16 in luma; 8 or 16 in chroma), each with the bS of its 4×4 /// luma block; the filter of chroma (chromaStyleFilteringFlag) or that of luma, which 4:4:4 uses for Cb and Cr. /// private static void Edge(Span plane, int origin, int along, int across, ReadOnlySpan bs, int count, int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, bool chromaStyle) where T : unmanaged { if (!Thresholds(qpP, qpQ, alphaOffset, betaOffset, bitDepth, out var alpha, out var beta, out var indexA)) { return; } var shift = count == 16 ? 2 : 1; var bdShift = bitDepth - 8; var max = (1 << bitDepth) - 1; for (var k = 0; k < count; k++) { var strength = bs[k >> shift]; if (strength == 0) { continue; } if (chromaStyle) { FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max); } else { FilterLuma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max); } } } /// /// bS of the edge between 4×4 luma blocks of and of /// (§8.7.2.1). Field macroblocks (all those of a field picture) take 4 only across vertical /// edges and compare vertical vectors in field units; between a frame and a field macroblock (mixed edges of MBAFF /// frames) it is at least 1. /// private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge, bool vertical) { bool fieldP = picture.MbField[pm], fieldQ = picture.MbField[qm]; if (picture.MbIntra[pm] || picture.MbIntra[qm] || (anySwitching && (sliceSwitching[mbSlice[pm]] || sliceSwitching[mbSlice[qm]]))) { return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3; } if (HasCoefficients(pm, pb) || HasCoefficients(qm, qb)) { return 2; } if (fieldP != fieldQ) { return 1; } var limit = fieldQ ? 2 : 4; int pi = (pm * 4) + B8OfRaster(pb), qi = (qm * 4) + B8OfRaster(qb); var l1 = mbCount * 4; var p0 = UsedReference(picture, pi); var p1 = UsedReference(picture, l1 + pi); var q0 = UsedReference(picture, qi); var q1 = UsedReference(picture, l1 + qi); var countP = (p0.Pic is null ? 0 : 1) + (p1.Pic is null ? 0 : 1); var countQ = (q0.Pic is null ? 0 : 1) + (q1.Pic is null ? 0 : 1); if (countP != countQ) { return 1; } var mv = picture.Mv; var l1Mv = mbCount * 32; int pv0 = ((pm * 16) + pb) * 2, qv0 = ((qm * 16) + qb) * 2; int pv1 = l1Mv + pv0, qv1 = l1Mv + qv0; if (countP == 1) { var refP = p0.Pic is not null ? p0 : p1; var refQ = q0.Pic is not null ? q0 : q1; if (refP != refQ) { return 1; } return MvFar(mv, p0.Pic is not null ? pv0 : pv1, q0.Pic is not null ? qv0 : qv1, limit) ? 1 : 0; } if (countP == 0) { return 0; } var sameSet = (p0 == q0 && p1 == q1) || (p0 == q1 && p1 == q0); if (!sameSet) { return 1; } if (p0 != p1) { return p0 == q0 ? (MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit) ? 1 : 0) : (MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit) ? 1 : 0); } // Both motion vectors of both blocks refer to the same picture. var straight = MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit); var crossed = MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit); return straight && crossed ? 1 : 0; } /// The picture (frame, or field of a frame store) a block refers to in a list; empty when the list is not used. private static RefEntry UsedReference(Picture picture, int index) => picture.RefIdx[index] < 0 ? default : new RefEntry(picture.RefPic[index] ?? picture, picture.RefPar[index]); private static bool MvFar(short[] mv, int a, int b, int verticalLimit) => Math.Abs(mv[a] - mv[b]) >= 4 || Math.Abs(mv[a + 1] - mv[b + 1]) >= verticalLimit; /// /// The transform block holding the 4×4 luma block has coefficients; in 4:4:4 (not coded as /// separate planes) those of the Cb and Cr blocks at the same place count too. /// private bool HasCoefficients(int m, int blk) { var planes = chromaArrayType == 3 ? 3 : 1; for (var plane = 0; plane < planes; plane++) { var baseIndex = (m * NzPerMb) + (plane * 16); if (!mbT8[m]) { if (nz[baseIndex + blk] != 0) { return true; } continue; } // The 8×8 transform block containing the 4×4 block. var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2); if ((nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0) { return true; } } return false; } /// The filter of luma edges (§8.7.2.3, §8.7.2.4), also that of Cb and Cr in 4:4:4; tC0 scaled by . private static void FilterLuma(Span s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max) where T : unmanaged { int p0 = Get(s[o - step]), q0 = Get(s[o]); if (Math.Abs(p0 - q0) >= alpha) { return; } int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]); if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta) { return; } int p2 = Get(s[o - (3 * step)]), q2 = Get(s[o + (2 * step)]); var ap = Math.Abs(p2 - p0) < beta; var aq = Math.Abs(q2 - q0) < beta; if (bS < 4) { var tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift; var tc = tc0 + (ap ? 1 : 0) + (aq ? 1 : 0); var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc); s[o - step] = Make(Clip(p0 + delta, max)); s[o] = Make(Clip(q0 - delta, max)); if (ap) { s[o - (2 * step)] = Make(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0)); } if (aq) { s[o + step] = Make(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0)); } return; } var strong = Math.Abs(p0 - q0) < ((alpha >> 2) + 2); if (ap && strong) { var p3 = Get(s[o - (4 * step)]); s[o - step] = Make((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3); s[o - (2 * step)] = Make((p2 + p1 + p0 + q0 + 2) >> 2); s[o - (3 * step)] = Make(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3); } else { s[o - step] = Make(((2 * p1) + p0 + q1 + 2) >> 2); } if (aq && strong) { var q3 = Get(s[o + (3 * step)]); s[o] = Make((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3); s[o + step] = Make((p0 + q0 + q1 + q2 + 2) >> 2); s[o + (2 * step)] = Make(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3); } else { s[o] = Make(((2 * q1) + q0 + p1 + 2) >> 2); } } /// The filter of the chroma edges of 4:2:0 and 4:2:2 (chromaStyleFilteringFlag). private static void FilterChroma(Span s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max) where T : unmanaged { int p0 = Get(s[o - step]), q0 = Get(s[o]); if (Math.Abs(p0 - q0) >= alpha) { return; } int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]); if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta) { return; } if (bS < 4) { var tc = (H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift) + 1; var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc); s[o - step] = Make(Clip(p0 + delta, max)); s[o] = Make(Clip(q0 - delta, max)); return; } s[o - step] = Make(((2 * p1) + p0 + q1 + 2) >> 2); s[o] = Make(((2 * q1) + q0 + p1 + 2) >> 2); } }