using System.Buffers.Binary;
using System.Security.Cryptography;
namespace Febe.Tests.Codecs.H265;
/// hash_type of the decoded picture hash SEI message (ITU-T H.265, D.2.20 and D.3.19).
internal enum H265HashType
{
Md5 = 0,
Crc = 1,
Checksum = 2,
}
///
/// The decoded picture hash of one coded picture: one value per colour component (one for 4:0:0, otherwise three),
/// computed by the encoder over the whole decoded sample arrays (pic_width_in_luma_samples × pic_height_in_luma_samples,
/// before the conformance window crops them).
///
/// Index of the coded picture in decoding order, counting every picture of the bitstream (also
/// the RASL pictures a decoder skips).
internal sealed record H265PictureHash(int Picture, H265HashType Type, byte[][] Planes);
///
/// Reads the decoded picture hash SEI messages of an Annex B bitstream, independently of any decoder, so that a decoded
/// picture can be checked against what its encoder computed (most conformance streams carry an MD5 per picture, also
/// when their zip has no reconstructed YUV file). Written from the text of ITU-T H.265 (7.3.1, 7.3.5, D.2.20, D.3.19).
///
internal static class H265PictureHashes
{
private const int SuffixSei = 40;
public static List Read(ReadOnlySpan annexB)
{
var hashes = new List();
var picture = -1;
foreach (var (start, length) in NalUnits(annexB))
{
var nal = annexB.Slice(start, length);
if (nal.Length < 3 || (nal[0] & 0x80) != 0)
{
continue;
}
var type = (nal[0] >> 1) & 63;
var layer = ((nal[0] & 1) << 5) | (nal[1] >> 3);
if (layer != 0)
{
continue;
}
if (type < 32)
{
// first_slice_segment_in_pic_flag is the first bit of every slice segment header; the byte after the
// two-byte NAL header can never be an emulation prevention byte.
if ((nal[2] & 0x80) != 0)
{
picture++;
}
}
else if (type == SuffixSei && picture >= 0)
{
ReadSei(Unescape(nal[2..]), picture, hashes);
}
}
return hashes;
}
///
/// The hash of one decoded sample array as D.3.19 defines it: samples in raster order, one byte each up to 8 bits,
/// otherwise two bytes with the low one first.
///
public static byte[] Compute(H265HashType type, ReadOnlySpan samples, int width, int height, int stride, int bitDepth)
{
var bytesPerSample = bitDepth > 8 ? 2 : 1;
if (type == H265HashType.Checksum)
{
uint sum = 0;
for (var y = 0; y < height; y++)
{
var row = samples.Slice(y * stride, width);
for (var x = 0; x < width; x++)
{
var mask = (uint)((x & 0xFF) ^ (y & 0xFF) ^ (x >> 8) ^ (y >> 8));
sum += (row[x] & 0xFFu) ^ mask;
if (bytesPerSample == 2)
{
sum += (uint)(row[x] >> 8) ^ mask;
}
}
}
var result = new byte[4];
BinaryPrimitives.WriteUInt32BigEndian(result, sum);
return result;
}
// MD5 and CRC both read pictureData, the samples as bytes; the CRC needs two zero bytes after them.
var data = new byte[width * height * bytesPerSample + 2];
var at = 0;
for (var y = 0; y < height; y++)
{
var row = samples.Slice(y * stride, width);
for (var x = 0; x < width; x++)
{
data[at++] = (byte)row[x];
if (bytesPerSample == 2)
{
data[at++] = (byte)(row[x] >> 8);
}
}
}
if (type == H265HashType.Md5)
{
return MD5.HashData(data.AsSpan(0, at));
}
uint crc = 0xFFFF;
for (var bit = 0; bit < (at + 2) * 8; bit++)
{
var msb = (crc >> 15) & 1;
var value = (uint)(data[bit >> 3] >> (7 - (bit & 7))) & 1;
crc = (((crc << 1) + value) & 0xFFFF) ^ (msb * 0x1021);
}
return [(byte)(crc >> 8), (byte)crc];
}
private static void ReadSei(byte[] rbsp, int picture, List hashes)
{
var at = 0;
// sei_message() repeats while more_rbsp_data(): stop at the byte that holds only the stop bit.
while (at < rbsp.Length && !(at == rbsp.Length - 1 && rbsp[at] == 0x80))
{
var payloadType = ReadFfCoded(rbsp, ref at);
var payloadSize = ReadFfCoded(rbsp, ref at);
if (payloadType < 0 || payloadSize < 0 || at + payloadSize > rbsp.Length)
{
throw new InvalidDataException("Messaggio SEI troncato.");
}
if (payloadType == 132 && payloadSize >= 1)
{
var type = (H265HashType)rbsp[at];
var size = type switch { H265HashType.Md5 => 16, H265HashType.Crc => 2, H265HashType.Checksum => 4, _ => 0 };
if (size == 0 || (payloadSize - 1) % size != 0 || (payloadSize - 1) / size is not (1 or 3))
{
throw new InvalidDataException($"Hash dell'immagine non valido: tipo {(int)type}, {payloadSize} byte.");
}
var planes = new byte[(payloadSize - 1) / size][];
for (var c = 0; c < planes.Length; c++)
{
planes[c] = rbsp.AsSpan(at + 1 + c * size, size).ToArray();
}
if (hashes.Count > 0 && hashes[^1].Picture == picture)
{
throw new InvalidDataException($"Due hash per l'immagine {picture}.");
}
hashes.Add(new H265PictureHash(picture, type, planes));
}
at += payloadSize;
}
}
private static int ReadFfCoded(byte[] rbsp, ref int at)
{
var value = 0;
while (at < rbsp.Length && rbsp[at] == 0xFF)
{
value += 255;
at++;
}
return at < rbsp.Length ? value + rbsp[at++] : -1;
}
/// Removes the emulation prevention bytes (0x03 after two zero bytes).
private static byte[] Unescape(ReadOnlySpan payload)
{
var result = new byte[payload.Length];
var length = 0;
var zeros = 0;
foreach (var b in payload)
{
if (zeros >= 2 && b == 3)
{
zeros = 0;
continue;
}
result[length++] = b;
zeros = b == 0 ? zeros + 1 : 0;
}
return result[..length];
}
/// Start and length of each NAL unit after a 0x000001 start code, trailing zero bytes excluded.
private static List<(int Start, int Length)> NalUnits(ReadOnlySpan data)
{
var units = new List<(int, int)>();
var start = -1;
var i = 0;
while (i + 2 < data.Length)
{
var next = data[i..].IndexOf((ReadOnlySpan)[0, 0, 1]);
if (next < 0)
{
break;
}
next += i;
if (start >= 0)
{
units.Add((start, TrimZeros(data, start, next)));
}
start = next + 3;
i = start;
}
if (start >= 0 && start < data.Length)
{
units.Add((start, TrimZeros(data, start, data.Length)));
}
return units;
}
private static int TrimZeros(ReadOnlySpan data, int start, int end)
{
while (end > start && data[end - 1] == 0)
{
end--;
}
return end - start;
}
}