Files
Febe/tests/Febe.Tests/Media/Containers/HevcVideoTests.cs
T
Alby96andClaude Opus 5.5 ac85d1baed HEVC nella catena dei media e foto HEIC/HEIF decodificate in casa (#58)
Le miniature e i fotogrammi dei video HEVC (i video dei telefoni) e le foto
HEIC non avevano un decodificatore: ora passano dal decodificatore HEVC
scritto in casa, senza componenti esterni.

- Contenitori: hvcC dai sample entry hvc1/hev1 dei file ISO e dalla
  CodecPrivate di Matroska V_MPEGH/ISO/HEVC (VideoTrack.HevcConfiguration);
  HEVC in AVI come Annex B. Lo scrittore MP4 sa scrivere anche hvc1.
- H265Decoder: fotogrammi in ordine di decodifica (FrameDecoded con Wanted),
  unità di accesso Annex B, punto d'accesso di un campione (IDR/BLA esatti,
  CRA vicino).
- VideoFrameDecoder sceglie H.264 o HEVC dal codec della traccia; il
  fotogramma da cui parte la corsa vale per un campione senza immagine
  (RASL di una CRA). Una sola conversione Y'CbCr->RGB (Codecs/YuvToRgb)
  per H.264, HEVC 8-12 bit 4:0:0/4:2:0/4:2:2/4:4:4 e HEIF.
- Febe.Core.Codecs.Heif (ISO/IEC 23008-12): meta, iinf, iloc (file e idat),
  iref, iprp/ipco/ipma; elemento hvc1 o griglia di tessere decodificate in
  parallelo, colr nclx/ICC, piano alfa, clap, irot/imir come orientamento
  EXIF, elemento Exif. Uscita HeifImage, con la stessa forma di RgbaImage
  del ramo funzione/codec-immagini (da unire).
- ImageDecoding manda gli HEIF al decodificatore di casa: miniature,
  impronte, dimensioni e anteprime valgono anche per gli HEIC;
  ExifDateReader legge la data dall'elemento Exif nei primi 512 KB.
- Prove su file costruiti dai flussi H.265.1 (MP4, frammentato, Matroska,
  AVI con e senza indice, Main 10, griglie, rotazioni, clap, alfa, nclx,
  Exif, file rovinati con semi fissi). Documenti: docker.md, LEGGIMI
  dell'importazione, una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:38:09 +01:00

151 lines
7.4 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 Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H265;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// HEVC videos through the containers and the frame decoder: the test videos are built from streams of the ITU-T H.265.1
/// set, so the frame expected is the one the decoder gives straight from the stream (itself bit exact on those streams).
/// </summary>
[TestClass]
public sealed class HevcVideoTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
/// <summary>416×240, 8 bit, 60 frames shown in another order than they are decoded.</summary>
private const string Moving = "INITQP_A_Sony_1";
[TestMethod]
[DataRow("mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("frammentato.mp4")]
[DataRow("senza-indice.avi")]
[DataRow("senza-indice-con-parametri.avi")]
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.IsTrue(es.Rank.Where((r, i) => r != i).Any(), "il flusso deve riordinare i fotogrammi");
using var temp = new TempFolder("fotogramma-hevc");
var data = kind switch
{
"mkv" => TestVideos.Matroska(es),
"avi" => TestVideos.Avi(es),
"senza-indice.avi" => TestVideos.Avi(es, index: false),
"senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false),
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
_ => TestVideos.Mp4(es),
};
var path = TestVideos.Write(temp, "video." + kind, data);
var container = ContainerReader.ReadFile(path, Now);
Assert.AreEqual(VideoCodec.Hevc, container!.Video!.Codec);
Assert.AreEqual(kind.EndsWith("avi", StringComparison.Ordinal), container.Video.AnnexB);
if (!container.Video.AnnexB)
{
CollectionAssert.AreEqual(es.AvcC, container.Video.HevcConfiguration, "hvcC del contenitore");
}
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
Assert.IsNotNull(image);
// AVI has no presentation times: there frames are shown in decoding order.
var position = Math.Min(30, es.Count - 1);
var rank = kind.EndsWith("avi", StringComparison.Ordinal) ? es.Rank[position] : position;
var reference = VideoFrameDecoder.ToImage(Shown(Moving)[rank], 0, 0);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
}
[TestMethod]
[DataRow("INITQP_B_Main10_Sony_1")]
[DataRow("WPP_B_ericsson_MAIN10_2")]
public async Task Main10VideosGiveTheirFrame(string name)
{
var es = ElementaryStream.LoadHevc(name);
using var temp = new TempFolder("fotogramma-hevc-10");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 270));
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero);
Assert.IsNotNull(image);
var reference = VideoFrameDecoder.ToImage(Shown(name)[0], 270, 0);
Assert.AreEqual(10, Shown(name)[0].BitDepthLuma);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
Assert.AreEqual((es.Height, es.Width), (image.Width, image.Height), "ruotato di un quarto");
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path);
Assert.IsNotNull(bmp);
Assert.AreEqual((byte)'B', bmp[0]);
}
[TestMethod]
public async Task AnHevcVideoOfAStillPictureIsRecognisedAndOneThatMovesIsNot()
{
var es = ElementaryStream.LoadHevc(Moving);
using var temp = new TempFolder("fermo-hevc");
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsStill);
Assert.AreEqual(0, result.Difference);
var moving = TestVideos.Write(temp, "movimento.mkv", TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4")));
var other = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(moving);
Assert.IsNotNull(other);
Assert.IsFalse(other.IsStill, $"differenza {other.Difference}");
}
[TestMethod]
public void AccessPointsAreTheIrapPictures()
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.LengthPrefixed(0), 4));
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.WithStartCodes(0), 0));
var inter = Enumerable.Range(0, es.Count).First(i => !es.Key[i]);
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint(es.LengthPrefixed(inter), 4));
// A CRA picture (NAL unit type 21): decoding starts there, its RASL pictures are lost.
byte[] cra = [0, 0, 0, 3, 21 << 1, 1, 0x80];
Assert.AreEqual(H265AccessPoint.Cra, H265Decoder.AccessPoint(cra, 4));
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint([0, 0, 0, 2, 34 << 1, 1], 4), "solo parametri");
}
[TestMethod]
public void TenBitFramesAndOtherChromaFormatsBecomeTheRightColours()
{
static H265Frame Flat(ushort y, ushort c, int format, int bits, int matrix, bool full)
{
var chroma = format == 0 ? 0 : format == 3 ? 4 : format == 2 ? 2 : 1;
return new(2, 2, format, bits, bits, [y, y, y, y], [.. Enumerable.Repeat(c, chroma)], [.. Enumerable.Repeat(c, chroma)], 0, 0, matrix, full);
}
// Limited range at 10 bits: 64 is black, 940 white.
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
// The same grey at 8, 10 and 12 bits, in every chroma format (4:0:0 has no chroma at all).
var grey = VideoFrameDecoder.ToImage(Flat(128, 128, 1, 8, 6, true), 0, 0).Rgb;
foreach (var format in new[] { 0, 1, 2, 3 })
{
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(512, 512, format, 10, 6, true), 0, 0).Rgb, $"formato {format}");
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(2048, 2048, format, 12, 6, true), 0, 0).Rgb, $"formato {format}, 12 bit");
}
// Pure red of BT.601 at 10 bits (limited range): Y 324, Cb 360, Cr 960.
var red = VideoFrameDecoder.ToImage(new H265Frame(2, 2, 1, 10, 10, [324, 324, 324, 324], [360], [960], 0, 0, 6, false), 0, 0).Rgb;
Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}");
}
/// <summary>The frames of a conformance stream in output order, decoded straight from its Annex B form.</summary>
private static List<H265Frame> Shown(string name)
{
var frames = new List<H265Frame>();
var decoder = new H265Decoder();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(name).BitstreamPath));
return frames;
}
}