Files
Febe/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs
T
Alby96andClaude Opus 5.5 b23632fc96 Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)
Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori
di contenitori.

- Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione
  come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni),
  altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale
  il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come
  l'estrattore con ffmpeg che sostituisce.
- H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé
  stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da
  pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num;
  immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di
  riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in
  un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica.
- Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano;
  scala dei tempi esatta per ogni TimecodeScale.
- MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le
  altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né
  campioni dei frammenti.
- AVI: durata impossibile ignota senza perdere la data.
- Sonda dei metadati davvero asincrona, annullabile fra i frammenti.
- Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine
  ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice),
  AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI,
  TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di
  tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile.
  Provate contro il codice senza le correzioni: falliscono tutte.
- decisioni.md: quattro righe del 18 novembre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:13:45 +01:00

539 lines
17 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder
{
private int weightMode;
private int[] implicitW0 = [];
/// <summary>
/// The neighbouring 4×4 luma block covering (<paramref name="xN"/>, <paramref name="yN"/>) 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, <see cref="blkDone"/>).
/// </summary>
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]);
}
/// <summary>
/// Luma motion vector prediction (§8.4.1.3). <paramref name="directional"/>: 0 none, 1/2 the upper/lower 16×8
/// partition, 3/4 the left/right 8×16 partition.
/// </summary>
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);
/// <summary>Direct prediction (§8.4.1.2) of the sub-macroblocks <paramref name="first"/> to <paramref name="end"/> − 1.</summary>
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;
}
/// <summary>A reference picture of the slice; a substitute when the stream refers to a missing one.</summary>
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);
}
}
}
}
/// <summary>Inter prediction of one partition with its motion (§8.4.2), written into the current picture.</summary>
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<byte> a = stackalloc byte[256];
Span<byte> 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<byte> a, ReadOnlySpan<byte> 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]);
}
}
}