using System.Buffers.Binary;
namespace Febe.Core.Codecs.H264;
/// A malformed or unsupported H.264 stream.
public sealed class H264Exception(string message) : Exception(message);
///
/// 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 .
///
internal sealed class RbspReader
{
private readonly byte[] data;
private readonly int length;
private readonly int stopBit;
private int position;
/// The payload, followed by at least sixteen bytes of padding.
/// Bytes of payload.
/// First byte to read (after the NAL unit header).
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;
/// more_rbsp_data(): true while bits remain before the stop bit.
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;
/// ue(v): Exp-Golomb code (§9.1).
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));
}
/// se(v): signed Exp-Golomb code (§9.1.1).
internal int ReadSe()
{
var code = ReadUe();
var magnitude = (int)((code + 1) >> 1);
return (code & 1) != 0 ? magnitude : -magnitude;
}
/// A ue(v) value that must not exceed .
internal int ReadUe(int max)
{
var value = ReadUe();
if (value > (uint)max)
{
throw new H264Exception("Valore fuori dall'intervallo ammesso.");
}
return (int)value;
}
}
///
/// 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 [1..3]: the emulation prevention bytes are removed only after them.
///
internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int Length)
{
/// Bytes of the NAL unit header: 4 for the extension units, else 1.
internal int HeaderLength => HasExtensionHeader(Type) && Length >= 4 ? 4 : 1;
/// svc_extension_flag of an extension unit: 1 for SVC (Annex G), 0 for MVC (Annex H).
internal bool IsSvc => (Rbsp[1] & 0x80) != 0;
/// A reader positioned after the header.
internal RbspReader Reader() => new(Rbsp, Length, HeaderLength);
/// NAL unit types whose header has the three extension bytes.
internal static bool HasExtensionHeader(int type) => type is 14 or 20 or 21;
}
///
/// 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.
///
internal static class NalUnits
{
/// Bytes of zero padding a buffer keeps past the payload (see ).
internal const int Padding = 16;
/// Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer.
internal static NalUnit Parse(ReadOnlySpan nal)
{
byte[]? buffer = null;
return Unescape(nal, ref buffer);
}
///
/// Removes the emulation prevention bytes of one NAL unit into , grown when needed; the
/// unit is valid until the buffer is used again.
///
internal static NalUnit Unescape(ReadOnlySpan 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 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);
}
///
/// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from ,
/// which moves past it; false when there is none left.
///
internal static bool NextAnnexB(ReadOnlySpan stream, ref int position, out Range unit)
{
ReadOnlySpan 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;
}
///
/// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from
/// ; false at the end or at a damaged length (what was read stands).
///
internal static bool NextLengthPrefixed(ReadOnlySpan 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;
}
/// The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests).
internal static List SplitAnnexB(ReadOnlySpan stream)
{
var units = new List();
var position = 0;
while (NextAnnexB(stream, ref position, out var unit))
{
units.Add(Parse(stream[unit]));
}
return units;
}
/// The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests).
internal static List SplitLengthPrefixed(ReadOnlySpan sample, int lengthSize)
{
var units = new List();
var position = 0;
while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
units.Add(Parse(sample[unit]));
}
return units;
}
}