MVC (Annex H): SPS di sottoinsieme, prefissi NAL 14 e slice NAL 20, un decodificatore per vista con il suo stato, predizione fra viste (riferimenti della stessa unità di accesso in coda alle liste, modifiche 4 e 5). Escono tutte le viste, ciascuna con il suo ViewId; VideoFrameDecoder chiede solo la vista base, che è il video 2D, per le miniature. I flussi MVC della serie non hanno ricostruzione ufficiale: le prove controllano che ogni vista si decodifichi pulita e che la vista base resti identica a quella di H.264 puro. SVC (Annex G): lo strato base sempre; sopra, gli strati di qualità della stessa risoluzione in CAVLC, decodificati uno sull'altro. Un macroblocco intra con base_mode_flag somma il residuo accumulato alla ricostruzione dello strato in cui era intra e per i vicini conta come I_BL. SVCBMT-13 coincide ora con lo strato L2 ufficiale in tutti i 20 fotogrammi. Scalabilità spaziale, CGS e CABAC negli strati di miglioramento non sono ancora scritti: il decodificatore dà lo strato base esatto e dice perché, e SVCBST-19 e SVCBCT-1 restano inconclusivi con l'elenco di ciò che manca. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
299 lines
9.8 KiB
C#
299 lines
9.8 KiB
C#
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. The units of the scalable and multiview extensions (prefix 14, slice extension 20 and
|
|
/// 21) carry three more header bytes (nal_unit_header_svc_extension or nal_unit_header_mvc_extension, §7.3.1), kept as
|
|
/// they are in <see cref="Rbsp"/>[1..3]: the emulation prevention bytes are removed only after them.
|
|
/// </summary>
|
|
internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int Length)
|
|
{
|
|
/// <summary>Bytes of the NAL unit header: 4 for the extension units, else 1.</summary>
|
|
internal int HeaderLength => HasExtensionHeader(Type) && Length >= 4 ? 4 : 1;
|
|
|
|
/// <summary>svc_extension_flag of an extension unit: 1 for SVC (Annex G), 0 for MVC (Annex H).</summary>
|
|
internal bool IsSvc => (Rbsp[1] & 0x80) != 0;
|
|
|
|
/// <summary>A reader positioned after the header.</summary>
|
|
internal RbspReader Reader() => new(Rbsp, Length, HeaderLength);
|
|
|
|
/// <summary>NAL unit types whose header has the three extension bytes.</summary>
|
|
internal static bool HasExtensionHeader(int type) => type is 14 or 20 or 21;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units, one at a time, and
|
|
/// removal of their emulation prevention bytes into a buffer the caller keeps: decoding a sample allocates nothing.
|
|
/// </summary>
|
|
internal static class NalUnits
|
|
{
|
|
/// <summary>Bytes of zero padding a buffer keeps past the payload (see <see cref="RbspReader"/>).</summary>
|
|
internal const int Padding = 16;
|
|
|
|
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer.</summary>
|
|
internal static NalUnit Parse(ReadOnlySpan<byte> nal)
|
|
{
|
|
byte[]? buffer = null;
|
|
return Unescape(nal, ref buffer);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes the emulation prevention bytes of one NAL unit into <paramref name="buffer"/>, grown when needed; the
|
|
/// unit is valid until the buffer is used again.
|
|
/// </summary>
|
|
internal static NalUnit Unescape(ReadOnlySpan<byte> nal, ref byte[]? buffer)
|
|
{
|
|
if (nal.Length < 1)
|
|
{
|
|
throw new H264Exception("Unità NAL vuota.");
|
|
}
|
|
|
|
if (buffer is null || buffer.Length < nal.Length + Padding)
|
|
{
|
|
buffer = new byte[Math.Max(nal.Length + Padding, (buffer?.Length ?? 0) * 2)];
|
|
}
|
|
|
|
// Copied run by run between the 0x000003 patterns (a vectorised search), as the byte-by-byte rule of §7.4.1,
|
|
// after the header: the three extension bytes of the units 14, 20 and 21 are not part of the RBSP.
|
|
ReadOnlySpan<byte> pattern = [0, 0, 3];
|
|
var target = buffer.AsSpan();
|
|
var head = NalUnit.HasExtensionHeader(nal[0] & 0x1F) ? Math.Min(4, nal.Length) : 0;
|
|
nal[..head].CopyTo(target);
|
|
var count = head;
|
|
var rest = nal[head..];
|
|
while (true)
|
|
{
|
|
var i = rest.IndexOf(pattern);
|
|
if (i < 0)
|
|
{
|
|
rest.CopyTo(target[count..]);
|
|
count += rest.Length;
|
|
break;
|
|
}
|
|
|
|
rest[..(i + 2)].CopyTo(target[count..]);
|
|
count += i + 2;
|
|
rest = rest[(i + 3)..];
|
|
}
|
|
|
|
target.Slice(count, Padding).Clear();
|
|
return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from <paramref name="position"/>,
|
|
/// which moves past it; false when there is none left.
|
|
/// </summary>
|
|
internal static bool NextAnnexB(ReadOnlySpan<byte> stream, ref int position, out Range unit)
|
|
{
|
|
ReadOnlySpan<byte> startCode = [0, 0, 1];
|
|
while (position < stream.Length)
|
|
{
|
|
var found = stream[position..].IndexOf(startCode);
|
|
if (found < 0)
|
|
{
|
|
break;
|
|
}
|
|
|
|
var start = position + found + 3;
|
|
var next = start < stream.Length ? stream[start..].IndexOf(startCode) : -1;
|
|
var end = next < 0 ? stream.Length : start + next;
|
|
position = end;
|
|
|
|
// Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits).
|
|
var trimmed = end;
|
|
while (trimmed > start && stream[trimmed - 1] == 0)
|
|
{
|
|
trimmed--;
|
|
}
|
|
|
|
if (trimmed > start)
|
|
{
|
|
unit = start..trimmed;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
position = stream.Length;
|
|
unit = default;
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from
|
|
/// <paramref name="position"/>; false at the end or at a damaged length (what was read stands).
|
|
/// </summary>
|
|
internal static bool NextLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize, ref int position, out Range unit)
|
|
{
|
|
unit = default;
|
|
if (position + lengthSize > sample.Length)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var size = 0;
|
|
for (var k = 0; k < lengthSize; k++)
|
|
{
|
|
size = (size << 8) | sample[position + k];
|
|
}
|
|
|
|
position += lengthSize;
|
|
if (size <= 0 || size > sample.Length - position)
|
|
{
|
|
position = sample.Length;
|
|
return false;
|
|
}
|
|
|
|
unit = position..(position + size);
|
|
position += size;
|
|
return true;
|
|
}
|
|
|
|
/// <summary>The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests).</summary>
|
|
internal static List<NalUnit> SplitAnnexB(ReadOnlySpan<byte> stream)
|
|
{
|
|
var units = new List<NalUnit>();
|
|
var position = 0;
|
|
while (NextAnnexB(stream, ref position, out var unit))
|
|
{
|
|
units.Add(Parse(stream[unit]));
|
|
}
|
|
|
|
return units;
|
|
}
|
|
|
|
/// <summary>The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests).</summary>
|
|
internal static List<NalUnit> SplitLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize)
|
|
{
|
|
var units = new List<NalUnit>();
|
|
var position = 0;
|
|
while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
|
|
{
|
|
units.Add(Parse(sample[unit]));
|
|
}
|
|
|
|
return units;
|
|
}
|
|
}
|