Decodificatore H.264 scritto in casa, provato sui flussi di conformità (#58)
Decodifica Baseline, Main e High a fotogrammi progressivi 4:2:0 a 8 bit (CAVLC e CABAC, slice I/P/B, trasformata 8x8 e matrici di quantizzazione, predizione pesata, diretta spaziale e temporale, gestione dei riferimenti, filtro di deblocco), scritta dallo standard ITU-T H.264 senza codice di terzi. I dodici flussi della suite ITU-T H.264.1 in tests/Febe.Tests/Media/H264/Conformita danno, fotogramma per fotogramma, gli MD5 della ricostruzione ufficiale. Le tabelle di inizializzazione CABAC sono trascritte dal testo della Raccomandazione (03/2005): quelle a memoria per cabac_init_idc 1 e 2 erano sbagliate e le prove le hanno scoperte. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9958745e53
commit
697de97ec3
55 files changed
+7072
No files matched your search
@@ -0,0 +1,233 @@
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>A malformed or unsupported H.264 stream.</summary>
|
||||
public sealed class H264Exception(string message) : Exception(message);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the bits of a raw byte sequence payload (RBSP): a NAL unit with its emulation prevention bytes removed
|
||||
/// (ITU-T H.264 §7.4.1). The buffer carries sixteen zero bytes past the end, so reads never need a bounds check; reading
|
||||
/// past the payload gives zeros and is detected by the callers through <see cref="BitsLeft"/>.
|
||||
/// </summary>
|
||||
internal sealed class RbspReader
|
||||
{
|
||||
private readonly byte[] data;
|
||||
private readonly int length;
|
||||
private readonly int stopBit;
|
||||
private int position;
|
||||
|
||||
/// <param name="data">The payload, followed by at least sixteen bytes of padding.</param>
|
||||
/// <param name="length">Bytes of payload.</param>
|
||||
/// <param name="startByte">First byte to read (after the NAL unit header).</param>
|
||||
internal RbspReader(byte[] data, int length, int startByte)
|
||||
{
|
||||
this.data = data;
|
||||
this.length = length;
|
||||
position = startByte * 8;
|
||||
|
||||
// The rbsp_stop_one_bit is the last bit set in the payload (trailing cabac_zero_words are all zero).
|
||||
var last = length - 1;
|
||||
while (last >= startByte && data[last] == 0)
|
||||
{
|
||||
last--;
|
||||
}
|
||||
|
||||
stopBit = last < startByte ? startByte * 8 : (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(data[last]);
|
||||
}
|
||||
|
||||
internal byte[] Data => data;
|
||||
|
||||
internal int Position
|
||||
{
|
||||
get => position;
|
||||
set => position = value;
|
||||
}
|
||||
|
||||
internal int BitsLeft => (length * 8) - position;
|
||||
|
||||
internal bool ByteAligned => (position & 7) == 0;
|
||||
|
||||
/// <summary>more_rbsp_data(): true while bits remain before the stop bit.</summary>
|
||||
internal bool MoreRbspData => position < stopBit;
|
||||
|
||||
internal uint Peek(int count)
|
||||
{
|
||||
var index = position >> 3;
|
||||
var word = BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(index, 8));
|
||||
return (uint)((word << (position & 7)) >> (64 - count));
|
||||
}
|
||||
|
||||
internal uint Read(int count)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var value = Peek(count);
|
||||
position += count;
|
||||
return value;
|
||||
}
|
||||
|
||||
internal void Skip(int count) => position += count;
|
||||
|
||||
internal int ReadBit()
|
||||
{
|
||||
var bit = (data[position >> 3] >> (7 - (position & 7))) & 1;
|
||||
position++;
|
||||
return bit;
|
||||
}
|
||||
|
||||
internal bool ReadFlag() => ReadBit() != 0;
|
||||
|
||||
/// <summary>ue(v): Exp-Golomb code (§9.1).</summary>
|
||||
internal uint ReadUe()
|
||||
{
|
||||
var zeros = 0;
|
||||
while (ReadBit() == 0)
|
||||
{
|
||||
if (++zeros > 31 || position > (length * 8) + 32)
|
||||
{
|
||||
throw new H264Exception("Codice Exp-Golomb non valido.");
|
||||
}
|
||||
}
|
||||
|
||||
if (zeros == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (uint)(((1UL << zeros) - 1) + Read(zeros));
|
||||
}
|
||||
|
||||
/// <summary>se(v): signed Exp-Golomb code (§9.1.1).</summary>
|
||||
internal int ReadSe()
|
||||
{
|
||||
var code = ReadUe();
|
||||
var magnitude = (int)((code + 1) >> 1);
|
||||
return (code & 1) != 0 ? magnitude : -magnitude;
|
||||
}
|
||||
|
||||
/// <summary>A ue(v) value that must not exceed <paramref name="max"/>.</summary>
|
||||
internal int ReadUe(int max)
|
||||
{
|
||||
var value = ReadUe();
|
||||
if (value > (uint)max)
|
||||
{
|
||||
throw new H264Exception("Valore fuori dall'intervallo ammesso.");
|
||||
}
|
||||
|
||||
return (int)value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One NAL unit, with its RBSP.</summary>
|
||||
internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int Length)
|
||||
{
|
||||
/// <summary>A reader positioned after the one-byte header.</summary>
|
||||
internal RbspReader Reader() => new(Rbsp, Length, 1);
|
||||
}
|
||||
|
||||
/// <summary>Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units.</summary>
|
||||
internal static class NalUnits
|
||||
{
|
||||
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1).</summary>
|
||||
internal static NalUnit Parse(ReadOnlySpan<byte> nal)
|
||||
{
|
||||
if (nal.Length < 1)
|
||||
{
|
||||
throw new H264Exception("Unità NAL vuota.");
|
||||
}
|
||||
|
||||
var buffer = new byte[nal.Length + 16];
|
||||
var count = 0;
|
||||
var zeros = 0;
|
||||
for (var i = 0; i < nal.Length; i++)
|
||||
{
|
||||
var b = nal[i];
|
||||
if (zeros >= 2 && b == 3)
|
||||
{
|
||||
zeros = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer[count++] = b;
|
||||
zeros = b == 0 ? zeros + 1 : 0;
|
||||
}
|
||||
|
||||
return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count);
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of an Annex B byte stream (start codes 0x000001 or 0x00000001).</summary>
|
||||
internal static List<NalUnit> SplitAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
var units = new List<NalUnit>();
|
||||
var start = -1;
|
||||
var i = 0;
|
||||
while (i + 2 < stream.Length)
|
||||
{
|
||||
if (stream[i] == 0 && stream[i + 1] == 0 && stream[i + 2] == 1)
|
||||
{
|
||||
if (start >= 0)
|
||||
{
|
||||
AddTrimmed(units, stream[start..i]);
|
||||
}
|
||||
|
||||
i += 3;
|
||||
start = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
if (start >= 0 && start < stream.Length)
|
||||
{
|
||||
AddTrimmed(units, stream[start..]);
|
||||
}
|
||||
|
||||
return units;
|
||||
}
|
||||
|
||||
/// <summary>The NAL units of a sample whose units are each prefixed by a big-endian length.</summary>
|
||||
internal static List<NalUnit> SplitLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize)
|
||||
{
|
||||
var units = new List<NalUnit>();
|
||||
var offset = 0;
|
||||
while (offset + lengthSize <= sample.Length)
|
||||
{
|
||||
var size = 0;
|
||||
for (var k = 0; k < lengthSize; k++)
|
||||
{
|
||||
size = (size << 8) | sample[offset + k];
|
||||
}
|
||||
|
||||
offset += lengthSize;
|
||||
if (size <= 0 || size > sample.Length - offset)
|
||||
{
|
||||
break; // damaged: keep what was read
|
||||
}
|
||||
|
||||
units.Add(Parse(sample.Slice(offset, size)));
|
||||
offset += size;
|
||||
}
|
||||
|
||||
return units;
|
||||
}
|
||||
|
||||
private static void AddTrimmed(List<NalUnit> units, ReadOnlySpan<byte> nal)
|
||||
{
|
||||
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
|
||||
var end = nal.Length;
|
||||
while (end > 0 && nal[end - 1] == 0)
|
||||
{
|
||||
end--;
|
||||
}
|
||||
|
||||
if (end > 0)
|
||||
{
|
||||
units.Add(Parse(nal[..end]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user