using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace Febe.Tests.Codecs.H265;
///
/// 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.
///
///
/// 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.
///
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; }
/// The Annex B bitstream as published (.bit or .bin).
public string BitstreamPath { get; private set; } = "";
/// The readme of the stream's authors, as published.
public string ReadmePath { get; private set; } = "";
/// Format range extensions (4:0:0, 4:2:2, 4:4:4, more than 10 bits, RExt tools): not covered by «HEVC» for now.
public bool IsRangeExtension => Name.Contains("_RExt_", StringComparison.Ordinal);
/// Output size, or null when the stream changes size (then only lists them).
public (int Width, int Height)? Size { get; private set; }
public IReadOnlyList<(int Width, int Height)> Sizes { get; private set; } = [];
/// "4:0:0", "4:2:0", "4:2:2" or "4:4:4".
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; }
/// MD5 of the whole official reconstruction.
public string TotalMd5 { get; private set; } = "";
/// MD5 of each output frame, in output order; empty when the zip did not ship the YUV file.
public IReadOnlyList FrameMd5 { get; private set; } = [];
public static IEnumerable Names() =>
Directory.EnumerateDirectories(Root).Select(Path.GetFileName).OfType().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;
}
/// Bytes of one frame of the given size, as laid out in the official YUV file.
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);
}
///
/// 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.
///
public string? Compare(IReadOnlyList 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();
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 (?\d+x\d+|variabile\((\d+x\d+,)*\d+x\d+\)) (?4:[024]:[024]) (?\d+)(/(?\d+))? bit, (?\d+) fotogrammi, (?\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();
}