C4: decodificatore HEVC e HEIC in casa (#58) #64

Merged
Alby96 merged 12 commits from funzione/decoder-hevc into main 2026-11-26 14:40:07 +01:00
21 changed files with 2695 additions and 148 deletions
Showing only changes of commit ac85d1baed - Show all commits

No files matched your search

+1
View File
@@ -431,3 +431,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-18 | Decodificatore HEVC (ITU-T H.265), prima parte, scritto in casa in `src/Febe.Core/Codecs/H265` accanto a quello H.264: unità NAL Annex B e `hvcC`, VPS/SPS/PPS con liste di scala, VUI e indicatori RExt, intestazione di slice, POC, RPS, DPB e uscita (C.5.2), CABAC con le tabelle d'inizio della norma, albero di codifica, unità di predizione, residui (sign data hiding, transform skip), predizione intra, trasformate, PCM, deblocking e SAO, tile, WPP e segmenti dipendenti. Riusa da H.264 `rangeTabLps`, `transIdxLps` e la lettura delle unità NAL. Le slice P e B si rifiutano con un'eccezione: la predizione inter è la tappa successiva; con un interruttore interno le prove ne leggono la sintassi fino a `end_of_slice_segment_flag`, con le unità di predizione grigie. Profili accettati: 4:2:0 fino a 12 bit senza strumenti RExt | I 12 flussi di sole slice I (Main, Main 10, Main Still Picture) coincidono col YUV ufficiale; nei 136 flussi Main e Main 10 ogni immagine di sole slice I coincide con l'MD5 SEI del codificatore, dove il flusso lo porta, e ogni slice P e B si legge fino in fondo: un primo controllo della sintassi inter, che senza predizione non si può confrontare con gli hash |
| 2026-11-18 | Decodificatore HEVC, seconda parte: predizione inter scritta dalla norma in `H265Decoder.Inter.cs` (liste di riferimento di §8.3.4 con le modifiche, merge con candidati spaziali, temporale, bi-predittivi combinati e nulli, livello di merge parallelo, AMVP con scala per distanza di POC, TMVP sull'immagine co-locata alla griglia di 16×16, interpolazione a 8 prese per la luma e 4 per il croma, predizione pesata di base ed esplicita, niente bi-predizione per 8×4 e 4×8) e intensità del deblocking dal moto (immagini di riferimento confrontate per identità, a prescindere dalla lista). Ogni immagine tiene il moto di ogni blocco 4×4, la slice di ogni CTB e le liste delle sue slice (POC e lungo termine), che servono a chi la prende come co-locata. Un riferimento che manca è un'immagine grigia, intra, fuori dal DPB e mai in uscita (§8.3.3.2, ma senza metterla nel DPB per non cambiare il riempimento del buffer). I filtri d'interpolazione lavorano 8 campioni per volta coi vettori della BCL (`Vector128`), a 16 bit quando i campioni sono a 8 bit | I 136 flussi Main, Main 10 e Main Still Picture della serie di conformità danno esattamente il YUV ufficiale (MD5 di tutto il file, e di ogni fotogramma dove c'è) e ogni immagine coincide col suo hash SEI dove il flusso lo porta: confermati anche il numero di fotogrammi e gli MD5 scelti per i flussi senza YUV. Coi vettori l'interpolazione costa circa la metà; 1080p a 8 bit va a 20–25 fotogrammi al secondo su questa macchina |
| 2026-11-18 | Decodificatore HEVC, terza parte: anche le estensioni di formato (RExt), perché i loro 10 flussi sono nella serie di conformità: 4:0:0, 4:2:2 (due blocchi di croma quadrati per unità di trasformata con i loro cbf, modi intra della tabella 8-3, QP del croma senza la tabella del 4:2:0), 4:4:4 (un modo di croma per blocco NxN, croma filtrato come la luma), fino a 12 bit, predizione fra componenti, RDPCM implicito ed esplicito, rotazione e contesto unico del transform skip, smoothing intra spento, adattamento persistente di Rice (salvato e ripreso con i contesti di WPP e dei segmenti dipendenti), `chroma_qp_offset_list`, deblocking del croma sulla sua griglia di 8 campioni e SAO con CTB di croma non quadrati. Restano rifiutati con un'eccezione la precisione estesa e l'allineamento del CABAC, che nessun flusso della serie usa. Tile, WPP, segmenti dipendenti, liste di scala e riferimenti a lungo termine erano già nelle parti precedenti; una prova nuova controlla che ognuno sia acceso in almeno un flusso. Il ritaglio dei fotogrammi in uscita usa array non inizializzati | I 146 flussi della serie danno esattamente il YUV ufficiale e ogni immagine coincide col suo hash SEI dove c'è: nessuna prova è più inconcludente, quindi la regola della CI che non ne ammette di saltate è rispettata. La tabella 8-3 è stata ricavata dalla geometria degli angoli (spostamento orizzontale dimezzato) e confermata dagli hash di `ADJUST_IPRED_ANGLE_A` e dei flussi 4:2:2. Su questa macchina, in Release: 416×240 da 160 a 600 fotogrammi al secondo, 1080p a 8 bit 26–27 (35 senza la copia ritagliata), 4:2:2 a 10 bit 9; il deblocking e il SAO pesano circa un quinto, il resto è lettura CABAC e ricostruzione; nei cicli delle CTU non si alloca nulla |
| 2026-11-18 | HEVC nella catena dei media: `hvcC` letto 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; MPEG-PS/TS non hanno un lettore in questo ramo e restano fuori. `VideoFrameDecoder` sceglie H.264 o HEVC dal codec della traccia: il decodificatore HEVC dà ora anche i fotogrammi in ordine di decodifica (`FrameDecoded` con `Wanted`, come H.264), le unità di accesso Annex B e il punto d'accesso di un campione (IDR e BLA esatti, CRA vicino: le sue RASL si perdono e al loro posto vale il fotogramma da cui parte la corsa). La conversione Y′CbCr→RGB è una sola (`Codecs/YuvToRgb`) per H.264, HEVC a 8–12 bit in 4:0:0, 4:2:0, 4:2:2 e 4:4:4, e HEIF. Foto HEIC/HEIF (ISO/IEC 23008-12) decodificate in casa in `Febe.Core.Codecs.Heif`: `meta`/`iinf`/`iloc` (dal file e da `idat`)/`iref`/`iprp`/`ipco`/`ipma`, elemento `hvc1` o griglia (`grid`, tessere decodificate su al più 4 thread), `colr` nclx o ICC, piano alfa ausiliario, `clap` applicato, `irot`/`imir` restituiti come orientamento EXIF da applicare, elemento `Exif`. L'uscita è `HeifImage` (RGBA come `RgbaImage` del ramo funzione/codec-immagini, non unito qui): all'unione diventa un `RgbaImage` con l'orientamento nei metadati. Per ora `ImageDecoding` passa gli HEIF al decodificatore di casa prima di SkiaSharp, così miniature, impronte, dimensioni e anteprime dell'importazione valgono anche per gli HEIC, e `ExifDateReader` legge la data dall'elemento `Exif` quando sta nei primi 512 KB | Decisione di Alberto del 18 novembre 2026 (niente componenti esterni): i video e le foto dei telefoni sono HEVC e HEIC. L'orientamento EXIF dentro un HEIC resta solo informativo, perché HEIF dà la precedenza a `irot`/`imir` e i telefoni scrivono entrambi. Provato su file costruiti dai flussi di conformità H.265.1 (MP4, MP4 frammentato, Matroska, AVI con e senza indice, griglie, rotazioni e specchi, `clap`, alfa, nclx, Exif, file rovinati con semi fissi); nessun HEIC o video HEVC di un telefono vero è stato provato |
+2 -1
View File
@@ -72,7 +72,8 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»).
La password dell'interfaccia e la chiave della sessione non si passano mai sulla riga di comando e non finiscono nei
registri; Febe le toglie dall'ambiente di Chromium e Xvfb. Le miniature dei video
importati non chiedono programmi esterni: contenitori e H.264 si leggono con codice di Febe.
importati non chiedono programmi esterni: contenitori, H.264 e HEVC (anche Main 10, come i video dei telefoni) si
leggono con codice di Febe, e così le foto HEIC/HEIF (griglie di tessere, rotazione, trasparenza, EXIF).
## Porte
@@ -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;
@@ -0,0 +1,150 @@
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H265;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// HEVC videos through the containers and the frame decoder: the test videos are built from streams of the ITU-T H.265.1
/// set, so the frame expected is the one the decoder gives straight from the stream (itself bit exact on those streams).
/// </summary>
[TestClass]
public sealed class HevcVideoTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
/// <summary>416×240, 8 bit, 60 frames shown in another order than they are decoded.</summary>
private const string Moving = "INITQP_A_Sony_1";
[TestMethod]
[DataRow("mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("frammentato.mp4")]
[DataRow("senza-indice.avi")]
[DataRow("senza-indice-con-parametri.avi")]
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.IsTrue(es.Rank.Where((r, i) => r != i).Any(), "il flusso deve riordinare i fotogrammi");
using var temp = new TempFolder("fotogramma-hevc");
var data = kind switch
{
"mkv" => TestVideos.Matroska(es),
"avi" => TestVideos.Avi(es),
"senza-indice.avi" => TestVideos.Avi(es, index: false),
"senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false),
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
_ => TestVideos.Mp4(es),
};
var path = TestVideos.Write(temp, "video." + kind, data);
var container = ContainerReader.ReadFile(path, Now);
Assert.AreEqual(VideoCodec.Hevc, container!.Video!.Codec);
Assert.AreEqual(kind.EndsWith("avi", StringComparison.Ordinal), container.Video.AnnexB);
if (!container.Video.AnnexB)
{
CollectionAssert.AreEqual(es.AvcC, container.Video.HevcConfiguration, "hvcC del contenitore");
}
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
Assert.IsNotNull(image);
// AVI has no presentation times: there frames are shown in decoding order.
var position = Math.Min(30, es.Count - 1);
var rank = kind.EndsWith("avi", StringComparison.Ordinal) ? es.Rank[position] : position;
var reference = VideoFrameDecoder.ToImage(Shown(Moving)[rank], 0, 0);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
}
[TestMethod]
[DataRow("INITQP_B_Main10_Sony_1")]
[DataRow("WPP_B_ericsson_MAIN10_2")]
public async Task Main10VideosGiveTheirFrame(string name)
{
var es = ElementaryStream.LoadHevc(name);
using var temp = new TempFolder("fotogramma-hevc-10");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 270));
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero);
Assert.IsNotNull(image);
var reference = VideoFrameDecoder.ToImage(Shown(name)[0], 270, 0);
Assert.AreEqual(10, Shown(name)[0].BitDepthLuma);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
Assert.AreEqual((es.Height, es.Width), (image.Width, image.Height), "ruotato di un quarto");
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path);
Assert.IsNotNull(bmp);
Assert.AreEqual((byte)'B', bmp[0]);
}
[TestMethod]
public async Task AnHevcVideoOfAStillPictureIsRecognisedAndOneThatMovesIsNot()
{
var es = ElementaryStream.LoadHevc(Moving);
using var temp = new TempFolder("fermo-hevc");
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsStill);
Assert.AreEqual(0, result.Difference);
var moving = TestVideos.Write(temp, "movimento.mkv", TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4")));
var other = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(moving);
Assert.IsNotNull(other);
Assert.IsFalse(other.IsStill, $"differenza {other.Difference}");
}
[TestMethod]
public void AccessPointsAreTheIrapPictures()
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.LengthPrefixed(0), 4));
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.WithStartCodes(0), 0));
var inter = Enumerable.Range(0, es.Count).First(i => !es.Key[i]);
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint(es.LengthPrefixed(inter), 4));
// A CRA picture (NAL unit type 21): decoding starts there, its RASL pictures are lost.
byte[] cra = [0, 0, 0, 3, 21 << 1, 1, 0x80];
Assert.AreEqual(H265AccessPoint.Cra, H265Decoder.AccessPoint(cra, 4));
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint([0, 0, 0, 2, 34 << 1, 1], 4), "solo parametri");
}
[TestMethod]
public void TenBitFramesAndOtherChromaFormatsBecomeTheRightColours()
{
static H265Frame Flat(ushort y, ushort c, int format, int bits, int matrix, bool full)
{
var chroma = format == 0 ? 0 : format == 3 ? 4 : format == 2 ? 2 : 1;
return new(2, 2, format, bits, bits, [y, y, y, y], [.. Enumerable.Repeat(c, chroma)], [.. Enumerable.Repeat(c, chroma)], 0, 0, matrix, full);
}
// Limited range at 10 bits: 64 is black, 940 white.
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
// The same grey at 8, 10 and 12 bits, in every chroma format (4:0:0 has no chroma at all).
var grey = VideoFrameDecoder.ToImage(Flat(128, 128, 1, 8, 6, true), 0, 0).Rgb;
foreach (var format in new[] { 0, 1, 2, 3 })
{
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(512, 512, format, 10, 6, true), 0, 0).Rgb, $"formato {format}");
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(2048, 2048, format, 12, 6, true), 0, 0).Rgb, $"formato {format}, 12 bit");
}
// Pure red of BT.601 at 10 bits (limited range): Y 324, Cb 360, Cr 960.
var red = VideoFrameDecoder.ToImage(new H265Frame(2, 2, 1, 10, 10, [324, 324, 324, 324], [360], [960], 0, 0, 6, false), 0, 0).Rgb;
Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}");
}
/// <summary>The frames of a conformance stream in output order, decoded straight from its Annex B form.</summary>
private static List<H265Frame> Shown(string name)
{
var frames = new List<H265Frame>();
var decoder = new H265Decoder();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(name).BitstreamPath));
return frames;
}
}
@@ -21,6 +21,8 @@ public sealed class MalformedInputTests
[DataRow("frammentato.mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("hevc.mp4")]
[DataRow("hevc.mkv")]
public void TruncatedFilesNeverBreakTheReaders(string kind)
{
var file = Build(kind);
@@ -51,6 +53,9 @@ public sealed class MalformedInputTests
[DataRow("frammentato.mp4", 5812)]
[DataRow("mkv", 5813)]
[DataRow("avi", 5814)]
[DataRow("hevc.mp4", 5815)]
[DataRow("hevc.mkv", 5816)]
[DataRow("hevc.avi", 5817)]
public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed)
{
var file = Build(kind);
@@ -246,7 +251,10 @@ public sealed class MalformedInputTests
private static byte[] Build(string kind)
{
var es = ElementaryStream.Load("CABA3_SVA_B");
// «hevc.»: the same containers around an HEVC stream.
var hevc = kind.StartsWith("hevc.", StringComparison.Ordinal);
var es = hevc ? ElementaryStream.LoadHevc("INITQP_A_Sony_1") : ElementaryStream.Load("CABA3_SVA_B");
kind = hevc ? kind[5..] : kind;
return kind switch
{
"frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true),
+69 -12
View File
@@ -13,7 +13,7 @@ namespace Febe.Tests.Codecs.Containers;
/// </summary>
internal sealed class ElementaryStream
{
private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height)
private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height, bool hevc = false)
{
Name = name;
Units = units;
@@ -22,10 +22,14 @@ internal sealed class ElementaryStream
AvcC = avcC;
Width = width;
Height = height;
Hevc = hevc;
}
public string Name { get; }
/// <summary>An HEVC stream (of the H.265.1 set): then <see cref="AvcC"/> holds its <c>hvcC</c> record.</summary>
public bool Hevc { get; }
/// <summary>The NAL units (without start codes) of each access unit, in decoding order.</summary>
public List<List<byte[]>> Units { get; }
@@ -119,22 +123,74 @@ internal sealed class ElementaryStream
return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height);
}
/// <summary>
/// An HEVC stream of the H.265.1 set cut into access units (§7.4.2.4.4: parameter sets, delimiters and prefix SEI
/// open the next one), with an <c>hvcC</c> record of its VPS, SPS and PPS. Every access unit must give one output
/// frame: streams with skipped RASL pictures or pic_output_flag 0 do not fit.
/// </summary>
public static ElementaryStream LoadHevc(string name)
{
var annexB = File.ReadAllBytes(H265.H265ConformanceStream.Load(name).BitstreamPath);
var units = new List<List<byte[]>>();
List<byte[]>? current = null;
var hasSlice = false;
foreach (var nal in SplitAnnexB(annexB))
{
var type = (nal[0] >> 1) & 63;
var startsPicture = type < 32 && nal.Length > 2 && (nal[2] & 0x80) != 0; // first_slice_segment_in_pic_flag
var beforePicture = type is (>= 32 and <= 35) or 39 or (>= 41 and <= 44) or (>= 48 and <= 55);
if (current is null || (hasSlice && (startsPicture || beforePicture)))
{
current = [];
units.Add(current);
hasSlice = false;
}
current.Add(nal);
hasSlice |= type < 32;
}
var key = units.Select(u => u.Any(n => ((n[0] >> 1) & 63) is >= 16 and <= 23)).ToArray();
var decoder = new Febe.Core.Codecs.H265.H265Decoder();
var frames = new List<Febe.Core.Codecs.H265.H265Frame>();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(annexB);
Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi");
var rank = new int[frames.Count];
for (var i = 0; i < frames.Count; i++)
{
rank[frames[i].DecodeIndex] = i; // FrameOutput comes in output order
}
var sets = units.SelectMany(u => u).Where(n => ((n[0] >> 1) & 63) is >= 32 and <= 34).DistinctBy(Convert.ToBase64String).ToList();
var hvcC = new List<byte>(new byte[21]) { 0xFC | 3, (byte)sets.Count };
hvcC[0] = 1;
foreach (var set in sets)
{
hvcC.AddRange([(byte)(0x80 | ((set[0] >> 1) & 63)), 0, 1, (byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
return new ElementaryStream(name, units, rank, key, [.. hvcC], frames[0].Width, frames[0].Height, hevc: true);
}
private static bool IsParameterSet(byte[] nal, bool hevc) => hevc ? ((nal[0] >> 1) & 63) is >= 32 and <= 34 : (nal[0] & 0x1F) is 7 or 8;
/// <summary>The same stream with only its first access unit, repeated: a video of a still picture.</summary>
public ElementaryStream FirstPictureRepeated(int times)
{
var units = Enumerable.Repeat(Units[0], times).ToList();
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height);
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height, Hevc);
}
/// <summary>
/// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a
/// The same stream with its parameter sets repeated in every access unit, as some cameras and recorders write them: a
/// decoder started at any of its P or B frames finds its parameter sets.
/// </summary>
public ElementaryStream WithParameterSetsEverywhere()
{
var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList();
var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList();
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height);
var sets = Units[0].Where(n => IsParameterSet(n, Hevc)).ToList();
var units = Units.Select(u => u.Any(n => IsParameterSet(n, Hevc)) ? u : [.. sets, .. u]).ToList();
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height, Hevc);
}
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
@@ -227,7 +283,8 @@ internal static class TestVideos
Width = es.Width,
Height = es.Height,
Rotation = rotation,
AvcConfiguration = es.AvcC,
AvcConfiguration = es.Hevc ? null : es.AvcC,
HevcConfiguration = es.Hevc ? es.AvcC : null,
},
};
if (audio)
@@ -365,7 +422,7 @@ internal static class TestVideos
var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height)));
var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]),
Element(0x86, "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
Element(0x86, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
var blocks = new List<byte[]> { Element(0xE7, [0]) };
for (var i = 0; i < es.Count; i++)
{
@@ -392,7 +449,7 @@ internal static class TestVideos
}
var strh = new List<byte>();
strh.AddRange("vidsH264"u8.ToArray());
strh.AddRange(es.Hevc ? "vidsHEVC"u8.ToArray() : "vidsH264"u8.ToArray());
foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 })
{
strh.AddRange(Le32(v));
@@ -406,7 +463,7 @@ internal static class TestVideos
}
strf.AddRange([1, 0, 24, 0]);
strf.AddRange("H264"u8.ToArray());
strf.AddRange(es.Hevc ? "HEVC"u8.ToArray() : "H264"u8.ToArray());
strf.AddRange(new byte[20]);
var hdrl = new List<byte[]> { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) };
if (idit is not null)
@@ -445,9 +502,9 @@ internal static class TestVideos
return path;
}
private static byte[] Avc1(ElementaryStream es) => Box("avc1",
private static byte[] Avc1(ElementaryStream es) => Box(es.Hevc ? "hvc1" : "avc1",
[.. new byte[6], 0, 1, .. new byte[16], .. U16((ushort)es.Width), .. U16((ushort)es.Height), .. U32(0x00480000), .. U32(0x00480000),
.. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box("avcC", es.AvcC)]);
.. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box(es.Hevc ? "hvcC" : "avcC", es.AvcC)]);
private static byte[] Box(string type, params byte[][] children)
{
@@ -0,0 +1,368 @@
using Febe.Core.Codecs.H265;
using Febe.Core.Codecs.Heif;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Heif;
/// <summary>
/// HEIC/HEIF still images (ISO/IEC 23008-12) built from pictures of the ITU-T H.265.1 set: the pixels expected are those
/// of the picture decoded straight from its stream, converted to RGB as video frames are.
/// </summary>
[TestClass]
public sealed class HeifDecoderTests
{
/// <summary>416×240 streams, 8 bit, whose first picture is intra: tiles of a grid.</summary>
private static readonly string[] Tiles = ["INITQP_A_Sony_1", "AMVP_A_MTK_4", "RPS_A_docomo_5", "MERGE_A_TI_3"];
[TestMethod]
[DataRow("INITQP_A_Sony_1", false)]
[DataRow("INITQP_B_Main10_Sony_1", false)]
[DataRow("IPRED_C_Mitsubishi_3", true)]
[DataRow("GENERAL_8b_444_RExt_Sony_2", false)]
[DataRow("GENERAL_8b_400_RExt_Sony_1", true)]
public void ACodedImageIsItsPicture(string name, bool inIdat)
{
var picture = CodedPicture.First(name);
var builder = new HeifBuilder { InIdat = inIdat };
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe);
var file = builder.Build();
var image = HeifDecoder.Decode(file);
Assert.AreEqual((picture.Frame.Width, picture.Frame.Height), (image.Width, image.Height));
Assert.AreEqual(1, image.Orientation);
Assert.IsFalse(image.HasAlpha);
Assert.AreEqual(picture.Frame.BitDepthLuma, image.BitDepth);
CollectionAssert.AreEqual(Rgba(picture.Frame), image.Pixels);
using var stream = new MemoryStream(file);
Assert.AreEqual(new HeifInfo(image.Width, image.Height, 1, false, 1), HeifDecoder.ReadInfo(stream));
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public void AGridIsItsTilesSideBySideCutToItsSize(bool wide)
{
// Four tiles of 416×240 in two rows of two, the output 20 and 12 pixels short of them: as phones cut their
// 512×512 tiles to the size of the photo.
var pictures = Tiles.Select(CodedPicture.First).ToArray();
var (tw, th) = (pictures[0].Frame.Width, pictures[0].Frame.Height);
var (width, height) = ((2 * tw) - 20, (2 * th) - 12);
var builder = new HeifBuilder { WideIndices = wide };
var ispe = builder.Property(HeifBuilder.Ispe(tw, th));
var gridIspe = builder.Property(HeifBuilder.Ispe(width, height));
builder.Item(1, "grid", HeifBuilder.GridData(2, 2, width, height, wide), gridIspe);
for (var i = 0; i < 4; i++)
{
var hvcC = builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC));
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -hvcC, ispe);
}
builder.Reference("dimg", 1, 10, 11, 12, 13);
var image = HeifDecoder.Decode(builder.Build());
Assert.AreEqual((width, height), (image.Width, image.Height));
var expected = new byte[width * height * 4];
for (var i = 0; i < 4; i++)
{
var tile = Rgba(pictures[i].Frame);
var (x0, y0) = (i % 2 * tw, i / 2 * th);
for (var y = 0; y < th && y0 + y < height; y++)
{
var w = Math.Min(tw, width - x0);
tile.AsSpan(y * tw * 4, w * 4).CopyTo(expected.AsSpan((((y0 + y) * width) + x0) * 4));
}
}
CollectionAssert.AreEqual(expected, image.Pixels);
using var stream = new MemoryStream(builder.Build());
Assert.AreEqual(4, HeifDecoder.ReadInfo(stream).Tiles);
}
[TestMethod]
[DataRow(new[] { "irot1" }, 8)]
[DataRow(new[] { "irot3" }, 6)]
[DataRow(new[] { "irot2" }, 3)]
[DataRow(new[] { "imir0" }, 2)]
[DataRow(new[] { "imir1" }, 4)]
[DataRow(new[] { "irot1", "imir0" }, 7)]
[DataRow(new[] { "irot3", "imir0" }, 5)]
[DataRow(new[] { "irot1", "imir1" }, 5)]
[DataRow(new[] { "irot2", "imir0" }, 4)]
[DataRow(new[] { "imir0", "imir1" }, 3)]
public void RotationsAndMirrorsBecomeOneOrientation(string[] transforms, int orientation)
{
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder();
var properties = new List<int>
{
-builder.Property(HeifBuilder.HvcCProperty(picture.HvcC)),
builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height)),
};
foreach (var t in transforms)
{
var value = t[^1] - '0';
properties.Add(-builder.Property(t.StartsWith("irot", StringComparison.Ordinal) ? HeifBuilder.Irot(value) : HeifBuilder.Imir(value)));
}
builder.Item(1, "hvc1", picture.Data, [.. properties]);
var file = builder.Build();
var image = HeifDecoder.Decode(file);
Assert.AreEqual(orientation, image.Orientation);
CollectionAssert.AreEqual(Rgba(picture.Frame), image.Pixels, "l'orientamento non tocca i pixel");
// Through the image decoding of the library: upright, so a quarter turn swaps the sides.
using var stream = new MemoryStream(file);
var size = ImageDecoding.ReadSize(stream);
var quarter = orientation >= 5;
Assert.AreEqual(quarter ? (image.Height, image.Width) : (image.Width, image.Height), size);
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNotNull(bitmap);
Assert.AreEqual(size, (bitmap.Width, bitmap.Height));
}
[TestMethod]
public void TheLibraryTurnsTheImageUprightAndMakesItsThumbnail()
{
// irot 3: a quarter turn anticlockwise three times, i.e. 90° clockwise. The top-left pixel ends top right.
var picture = CodedPicture.First(Tiles[1]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
var irot = builder.Property(HeifBuilder.Irot(3));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, -irot);
var file = builder.Build();
var rgba = Rgba(picture.Frame);
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNotNull(bitmap);
Assert.AreEqual((picture.Frame.Height, picture.Frame.Width), (bitmap.Width, bitmap.Height));
var corner = bitmap.GetPixel(bitmap.Width - 1, 0);
Assert.AreEqual((rgba[0], rgba[1], rgba[2]), (corner.Red, corner.Green, corner.Blue));
using var temp = new TempFolder("miniatura-heic");
var store = new ThumbnailStore(temp.Combine("miniature"));
var key = new string('a', 64);
Assert.IsTrue(store.Create(key, new MemoryStream(file)), "miniatura di un HEIC");
Assert.IsTrue(store.Exists(key));
Assert.IsNotNull(PerceptualHash.Compute(new MemoryStream(file)), "impronta visiva di un HEIC");
}
[TestMethod]
public void TheCleanApertureCutsThePicture()
{
var picture = CodedPicture.First(Tiles[2]);
var (w, h) = (picture.Frame.Width, picture.Frame.Height);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(w, h));
// 200×100 centred, then moved 10 right and 20 down: left = 10 + (w − 1)/2 − 99.5, top = 20 + (h − 1)/2 − 49.5.
var clap = builder.Property(HeifBuilder.Clap(200, 100, 10, 20));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, -clap);
var image = HeifDecoder.Decode(builder.Build());
Assert.AreEqual((200, 100), (image.Width, image.Height));
var left = (int)Math.Round(10 + ((w - 1) / 2.0) - 99.5);
var top = (int)Math.Round(20 + ((h - 1) / 2.0) - 49.5);
var full = Rgba(picture.Frame);
for (var y = 0; y < 100; y++)
{
CollectionAssert.AreEqual(full.AsSpan((((top + y) * w) + left) * 4, 800).ToArray(), image.Pixels.AsSpan(y * 800, 800).ToArray(), $"riga {y}");
}
}
[TestMethod]
public void TheAlphaPlaneFillsTheAlpha()
{
// The alpha plane is another picture of the same size: here the luma of the image itself.
var picture = CodedPicture.First(Tiles[0]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
var auxC = builder.Property(HeifBuilder.AuxC("urn:mpeg:hevc:2015:auxid:1"));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe).Item(2, "hvc1", picture.Data, -hvcC, ispe, -auxC).Reference("auxl", 2, 1);
var file = builder.Build();
var image = HeifDecoder.Decode(file);
Assert.IsTrue(image.HasAlpha);
using (var stream = new MemoryStream(file))
{
Assert.IsTrue(HeifDecoder.ReadInfo(stream).HasAlpha);
}
var frame = picture.Frame;
var expected = Rgba(frame);
for (var i = 0; i < frame.Y.Length; i++)
{
var v = frame.FullRange ? frame.Y[i] : (((frame.Y[i] - 16) * (int)Math.Round(255.0 / 219.0 * 65536)) + 32768) >> 16;
expected[(i * 4) + 3] = (byte)Math.Clamp(v, 0, 255);
}
CollectionAssert.AreEqual(expected, image.Pixels);
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file));
Assert.IsNotNull(bitmap, "anche con la trasparenza");
}
[TestMethod]
public void ColourComesFromNclxWhenThereIsOne()
{
var picture = CodedPicture.First(Tiles[3]);
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
var colr = builder.Property(HeifBuilder.Nclx(9, true));
var icc = builder.Property(HeifBuilder.Icc([1, 2, 3, 4, 5]));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, colr, icc);
var image = HeifDecoder.Decode(builder.Build());
var asIf = picture.Frame with { MatrixCoefficients = 9, FullRange = true };
CollectionAssert.AreEqual(Rgba(asIf), image.Pixels);
CollectionAssert.AreNotEqual(Rgba(picture.Frame), image.Pixels, "BT.2020 a gamma piena non è il colore del VUI");
CollectionAssert.AreEqual(new byte[] { 1, 2, 3, 4, 5 }, image.IccProfile);
}
[TestMethod]
public void TheExifItemGivesItsBlockOrientationAndDate()
{
var picture = CodedPicture.First(Tiles[0]);
// A TIFF block with only an Orientation tag (6), big endian.
byte[] oriented = [.. "MM\0*"u8, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0, 0, 0];
var image = HeifDecoder.Decode(WithExif(picture, oriented));
CollectionAssert.AreEqual(oriented, image.Exif);
Assert.AreEqual(6, image.ExifOrientation);
Assert.AreEqual(1, image.Orientation, "l'orientamento EXIF è solo informativo");
// The shooting date of an HEIC, as the import reads it from the first bytes of the file.
var dated = WithExif(picture, ImportTestFiles.Tiff("2023:07:08 09:10:11", offsetOriginal: "+02:00"));
var date = ExifDateReader.Read(dated, TimeZoneInfo.Utc);
Assert.AreEqual(new DateTimeOffset(2023, 7, 8, 9, 10, 11, TimeSpan.FromHours(2)), date);
Assert.IsNull(ExifDateReader.Read(dated.AsSpan(0, 200), TimeZoneInfo.Utc), "il blocco oltre i byte letti non si trova");
}
[TestMethod]
public void WhatIsNotAnHevcImageIsRefused()
{
var picture = CodedPicture.First(Tiles[0]);
// AVIF: an av01 primary item.
var avif = new HeifBuilder { Brand = "avif" };
avif.Item(1, "av01", [1, 2, 3]);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(avif.Build()));
// An essential property Febe does not know.
var unknown = new HeifBuilder();
var hvcC = unknown.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var odd = unknown.Property([0, 0, 0, 9, .. "zzzz"u8, 1]);
unknown.Item(1, "hvc1", picture.Data, -hvcC, -odd);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(unknown.Build()));
// A grid that names fewer tiles than its rows and columns.
var grid = new HeifBuilder();
var p = grid.Property(HeifBuilder.HvcCProperty(picture.HvcC));
grid.Item(1, "grid", HeifBuilder.GridData(1, 2, 100, 100)).Item(2, "hvc1", picture.Data, -p).Reference("dimg", 1, 2);
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(grid.Build()));
// Not HEIF at all, and a picture whose HEVC data is cut.
Assert.IsFalse(HeifDecoder.Looks("not a heif file at all"u8));
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode([0, 0, 0, 16, .. "ftypheic"u8, 0, 0, 0, 0]));
var cut = new HeifBuilder();
var c = cut.Property(HeifBuilder.HvcCProperty(picture.HvcC));
cut.Item(1, "hvc1", picture.Data[..(picture.Data.Length / 3)], -c, cut.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height)));
Assert.ThrowsExactly<HeifException>(() => HeifDecoder.Decode(cut.Build()));
using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(cut.Build()));
Assert.IsNull(bitmap, "un HEIC rovinato non ha miniatura, senza eccezioni");
}
[TestMethod]
[DataRow(6101)]
[DataRow(6102)]
public void DamagedFilesOnlyRaiseHeifException(int seed)
{
var pictures = Tiles.Take(2).Select(CodedPicture.First).ToArray();
var builder = new HeifBuilder();
var ispe = builder.Property(HeifBuilder.Ispe(pictures[0].Frame.Width, pictures[0].Frame.Height));
var rot = builder.Property(HeifBuilder.Irot(1));
builder.Item(1, "grid", HeifBuilder.GridData(1, 2, 800, 240), -rot);
for (var i = 0; i < 2; i++)
{
builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe);
}
builder.Reference("dimg", 1, 10, 11);
builder.Item(20, "Exif", HeifBuilder.ExifData(ImportTestFiles.Tiff("2020:01:02 03:04:05"))).Reference("cdsc", 20, 1);
var file = builder.Build();
var whole = HeifDecoder.Decode(file);
Assert.AreEqual((800, 240, 8), (whole.Width, whole.Height, whole.Orientation));
var random = new Random(seed);
var decoded = 0;
for (var trial = 0; trial < 150; trial++)
{
var copy = (byte[])file.Clone();
var changes = random.Next(1, 6);
for (var k = 0; k < changes; k++)
{
// Mostly in the boxes before the data, where a change hits the structure.
var at = random.Next(4) == 0 ? random.Next(copy.Length) : random.Next(Math.Min(copy.Length, 700));
copy[at] = (byte)random.Next(256);
}
if (random.Next(5) == 0)
{
copy = copy[..random.Next(copy.Length)];
}
try
{
_ = HeifDecoder.Decode(copy);
decoded++;
}
catch (HeifException)
{
}
using var stream = new MemoryStream(copy);
try
{
_ = HeifDecoder.ReadInfo(stream);
}
catch (HeifException)
{
}
_ = HeifDecoder.FindExif(copy); // null or a block, never an exception
_ = ExifDateReader.Read(copy, TimeZoneInfo.Utc);
}
Assert.IsGreaterThan(0, decoded, "nessuna variante decodificata");
}
private static byte[] WithExif(CodedPicture picture, byte[] tiff)
{
var builder = new HeifBuilder();
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe).Item(2, "Exif", HeifBuilder.ExifData(tiff)).Reference("cdsc", 2, 1);
return builder.Build();
}
/// <summary>The frame in RGBA, as the video frames are converted (the same coefficients, opaque).</summary>
private static byte[] Rgba(H265Frame frame)
{
var rgb = VideoFrameDecoder.ToImage(frame, 0, 0).Rgb;
var rgba = new byte[rgb.Length / 3 * 4];
for (int i = 0, o = 0; i < rgb.Length; i += 3, o += 4)
{
rgba[o] = rgb[i];
rgba[o + 1] = rgb[i + 1];
rgba[o + 2] = rgb[i + 2];
rgba[o + 3] = 255;
}
return rgba;
}
}
+239
View File
@@ -0,0 +1,239 @@
using System.Text;
using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
using Febe.Tests.Codecs.H265;
namespace Febe.Tests.Codecs.Heif;
/// <summary>
/// The first picture of a stream of the ITU-T H.265.1 set, as a HEIF image item holds it: its parameter sets in an
/// <c>hvcC</c> record, its NAL units with 4-byte lengths; and the picture itself, decoded straight from the Annex B
/// stream (not through <c>hvcC</c>), to compare with.
/// </summary>
internal sealed class CodedPicture
{
private CodedPicture(byte[] hvcC, byte[] data, H265Frame frame)
{
HvcC = hvcC;
Data = data;
Frame = frame;
}
public byte[] HvcC { get; }
public byte[] Data { get; }
public H265Frame Frame { get; }
public static CodedPicture First(string name)
{
var annexB = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath);
var sets = new List<byte[]>();
var picture = new List<byte[]>();
var position = 0;
var end = annexB.Length;
while (NalUnits.NextAnnexB(annexB, ref position, out var range))
{
var nal = annexB[range];
var type = (nal[0] >> 1) & 63;
if (type < 32 && (nal[2] & 0x80) != 0 && picture.Count > 0)
{
end = range.Start.Value;
break; // the second picture starts
}
if (type is >= 32 and <= 34)
{
if (picture.Count > 0)
{
end = range.Start.Value;
break;
}
sets.Add(nal);
}
else if (type < 32)
{
picture.Add(nal);
}
}
var hvcC = new List<byte>(new byte[21]) { 0xFC | 3, (byte)sets.Count };
hvcC[0] = 1;
foreach (var set in sets)
{
hvcC.AddRange([(byte)(0x80 | ((set[0] >> 1) & 63)), 0, 1, (byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
var data = new List<byte>();
foreach (var nal in picture)
{
data.AddRange([(byte)(nal.Length >> 24), (byte)(nal.Length >> 16), (byte)(nal.Length >> 8), (byte)nal.Length, .. nal]);
}
H265Frame? first = null;
var decoder = new H265Decoder();
decoder.FrameDecoded += f => first ??= f;
decoder.DecodeAnnexB(annexB.AsSpan(0, end)); // the first picture only
return new CodedPicture([.. hvcC], [.. data], first!);
}
}
/// <summary>
/// A builder of HEIF files (ISO/IEC 23008-12) for the tests: <c>ftyp</c>, a <c>meta</c> box with <c>hdlr</c>,
/// <c>pitm</c>, <c>iinf</c>, <c>iloc</c> (version 1, offsets in the file or in <c>idat</c>), <c>iref</c> and
/// <c>iprp</c>, then one <c>mdat</c> with the data of the items.
/// </summary>
internal sealed class HeifBuilder
{
private readonly List<Entry> items = [];
private readonly List<byte[]> properties = [];
private readonly List<(string Type, uint From, uint[] To)> references = [];
public uint Primary { get; set; } = 1;
/// <summary>Major brand of the ftyp box.</summary>
public string Brand { get; set; } = "heic";
/// <summary>The item data goes into idat instead of mdat.</summary>
public bool InIdat { get; set; }
/// <summary>The ipma entries use 16-bit property indices (flags bit 0).</summary>
public bool WideIndices { get; set; }
/// <summary>Adds an item; <paramref name="properties"/> are indices from <see cref="Property"/>, negative for essential.</summary>
public HeifBuilder Item(uint id, string type, byte[] data, params int[] properties)
{
items.Add(new Entry(id, type, data, properties));
return this;
}
/// <summary>Adds a property box and returns its 1-based index.</summary>
public int Property(byte[] box)
{
properties.Add(box);
return properties.Count;
}
public HeifBuilder Reference(string type, uint from, params uint[] to)
{
references.Add((type, from, to));
return this;
}
public static byte[] HvcCProperty(byte[] hvcC) => Box("hvcC", hvcC);
public static byte[] Ispe(int width, int height) => FullBox("ispe", 0, [.. U32((uint)width), .. U32((uint)height)]);
public static byte[] Irot(int quarterTurnsAnticlockwise) => Box("irot", [(byte)quarterTurnsAnticlockwise]);
public static byte[] Imir(int axis) => Box("imir", [(byte)axis]);
public static byte[] Clap(int width, int height, int horizontalOffset, int verticalOffset) =>
Box("clap", [.. U32((uint)width), .. U32(1), .. U32((uint)height), .. U32(1), .. U32((uint)horizontalOffset), .. U32(1),
.. U32((uint)verticalOffset), .. U32(1)]);
public static byte[] Nclx(int matrix, bool fullRange) =>
Box("colr", [.. "nclx"u8, 0, 1, 0, 13, (byte)(matrix >> 8), (byte)matrix, fullRange ? (byte)0x80 : (byte)0]);
public static byte[] Icc(byte[] profile) => Box("colr", [.. "prof"u8, .. profile]);
public static byte[] AuxC(string type) => FullBox("auxC", 0, [.. Encoding.ASCII.GetBytes(type), 0]);
/// <summary>The data of a grid item (version 0): rows, columns, output size in 16 or 32 bits.</summary>
public static byte[] GridData(int rows, int columns, int width, int height, bool wide = false) => wide
? [0, 1, (byte)(rows - 1), (byte)(columns - 1), .. U32((uint)width), .. U32((uint)height)]
: [0, 0, (byte)(rows - 1), (byte)(columns - 1), (byte)(width >> 8), (byte)width, (byte)(height >> 8), (byte)height];
/// <summary>The data of an Exif item: the offset of the TIFF header after «Exif\0\0», then both.</summary>
public static byte[] ExifData(byte[] tiff) => [0, 0, 0, 6, .. "Exif\0\0"u8, .. tiff];
public byte[] Build()
{
var ftyp = Box("ftyp", [.. Encoding.ASCII.GetBytes(Brand), 0, 0, 0, 0, .. "mif1"u8, .. Encoding.ASCII.GetBytes(Brand)]);
// The meta box is built twice: the first time only to learn its size, so that the offsets into mdat are known.
var meta = Meta(0);
var mdatStart = ftyp.Length + meta.Length + 8;
meta = Meta(mdatStart);
var payload = InIdat ? [] : items.SelectMany(i => i.Data).ToArray();
return [.. ftyp, .. meta, .. Box("mdat", payload)];
}
private byte[] Meta(int mdatStart)
{
var hdlr = FullBox("hdlr", 0, [0, 0, 0, 0, .. "pict"u8, .. new byte[12], 0]);
var pitm = FullBox("pitm", 0, U16((ushort)Primary));
var infe = items.Select(i => FullBox("infe", 2u << 24, [.. U16((ushort)i.Id), 0, 0, .. Encoding.ASCII.GetBytes(i.Type), 0])).ToList();
var iinf = FullBox("iinf", 0, [.. U16((ushort)items.Count), .. infe.SelectMany(b => b)]);
// iloc version 1: offset_size 4, length_size 4, base_offset_size 0, index_size 0.
var iloc = new List<byte> { 0x44, 0x00 };
iloc.AddRange(U16((ushort)items.Count));
var offset = InIdat ? 0 : mdatStart;
foreach (var item in items)
{
iloc.AddRange(U16((ushort)item.Id));
iloc.AddRange(U16(InIdat ? (ushort)1 : (ushort)0)); // construction_method
iloc.AddRange(U16(0));
iloc.AddRange(U16(1));
iloc.AddRange(U32((uint)offset));
iloc.AddRange(U32((uint)item.Data.Length));
offset += item.Data.Length;
}
var ipma = new List<byte>();
var associated = items.Where(i => i.Properties.Length > 0).ToList();
ipma.AddRange(U32((uint)associated.Count));
foreach (var item in associated)
{
ipma.AddRange(U16((ushort)item.Id));
ipma.Add((byte)item.Properties.Length);
foreach (var p in item.Properties)
{
var index = Math.Abs(p);
if (WideIndices)
{
ipma.AddRange(U16((ushort)((p < 0 ? 0x8000 : 0) | index)));
}
else
{
ipma.Add((byte)((p < 0 ? 0x80 : 0) | index));
}
}
}
var iprp = Box("iprp", Box("ipco", [.. properties.SelectMany(b => b)]), FullBox("ipma", WideIndices ? 1u : 0u, [.. ipma]));
var children = new List<byte[]> { hdlr, pitm, FullBox("iloc", 1u << 24, [.. iloc]), iinf };
if (references.Count > 0)
{
var refs = references.Select(r => Box(r.Type, [.. U16((ushort)r.From), .. U16((ushort)r.To.Length), .. r.To.SelectMany(t => U16((ushort)t))]));
children.Add(FullBox("iref", 0, [.. refs.SelectMany(b => b)]));
}
children.Add(iprp);
if (InIdat)
{
children.Add(Box("idat", [.. items.SelectMany(i => i.Data)]));
}
return FullBox("meta", 0, [.. children.SelectMany(b => b)]);
}
private static byte[] Box(string type, params byte[][] children)
{
var body = children.SelectMany(c => c).ToArray();
return [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body];
}
private static byte[] Box(string type, byte[] body) => [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body];
/// <summary>A full box: <paramref name="versionAndFlags"/> holds the version in its top byte and the flags below.</summary>
private static byte[] FullBox(string type, uint versionAndFlags, byte[] body) => Box(type, [.. U32(versionAndFlags), .. body]);
private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v];
private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v];
private sealed record Entry(uint Id, string Type, byte[] Data, int[] Properties);
}