Files
Febe/tests/Febe.Tests/Media/H265/H265ConformanceStream.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

173 lines
7.2 KiB
C#

using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace Febe.Tests.Codecs.H265;
/// <summary>
/// One stream of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there): the bitstream as
/// published, the readme of its authors and riferimento.md5, written once from the official reconstruction.
/// </summary>
/// <remarks>
/// riferimento.md5 has a header line «# name WxH chroma bits bit, N fotogrammi, B byte» (WxH is «variabile(…)» when
/// the stream changes size), the line «tutto md5» with the MD5 of the whole official YUV file, and one «i md5» line per
/// output frame only for the streams whose zip shipped the YUV file itself. Frames are laid out as in that file: planes
/// Y, Cb, Cr cropped to the conformance window, one byte per sample up to 8 bits, otherwise two bytes little endian for
/// every plane.
/// </remarks>
internal sealed partial class H265ConformanceStream
{
private H265ConformanceStream(string name, string folder)
{
Name = name;
Folder = folder;
}
public static string Root => Path.Combine(AppContext.BaseDirectory, "Media", "H265", "Conformita");
public string Name { get; }
public string Folder { get; }
/// <summary>The Annex B bitstream as published (.bit or .bin).</summary>
public string BitstreamPath { get; private set; } = "";
/// <summary>The readme of the stream's authors, as published.</summary>
public string ReadmePath { get; private set; } = "";
/// <summary>Format range extensions (4:0:0, 4:2:2, 4:4:4, more than 10 bits, RExt tools): not covered by «HEVC» for now.</summary>
public bool IsRangeExtension => Name.Contains("_RExt_", StringComparison.Ordinal);
/// <summary>Output size, or null when the stream changes size (then only <see cref="Sizes"/> lists them).</summary>
public (int Width, int Height)? Size { get; private set; }
public IReadOnlyList<(int Width, int Height)> Sizes { get; private set; } = [];
/// <summary>"4:0:0", "4:2:0", "4:2:2" or "4:4:4".</summary>
public string Chroma { get; private set; } = "";
public int LumaBitDepth { get; private set; }
public int ChromaBitDepth { get; private set; }
public int FrameCount { get; private set; }
public long ByteCount { get; private set; }
/// <summary>MD5 of the whole official reconstruction.</summary>
public string TotalMd5 { get; private set; } = "";
/// <summary>MD5 of each output frame, in output order; empty when the zip did not ship the YUV file.</summary>
public IReadOnlyList<string> FrameMd5 { get; private set; } = [];
public static IEnumerable<string> Names() =>
Directory.EnumerateDirectories(Root).Select(Path.GetFileName).OfType<string>().Order(StringComparer.Ordinal);
public static H265ConformanceStream Load(string name)
{
var folder = Path.Combine(Root, name);
var stream = new H265ConformanceStream(name, folder);
var files = Directory.GetFiles(folder);
stream.BitstreamPath = files.Single(f => Path.GetExtension(f) is ".bit" or ".bin");
stream.ReadmePath = files.Single(f => Path.GetExtension(f) == ".txt");
stream.ReadReference(Path.Combine(folder, "riferimento.md5"));
return stream;
}
/// <summary>Bytes of one frame of the given size, as laid out in the official YUV file.</summary>
public long FrameBytes(int width, int height)
{
long chroma = Chroma switch
{
"4:0:0" => 0,
"4:2:0" => 2L * ((width + 1) / 2) * ((height + 1) / 2),
"4:2:2" => 2L * ((width + 1) / 2) * height,
_ => 2L * width * height,
};
return ((long)width * height + chroma) * (Math.Max(LumaBitDepth, ChromaBitDepth) > 8 ? 2 : 1);
}
/// <summary>
/// Compares decoded frames, in output order and in the layout of the YUV file, with the reference: frame by frame
/// when the reference has them, then the MD5 of all of them together. Returns null when they match.
/// </summary>
public string? Compare(IReadOnlyList<byte[]> frames)
{
for (var i = 0; i < Math.Min(frames.Count, FrameMd5.Count); i++)
{
if (Convert.ToHexStringLower(MD5.HashData(frames[i])) != FrameMd5[i])
{
return $"{Name}: il fotogramma {i} è diverso dal riferimento.";
}
}
if (frames.Count != FrameCount)
{
return $"{Name}: {frames.Count} fotogrammi invece di {FrameCount}.";
}
using var all = IncrementalHash.CreateHash(HashAlgorithmName.MD5);
foreach (var frame in frames)
{
all.AppendData(frame);
}
return Convert.ToHexStringLower(all.GetHashAndReset()) == TotalMd5 ? null : $"{Name}: l'MD5 di tutti i fotogrammi è diverso dal riferimento.";
}
private void ReadReference(string path)
{
var lines = File.ReadAllLines(path);
var header = HeaderPattern().Match(lines[0]);
if (!header.Success)
{
throw new InvalidDataException($"{Name}: intestazione di riferimento.md5 non riconosciuta: {lines[0]}");
}
var sizes = SizePattern().Matches(header.Groups["size"].Value)
.Select(m => (int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture), int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture)))
.ToList();
Sizes = sizes;
Size = header.Groups["size"].Value.StartsWith("variabile(", StringComparison.Ordinal) ? null : sizes.Single();
Chroma = header.Groups["chroma"].Value;
LumaBitDepth = int.Parse(header.Groups["luma"].Value, CultureInfo.InvariantCulture);
ChromaBitDepth = header.Groups["cbits"].Success ? int.Parse(header.Groups["cbits"].Value, CultureInfo.InvariantCulture) : LumaBitDepth;
FrameCount = int.Parse(header.Groups["frames"].Value, CultureInfo.InvariantCulture);
ByteCount = long.Parse(header.Groups["bytes"].Value, CultureInfo.InvariantCulture);
var frames = new List<string>();
foreach (var line in lines.Skip(1))
{
var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2 || !Md5Pattern().IsMatch(parts[1]))
{
throw new InvalidDataException($"{Name}: riga di riferimento.md5 non riconosciuta: {line}");
}
if (parts[0] == "tutto")
{
TotalMd5 = parts[1];
}
else if (int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var index) && index == frames.Count)
{
frames.Add(parts[1]);
}
else
{
throw new InvalidDataException($"{Name}: riferimento.md5 fuori ordine: {line}");
}
}
FrameMd5 = frames;
}
[GeneratedRegex(@"^# \S+\.yuv (?<size>\d+x\d+|variabile\((\d+x\d+,)*\d+x\d+\)) (?<chroma>4:[024]:[024]) (?<luma>\d+)(/(?<cbits>\d+))? bit, (?<frames>\d+) fotogrammi, (?<bytes>\d+) byte$")]
private static partial Regex HeaderPattern();
[GeneratedRegex(@"(\d+)x(\d+)")]
private static partial Regex SizePattern();
[GeneratedRegex("^[0-9a-f]{32}$")]
private static partial Regex Md5Pattern();
}