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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 17:38:09 +01:00
1 parent 3cabd87316
commit ac85d1baed
21 files changed
+2695 -148

No files matched your search

+204 -120
View File
@@ -1,6 +1,9 @@
using System.Buffers.Binary;
using System.Numerics;
using Febe.Core.Codecs;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
namespace Febe.Core.Library;
@@ -51,9 +54,9 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff
/// <summary>
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
/// the container readers of <see cref="ContainerReader"/> and the H.264 decoder written in house
/// (<see cref="H264Decoder"/>). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the
/// neutral tile.
/// the container readers of <see cref="ContainerReader"/> and the H.264 and HEVC decoders written in house
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
/// interface shows the neutral tile.
/// </summary>
public sealed class VideoFrameDecoder
{
@@ -179,8 +182,10 @@ public sealed class VideoFrameDecoder
target = start;
}
var frames = decoding.Decode([target], ct);
if (!frames.TryGetValue(target, out var frame) && target != 0)
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
// of the HEVC CRA picture decoding starts from, a damaged sample).
var frames = decoding.Decode(start < target ? [start, target] : [target], ct);
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
{
frames = new Decoding(stream, video, maxRun).Decode([0], ct);
frames.TryGetValue(0, out frame);
@@ -282,17 +287,21 @@ public sealed class VideoFrameDecoder
}
}
private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or IOException or EndOfStreamException
or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException or InvalidOperationException
or OverflowException or InvalidDataException;
private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or H265Exception or IOException
or EndOfStreamException or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException
or InvalidOperationException or OverflowException or InvalidDataException;
/// <summary>The H.264 video track of a container with its samples; null for other codecs or without video.</summary>
/// <summary>The H.264 or HEVC video track of a container with its samples; null for other codecs or without video.</summary>
private static VideoTrack? Open(Stream stream)
{
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
var container = ContainerReader.Read(stream, AnyDate, samples: true);
return container?.Video is { Codec: VideoCodec.H264, Samples.Count: > 0 } video
&& (video.AnnexB || video.AvcConfiguration is not null)
return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
{
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
_ => false,
}
? video
: null;
}
@@ -342,15 +351,97 @@ public sealed class VideoFrameDecoder
return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys];
}
/// <summary>Where decoding can start, whatever the codec.</summary>
private enum StartPoint
{
/// <summary>Decoding cannot start here.</summary>
None,
/// <summary>Close: an H.264 picture of I slices that is not IDR, an HEVC CRA picture (its RASL pictures are lost).</summary>
Intra,
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
Idr,
}
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
private static int LengthSize(VideoTrack video)
{
if (video.AnnexB)
{
return 0;
}
return video.Codec == VideoCodec.Hevc
? video.HevcConfiguration is { Length: > 21 } hvcC ? (hvcC[21] & 3) + 1 : 4
: video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4;
}
/// <summary>A decoded frame of either codec.</summary>
private sealed class Frame(H264Frame? avc, H265Frame? hevc)
{
internal H264Frame? Avc { get; } = avc;
internal H265Frame? Hevc { get; } = hevc;
}
/// <summary>The decoder of the track's codec, configured from its configuration record.</summary>
private sealed class Runner
{
private readonly H264Decoder? avc;
private readonly H265Decoder? hevc;
private readonly int lengthSize;
internal Runner(VideoTrack video, Func<bool> wanted, Action<Frame> found)
{
if (video.Codec == VideoCodec.Hevc)
{
hevc = new H265Decoder { Wanted = _ => wanted() };
hevc.FrameDecoded += frame => found(new Frame(null, frame));
lengthSize = video.AnnexB ? 0 : hevc.ConfigureHvcC(video.HevcConfiguration);
}
else
{
avc = new H264Decoder { Wanted = _ => wanted() };
avc.FrameDecoded += frame => found(new Frame(frame, null));
lengthSize = video.AnnexB ? 0 : avc.ConfigureAvcC(video.AvcConfiguration);
}
}
internal void Decode(ReadOnlySpan<byte> sample)
{
if (hevc is not null)
{
if (lengthSize == 0)
{
hevc.DecodeAccessUnitAnnexB(sample);
}
else
{
hevc.DecodeSample(sample, lengthSize);
}
}
else if (lengthSize == 0)
{
avc!.DecodeAccessUnitAnnexB(sample);
}
else
{
avc!.DecodeSample(sample, lengthSize);
}
}
}
/// <summary>
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
/// </summary>
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
{
private readonly Dictionary<int, H264Frame> found = [];
private readonly Dictionary<int, Frame> found = [];
private readonly HashSet<int> wanted = [];
private readonly int[] keys = KeyIndices(video);
private readonly Dictionary<int, H264AccessPoint> accessPoints = [];
private readonly Dictionary<int, StartPoint> accessPoints = [];
private readonly int lengthSize = LengthSize(video);
private byte[] buffer = new byte[64 * 1024];
/// <summary>The sample being decoded: the picture it finishes is that sample's frame.</summary>
@@ -360,9 +451,9 @@ public sealed class VideoFrameDecoder
/// The sample where decoding for <paramref name="index"/> starts. A container without an index (an AVI cut short,
/// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give
/// a corrupt picture, or none: so the samples flagged as key are looked at, from the nearest one back. The nearest
/// IDR picture is taken when it is within the run limit (the frame comes out exact); otherwise the nearest
/// picture of I slices (close, though pictures after it may refer to earlier ones); otherwise the IDR picture
/// further back, or the first sample.
/// exact start (an IDR picture, or an HEVC BLA picture) is taken when it is within the run limit (the frame comes
/// out exact); otherwise the nearest close one (an H.264 picture of I slices, an HEVC CRA picture: close, though
/// pictures after it may refer to earlier ones); otherwise the exact start further back, or the first sample.
/// </summary>
internal int RunStart(int index)
{
@@ -378,90 +469,91 @@ public sealed class VideoFrameDecoder
accessPoints[candidate] = point;
}
if (point == H264AccessPoint.Idr)
if (point == StartPoint.Idr)
{
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
}
if (point == H264AccessPoint.IntraPicture && intra < 0)
if (point == StartPoint.Intra && intra < 0)
{
intra = candidate;
}
if (index - candidate > maxRun && intra >= 0)
{
return intra; // no IDR picture within reach: the nearest picture of I slices
return intra; // no exact start within reach: the nearest close one
}
}
// The first sample, where every stream starts (or the end of the search): it counts as an IDR picture.
// The first sample, where every stream starts (or the end of the search): it counts as an exact start.
return index <= maxRun || intra < 0 ? 0 : intra;
}
private H264AccessPoint AccessPointOf(int index)
private StartPoint AccessPointOf(int index)
{
try
{
var sample = ContainerReader.ReadSample(stream, video.Samples[index], ref buffer);
var lengthSize = video.AnnexB ? 0 : video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4;
return H264Decoder.AccessPoint(sample, lengthSize);
if (video.Codec == VideoCodec.Hevc)
{
return H265Decoder.AccessPoint(sample, lengthSize) switch
{
H265AccessPoint.Idr => StartPoint.Idr,
H265AccessPoint.Cra => StartPoint.Intra,
_ => StartPoint.None,
};
}
return H264Decoder.AccessPoint(sample, lengthSize) switch
{
H264AccessPoint.Idr => StartPoint.Idr,
H264AccessPoint.IntraPicture => StartPoint.Intra,
_ => StartPoint.None,
};
}
catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException)
{
return H264AccessPoint.None;
return StartPoint.None;
}
}
internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct)
internal Dictionary<int, Frame> Decode(int[] targets, CancellationToken ct)
{
foreach (var t in targets)
{
wanted.Add(t);
}
H264Decoder? decoder = null;
Runner? runner = null;
var next = 0;
var lengthSize = 4;
foreach (var target in targets)
{
var key = RunStart(target);
if (decoder is null || next > target || key >= next)
if (runner is null || next > target || key >= next)
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
// sample without a picture (only parameter sets, or damaged) must not shift the frames after it.
decoder = new H264Decoder { Wanted = _ => wanted.Contains(current) };
decoder.FrameDecoded += frame => found.TryAdd(current, frame);
runner = null;
next = key;
}
try
{
if (next == key && !video.AnnexB)
{
lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
}
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
// sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift
// the frames after it.
runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
for (; next <= target; next++)
{
ct.ThrowIfCancellationRequested();
current = next;
var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer);
if (video.AnnexB)
{
decoder.DecodeAccessUnitAnnexB(sample);
}
else
{
decoder.DecodeSample(sample, lengthSize);
}
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer));
}
}
catch (Exception ex) when (ex is H264Exception or ContainerException or EndOfStreamException or IndexOutOfRangeException
or ArgumentException or InvalidOperationException)
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
// This run is damaged (or its samples lie past the end of a truncated file): the next target starts
// again from its own key frame, and what was decoded so far stands.
decoder = null;
runner = null;
}
}
@@ -470,34 +562,50 @@ public sealed class VideoFrameDecoder
}
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
private static double[] Grid(H264Frame frame)
private static double[] Grid(Frame frame) => frame.Hevc is { } h ? Grid(Planes(h)) : Grid(Planes(frame.Avc!));
/// <summary>
/// The grid on an 8-bit scale: luma means in the first half, mean distances of the chroma from its middle in the
/// second (zero for a monochrome picture).
/// </summary>
private static double[] Grid<T>(in YuvPlanes<T> frame)
where T : unmanaged, IBinaryInteger<T>
{
var grid = new double[GridSize * GridSize * 2];
var counts = new int[GridSize * GridSize];
var lumaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthY - 8));
ReadOnlySpan<T> luma = frame.Y;
for (var y = 0; y < frame.Height; y++)
{
var gy = y * GridSize / frame.Height;
var row = frame.Y.AsSpan(y * frame.Width, frame.Width);
var row = luma.Slice(y * frame.Width, frame.Width);
for (var x = 0; x < row.Length; x++)
{
var cell = (gy * GridSize) + (x * GridSize / frame.Width);
grid[cell] += row[x];
grid[cell] += int.CreateTruncating(row[x]) * lumaScale;
counts[cell]++;
}
}
var cw = (frame.Width + 1) / 2;
var ch = (frame.Height + 1) / 2;
var chromaCounts = new int[GridSize * GridSize];
for (var y = 0; y < ch; y++)
if (!frame.Monochrome)
{
var gy = y * GridSize / ch;
for (var x = 0; x < cw; x++)
var cw = frame.ChromaWidth;
var ch = (frame.Height + (1 << frame.ChromaShiftY) - 1) >> frame.ChromaShiftY;
var middle = 1 << (frame.BitDepthC - 1);
var chromaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthC - 8)) / 2;
ReadOnlySpan<T> cb = frame.Cb, cr = frame.Cr;
for (var y = 0; y < ch; y++)
{
var cell = (gy * GridSize) + (x * GridSize / cw);
var i = (y * cw) + x;
grid[(GridSize * GridSize) + cell] += (Math.Abs(frame.Cb[i] - 128) + Math.Abs(frame.Cr[i] - 128)) / 2.0;
chromaCounts[cell]++;
var gy = y * GridSize / ch;
for (var x = 0; x < cw; x++)
{
var cell = (gy * GridSize) + (x * GridSize / cw);
var i = (y * cw) + x;
grid[(GridSize * GridSize) + cell] +=
(Math.Abs(int.CreateTruncating(cb[i]) - middle) + Math.Abs(int.CreateTruncating(cr[i]) - middle)) * chromaScale;
chromaCounts[cell]++;
}
}
}
@@ -511,80 +619,56 @@ public sealed class VideoFrameDecoder
return grid;
}
private static YuvPlanes<byte> Planes(H264Frame frame) =>
new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, 1, 1, false, 8, 8);
private static YuvPlanes<ushort> Planes(H265Frame frame)
{
var (sx, sy) = frame.ChromaFormat switch
{
1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma);
}
private static VideoImage ToImage(Frame frame, int rotation, int maxLongSide) =>
frame.Hevc is { } h ? ToImage(h, rotation, maxLongSide) : ToImage(frame.Avc!, rotation, maxLongSide);
/// <summary>
/// The frame in RGB: BT.709 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited
/// or full range, reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide)
{
var (kr, kb) = frame.MatrixCoefficients switch
{
1 => (0.2126, 0.0722),
4 => (0.30, 0.11),
5 or 6 => (0.299, 0.114),
7 => (0.212, 0.087),
9 or 10 => (0.2627, 0.0593),
_ => frame.Height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114),
};
var kg = 1 - kr - kb;
var yScale = frame.FullRange ? 1.0 : 255.0 / 219.0;
var cScale = frame.FullRange ? 1.0 : 255.0 / 224.0;
var yOffset = frame.FullRange ? 0 : 16;
const int Shift = 16;
const double One = 1 << Shift;
var cy = (int)Math.Round(yScale * One);
var crR = (int)Math.Round(2 * (1 - kr) * cScale * One);
var cbB = (int)Math.Round(2 * (1 - kb) * cScale * One);
var cbG = (int)Math.Round(2 * kb * (1 - kb) / kg * cScale * One);
var crG = (int)Math.Round(2 * kr * (1 - kr) / kg * cScale * One);
const int Half = 1 << (Shift - 1);
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) =>
ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
/// <summary>
/// An HEVC frame in RGB, as <see cref="ToImage(H264Frame, int, int)"/>: any chroma format (4:0:0 in grey) and bit
/// depth, brought to 8 bits.
/// </summary>
internal static VideoImage ToImage(H265Frame frame, int rotation, int maxLongSide) =>
ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
private static VideoImage ToImage<T>(in YuvPlanes<T> planes, int matrix, bool fullRange, int rotation, int maxLongSide)
where T : unmanaged, IBinaryInteger<T>
{
var factor = 1;
if (maxLongSide > 0)
{
var longSide = Math.Max(frame.Width, frame.Height);
var longSide = Math.Max(planes.Width, planes.Height);
factor = Math.Max(1, (longSide + maxLongSide - 1) / maxLongSide);
}
var width = Math.Max(1, frame.Width / factor);
var height = Math.Max(1, frame.Height / factor);
var width = Math.Max(1, planes.Width / factor);
var height = Math.Max(1, planes.Height / factor);
factor = Math.Min(factor, Math.Min(planes.Width, planes.Height)); // a frame thinner than the factor
var rgb = new byte[width * height * 3];
var cw = (frame.Width + 1) / 2;
var area = factor * factor;
for (var oy = 0; oy < height; oy++)
{
for (var ox = 0; ox < width; ox++)
{
int r = 0, g = 0, b = 0;
for (var dy = 0; dy < factor; dy++)
{
var y = (oy * factor) + dy;
var lumaRow = y * frame.Width;
var chromaRow = (y >> 1) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var l = (frame.Y[lumaRow + x] - yOffset) * cy;
var u = frame.Cb[chromaRow + (x >> 1)] - 128;
var v = frame.Cr[chromaRow + (x >> 1)] - 128;
r += Clip((l + (crR * v) + Half) >> Shift);
g += Clip((l - (cbG * u) - (crG * v) + Half) >> Shift);
b += Clip((l + (cbB * u) + Half) >> Shift);
}
}
var o = ((oy * width) + ox) * 3;
rgb[o] = (byte)(r / area);
rgb[o + 1] = (byte)(g / area);
rgb[o + 2] = (byte)(b / area);
}
}
var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
YuvToRgb.Convert(planes, k, factor, rgb, width * 3, 3, width, height);
return Rotate(new VideoImage(width, height, rgb), rotation);
}
private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
private static VideoImage Rotate(VideoImage image, int rotation)
{
rotation = ((rotation % 360) + 360) % 360;