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;
}