Files
Febe/tests/Febe.Tests/Media/H265/H265PictureHashes.cs
T
Alby96andClaude Opus 5.5 6274c4ee03 Flussi di conformità HEVC (ITU-T H.265.1) e prove pronte per il decodificatore (#58)
Prima di scrivere il decodificatore HEVC serve un riferimento ufficiale per ogni
strumento: 136 flussi Main, Main 10 e Main Still Picture (il profilo delle foto
HEIC) e 10 RExt, circa 29 MB, con il readme degli autori e riferimento.md5
(MD5 di tutto il YUV ufficiale; per i 15 flussi che lo hanno nello zip anche di
ogni fotogramma). I YUV restano fuori; i flussi grandi già coperti da altri sono
elencati con il motivo in LEGGIMI.md.

Le prove di decodifica sono inconcludenti finché il decodificatore non c'è, e
quelle RExt finché Alberto non decide se servono. Già da ora si controllano i
riferimenti e gli hash SEI delle immagini, letti con un lettore scritto dalla
norma (D.3.19), che permetteranno di verificare immagine per immagine anche i
flussi senza YUV. Le 146 prove saltate non passano la regola della CI che non
ammette prove saltate.

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

245 lines
8.0 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.
using System.Buffers.Binary;
using System.Security.Cryptography;
namespace Febe.Tests.Codecs.H265;
/// <summary>hash_type of the decoded picture hash SEI message (ITU-T H.265, D.2.20 and D.3.19).</summary>
internal enum H265HashType
{
Md5 = 0,
Crc = 1,
Checksum = 2,
}
/// <summary>
/// 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).
/// </summary>
/// <param name="Picture">Index of the coded picture in decoding order, counting every picture of the bitstream (also
/// the RASL pictures a decoder skips).</param>
internal sealed record H265PictureHash(int Picture, H265HashType Type, byte[][] Planes);
/// <summary>
/// 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).
/// </summary>
internal static class H265PictureHashes
{
private const int SuffixSei = 40;
public static List<H265PictureHash> Read(ReadOnlySpan<byte> annexB)
{
var hashes = new List<H265PictureHash>();
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;
}
/// <summary>
/// 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.
/// </summary>
public static byte[] Compute(H265HashType type, ReadOnlySpan<ushort> 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<H265PictureHash> 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;
}
/// <summary>Removes the emulation prevention bytes (0x03 after two zero bytes).</summary>
private static byte[] Unescape(ReadOnlySpan<byte> 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];
}
/// <summary>Start and length of each NAL unit after a 0x000001 start code, trailing zero bytes excluded.</summary>
private static List<(int Start, int Length)> NalUnits(ReadOnlySpan<byte> data)
{
var units = new List<(int, int)>();
var start = -1;
var i = 0;
while (i + 2 < data.Length)
{
var next = data[i..].IndexOf((ReadOnlySpan<byte>)[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<byte> data, int start, int end)
{
while (end > start && data[end - 1] == 0)
{
end--;
}
return end - start;
}
}