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

@@ -266,6 +266,7 @@ public static class IsoBmffReader
internal int Channels;
internal int SampleRate;
internal byte[]? Avcc;
internal byte[]? Hvcc;
internal byte[]? Asc;
internal long EditOffset;
internal List<MediaSample> Samples = [];
@@ -505,6 +506,10 @@ public static class IsoBmffReader
{
track.Avcc = data[s..(s + c)];
}
else if (t == "hvcC")
{
track.Hvcc = data[s..(s + c)];
}
}
}
else if (track.Handler == "soun" && size >= 8 + 28)
@@ -925,6 +930,7 @@ public static class IsoBmffReader
Timescale = video.Timescale > 0 ? video.Timescale : 1,
Duration = DurationOf(video),
AvcConfiguration = video.Avcc,
HevcConfiguration = video.Hvcc,
Samples = video.Samples,
};
}
@@ -595,6 +595,7 @@ public static class MatroskaReader
Height = v.Height,
Rotation = roll is 90 or 180 or 270 ? roll : 0,
AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null,
HevcConfiguration = v.CodecId == "V_MPEGH/ISO/HEVC" ? v.CodecPrivate : null,
Timescale = timescale,
Duration = trackUnits,
Samples = samples,
@@ -13,7 +13,7 @@ public enum ContainerFormat
Avi,
}
/// <summary>Video codecs recognised in a container; only <see cref="H264"/> can be decoded.</summary>
/// <summary>Video codecs recognised in a container; <see cref="H264"/> and <see cref="Hevc"/> can be decoded.</summary>
public enum VideoCodec
{
Unknown,
@@ -79,6 +79,13 @@ public sealed class VideoTrack : MediaTrack
/// <summary>The AVCDecoderConfigurationRecord (<c>avcC</c>) of an H.264 track stored with length prefixes.</summary>
public byte[]? AvcConfiguration { get; init; }
/// <summary>
/// The HEVCDecoderConfigurationRecord (<c>hvcC</c>, ISO/IEC 14496-15 §8.3.3) of an HEVC track stored with length
/// prefixes: the <c>hvcC</c> box of an <c>hvc1</c> or <c>hev1</c> sample entry, the CodecPrivate of a Matroska
/// <c>V_MPEGH/ISO/HEVC</c> track.
/// </summary>
public byte[]? HevcConfiguration { get; init; }
/// <summary>True when the samples are an Annex B byte stream (start codes), as in AVI.</summary>
public bool AnnexB { get; init; }
+12 -5
View File
@@ -6,7 +6,10 @@ namespace Febe.Core.Codecs.Containers;
/// <summary>A sample to write: its size, its times in track units, whether it is a sync sample.</summary>
public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key);
/// <summary>A track to write: H.264 video (with its <c>avcC</c>) or AAC audio (with its AudioSpecificConfig).</summary>
/// <summary>
/// A track to write: H.264 video (with its <c>avcC</c>), HEVC video (with its <c>hvcC</c>, as an <c>hvc1</c> sample entry) or
/// AAC audio (with its AudioSpecificConfig).
/// </summary>
public sealed class Mp4OutputTrack
{
public required bool IsVideo { get; init; }
@@ -27,6 +30,9 @@ public sealed class Mp4OutputTrack
public byte[]? AvcConfiguration { get; init; }
/// <summary>The <c>hvcC</c> of an HEVC video track (then <see cref="AvcConfiguration"/> stays null).</summary>
public byte[]? HevcConfiguration { get; init; }
public byte[]? AacConfiguration { get; init; }
public int SampleRate { get; init; }
@@ -59,7 +65,7 @@ public static class Mp4Writer
foreach (var track in tracks)
{
if (track.IsVideo ? track.AvcConfiguration is null : track.AacConfiguration is null)
if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null)
{
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
}
@@ -533,7 +539,8 @@ public static class Mp4Writer
private static Box Avc1(Mp4OutputTrack track)
{
var entry = new Box("avc1");
var hevc = track.HevcConfiguration is not null;
var entry = new Box(hevc ? "hvc1" : "avc1");
entry.Zero(6);
entry.U16(1);
entry.Zero(16);
@@ -546,8 +553,8 @@ public static class Mp4Writer
entry.Zero(32);
entry.U16(0x0018);
entry.U16(0xFFFF);
var avcC = new Box("avcC");
avcC.Bytes(track.AvcConfiguration);
var avcC = new Box(hevc ? "hvcC" : "avcC");
avcC.Bytes(hevc ? track.HevcConfiguration : track.AvcConfiguration);
entry.Child(avcC);
return entry;
}
+80
View File
@@ -2,6 +2,19 @@ using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.H265;
/// <summary>What an access unit offers to start decoding from (see <see cref="H265Decoder.AccessPoint"/>).</summary>
public enum H265AccessPoint
{
/// <summary>A picture that is not IRAP, or no picture: decoding cannot start here.</summary>
None,
/// <summary>A CRA picture: decoding starts here, but its RASL pictures (shown before it) are skipped.</summary>
Cra,
/// <summary>An IDR or BLA picture: nothing decoded after it refers to anything before.</summary>
Idr,
}
/// <summary>
/// An HEVC (ITU-T H.265 | ISO/IEC 23008-2) decoder written from the Recommendation, for the Main, Main 10 and Main Still
/// Picture profiles and the format range extensions up to 12 bits: 4:0:0, 4:2:0, 4:2:2 and 4:4:4, tiles, wavefronts,
@@ -50,6 +63,16 @@ public sealed partial class H265Decoder
/// <summary>Raised for each frame in output order (the bumping process of C.5.2.4), cropped.</summary>
public event Action<H265Frame>? FrameOutput;
/// <summary>
/// Raised for each picture once decoded and filtered, in decoding order and cropped, when <see cref="Wanted"/> accepts
/// its decoding index: a caller that maps pictures to the samples of a container takes them here, without waiting for
/// the output order. Pictures with pic_output_flag 0 are raised too.
/// </summary>
public event Action<H265Frame>? FrameDecoded;
/// <summary>Which pictures <see cref="FrameDecoded"/> hands out, by decoding index; null hands out all of them.</summary>
public Func<long, bool>? Wanted { get; set; }
/// <summary>Raised for each picture once decoded and filtered, in decoding order (for the decoded picture hash).</summary>
internal event Action<Picture>? PictureDecoded;
@@ -125,6 +148,58 @@ public sealed partial class H265Decoder
FinishPicture();
}
/// <summary>Decodes one access unit in Annex B form (an AVI chunk, a PES packet) and finishes its picture.</summary>
public void DecodeAccessUnitAnnexB(ReadOnlySpan<byte> accessUnit)
{
var position = 0;
while (NalUnits.NextAnnexB(accessUnit, ref position, out var unit))
{
Decode(accessUnit[unit]);
}
FinishPicture();
}
/// <summary>
/// Whether decoding can start at this access unit (§8.1.3): exactly at an IDR or BLA picture; at a CRA picture too,
/// but then its RASL pictures, which follow it in decoding order and refer to pictures before it, are not decoded.
/// <paramref name="lengthSize"/> is the size of the NAL length fields, 0 for Annex B.
/// </summary>
public static H265AccessPoint AccessPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
{
var position = 0;
while (true)
{
Range unit;
var more = lengthSize == 0
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
if (!more)
{
return H265AccessPoint.None;
}
var nal = accessUnit[unit];
if (nal.Length < 3 || (nal[0] & 0x80) != 0 || (((nal[0] & 1) << 5) | (nal[1] >> 3)) != 0)
{
continue; // too short, forbidden bit set, or a layer above 0
}
var type = (nal[0] >> 1) & 63;
if (type > 31)
{
continue; // parameter sets, SEI, delimiters: the picture comes after them
}
return type switch
{
>= 16 and <= 20 => H265AccessPoint.Idr,
21 => H265AccessPoint.Cra,
_ => H265AccessPoint.None,
};
}
}
/// <summary>Finishes the picture being decoded and outputs every picture still waiting, in output order.</summary>
public void Flush()
{
@@ -560,6 +635,11 @@ public sealed partial class H265Decoder
}
PictureDecoded?.Invoke(picture);
if (FrameDecoded is { } decoded && (Wanted?.Invoke(picture.DecodeIndex) ?? true))
{
decoded(picture.ToFrame());
}
foreach (var other in dpb)
{
if (other.NeededForOutput)
+617
View File
@@ -0,0 +1,617 @@
using System.Buffers.Binary;
using System.Text;
using Febe.Core.Codecs.H265;
namespace Febe.Core.Codecs.Heif;
/// <summary>
/// Decoder of HEIF still images with HEVC pictures (HEIC, ISO/IEC 23008-12), written from the standard on the HEVC
/// decoder of <see cref="H265Decoder"/>: the primary item, coded (<c>hvc1</c>) or a grid of coded tiles (<c>grid</c>, as
/// phones write their photos), its colour (<c>colr</c> nclx, otherwise the VUI of the pictures), its alpha plane (an
/// auxiliary image), the clean aperture (<c>clap</c>), rotation and mirroring (<c>irot</c>, <c>imir</c>, returned as an
/// orientation), and the EXIF block (<c>Exif</c> item). Not handled (a <see cref="HeifException"/>): images of other
/// codecs (AVIF, JPEG), derived images other than grids (overlays, identity), image sequences (<c>moov</c> only),
/// protected items, and essential properties Febe does not know.
/// </summary>
public static class HeifDecoder
{
private const string AlphaHevc = "urn:mpeg:hevc:2015:auxid:1";
private const string AlphaCicp = "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha";
/// <summary>Properties Febe knows: an essential property outside these makes an item undecodable (§6.5.2).</summary>
private static readonly HashSet<uint> Known =
[
HeifFile.HvcC, HeifFile.Ispe, HeifFile.Colr, HeifFile.Irot, HeifFile.Imir, HeifFile.Clap, HeifFile.AuxC, HeifFile.Pixi,
0x70617370, // 'pasp'
0x636C6C69, // 'clli'
0x6D646376, // 'mdcv'
0x72726566, // 'rref'
];
/// <summary>True when the first bytes are those of a HEIF file of still images (an <c>ftyp</c> with a HEIF brand).</summary>
public static bool Looks(ReadOnlySpan<byte> start) => HeifFile.Looks(start);
/// <summary>Size, orientation and alpha of the primary image, without decoding it.</summary>
public static HeifInfo ReadInfo(Stream stream, HeifLimits? limits = null)
{
ArgumentNullException.ThrowIfNull(stream);
limits ??= HeifLimits.Default;
return Guard(() =>
{
var file = HeifFile.Read(stream, limits);
var primary = Primary(file);
var (width, height, tiles) = CodedSize(stream, file, primary, limits);
var crop = CleanAperture(file, primary, width, height);
return new HeifInfo(crop.Width, crop.Height, OrientationOf(file, primary), AlphaOf(file, primary) is not null, tiles);
});
}
/// <summary>Decodes the primary image of a seekable stream.</summary>
public static HeifImage Decode(Stream stream, HeifLimits? limits = null)
{
ArgumentNullException.ThrowIfNull(stream);
limits ??= HeifLimits.Default;
return Guard(() => DecodePrimary(stream, limits));
}
/// <summary>Decodes the primary image of a whole file in memory.</summary>
public static HeifImage Decode(byte[] data, HeifLimits? limits = null)
{
ArgumentNullException.ThrowIfNull(data);
using var stream = new MemoryStream(data, writable: false);
return Decode(stream, limits);
}
/// <summary>
/// The EXIF block (a TIFF structure) of the primary image of a HEIF file whose first bytes are
/// <paramref name="head"/>; null when there is none, the file is not HEIF, or the block lies past those bytes.
/// </summary>
public static byte[]? FindExif(ReadOnlySpan<byte> head)
{
if (!HeifFile.Looks(head))
{
return null;
}
using var stream = new MemoryStream(head.ToArray(), writable: false);
try
{
var file = HeifFile.Read(stream, HeifLimits.Default);
return ExifOf(stream, file, file.Item(file.PrimaryId), HeifLimits.Default);
}
catch (Exception ex) when (ex is HeifException or EndOfStreamException or ArgumentException or IndexOutOfRangeException
or OverflowException or InvalidOperationException)
{
return null;
}
}
/// <summary>Runs <paramref name="work"/>, turning every sign of a damaged file into a <see cref="HeifException"/>.</summary>
private static T Guard<T>(Func<T> work)
{
try
{
return work();
}
catch (H265Exception ex)
{
throw new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.Message);
}
catch (AggregateException ex) when (ex.InnerException is H265Exception or HeifException)
{
throw ex.InnerException is HeifException heif ? heif : new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.InnerException.Message);
}
catch (Exception ex) when (ex is EndOfStreamException or ArgumentException or IndexOutOfRangeException or OverflowException
or InvalidOperationException)
{
throw new HeifException("File HEIF troncato o danneggiato.");
}
}
private static HeifItem Primary(HeifFile file)
{
var primary = file.Item(file.PrimaryId) ?? throw new HeifException("Manca l'immagine principale HEIF.");
CheckDecodable(file, primary);
return primary;
}
private static void CheckDecodable(HeifFile file, HeifItem item)
{
if (item.Type is not (HeifFile.Hvc1 or HeifFile.Grid))
{
throw new HeifException(item.Type == 0x61763031 // 'av01'
? "Immagine AVIF: il codec AV1 non è gestito."
: "Tipo di immagine HEIF non gestito.");
}
foreach (var (index, essential) in item.Properties)
{
if (essential && (index >= file.Properties.Count || !Known.Contains(file.Properties[index].Type)))
{
throw new HeifException("Proprietà essenziale HEIF non gestita.");
}
}
}
/// <summary>The grid description of §6.6.2.3.1: rows, columns, output size.</summary>
private static (int Rows, int Columns, int Width, int Height) GridOf(Stream stream, HeifFile file, HeifItem grid, HeifLimits limits)
{
var data = file.ReadItem(stream, grid, limits);
if (data.Length < 8 || data[0] != 0)
{
throw new HeifException("Descrizione della griglia HEIF non valida.");
}
var wide = (data[1] & 1) != 0;
var rows = data[2] + 1;
var columns = data[3] + 1;
int width, height;
if (wide)
{
if (data.Length < 12)
{
throw new HeifException("Descrizione della griglia HEIF troncata.");
}
width = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4)), int.MaxValue);
height = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(8)), int.MaxValue);
}
else
{
width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(4));
height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(6));
}
if (rows * columns > limits.MaxTiles || grid.DerivedFrom.Count != rows * columns)
{
throw new HeifException("Tessere della griglia HEIF mancanti o in eccesso.");
}
return (rows, columns, width, height);
}
/// <summary>The size of an image before the clean aperture: of the grid output, or of the coded picture.</summary>
private static (int Width, int Height, int Tiles) CodedSize(Stream stream, HeifFile file, HeifItem item, HeifLimits limits)
{
int width, height, tiles = 1;
if (item.Type == HeifFile.Grid)
{
(var rows, var columns, width, height) = GridOf(stream, file, item, limits);
tiles = rows * columns;
}
else
{
(width, height) = Ispe(file, item) ?? throw new HeifException("Manca la dimensione (ispe) dell'immagine HEIF.");
}
if (width <= 0 || height <= 0 || (long)width * height > Math.Min(limits.MaxPixels, Array.MaxLength / 4))
{
throw new HeifException("Dimensioni dell'immagine HEIF non valide o eccessive.");
}
return (width, height, tiles);
}
private static (int Width, int Height)? Ispe(HeifFile file, HeifItem item)
{
if (file.Property(item, HeifFile.Ispe) is not { } p)
{
return null;
}
var body = file.Body(p);
return ((int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(body[4..]), int.MaxValue),
(int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(body[8..]), int.MaxValue));
}
private static HeifImage DecodePrimary(Stream stream, HeifLimits limits)
{
var file = HeifFile.Read(stream, limits);
var primary = Primary(file);
var (width, height, _) = CodedSize(stream, file, primary, limits);
var pixels = new byte[(long)width * height * 4];
var bitDepth = 8;
var nclx = Nclx(file, primary);
DecodeImage(stream, file, primary, limits, (frame, x0, y0) =>
{
var w = Math.Min(frame.Width, width - x0);
var h = Math.Min(frame.Height, height - y0);
if (w <= 0 || h <= 0)
{
return;
}
bitDepth = frame.BitDepthLuma;
var planes = Planes(frame);
var (matrix, full) = nclx ?? (frame.MatrixCoefficients, frame.FullRange);
var k = YuvToRgb.For(matrix, full, frame.BitDepthLuma, frame.BitDepthChroma, frame.Height);
YuvToRgb.Convert(planes, k, 1, pixels.AsSpan(((y0 * width) + x0) * 4), width * 4, 4, w, h);
});
var hasAlpha = false;
if (AlphaOf(file, primary) is { } alpha)
{
try
{
CheckDecodable(file, alpha);
var (aw, ah, _) = CodedSize(stream, file, alpha, limits);
if (aw == width && ah == height)
{
DecodeImage(stream, file, alpha, limits, (frame, x0, y0) => WriteAlpha(frame, pixels, width, height, x0, y0));
hasAlpha = true;
}
}
catch (HeifException)
{
// An alpha plane that cannot be decoded: the image stands, opaque.
}
}
var crop = CleanAperture(file, primary, width, height);
if (crop != (0, 0, width, height))
{
var cropped = new byte[(long)crop.Width * crop.Height * 4];
for (var y = 0; y < crop.Height; y++)
{
pixels.AsSpan((((crop.Top + y) * width) + crop.Left) * 4, crop.Width * 4).CopyTo(cropped.AsSpan(y * crop.Width * 4));
}
(pixels, width, height) = (cropped, crop.Width, crop.Height);
}
var exif = ExifOf(stream, file, primary, limits);
return new HeifImage(width, height, pixels)
{
Orientation = OrientationOf(file, primary),
HasAlpha = hasAlpha,
BitDepth = bitDepth,
Exif = exif,
ExifOrientation = exif is null ? 1 : ExifOrientationOf(exif),
IccProfile = IccOf(file, primary),
};
}
/// <summary>
/// Decodes a coded image or the tiles of a grid, handing each picture to <paramref name="place"/> with the position
/// of its top-left sample in the image. Tiles are decoded on several threads; <paramref name="place"/> writes
/// disjoint areas.
/// </summary>
private static void DecodeImage(Stream stream, HeifFile file, HeifItem item, HeifLimits limits, Action<H265Frame, int, int> place)
{
if (item.Type == HeifFile.Hvc1)
{
var frame = DecodeTile(new H265Decoder(), file, item, file.ReadItem(stream, item, limits));
place(frame, 0, 0);
return;
}
var (_, columns, _, _) = GridOf(stream, file, item, limits);
var tiles = new HeifItem[item.DerivedFrom.Count];
var data = new byte[tiles.Length][];
for (var i = 0; i < tiles.Length; i++)
{
tiles[i] = file.Item(item.DerivedFrom[i]) ?? throw new HeifException("Tessera della griglia HEIF mancante.");
if (tiles[i].Type != HeifFile.Hvc1)
{
throw new HeifException("Tessera della griglia HEIF non HEVC.");
}
CheckDecodable(file, tiles[i]);
data[i] = file.ReadItem(stream, tiles[i], limits); // the stream is read here, by one thread only
}
// Every tile has the size of the first (§6.6.2.3.1): its ispe, or the first decoded picture.
var first = DecodeTile(new H265Decoder(), file, tiles[0], data[0]);
var (tileWidth, tileHeight) = Ispe(file, tiles[0]) ?? (first.Width, first.Height);
place(first, 0, 0);
var options = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, limits.MaxParallelism) };
Parallel.For(1, tiles.Length, options, () => new H265Decoder(), (i, _, decoder) =>
{
var frame = DecodeTile(decoder, file, tiles[i], data[i]);
place(frame, i % columns * tileWidth, i / columns * tileHeight);
return decoder;
}, _ => { });
}
/// <summary>One coded picture: its <c>hvcC</c>, then its sample of length-prefixed NAL units.</summary>
private static H265Frame DecodeTile(H265Decoder decoder, HeifFile file, HeifItem item, byte[] data)
{
var hvcC = file.Property(item, HeifFile.HvcC) ?? throw new HeifException("Manca la configurazione hvcC dell'immagine HEIF.");
H265Frame? frame = null;
void Take(H265Frame f) => frame ??= f;
decoder.FrameDecoded += Take;
try
{
var lengthSize = decoder.ConfigureHvcC(file.Body(hvcC));
decoder.DecodeSample(data, lengthSize);
decoder.Flush();
}
finally
{
decoder.FrameDecoded -= Take;
}
return frame ?? throw new HeifException("Nessuna immagine nei dati HEVC dell'elemento HEIF.");
}
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);
}
/// <summary>The luma of an alpha picture into the alpha bytes: full range as is, limited range stretched.</summary>
private static void WriteAlpha(H265Frame frame, byte[] pixels, int width, int height, int x0, int y0)
{
var w = Math.Min(frame.Width, width - x0);
var h = Math.Min(frame.Height, height - y0);
var shift = Math.Max(0, frame.BitDepthLuma - 8);
var offset = 16 << shift;
var scale = (int)Math.Round(255.0 / 219.0 / (1 << shift) * 65536);
for (var y = 0; y < h; y++)
{
var source = frame.Y.AsSpan(y * frame.Width, w);
var target = pixels.AsSpan(((((y0 + y) * width) + x0) * 4) + 3);
for (var x = 0; x < source.Length; x++)
{
var v = frame.FullRange ? source[x] >> shift : (((source[x] - offset) * scale) + 32768) >> 16;
target[x * 4] = (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
}
}
}
/// <summary>The alpha plane of an image: an item that is its auxiliary image (<c>auxl</c>) of the alpha type.</summary>
private static HeifItem? AlphaOf(HeifFile file, HeifItem image)
{
foreach (var item in file.Items)
{
if (!item.AuxiliaryOf.Contains(image.Id) || file.Property(item, HeifFile.AuxC) is not { } auxC)
{
continue;
}
var body = file.Body(auxC)[4..];
var end = body.IndexOf((byte)0);
var type = Encoding.ASCII.GetString(end >= 0 ? body[..end] : body);
if (type is AlphaHevc or AlphaCicp)
{
return item;
}
}
return null;
}
/// <summary>matrix_coefficients and full_range_flag of an nclx <c>colr</c> property, of the image or its first tile.</summary>
private static (int Matrix, bool Full)? Nclx(HeifFile file, HeifItem image)
{
foreach (var candidate in ColourCarriers(file, image))
{
foreach (var (index, _) in candidate.Properties)
{
var p = index < file.Properties.Count ? file.Properties[index] : default;
if (p.Type != HeifFile.Colr || p.Length < 11)
{
continue;
}
var body = file.Body(p);
if (body[..4].SequenceEqual("nclx"u8))
{
return (BinaryPrimitives.ReadUInt16BigEndian(body[8..]), (body[10] & 0x80) != 0);
}
}
}
return null;
}
private static byte[]? IccOf(HeifFile file, HeifItem image)
{
foreach (var candidate in ColourCarriers(file, image))
{
foreach (var (index, _) in candidate.Properties)
{
var p = index < file.Properties.Count ? file.Properties[index] : default;
if (p.Type == HeifFile.Colr && p.Length > 4)
{
var body = file.Body(p);
if (body[..4].SequenceEqual("prof"u8) || body[..4].SequenceEqual("rICC"u8))
{
return body[4..].ToArray();
}
}
}
}
return null;
}
private static IEnumerable<HeifItem> ColourCarriers(HeifFile file, HeifItem image)
{
yield return image;
if (image.DerivedFrom.Count > 0 && file.Item(image.DerivedFrom[0]) is { } tile)
{
yield return tile;
}
}
/// <summary>
/// The clean aperture of ISO/IEC 14496-12 §12.1.4: a rectangle centred on the picture centre moved by the offsets;
/// the whole image when there is none or it does not fit.
/// </summary>
private static (int Left, int Top, int Width, int Height) CleanAperture(HeifFile file, HeifItem image, int width, int height)
{
if (file.Property(image, HeifFile.Clap) is not { Length: >= 32 } p)
{
return (0, 0, width, height);
}
var body = file.Body(p);
var cw = Ratio(BinaryPrimitives.ReadUInt32BigEndian(body), BinaryPrimitives.ReadUInt32BigEndian(body[4..]));
var ch = Ratio(BinaryPrimitives.ReadUInt32BigEndian(body[8..]), BinaryPrimitives.ReadUInt32BigEndian(body[12..]));
var ho = Ratio(BinaryPrimitives.ReadInt32BigEndian(body[16..]), BinaryPrimitives.ReadUInt32BigEndian(body[20..]));
var vo = Ratio(BinaryPrimitives.ReadInt32BigEndian(body[24..]), BinaryPrimitives.ReadUInt32BigEndian(body[28..]));
if (double.IsNaN(cw) || double.IsNaN(ch) || double.IsNaN(ho) || double.IsNaN(vo))
{
return (0, 0, width, height);
}
var left = (int)Math.Round(ho + ((width - 1) / 2.0) - ((cw - 1) / 2.0));
var top = (int)Math.Round(vo + ((height - 1) / 2.0) - ((ch - 1) / 2.0));
var w = (int)Math.Round(cw);
var h = (int)Math.Round(ch);
if (w <= 0 || h <= 0 || left < 0 || top < 0 || left + w > width || top + h > height)
{
return (0, 0, width, height);
}
return (left, top, w, h);
}
private static double Ratio(double numerator, uint denominator) => denominator == 0 ? double.NaN : numerator / denominator;
/// <summary>
/// The rotations (<c>irot</c>: quarter turns anticlockwise) and mirrors (<c>imir</c>: axis 0 vertical, left and
/// right swap; axis 1 horizontal, top and bottom swap) of the image, composed in the order of its properties, as one
/// EXIF orientation. The transform is kept as a clockwise rotation of r quarter turns after an optional left-right
/// mirror.
/// </summary>
internal static int OrientationOf(HeifFile file, HeifItem image)
{
var r = 0;
var mirrored = false;
foreach (var (index, _) in image.Properties)
{
if (index >= file.Properties.Count)
{
continue;
}
var p = file.Properties[index];
if (p.Length < 1)
{
continue;
}
var value = file.Meta[p.Start];
if (p.Type == HeifFile.Irot)
{
r = (r + 4 - (value & 3)) & 3;
}
else if (p.Type == HeifFile.Imir)
{
// A left-right mirror after R(r)·M^m is R(−r)·M^(m+1); a top-bottom one is R(2)·(left-right).
r = (value & 1) == 0 ? (4 - r) & 3 : (6 - r) & 3;
mirrored = !mirrored;
}
}
return mirrored ? r switch { 0 => 2, 1 => 7, 2 => 4, _ => 5 } : r switch { 0 => 1, 1 => 6, 2 => 3, _ => 8 };
}
/// <summary>The EXIF item describing the image (or the only EXIF item of the file), without its offset prefix.</summary>
private static byte[]? ExifOf(Stream stream, HeifFile file, HeifItem? image, HeifLimits limits)
{
HeifItem? exif = null;
var count = 0;
foreach (var item in file.Items)
{
if (item.Type != HeifFile.Exif)
{
continue;
}
count++;
if (image is not null && item.Describes.Contains(image.Id))
{
exif = item;
break;
}
exif ??= item;
}
if (exif is null || (count > 1 && (image is null || !exif.Describes.Contains(image.Id))))
{
return null;
}
try
{
// exif_tiff_header_offset, then (usually «Exif\0\0» and) the TIFF header (ISO/IEC 23008-12 Annex A.2.1).
var data = file.ReadItem(stream, exif, limits);
if (data.Length < 12)
{
return null;
}
var offset = BinaryPrimitives.ReadUInt32BigEndian(data);
var start = 4 + (long)offset;
if (start + 8 > data.Length)
{
return null;
}
var tiff = data.AsSpan((int)start);
return tiff[..4].SequenceEqual("II*\0"u8) || tiff[..4].SequenceEqual("MM\0*"u8) ? tiff.ToArray() : null;
}
catch (Exception ex) when (ex is HeifException or EndOfStreamException or IOException)
{
return null; // an EXIF block that cannot be read: the image stands without it
}
}
/// <summary>The Orientation tag (0x0112) of the first IFD of a TIFF structure; 1 without it or when damaged.</summary>
internal static int ExifOrientationOf(ReadOnlySpan<byte> tiff)
{
if (tiff.Length < 8)
{
return 1;
}
var little = tiff[0] == (byte)'I';
var ifd = U32(tiff[4..], little);
if (ifd > (uint)(tiff.Length - 2))
{
return 1;
}
var entries = U16(tiff[(int)ifd..], little);
for (var i = 0; i < entries; i++)
{
var entry = (long)ifd + 2 + (12L * i);
if (entry + 12 > tiff.Length)
{
break;
}
var e = tiff.Slice((int)entry, 12);
if (U16(e, little) != 0x0112)
{
continue;
}
var value = U16(e[2..], little) switch
{
3 => U16(e[8..], little),
4 => U32(e[8..], little),
_ => 0u,
};
return value is >= 1 and <= 8 ? (int)value : 1;
}
return 1;
}
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
private static uint U32(ReadOnlySpan<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b);
}
+557
View File
@@ -0,0 +1,557 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Containers;
namespace Febe.Core.Codecs.Heif;
/// <summary>An item of a HEIF file (ISO/IEC 23008-12 §6.2, the <c>iinf</c>, <c>iloc</c> and <c>ipma</c> entries of one ID).</summary>
internal sealed class HeifItem(uint id)
{
internal uint Id { get; } = id;
/// <summary>item_type of the <c>infe</c> box: <c>hvc1</c>, <c>grid</c>, <c>Exif</c>, <c>mime</c>, ...; 0 when unknown.</summary>
internal uint Type { get; set; }
/// <summary>construction_method of <c>iloc</c>: 0 from the file, 1 from the <c>idat</c> box.</summary>
internal int ConstructionMethod { get; set; }
/// <summary>The extents of the item's data: offset (base_offset added) and length (0: to the end of the file).</summary>
internal List<(long Offset, long Length)> Extents { get; } = [];
/// <summary>Whether <c>iloc</c> lists the item at all.</summary>
internal bool Located { get; set; }
/// <summary>The associated properties, in the order of <c>ipma</c>: index in <see cref="HeifFile.Properties"/>, essential.</summary>
internal List<(int Index, bool Essential)> Properties { get; } = [];
/// <summary>The items this one is derived from (<c>dimg</c>), in order: the tiles of a grid.</summary>
internal List<uint> DerivedFrom { get; } = [];
/// <summary>The items this one is an auxiliary image of (<c>auxl</c>).</summary>
internal List<uint> AuxiliaryOf { get; } = [];
/// <summary>The items this one describes (<c>cdsc</c>): an <c>Exif</c> item and its image.</summary>
internal List<uint> Describes { get; } = [];
}
/// <summary>A property of the <c>ipco</c> box: its type and where its body lies in <see cref="HeifFile.Meta"/>.</summary>
internal readonly record struct HeifProperty(uint Type, int Start, int Length);
/// <summary>
/// The structure of a HEIF file, read from the boxes of its file-level <c>meta</c> box (ISO/IEC 23008-12 §6 and
/// ISO/IEC 14496-12 §8.11): primary item, items with their locations, properties and references. Only the
/// <c>meta</c> box is kept in memory; item data is read from the stream when asked for.
/// </summary>
internal sealed class HeifFile
{
internal const uint Hvc1 = 0x68766331; // 'hvc1'
internal const uint Grid = 0x67726964; // 'grid'
internal const uint Exif = 0x45786966; // 'Exif'
internal const uint HvcC = 0x68766343; // 'hvcC'
internal const uint Ispe = 0x69737065; // 'ispe'
internal const uint Colr = 0x636F6C72; // 'colr'
internal const uint Irot = 0x69726F74; // 'irot'
internal const uint Imir = 0x696D6972; // 'imir'
internal const uint Clap = 0x636C6170; // 'clap'
internal const uint AuxC = 0x61757843; // 'auxC'
internal const uint Pixi = 0x70697869; // 'pixi'
private const int MaxItems = 100_000;
private readonly Dictionary<uint, HeifItem> items = [];
private HeifFile(byte[] meta, long fileLength)
{
Meta = meta;
FileLength = fileLength;
}
/// <summary>The body of the <c>meta</c> box.</summary>
internal byte[] Meta { get; }
internal long FileLength { get; }
internal uint PrimaryId { get; private set; }
internal List<HeifProperty> Properties { get; } = [];
/// <summary>The body of the <c>idat</c> box (start and length in <see cref="Meta"/>); length −1 without one.</summary>
internal (int Start, int Length) Idat { get; private set; } = (0, -1);
internal IEnumerable<HeifItem> Items => items.Values;
internal HeifItem? Item(uint id) => items.GetValueOrDefault(id);
/// <summary>True when the file starts with an <c>ftyp</c> box naming a HEIF brand of still images with HEVC.</summary>
internal static bool Looks(ReadOnlySpan<byte> start)
{
if (start.Length < 16 || !start.Slice(4, 4).SequenceEqual("ftyp"u8))
{
return false;
}
var size = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(start), (uint)start.Length);
if (IsHeifBrand(start.Slice(8, 4)))
{
return true;
}
for (var b = 16; b + 4 <= size; b += 4)
{
if (IsHeifBrand(start.Slice(b, 4)))
{
return true;
}
}
return false;
}
private static bool IsHeifBrand(ReadOnlySpan<byte> brand) =>
brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) || brand.SequenceEqual("heim"u8) || brand.SequenceEqual("heis"u8)
|| brand.SequenceEqual("mif1"u8) || brand.SequenceEqual("mif2"u8) || brand.SequenceEqual("MiHE"u8);
/// <summary>Reads the top-level boxes of a seekable stream up to its file-level <c>meta</c> box and parses it.</summary>
internal static HeifFile Read(Stream stream, HeifLimits limits)
{
var length = stream.Length;
long position = 0;
Span<byte> header = stackalloc byte[16];
for (var i = 0; i < 10_000 && position + 8 <= length; i++)
{
stream.Position = position;
stream.ReadExactly(header[..8]);
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
var headerSize = 8;
if (size == 1)
{
if (position + 16 > length)
{
break;
}
stream.ReadExactly(header.Slice(8, 8));
var wide = BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
size = wide > long.MaxValue ? -1 : (long)wide;
headerSize = 16;
}
else if (size == 0)
{
size = length - position;
}
if (size < headerSize || size > length - position)
{
throw new HeifException("Box HEIF danneggiato.");
}
if (header.Slice(4, 4).SequenceEqual("meta"u8))
{
var bodyLength = size - headerSize;
if (bodyLength > limits.MaxMetaBytes || bodyLength < 4)
{
throw new HeifException("Box meta HEIF troppo grande o vuoto.");
}
var meta = new byte[bodyLength];
stream.ReadExactly(meta);
var file = new HeifFile(meta, length);
try
{
file.Parse();
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or ArgumentException or OverflowException)
{
throw new HeifException("Box meta HEIF danneggiato.");
}
return file;
}
position += size;
}
throw new HeifException("Manca il box meta HEIF.");
}
private HeifItem ItemOf(uint id)
{
if (!items.TryGetValue(id, out var item))
{
if (items.Count >= MaxItems)
{
throw new HeifException("Troppi elementi HEIF.");
}
item = new HeifItem(id);
items[id] = item;
}
return item;
}
private void Parse()
{
// meta is a full box: version and flags first.
var handlerSeen = false;
foreach (var (type, start, count) in IsoBmffReader.Children(Meta, 4, Meta.Length - 4))
{
var body = Meta.AsSpan(start, count);
switch (type)
{
case "hdlr":
handlerSeen = true;
if (!body.Slice(8, 4).SequenceEqual("pict"u8))
{
throw new HeifException("Il file HEIF non contiene immagini.");
}
break;
case "pitm":
PrimaryId = body[0] == 0 ? BinaryPrimitives.ReadUInt16BigEndian(body[4..]) : BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
break;
case "iinf":
ParseIinf(start, count);
break;
case "iloc":
ParseIloc(body);
break;
case "iref":
ParseIref(start, count);
break;
case "iprp":
ParseIprp(start, count);
break;
case "idat":
Idat = (start, count);
break;
}
}
if (!handlerSeen || PrimaryId == 0 && !items.ContainsKey(0))
{
throw new HeifException("Manca l'immagine principale HEIF.");
}
}
private void ParseIinf(int start, int count)
{
var version = Meta[start];
var entries = version == 0 ? 6 : 8;
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start + entries, count - entries))
{
if (type != "infe" || c < 4)
{
continue;
}
var body = Meta.AsSpan(s, c);
var v = body[0];
if (v < 2)
{
continue; // version 0 and 1 entries have no item_type: nothing Febe decodes
}
var flags = (body[1] << 16) | (body[2] << 8) | body[3];
var p = 4;
uint id;
if (v == 2)
{
id = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
}
else
{
id = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
p += 2; // item_protection_index
var item = ItemOf(id);
item.Type = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
_ = flags; // bit 0: hidden; a hidden item is still decoded when another one refers to it
}
}
private void ParseIloc(ReadOnlySpan<byte> body)
{
var version = body[0];
if (version > 2)
{
throw new HeifException("Versione di iloc non gestita.");
}
var offsetSize = body[4] >> 4;
var lengthSize = body[4] & 15;
var baseOffsetSize = body[5] >> 4;
var indexSize = version is 1 or 2 ? body[5] & 15 : 0;
var p = 6;
long count;
if (version < 2)
{
count = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
}
else
{
count = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if (count > MaxItems)
{
throw new HeifException("Troppi elementi HEIF.");
}
for (var i = 0; i < count; i++)
{
uint id;
if (version < 2)
{
id = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
}
else
{
id = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
var method = 0;
if (version is 1 or 2)
{
method = BinaryPrimitives.ReadUInt16BigEndian(body[p..]) & 15;
p += 2;
}
p += 2; // data_reference_index: 0, this file
var baseOffset = ReadSized(body, ref p, baseOffsetSize);
var extents = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
var item = ItemOf(id);
item.Located = true;
item.ConstructionMethod = method;
item.Extents.Clear();
for (var e = 0; e < extents; e++)
{
if (indexSize > 0)
{
_ = ReadSized(body, ref p, indexSize);
}
var offset = ReadSized(body, ref p, offsetSize);
var length = ReadSized(body, ref p, lengthSize);
item.Extents.Add((checked(baseOffset + offset), length));
}
}
}
private static long ReadSized(ReadOnlySpan<byte> body, ref int p, int size)
{
long value;
switch (size)
{
case 0:
return 0;
case 4:
value = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
break;
case 8:
var wide = BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
if (wide > long.MaxValue)
{
throw new HeifException("Posizione HEIF fuori misura.");
}
value = (long)wide;
break;
default:
throw new HeifException("Ampiezza di campo di iloc non valida.");
}
p += size;
return value;
}
private void ParseIref(int start, int count)
{
var wide = Meta[start] != 0;
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start + 4, count - 4))
{
var body = Meta.AsSpan(s, c);
var p = 0;
var from = Id(body, ref p, wide);
var references = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
var item = ItemOf(from);
var list = type switch
{
"dimg" => item.DerivedFrom,
"auxl" => item.AuxiliaryOf,
"cdsc" => item.Describes,
_ => null,
};
for (var r = 0; r < references; r++)
{
var to = Id(body, ref p, wide);
list?.Add(to);
}
}
}
private static uint Id(ReadOnlySpan<byte> body, ref int p, bool wide)
{
if (wide)
{
var id = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
return id;
}
var narrow = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
return narrow;
}
private void ParseIprp(int start, int count)
{
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start, count))
{
if (type == "ipco")
{
foreach (var (t, ps, pc) in IsoBmffReader.Children(Meta, s, c))
{
Properties.Add(new HeifProperty(BinaryPrimitives.ReadUInt32BigEndian(System.Text.Encoding.Latin1.GetBytes(t)), ps, pc));
}
}
}
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start, count))
{
if (type != "ipma")
{
continue;
}
var body = Meta.AsSpan(s, c);
var version = body[0];
var large = (body[3] & 1) != 0;
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
var p = 8;
for (var e = 0u; e < entries; e++)
{
var id = Id(body, ref p, version >= 1);
var associations = body[p++];
var item = ItemOf(id);
for (var a = 0; a < associations; a++)
{
int index;
bool essential;
if (large)
{
var v = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
essential = (v & 0x8000) != 0;
index = v & 0x7FFF;
}
else
{
var v = body[p++];
essential = (v & 0x80) != 0;
index = v & 0x7F;
}
if (index > 0)
{
item.Properties.Add((index - 1, essential)); // index 0: no property
}
}
}
}
}
/// <summary>The first property of <paramref name="type"/> associated with <paramref name="item"/>, or null.</summary>
internal HeifProperty? Property(HeifItem item, uint type)
{
foreach (var (index, _) in item.Properties)
{
if (index < Properties.Count && Properties[index].Type == type)
{
return Properties[index];
}
}
return null;
}
internal ReadOnlySpan<byte> Body(HeifProperty property) => Meta.AsSpan(property.Start, property.Length);
/// <summary>The bytes of an item, its extents one after the other.</summary>
internal byte[] ReadItem(Stream stream, HeifItem item, HeifLimits limits)
{
if (!item.Located || item.Extents.Count == 0)
{
throw new HeifException("Elemento HEIF senza dati.");
}
long total = 0;
var spans = new (long Offset, long Length)[item.Extents.Count];
for (var i = 0; i < spans.Length; i++)
{
var (offset, length) = item.Extents[i];
long available;
switch (item.ConstructionMethod)
{
case 0:
available = FileLength - offset;
break;
case 1:
if (Idat.Length < 0)
{
throw new HeifException("Manca il box idat HEIF.");
}
available = Idat.Length - offset;
break;
default:
throw new HeifException("Costruzione di elemento HEIF non gestita.");
}
if (offset < 0 || available < 0)
{
throw new HeifException("Elemento HEIF fuori dal file.");
}
length = length == 0 ? available : length;
if (length > available)
{
throw new HeifException("Elemento HEIF fuori dal file.");
}
spans[i] = (offset, length);
total += length;
if (total > limits.MaxItemBytes)
{
throw new HeifException("Elemento HEIF troppo grande.");
}
}
var data = new byte[total];
var position = 0;
foreach (var (offset, length) in spans)
{
if (item.ConstructionMethod == 1)
{
Meta.AsSpan(Idat.Start + (int)offset, (int)length).CopyTo(data.AsSpan(position));
}
else
{
stream.Position = offset;
stream.ReadExactly(data, position, (int)length);
}
position += (int)length;
}
return data;
}
}
+94
View File
@@ -0,0 +1,94 @@
namespace Febe.Core.Codecs.Heif;
/// <summary>A HEIF file that cannot be decoded: damaged, truncated, or of a kind Febe does not handle.</summary>
public sealed class HeifException(string message) : Exception(message);
/// <summary>
/// The still image of a HEIF file (HEIC: ISO/IEC 23008-12 with HEVC pictures), decoded: <see cref="Width"/> ×
/// <see cref="Height"/> pixels, top row first, four bytes each R, G, B, A (8 bits, alpha not premultiplied, 255 without
/// an alpha plane). The clean aperture (<c>clap</c>) is already applied; the rotation and mirroring are not: they are in
/// <see cref="Orientation"/>, as an EXIF orientation, for the caller to apply.
/// </summary>
/// <remarks>
/// The same layout as <c>RgbaImage</c> of the image codecs (branch funzione/codec-immagini, not merged here): when that
/// branch is merged, <see cref="Pixels"/> becomes the buffer of an <c>RgbaImage</c> and <see cref="Orientation"/> its
/// <c>ImageMetadata.Orientation</c>, so that <c>ImageOrientation.Apply</c> turns it upright.
/// </remarks>
public sealed class HeifImage
{
internal HeifImage(int width, int height, byte[] pixels)
{
Width = width;
Height = height;
Pixels = pixels;
}
/// <summary>Width in pixels as stored (orientation not applied).</summary>
public int Width { get; }
/// <summary>Height in pixels as stored.</summary>
public int Height { get; }
/// <summary>The pixels, R, G, B, A, row after row.</summary>
public byte[] Pixels { get; }
/// <summary>
/// How the pixels must be turned to be shown, as an EXIF orientation 1-8 (1: as they are; 6: 90° clockwise; 3: 180°;
/// 8: 90° anticlockwise; 2, 4, 5, 7 with a mirror), from the <c>irot</c> and <c>imir</c> properties of the image in
/// the order the file lists them. The EXIF block's own orientation is not part of it (HEIF says the transformative
/// properties rule, and phones write both): it is in <see cref="ExifOrientation"/>.
/// </summary>
public int Orientation { get; init; } = 1;
/// <summary>Whether an alpha plane (an auxiliary image) filled the alpha of <see cref="Pixels"/>.</summary>
public bool HasAlpha { get; init; }
/// <summary>Bits per luma sample of the coded pictures (8, 10, 12); the pixels have 8 whatever this is.</summary>
public int BitDepth { get; init; } = 8;
/// <summary>The EXIF block of the image (its <c>Exif</c> item) as a TIFF structure, or null.</summary>
public byte[]? Exif { get; init; }
/// <summary>The Orientation tag of <see cref="Exif"/>, 1-8; 1 without it. Informative only: see <see cref="Orientation"/>.</summary>
public int ExifOrientation { get; init; } = 1;
/// <summary>The ICC profile of a <c>colr</c> property of type <c>prof</c> or <c>rICC</c>, or null.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>The image as shown: <see cref="Width"/> and <see cref="Height"/> swapped when the orientation turns it a quarter.</summary>
public (int Width, int Height) DisplaySize => Orientation >= 5 ? (Height, Width) : (Width, Height);
}
/// <summary>What a HEIF file says about its primary image, read without decoding any picture.</summary>
/// <param name="Width">Width as stored, after the clean aperture.</param>
/// <param name="Height">Height as stored, after the clean aperture.</param>
/// <param name="Orientation">As <see cref="HeifImage.Orientation"/>.</param>
/// <param name="HasAlpha">Whether an alpha plane goes with the image.</param>
/// <param name="Tiles">Coded pictures of the image: 1, or the tiles of a grid.</param>
public sealed record HeifInfo(int Width, int Height, int Orientation, bool HasAlpha, int Tiles)
{
/// <summary>The size as shown (orientation applied).</summary>
public (int Width, int Height) DisplaySize => Orientation >= 5 ? (Height, Width) : (Width, Height);
}
/// <summary>Bounds that keep a damaged or hostile file from taking the memory or the processors.</summary>
public sealed record HeifLimits
{
/// <summary>The default limits.</summary>
public static HeifLimits Default { get; } = new();
/// <summary>Pixels of the image at most (100 megapixels: 400 MB of RGBA).</summary>
public long MaxPixels { get; init; } = 100_000_000;
/// <summary>Bytes of the <c>meta</c> box at most.</summary>
public int MaxMetaBytes { get; init; } = 32 * 1024 * 1024;
/// <summary>Bytes of one item at most.</summary>
public int MaxItemBytes { get; init; } = 128 * 1024 * 1024;
/// <summary>Tiles of a grid at most (256 × 256).</summary>
public int MaxTiles { get; init; } = 65_536;
/// <summary>Tiles decoded at the same time at most.</summary>
public int MaxParallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
}
+193
View File
@@ -0,0 +1,193 @@
using System.Numerics;
namespace Febe.Core.Codecs;
/// <summary>
/// The sample planes of a decoded picture, whatever its codec: luma <see cref="Width"/> × <see cref="Height"/>, chroma
/// subsampled by <c>1 &lt;&lt; ChromaShiftX</c> and <c>1 &lt;&lt; ChromaShiftY</c> (4:2:0: 1 and 1; 4:2:2: 1 and 0; 4:4:4:
/// 0 and 0), no chroma at all for a monochrome picture. Samples are 8-bit bytes (H.264) or 16-bit values of any bit
/// depth up to 16 (HEVC).
/// </summary>
internal readonly struct YuvPlanes<T>(
T[] y, T[] cb, T[] cr, int width, int height, int chromaShiftX, int chromaShiftY, bool monochrome, int bitDepthY, int bitDepthC)
where T : unmanaged, IBinaryInteger<T>
{
internal T[] Y { get; } = y;
internal T[] Cb { get; } = cb;
internal T[] Cr { get; } = cr;
internal int Width { get; } = width;
internal int Height { get; } = height;
internal int ChromaShiftX { get; } = chromaShiftX;
internal int ChromaShiftY { get; } = chromaShiftY;
internal bool Monochrome { get; } = monochrome;
internal int BitDepthY { get; } = bitDepthY;
internal int BitDepthC { get; } = bitDepthC;
/// <summary>Width of a chroma row (rounded up, as for odd H.264 widths).</summary>
internal int ChromaWidth => (Width + (1 << ChromaShiftX) - 1) >> ChromaShiftX;
}
/// <summary>
/// Conversion of Y′CbCr samples to 8-bit RGB (ITU-T H.273 for the meaning of matrix_coeffs and video_full_range_flag):
/// BT.709, BT.601, FCC, SMPTE 240M or BT.2020 (non-constant luminance) coefficients, the identity matrix (G, B and R
/// coded as Y, Cb and Cr), limited or full range, any bit depth; chroma taken at the nearest sample. Integer arithmetic
/// with 16 fractional bits, so every caller gets the same pixels.
/// </summary>
internal static class YuvToRgb
{
private const int Shift = 16;
private const double One = 1 << Shift;
private const int Half = 1 << (Shift - 1);
/// <summary>The integer coefficients for one matrix, range and bit depth.</summary>
internal readonly struct Coefficients
{
internal bool Identity { get; init; }
internal int LumaScale { get; init; }
internal int LumaOffset { get; init; }
internal int ChromaMiddle { get; init; }
internal int CrToR { get; init; }
internal int CbToB { get; init; }
internal int CbToG { get; init; }
internal int CrToG { get; init; }
/// <summary>Right shift that brings an identity-matrix sample to 8 bits, luma and chroma.</summary>
internal int IdentityShiftY { get; init; }
internal int IdentityShiftC { get; init; }
}
/// <summary>
/// The coefficients for <paramref name="matrix"/> (matrix_coeffs; unspecified or unknown: BT.709 from 720 lines up,
/// BT.601 below), <paramref name="fullRange"/> and the bit depths of the samples.
/// </summary>
internal static Coefficients For(int matrix, bool fullRange, int bitDepthY, int bitDepthC, int height)
{
if (matrix == 0)
{
return new Coefficients { Identity = true, IdentityShiftY = Math.Max(0, bitDepthY - 8), IdentityShiftC = Math.Max(0, bitDepthC - 8) };
}
var (kr, kb) = matrix 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),
_ => height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114),
};
var kg = 1 - kr - kb;
var yScale = (fullRange ? 1.0 : 255.0 / 219.0) / (1 << Math.Max(0, bitDepthY - 8));
var cScale = (fullRange ? 1.0 : 255.0 / 224.0) / (1 << Math.Max(0, bitDepthC - 8));
return new Coefficients
{
LumaScale = (int)Math.Round(yScale * One),
LumaOffset = fullRange ? 0 : 16 << Math.Max(0, bitDepthY - 8),
ChromaMiddle = 1 << (bitDepthC - 1),
CrToR = (int)Math.Round(2 * (1 - kr) * cScale * One),
CbToB = (int)Math.Round(2 * (1 - kb) * cScale * One),
CbToG = (int)Math.Round(2 * kb * (1 - kb) / kg * cScale * One),
CrToG = (int)Math.Round(2 * kr * (1 - kr) / kg * cScale * One),
};
}
/// <summary>
/// Converts the picture reduced by <paramref name="factor"/> (each output pixel the mean of factor × factor converted
/// pixels) into <paramref name="target"/>: <paramref name="width"/> × <paramref name="height"/> pixels of
/// <paramref name="pixelSize"/> bytes (3: R, G, B; 4: R, G, B and an alpha of 255), rows <paramref name="stride"/>
/// bytes apart. The output must fit in the picture: width × factor ≤ its width, height × factor ≤ its height.
/// </summary>
internal static void Convert<T>(in YuvPlanes<T> p, in Coefficients k, int factor, Span<byte> target, int stride, int pixelSize, int width, int height)
where T : unmanaged, IBinaryInteger<T>
{
var area = factor * factor;
var cw = p.ChromaWidth;
var sx = p.ChromaShiftX;
var sy = p.ChromaShiftY;
ReadOnlySpan<T> yPlane = p.Y, cbPlane = p.Cb, crPlane = p.Cr;
var mono = p.Monochrome;
for (var oy = 0; oy < height; oy++)
{
var row = target.Slice(oy * stride, width * pixelSize);
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 * p.Width;
var chromaRow = (y >> sy) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var luma = int.CreateTruncating(yPlane[lumaRow + x]);
int u, v;
if (mono)
{
u = v = k.ChromaMiddle;
}
else
{
var c = chromaRow + (x >> sx);
u = int.CreateTruncating(cbPlane[c]);
v = int.CreateTruncating(crPlane[c]);
}
if (k.Identity)
{
g += Clip(luma >> k.IdentityShiftY);
b += Clip(mono ? luma >> k.IdentityShiftY : u >> k.IdentityShiftC);
r += Clip(mono ? luma >> k.IdentityShiftY : v >> k.IdentityShiftC);
continue;
}
var l = (luma - k.LumaOffset) * k.LumaScale;
u -= k.ChromaMiddle;
v -= k.ChromaMiddle;
r += Clip((l + (k.CrToR * v) + Half) >> Shift);
g += Clip((l - (k.CbToG * u) - (k.CrToG * v) + Half) >> Shift);
b += Clip((l + (k.CbToB * u) + Half) >> Shift);
}
}
var o = ox * pixelSize;
if (area == 1)
{
row[o] = (byte)r;
row[o + 1] = (byte)g;
row[o + 2] = (byte)b;
}
else
{
row[o] = (byte)(r / area);
row[o + 1] = (byte)(g / area);
row[o + 2] = (byte)(b / area);
}
if (pixelSize == 4)
{
row[o + 3] = 255;
}
}
}
}
private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v;
}
+1 -1
View File
@@ -98,7 +98,7 @@ internal static class ContentAnalysis
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OutOfMemoryException)
{
return (null, null, null); // a format SkiaSharp cannot decode (e.g. HEIC): no size, no hash
return (null, null, null); // a format no decoder reads (e.g. AVIF): no size, no hash
}
}
+9 -3
View File
@@ -1,5 +1,6 @@
using System.Buffers.Binary;
using System.Globalization;
using Febe.Core.Codecs.Heif;
using Febe.Core.Domain;
namespace Febe.Core.Import;
@@ -11,8 +12,8 @@ namespace Febe.Core.Import;
/// camera wrote the zone. The modification date of IFD0 (0x0132) is not used: editors rewrite it.
/// <para>
/// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (<c>eXIf</c> chunk), WebP (<c>EXIF</c> chunk).
/// HEIC keeps its EXIF in an item of the <c>meta</c> box and is not read. Every offset is checked: a damaged block gives
/// no date, never an exception.
/// HEIC and HEIF keep their EXIF in an item of the <c>meta</c> box (<see cref="HeifDecoder.FindExif"/>): read when the
/// item lies within the first bytes read. Every offset is checked: a damaged block gives no date, never an exception.
/// </para>
/// </summary>
public static class ExifDateReader
@@ -46,7 +47,7 @@ public static class ExifDateReader
}
}
/// <summary>The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none.</summary>
/// <summary>The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG, WebP or HEIC; empty when there is none.</summary>
internal static ReadOnlySpan<byte> FindTiff(ReadOnlySpan<byte> data)
{
if (data.Length < 8)
@@ -74,6 +75,11 @@ public static class ExifDateReader
return FindInWebp(data);
}
if (HeifDecoder.FindExif(data) is { } heif)
{
return heif; // HEIC: the Exif item of the meta box, when it lies within these bytes
}
return [];
}
+5 -3
View File
@@ -21,7 +21,7 @@ var import = new ImportService(new ImportEnvironment
Clock = clock,
Thumbnails = new ThumbnailStore(data.Thumbnails),
HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta
Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 importati, decodificate in casa
Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 e HEVC importati, decodificate in casa
VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska e AVI (null: la stessa, predefinita)
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder,
@@ -159,8 +159,10 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per
## Limiti noti
- HEIC/HEIF: si riconoscono, ma SkiaSharp (pacchetto Linux senza dipendenze) non li decodifica: niente dimensioni,
impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica.
- HEIC/HEIF: dimensioni, impronta e miniatura vengono dal decodificatore scritto in casa (`Febe.Core.Codecs.Heif`, sul
decodificatore HEVC): immagine singola o griglia di tessere, `clap`, `irot`/`imir`, trasparenza. La data di scatto
si legge dall'elemento `Exif` solo se sta nei primi 512 KB del file. Restano senza miniatura gli HEIF che non sono
HEVC (AVIF, JPEG), le immagini derivate diverse dalle griglie e le sequenze di immagini.
- La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella
scrivibile per il sistema ma non per Febe non si riconosce; lì «Sposta» lascia l'originale e lo dice.
- La data `mvhd` si legge come UTC, come vuole il formato; alcune fotocamere vi scrivono l'ora locale.
+70 -1
View File
@@ -1,10 +1,12 @@
using Febe.Core.Codecs.Heif;
using SkiaSharp;
namespace Febe.Core.Library;
/// <summary>
/// Decodes images with SkiaSharp, applying the EXIF orientation (photos from phones) and, when the codec allows it,
/// decoding directly at a reduced size to save memory and time.
/// decoding directly at a reduced size to save memory and time. HEIC/HEIF photos, which SkiaSharp does not read, go
/// through the decoder written in house (<see cref="HeifDecoder"/>).
/// </summary>
internal static class ImageDecoding
{
@@ -28,6 +30,11 @@ internal static class ImageDecoding
return null;
}
if (HeifDecoder.Looks(data.AsSpan()))
{
return DecodeHeif(data);
}
using var codec = SKCodec.Create(data);
if (codec is null)
{
@@ -56,6 +63,25 @@ internal static class ImageDecoding
public static (int Width, int Height)? ReadSize(Stream stream)
{
ArgumentNullException.ThrowIfNull(stream);
if (stream.CanSeek)
{
var start = stream.Position;
Span<byte> head = stackalloc byte[64];
var read = stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
stream.Position = start;
if (HeifDecoder.Looks(head[..read]))
{
try
{
return HeifDecoder.ReadInfo(stream).DisplaySize;
}
catch (HeifException)
{
return null;
}
}
}
using var codec = SKCodec.Create(stream);
if (codec is null)
{
@@ -66,6 +92,49 @@ internal static class ImageDecoding
return SwapsAxes(codec.EncodedOrigin) ? (h, w) : (w, h);
}
/// <summary>
/// A HEIC/HEIF photo, which SkiaSharp does not decode: the decoder written in house (<see cref="HeifDecoder"/>), at
/// full size, turned upright by its <c>irot</c>/<c>imir</c> properties; null when it cannot be decoded.
/// </summary>
private static SKBitmap? DecodeHeif(SKData data)
{
HeifImage image;
try
{
using var stream = data.AsStream();
var info = HeifDecoder.ReadInfo(stream);
if ((long)info.Width * info.Height > MaxDecodedPixels)
{
return null;
}
stream.Position = 0;
image = HeifDecoder.Decode(stream);
}
catch (HeifException)
{
return null;
}
var bitmap = new SKBitmap(new SKImageInfo(image.Width, image.Height, SKColorType.Rgba8888, image.HasAlpha ? SKAlphaType.Unpremul : SKAlphaType.Premul));
System.Runtime.InteropServices.Marshal.Copy(image.Pixels, 0, bitmap.GetPixels(), image.Pixels.Length);
if (image.HasAlpha)
{
// The other paths give premultiplied pixels: the same here.
var premultiplied = new SKBitmap(new SKImageInfo(image.Width, image.Height, SKColorType.Rgba8888, SKAlphaType.Premul));
using (var canvas = new SKCanvas(premultiplied))
{
canvas.Clear(SKColors.Transparent);
canvas.DrawBitmap(bitmap, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest), null);
}
bitmap.Dispose();
bitmap = premultiplied;
}
return Orient(bitmap, (SKEncodedOrigin)image.Orientation);
}
private static SKSizeI ChooseDecodeSize(SKCodec codec, int? minLongSide)
{
var full = new SKSizeI(codec.Info.Width, codec.Info.Height);
+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;