diff --git a/docs/decisioni.md b/docs/decisioni.md index e34832c..5f0219b 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -432,3 +432,8 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | +| 2026-11-18 | Limiti del decodificatore HEVC e di quello HEIF contro i file danneggiati: un SPS con `sps_max_dec_pic_buffering` oltre il MaxDpbSize del livello 6.2 (A.4.2: 16 immagini fino a un quarto di MaxLumaPs, 12 fino a metà, 8 fino a tre quarti, poi 6) è rifiutato; il buffer delle immagini non supera mai `sps_max_dec_pic_buffering` + 1 (oltre, `H265Exception`); una sola immagine grigia generata, tenuta e riusata per dimensione e profondità, sta per ogni riferimento mancante (il suo POC viaggia nelle liste di riferimento, non nell'immagine). Nei file HEIF ogni immagine HEVC deve avere la dimensione del suo `ispe` (`H265Decoder.ExpectedFrameSize`, controllata prima di allocare l'immagine); i riquadri di una griglia hanno tutti lo stesso `ispe`, coprono l'uscita sporgendo meno di un riquadro e insieme non superano `MaxPixels`; i loro byte non superano né il file né `HeifLimits.MaxTotalBytes` (512 MB), e un riquadro nominato più volte si legge una volta; qualunque errore dei riquadri decodificati in parallelo esce come `HeifException` | Revisione del ramo: un flusso di pochi byte poteva far allocare gigabyte (48 immagini grigie da 236 MB per una sola immagine P, un buffer che cresce senza fine), un `ispe` piccolo non limitava l'immagine dell'SPS, riquadri che puntano agli stessi byte moltiplicavano il file, uno `ispe` enorme faceva traboccare le posizioni dei riquadri e l'eccezione usciva dal decodificatore come `AggregateException`. Un `OutOfMemoryException` non è fra gli errori che segnano un file come illeggibile. La stessa immagine grigia per riferimenti mancanti diversi cambia solo il deblocking dei flussi già rovinati | +| 2026-11-18 | Decodificatore HEVC: un SPS o un PPS ripetuto identico dentro un'unità di accesso si ignora (resta l'oggetto attivo); uno con lo stesso ID e un contenuto diverso, arrivato mentre un'immagine lo usa, vale dall'immagine dopo; fra i segmenti di un'immagine si confronta il contenuto, non l'oggetto. Le estensioni per i contenuti dello schermo (SCC: `sps_scc_extension_flag`, `pps_scc_extension_flag`, profili 9 e 11) sono rifiutate con `H265Exception` prima di decodificare; i profili High Throughput 4:4:4 (5) no, perché i loro strumenti in più sono già rifiutati uno per uno. `luma_offset_l0/l1` va da −WpOffsetHalfRangeY a WpOffsetHalfRangeY − 1 (7-45: 2^(BitDepthY−1) con `high_precision_offsets_enabled_flag`). La conversione dei colori (`YuvToRgb`) tratta YCgCo (matrice 8) con le sue equazioni; la 10 (BT.2020 a luminanza costante) è approssimata con la 9, le 11–14 con BT.709/601 come le sconosciute, e la documentazione lo dice | §7.4.2.4.4 permette di ripetere i parametri ovunque prima dell'ultima slice dell'unità di accesso: prima un flusso conforme che lo faceva era rifiutato. Senza il rifiuto un flusso SCC si leggeva con la sintassi della versione 1 e dava immagini sbagliate o un errore a caso. Gli scostamenti della luma oltre ±128 sono validi a 10 e 12 bit con l'alta precisione. Prove nuove su flussi HEVC scritti bit per bit con un codificatore CABAC di prova (`H265SyntheticStreams`) | +| 2026-11-18 | Righe precedenti superate. La riga del 18/11 sulla rimozione di ffmpeg diceva che HEVC si legge nei contenitori ma resta senza fotogramma: per HEVC la sostituisce la riga «HEVC nella catena dei media» (HEVC ha il suo fotogramma; VP9 e AV1 restano senza). La riga del 18/11 sui flussi di conformità diceva che le prove inconcludenti avrebbero fermato la verifica: la sostituisce, per questo, la terza parte del decodificatore (nessuna prova HEVC è più inconcludente). Nelle righe della seconda e della terza parte HEIF, «elemento `hvc1`», «elemento `Exif`» e «tessere» vogliono dire oggetto (item) e riquadro di HEIF: codice, messaggi e documenti dicono ora «oggetto» e «riquadro», perché nel glossario (appendice D) «elemento» è una pubblicazione e la tessera è quella dell'interfaccia | Le righe di questo file non si correggono, si aggiungono: senza questa riga chi legge troverebbe affermazioni opposte con la stessa data | +| 2026-11-18 | Da passare al binario dei documenti prima di unire il ramo, perché qui non si toccano: SPECIFICA §8.4 (fotogramma dei video importati «con ffmpeg» e «ffprobe dove è presente»), l'elenco dei pacchetti dell'immagine Docker (ffmpeg) e quello dei processi figli (ffmpeg, ffprobe), nessuna parola su HEVC e HEIC; `docs/stato.md` nomina ancora ffmpeg e ffprobe. SkiaSharp in §3 resta giusto finché la tappa C1 non lo toglie | Revisione del ramo: la specifica e lo stato non dicono più ciò che il codice fa | +| 2026-11-18 | Restano componenti esterni che la regola del 18 novembre non ammette e che questo ramo non toglie: NSIS per l'installatore (`ambiente-prove.sh`, `makensis`), Node nella CI (lavoro su `node:24-trixie`, `node --check` in `controlli.sh`), tini come processo 1 dell'immagine Docker (con `passwd` e `util-linux`). Alberto ha già detto: installatore senza NSIS, CI senza Node (passi in shell con git e curl). Piano, in una tappa sua: un costruttore dell'installatore scritto in casa; i passi della CI in shell e un controllo della sintassi dei file JavaScript scritto in casa; per il processo 1, Febe che raccoglie da sé i processi figli (Chromium, Xvfb) e inoltra i segnali, da decidere con Alberto perché `docker run --init` userebbe di nuovo tini | Revisione del ramo: le regole di oggi valgono anche per ciò che c'era prima, ma sostituire installatore, CI e processo 1 non è lavoro del decodificatore HEVC e va provato a parte (installatore su Windows, immagine nella CI) | diff --git a/docs/docker.md b/docs/docker.md index 7cb7f45..4192924 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -73,7 +73,7 @@ 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, 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). +leggono con codice di Febe, e così le foto HEIC/HEIF (griglie di riquadri, rotazione, trasparenza, EXIF). ## Porte diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs index 73d43ed..0f0c4ab 100644 --- a/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs +++ b/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs @@ -94,11 +94,11 @@ public sealed partial class H265Decoder { var entry = temp[h.ListModification[list] ? h.ListEntry[list][i] : i]; var longTerm = entry >= before + after; - var picture = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after]; + var (picture, refPoc) = entry < before ? refStCurrBefore[entry] : !longTerm ? refStCurrAfter[entry - before] : refLtCurr[entry - before - after]; h.RefPicList[list][i] = picture; - h.RefPoc[list][i] = picture.Poc; + h.RefPoc[list][i] = refPoc; h.RefIsLongTerm[list][i] = longTerm; - h.NoBackwardPred &= picture.Poc <= cur!.Poc; + h.NoBackwardPred &= refPoc <= cur!.Poc; } } @@ -307,6 +307,7 @@ public sealed partial class H265Decoder var motion = cur!.Motion; var target = slice.RefPicList[x][refIdx]; var targetLongTerm = slice.RefIsLongTerm[x][refIdx]; + var targetPoc = slice.RefPoc[x][refIdx]; var poc = cur.Poc; // A: A0 then A1. @@ -328,7 +329,7 @@ public sealed partial class H265Decoder { if (k == 0 ? availableA0 : availableA1) { - flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, targetLongTerm, poc, out ax, out ay); + flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, targetPoc, targetLongTerm, poc, out ax, out ay); } } @@ -361,7 +362,7 @@ public sealed partial class H265Decoder { if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2) { - flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, targetLongTerm, poc, out bx, out by); + flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, targetPoc, targetLongTerm, poc, out bx, out by); } } } @@ -434,7 +435,7 @@ public sealed partial class H265Decoder /// The second conditions of §8.5.3.2.7: a neighbour whose reference is long-term exactly when the target is, its /// vector scaled by the POC distances when both are short-term. /// - private bool ScaledCandidate(in MvField n, int x, Picture target, bool targetLongTerm, int poc, out int mx, out int my) + private bool ScaledCandidate(in MvField n, int x, int targetPoc, bool targetLongTerm, int poc, out int mx, out int my) { for (var pass = 0; pass < 2; pass++) { @@ -450,7 +451,7 @@ public sealed partial class H265Decoder if (!targetLongTerm) { var td = Math.Clamp(poc - slice.RefPoc[list][refIdx], -128, 127); - var tb = Math.Clamp(poc - target.Poc, -128, 127); + var tb = Math.Clamp(poc - targetPoc, -128, 127); if (td != 0) { mx = ScaleMv(mx, td, tb); diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.cs b/src/Febe.Core/Codecs/H265/H265Decoder.cs index c57a191..bf61065 100644 --- a/src/Febe.Core/Codecs/H265/H265Decoder.cs +++ b/src/Febe.Core/Codecs/H265/H265Decoder.cs @@ -22,8 +22,10 @@ public enum H265AccessPoint /// motion vector prediction, weighted prediction), deblocking and SAO, and the range extension tools (cross-component /// prediction, implicit and explicit RDPCM, transform skip rotation and contexts, persistent Rice adaptation, chroma QP /// offset lists, intra smoothing disabled, high precision offsets). Not handled (an ): extended -/// precision processing, the CABAC bypass alignment, separate colour planes, bit depths above 12; the layers above 0 of -/// scalable and multiview streams are ignored. +/// precision processing, the CABAC bypass alignment, the screen content coding extensions (SCC), separate colour planes, +/// bit depths above 12; the layers above 0 of scalable and multiview streams are ignored. Against damaged streams the +/// decoded picture buffer is bounded by the SPS (itself bounded by level 6.2) and one generated picture stands for every +/// missing reference. /// public sealed partial class H265Decoder { @@ -53,12 +55,31 @@ public sealed partial class H265Decoder private bool skipping; /// - /// The three lists of the reference picture set that the current picture uses (§8.3.2), a generated picture in place - /// of "no reference picture" (§8.3.3). + /// The three lists of the reference picture set that the current picture uses (§8.3.2), each picture with the POC the + /// set gives it; the generated picture in place of every "no reference picture" (§8.3.3). /// - private readonly List refStCurrBefore = []; - private readonly List refStCurrAfter = []; - private readonly List refLtCurr = []; + private readonly List<(Picture Picture, int Poc)> refStCurrBefore = []; + private readonly List<(Picture Picture, int Poc)> refStCurrAfter = []; + private readonly List<(Picture Picture, int Poc)> refLtCurr = []; + + /// + /// The picture that stands for every missing reference (§8.3.3.2), made once for a size, chroma format and bit depth + /// and shared: a damaged stream that names dozens of missing references costs one picture, not one each. + /// + private Picture? missing; + + /// + /// SPS and PPS that came, with an ID the current picture uses and a different content, between its slice segments: + /// they apply from the next picture (§7.4.2.4.4), and are installed when the current one is finished. + /// + private readonly List pendingSps = []; + private readonly List pendingPps = []; + + /// + /// Pictures the DPB may hold beyond sps_max_dec_pic_buffering_minus1 + 1 before the stream is refused: a conforming + /// stream never needs it (C.5.2.2), a damaged one that keeps every picture as a reference cannot grow it further. + /// + private const int DpbMargin = 1; /// Raised for each frame in output order (the bumping process of C.5.2.4), cropped. public event Action? FrameOutput; @@ -79,6 +100,13 @@ public sealed partial class H265Decoder /// Coded pictures met so far, also those skipped. public long PicturesDecoded => codedPictures; + /// + /// The size every picture must have once cropped (a HEIF image of known ispe), or null for any size the + /// levels allow. A picture of another size, or coded much larger than it (a conformance window that throws most of + /// it away), is refused with an before anything of its size is allocated. + /// + public (int Width, int Height)? ExpectedFrameSize { get; set; } + /// Decodes a whole Annex B byte stream, then outputs every picture left. public void DecodeAnnexB(ReadOnlySpan stream) { @@ -232,18 +260,11 @@ public sealed partial class H265Decoder DecodeSlice(H265NalUnit.Unescape(bytes, ref rbsp)); break; case 33: - { - var sps = Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader()); - spss[sps.Id] = sps; - break; - } - + InstallSps(Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader())); + break; case 34: - { - var pps = Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader()); - ppss[pps.Id] = pps; - break; - } + InstallPps(Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader())); + break; case 35: // access unit delimiter FinishPicture(); @@ -284,7 +305,7 @@ public sealed partial class H265Decoder return; } } - else if (!ReferenceEquals(s, sps) || !ReferenceEquals(p, pps)) + else if (!s.SameContent(sps) || !p.SameContent(pps)) { throw new H265Exception("Parametri diversi fra le slice di un'immagine."); } @@ -335,6 +356,21 @@ public sealed partial class H265Decoder throw new H265Exception("La precisione estesa e l'allineamento CABAC delle estensioni di formato HEVC non sono gestiti."); } + if (s.UsesScreenContentCoding || p.SccExtension) + { + throw new H265Exception("Le estensioni HEVC per i contenuti dello schermo (SCC) non sono gestite."); + } + + if (ExpectedFrameSize is { } expected) + { + // A conformance window crops at most what pads the picture to its coding blocks (at most 63 samples). + int width = s.Width - s.ConfLeft - s.ConfRight, height = s.Height - s.ConfTop - s.ConfBottom; + if (width != expected.Width || height != expected.Height || s.Width - width > 63 || s.Height - height > 63) + { + throw new H265Exception("Immagine HEVC di dimensioni diverse da quelle attese."); + } + } + p.Activate(s); // Picture order count (§8.3.1). @@ -400,6 +436,13 @@ public sealed partial class H265Decoder break; } } + + // Nothing left to output and still no room: every picture is kept as a reference, which a conforming stream + // never does. Without this bound a damaged one would keep up to 48 pictures (16 short-term, 32 long-term). + if (dpb.Count > s.MaxDecPicBufferingMinus1[t] + DpbMargin) + { + throw new H265Exception("Più immagini di riferimento di quante ne tiene il buffer dell'SPS."); + } } firstPicture = false; @@ -468,7 +511,7 @@ public sealed partial class H265Decoder if (h.UsedByCurrPicLt[i]) { - refLtCurr.Add(found >= 0 ? dpb[found] : MissingReference(s, pocLt)); + refLtCurr.Add(found >= 0 ? (dpb[found], dpb[found].Poc) : (MissingReference(s), pocLt)); } } @@ -479,7 +522,7 @@ public sealed partial class H265Decoder var picture = FindShortTerm(poc + rps.DeltaPocS0[i], keep); if (rps.UsedS0[i]) { - refStCurrBefore.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS0[i])); + refStCurrBefore.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS0[i])); } } @@ -488,7 +531,7 @@ public sealed partial class H265Decoder var picture = FindShortTerm(poc + rps.DeltaPocS1[i], keep); if (rps.UsedS1[i]) { - refStCurrAfter.Add(picture ?? MissingReference(s, poc + rps.DeltaPocS1[i])); + refStCurrAfter.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS1[i])); } } } @@ -504,19 +547,89 @@ public sealed partial class H265Decoder } /// - /// A picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block - /// intra. It is not put in the DPB and never output; only damaged or cut streams need one. + /// The picture for a reference that is not in the DPB (§8.3.3.2): every sample at the middle of its range, every block + /// intra. It is not put in the DPB and never output; only damaged or cut streams need one. One picture serves every + /// missing reference of the same size and bit depth (its POC travels in the reference lists, not in the picture): + /// it is never written, and a stream that names 48 missing references allocates it once. /// - private static Picture MissingReference(Sps s, int poc) + private Picture MissingReference(Sps s) { - var picture = new Picture(s) { Poc = poc, Generated = true }; - picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1))); - picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1))); - picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1))); - picture.Motion.AsSpan().Fill(MvField.Intra); + var picture = missing; + if (picture is null || !picture.Fits(s) || picture.Sps.BitDepthY != s.BitDepthY || picture.Sps.BitDepthC != s.BitDepthC) + { + picture = new Picture(s) { Generated = true }; + picture.Planes[0].AsSpan().Fill((ushort)(1 << (s.BitDepthY - 1))); + picture.Planes[1].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1))); + picture.Planes[2].AsSpan().Fill((ushort)(1 << (s.BitDepthC - 1))); + picture.Motion.AsSpan().Fill(MvField.Intra); + missing = picture; + } + + picture.Sps = s; return picture; } + /// + /// Takes a new SPS. An identical copy of the one in place is dropped, so the active object stays (§7.4.2.4.4 lets a + /// stream repeat it anywhere in an access unit); one that carries the ID of the current picture's SPS waits until + /// that picture is finished. + /// + private void InstallSps(Sps s) + { + if (cur is not null && s.Id == sps.Id) + { + if (pendingSps.Count > 0 || !s.SameContent(spss[s.Id])) + { + pendingSps.RemoveAll(x => x.Id == s.Id); + pendingSps.Add(s); + } + + return; + } + + if (!s.SameContent(spss[s.Id])) + { + spss[s.Id] = s; + } + } + + /// Takes a new PPS, as does. + private void InstallPps(Pps p) + { + if (cur is not null && p.Id == pps.Id) + { + if (pendingPps.Count > 0 || !p.SameContent(ppss[p.Id])) + { + pendingPps.RemoveAll(x => x.Id == p.Id); + pendingPps.Add(p); + } + + return; + } + + if (!p.SameContent(ppss[p.Id])) + { + ppss[p.Id] = p; + } + } + + /// Installs the parameter sets that waited for the end of the picture. + private void InstallPending() + { + foreach (var s in pendingSps) + { + spss[s.Id] = s; + } + + foreach (var p in pendingPps) + { + ppss[p.Id] = p; + } + + pendingSps.Clear(); + pendingPps.Clear(); + } + private Picture? FindShortTerm(int poc, Span keep) { for (var k = 0; k < dpb.Count; k++) @@ -619,6 +732,7 @@ public sealed partial class H265Decoder var picture = cur; cur = null; + InstallPending(); picture.IntraOnly = true; foreach (var header in slices) { diff --git a/src/Febe.Core/Codecs/H265/ParameterSets.cs b/src/Febe.Core/Codecs/H265/ParameterSets.cs index 17ea217..243bd6e 100644 --- a/src/Febe.Core/Codecs/H265/ParameterSets.cs +++ b/src/Febe.Core/Codecs/H265/ParameterSets.cs @@ -298,6 +298,9 @@ internal sealed class Sps /// Largest width or height of any level: Sqrt(MaxLumaPs × 8). internal const int MaxDimension = 16_888; + /// The RBSP after the NAL unit header, without trailing zero bytes: what "the same content" compares. + internal byte[] Raw = []; + internal int Id; internal int MaxSubLayersMinus1; internal int ProfileIdc; @@ -372,12 +375,36 @@ internal sealed class Sps internal int HighestTid => MaxSubLayersMinus1; + /// sps_scc_extension_flag: the screen content coding tools (palette, adaptive colour transform, ...). + internal bool SccExtension; + /// /// The range extension tools the decoder does not handle: extended_precision_processing_flag and /// cabac_bypass_alignment_enabled_flag, which only the 16-bit and High Throughput 4:4:4 profiles use. /// internal bool UsesUnsupportedTools => ExtendedPrecisionProcessing || CabacBypassAlignmentEnabled; + /// + /// The screen content coding extensions (§7.3.2.2.3; profiles 9, Screen-Extended, and 11, High Throughput + /// Screen-Extended, of A.3.7), whose coding units have a syntax the decoder does not read: palette mode, adaptive + /// colour transform, the current picture as a reference. The High Throughput 4:4:4 profiles (5) are not refused on + /// their own: their tools beyond RExt are those of . + /// + internal bool UsesScreenContentCoding => SccExtension || ProfileIdc is 9 or 11; + + /// + /// MaxDpbSize of A.4.2 for a picture of luma samples at level 6.2, the largest of any + /// level: 6 pictures of MaxLumaPs, up to 16 of a quarter of it (maxDpbPicBuf is 6). + /// + internal static int MaxDpbSize(long pictureSize) => + pictureSize <= MaxLumaPs >> 2 ? 16 : pictureSize <= MaxLumaPs >> 1 ? 12 : pictureSize <= (3L * MaxLumaPs) >> 2 ? 8 : 6; + + /// Whether is this SPS or one with the same content. + internal bool SameContent(Sps? other) => other is not null && (ReferenceEquals(this, other) || Raw.AsSpan().SequenceEqual(other.Raw)); + + /// The bytes holds, read before parsing starts (the reader is past the NAL unit header). + internal static byte[] RawOf(BitReader r) => r.Data.AsSpan(r.Position >> 3, r.Length - (r.Position >> 3)).TrimEnd((byte)0).ToArray(); + /// log2 of SubWidthC and SubHeightC (table 6-1). internal int ChromaShiftX => SubWidthC - 1; @@ -385,7 +412,7 @@ internal sealed class Sps internal static Sps Parse(BitReader r) { - var s = new Sps(); + var s = new Sps { Raw = RawOf(r) }; r.Skip(4); // sps_video_parameter_set_id s.MaxSubLayersMinus1 = r.ReadInt(3); if (s.MaxSubLayersMinus1 > 6) @@ -425,9 +452,17 @@ internal sealed class Sps s.BitDepthC = r.ReadUe(8) + 8; s.Log2MaxPocLsb = r.ReadUe(12) + 4; var orderingInfo = r.ReadFlag(); + var maxDpbSize = MaxDpbSize((long)s.Width * s.Height); for (var i = orderingInfo ? 0 : s.MaxSubLayersMinus1; i <= s.MaxSubLayersMinus1; i++) { + // The pictures the DPB holds must fit in the largest buffer of any level (A.4.2): with 16 pictures of the + // largest size a damaged SPS would make the decoder keep gigabytes. s.MaxDecPicBufferingMinus1[i] = r.ReadUe(15); + if (s.MaxDecPicBufferingMinus1[i] + 1 > maxDpbSize) + { + throw new H265Exception("Buffer delle immagini più grande di ogni livello HEVC."); + } + s.MaxNumReorderPics[i] = r.ReadUe(s.MaxDecPicBufferingMinus1[i]); s.MaxLatencyIncreasePlus1[i] = (int)Math.Min(r.ReadUe(), int.MaxValue); } @@ -503,7 +538,9 @@ internal sealed class Sps if (r.ReadFlag()) { var range = r.ReadFlag(); - r.Skip(7); // sps_multilayer_extension_flag, sps_3d_extension_flag, sps_scc_extension_flag, sps_extension_4bits + r.Skip(2); // sps_multilayer_extension_flag, sps_3d_extension_flag + s.SccExtension = r.ReadFlag(); + r.Skip(4); // sps_extension_4bits if (range) { s.TransformSkipRotationEnabled = r.ReadFlag(); @@ -517,7 +554,8 @@ internal sealed class Sps s.CabacBypassAlignmentEnabled = r.ReadFlag(); } - // Other extensions (multilayer, 3D, screen content) are not decoded: their data is ignored. + // The multilayer and 3D extensions only matter to layers above 0, which are ignored; their data and that + // of screen content coding (refused when the picture starts) are not read. } return s; @@ -745,6 +783,15 @@ internal sealed class Pps internal int Log2SaoOffsetScaleLuma; internal int Log2SaoOffsetScaleChroma; + /// pps_scc_extension_flag: screen content coding, refused as for the SPS. + internal bool SccExtension; + + /// The RBSP after the NAL unit header, without trailing zero bytes. + internal byte[] Raw = []; + + /// Whether is this PPS or one with the same content. + internal bool SameContent(Pps? other) => other is not null && (ReferenceEquals(this, other) || Raw.AsSpan().SequenceEqual(other.Raw)); + /// The tile layout of the SPS the arrays below were computed for. private Sps? layoutSps; @@ -763,6 +810,7 @@ internal sealed class Pps { var p = new Pps { + Raw = Sps.RawOf(r), Id = r.ReadUe(63), SpsId = r.ReadUe(15), DependentSliceSegmentsEnabled = r.ReadFlag(), @@ -836,7 +884,9 @@ internal sealed class Pps if (r.ReadFlag()) { var range = r.ReadFlag(); - r.Skip(7); // pps_multilayer_extension_flag, pps_3d_extension_flag, pps_scc_extension_flag, pps_extension_4bits + r.Skip(2); // pps_multilayer_extension_flag, pps_3d_extension_flag + p.SccExtension = r.ReadFlag(); + r.Skip(4); // pps_extension_4bits if (range) { if (p.TransformSkipEnabled) diff --git a/src/Febe.Core/Codecs/H265/SliceHeader.cs b/src/Febe.Core/Codecs/H265/SliceHeader.cs index 2643351..ae87d82 100644 --- a/src/Febe.Core/Codecs/H265/SliceHeader.cs +++ b/src/Febe.Core/Codecs/H265/SliceHeader.cs @@ -441,6 +441,9 @@ internal sealed class SliceHeader var offsetShift = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthY - 8; var offsetShiftC = sps.HighPrecisionOffsetsEnabled ? 0 : sps.BitDepthC - 8; + // WpOffsetHalfRangeY and WpOffsetHalfRangeC (7-45, 7-46): with high_precision_offsets_enabled_flag the offsets + // are in units of the bit depth and range over half of it. + var wpOffsetHalfY = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthY - 1 : 7); var wpOffsetHalfC = 1 << (sps.HighPrecisionOffsetsEnabled ? sps.BitDepthC - 1 : 7); Span lumaFlags = stackalloc bool[16]; Span chromaFlags = stackalloc bool[16]; @@ -464,7 +467,7 @@ internal sealed class SliceHeader if (lumaFlags[i]) { LumaWeight[list][i] += r.ReadSe(-128, 127); - LumaOffset[list][i] = r.ReadSe(-128, 127) << offsetShift; + LumaOffset[list][i] = r.ReadSe(-wpOffsetHalfY, wpOffsetHalfY - 1) << offsetShift; } for (var j = 0; j < 2; j++) diff --git a/src/Febe.Core/Codecs/Heif/HeifDecoder.cs b/src/Febe.Core/Codecs/Heif/HeifDecoder.cs index 05e0a5f..b9823db 100644 --- a/src/Febe.Core/Codecs/Heif/HeifDecoder.cs +++ b/src/Febe.Core/Codecs/Heif/HeifDecoder.cs @@ -97,9 +97,9 @@ public static class HeifDecoder { throw new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.Message); } - catch (AggregateException ex) when (ex.InnerException is H265Exception or HeifException) + catch (AggregateException ex) { - throw ex.InnerException is HeifException heif ? heif : new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.InnerException.Message); + throw Unwrap(ex); } catch (Exception ex) when (ex is EndOfStreamException or ArgumentException or IndexOutOfRangeException or OverflowException or InvalidOperationException) @@ -108,6 +108,32 @@ public static class HeifDecoder } } + /// + /// What the tiles decoded in parallel raised, as one : the first of theirs, else the first + /// HEVC error, else a damaged file, whatever the exceptions were. + /// + private static HeifException Unwrap(AggregateException aggregate) + { + var inner = aggregate.Flatten().InnerExceptions; + foreach (var ex in inner) + { + if (ex is HeifException heif) + { + return heif; + } + } + + foreach (var ex in inner) + { + if (ex is H265Exception hevc) + { + return new HeifException("Immagine HEVC del file HEIF non decodificabile: " + hevc.Message); + } + } + + return 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."); @@ -164,7 +190,7 @@ public static class HeifDecoder if (rows * columns > limits.MaxTiles || grid.DerivedFrom.Count != rows * columns) { - throw new HeifException("Tessere della griglia HEIF mancanti o in eccesso."); + throw new HeifException("Riquadri della griglia HEIF mancanti o in eccesso."); } return (rows, columns, width, height); @@ -241,7 +267,7 @@ public static class HeifDecoder hasAlpha = true; } } - catch (HeifException) + catch (Exception ex) when (ex is HeifException or H265Exception) { // An alpha plane that cannot be decoded: the image stands, opaque. } @@ -273,53 +299,108 @@ public static class HeifDecoder /// /// Decodes a coded image or the tiles of a grid, handing each picture to with the position - /// of its top-left sample in the image. Tiles are decoded on several threads; writes - /// disjoint areas. + /// of its top-left sample in the image, inside it. Tiles are decoded on several threads; + /// writes disjoint areas. Every picture must have the size of its ispe, checked by the HEVC decoder before it + /// allocates anything: a small ispe cannot hide a picture of the largest size. /// private static void DecodeImage(Stream stream, HeifFile file, HeifItem item, HeifLimits limits, Action place) { if (item.Type == HeifFile.Hvc1) { - var frame = DecodeTile(new H265Decoder(), file, item, file.ReadItem(stream, item, limits)); + var size = Ispe(file, item) ?? throw new HeifException("Manca la dimensione (ispe) dell'immagine HEIF."); + var frame = DecodeTile(new H265Decoder(), file, item, size, file.ReadItem(stream, item, limits)); place(frame, 0, 0); return; } - var (_, columns, _, _) = GridOf(stream, file, item, limits); + var (rows, columns, width, height) = GridOf(stream, file, item, limits); var tiles = new HeifItem[item.DerivedFrom.Count]; - var data = new byte[tiles.Length][]; + (int Width, int Height) tileSize = default; + long total = 0; + var budget = Math.Min(limits.MaxTotalBytes, file.FileLength); + var counted = new HashSet(); for (var i = 0; i < tiles.Length; i++) { - tiles[i] = file.Item(item.DerivedFrom[i]) ?? throw new HeifException("Tessera della griglia HEIF mancante."); + tiles[i] = file.Item(item.DerivedFrom[i]) ?? throw new HeifException("Riquadro della griglia HEIF mancante."); if (tiles[i].Type != HeifFile.Hvc1) { - throw new HeifException("Tessera della griglia HEIF non HEVC."); + throw new HeifException("Riquadro 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 same size (§6.6.2.3.1), the one of its ispe. + var size = Ispe(file, tiles[i]) ?? throw new HeifException("Manca la dimensione (ispe) di un riquadro HEIF."); + if (i == 0) + { + tileSize = size; + } + else if (size != tileSize) + { + throw new HeifException("Riquadri della griglia HEIF di dimensioni diverse."); + } + + // A tile named twice is read once; the bytes of all of them are never more than the file holds, so items + // whose extents point at the same bytes cannot make a small file cost much more memory than its size. + if (counted.Add(tiles[i].Id)) + { + total += file.ItemLength(tiles[i], limits); + if (total > budget) + { + throw new HeifException("Riquadri HEIF con più dati di quanti ne tiene il file."); + } + } } - // 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) => + // The tiles cover the image, the last row and column cut by less than a tile, and all of them together are not + // larger than the largest image: the output size alone bounds neither. + var (tileWidth, tileHeight) = tileSize; + if (tileWidth <= 0 || tileHeight <= 0 + || (long)tileWidth * columns < width || (long)tileHeight * rows < height + || (long)tileWidth * (columns - 1) >= width || (long)tileHeight * (rows - 1) >= height + || (double)tileWidth * columns * tileHeight * rows > Math.Min(limits.MaxPixels, Array.MaxLength / 4)) { - var frame = DecodeTile(decoder, file, tiles[i], data[i]); - place(frame, i % columns * tileWidth, i / columns * tileHeight); - return decoder; - }, _ => { }); + throw new HeifException("Riquadri della griglia HEIF che non corrispondono all'immagine."); + } + + var read = new Dictionary(); + var data = new byte[tiles.Length][]; + for (var i = 0; i < tiles.Length; i++) + { + if (!read.TryGetValue(tiles[i].Id, out var bytes)) + { + bytes = file.ReadItem(stream, tiles[i], limits); // the stream is read here, by one thread only + read[tiles[i].Id] = bytes; + } + + data[i] = bytes; + } + + place(DecodeTile(new H265Decoder(), file, tiles[0], tileSize, data[0]), 0, 0); + var options = new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, limits.MaxParallelism) }; + try + { + Parallel.For(1, tiles.Length, options, () => new H265Decoder(), (i, _, decoder) => + { + var frame = DecodeTile(decoder, file, tiles[i], tileSize, data[i]); + place(frame, i % columns * tileWidth, i / columns * tileHeight); + return decoder; + }, _ => { }); + } + catch (AggregateException ex) + { + throw Unwrap(ex); + } } - /// One coded picture: its hvcC, then its sample of length-prefixed NAL units. - private static H265Frame DecodeTile(H265Decoder decoder, HeifFile file, HeifItem item, byte[] data) + /// One coded picture of a known size: its hvcC, then its sample of length-prefixed NAL units. + private static H265Frame DecodeTile(H265Decoder decoder, HeifFile file, HeifItem item, (int Width, int Height) size, 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; + decoder.ExpectedFrameSize = size; try { var lengthSize = decoder.ConfigureHvcC(file.Body(hvcC)); @@ -331,7 +412,7 @@ public static class HeifDecoder decoder.FrameDecoded -= Take; } - return frame ?? throw new HeifException("Nessuna immagine nei dati HEVC dell'elemento HEIF."); + return frame ?? throw new HeifException("Nessuna immagine nei dati HEVC dell'oggetto HEIF."); } private static YuvPlanes Planes(H265Frame frame) diff --git a/src/Febe.Core/Codecs/Heif/HeifFile.cs b/src/Febe.Core/Codecs/Heif/HeifFile.cs index ec173fc..746d80d 100644 --- a/src/Febe.Core/Codecs/Heif/HeifFile.cs +++ b/src/Febe.Core/Codecs/Heif/HeifFile.cs @@ -179,7 +179,7 @@ internal sealed class HeifFile { if (items.Count >= MaxItems) { - throw new HeifException("Troppi elementi HEIF."); + throw new HeifException("Troppi oggetti HEIF."); } item = new HeifItem(id); @@ -299,7 +299,7 @@ internal sealed class HeifFile if (count > MaxItems) { - throw new HeifException("Troppi elementi HEIF."); + throw new HeifException("Troppi oggetti HEIF."); } for (var i = 0; i < count; i++) @@ -488,53 +488,7 @@ internal sealed class HeifFile /// The bytes of an item, its extents one after the other. 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 spans = Locate(item, limits, out var total); var data = new byte[total]; var position = 0; foreach (var (offset, length) in spans) @@ -554,4 +508,64 @@ internal sealed class HeifFile return data; } + + /// How many bytes would read for an item, checked as it checks them, without reading. + internal long ItemLength(HeifItem item, HeifLimits limits) + { + Locate(item, limits, out var total); + return total; + } + + /// The extents of an item, each checked against the file (or idat), and their total. + private (long Offset, long Length)[] Locate(HeifItem item, HeifLimits limits, out long total) + { + if (!item.Located || item.Extents.Count == 0) + { + throw new HeifException("Oggetto HEIF senza dati."); + } + + 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 oggetto HEIF non gestita."); + } + + if (offset < 0 || available < 0) + { + throw new HeifException("Oggetto HEIF fuori dal file."); + } + + length = length == 0 ? available : length; + if (length > available) + { + throw new HeifException("Oggetto HEIF fuori dal file."); + } + + spans[i] = (offset, length); + total += length; + if (total > limits.MaxItemBytes) + { + throw new HeifException("Oggetto HEIF troppo grande."); + } + } + + return spans; + } } diff --git a/src/Febe.Core/Codecs/Heif/HeifImage.cs b/src/Febe.Core/Codecs/Heif/HeifImage.cs index 5b30456..ca766cc 100644 --- a/src/Febe.Core/Codecs/Heif/HeifImage.cs +++ b/src/Febe.Core/Codecs/Heif/HeifImage.cs @@ -86,6 +86,12 @@ public sealed record HeifLimits /// Bytes of one item at most. public int MaxItemBytes { get; init; } = 128 * 1024 * 1024; + /// + /// Bytes of all the coded pictures of one image (the tiles of a grid) at most. They are also never more than the + /// file: items whose extents point at the same bytes cannot make the decoder read a small file many times over. + /// + public long MaxTotalBytes { get; init; } = 512L * 1024 * 1024; + /// Tiles of a grid at most (256 × 256). public int MaxTiles { get; init; } = 65_536; diff --git a/src/Febe.Core/Codecs/YuvToRgb.cs b/src/Febe.Core/Codecs/YuvToRgb.cs index e378c84..3b93c15 100644 --- a/src/Febe.Core/Codecs/YuvToRgb.cs +++ b/src/Febe.Core/Codecs/YuvToRgb.cs @@ -38,9 +38,16 @@ internal readonly struct YuvPlanes( /// /// 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. +/// BT.709 (1), FCC (4), BT.601 (5, 6), SMPTE 240M (7) or BT.2020 non-constant luminance (9) coefficients, the identity +/// matrix (0: G, B and R coded as Y, Cb and Cr), YCgCo (8: Y, Cg and Co in place of Y, Cb and Cr, the inverse of the +/// equations of H.273 for MatrixCoefficients 8), 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. +/// +/// Approximated: BT.2020 constant luminance (10) is converted with the non-constant luminance coefficients of 9, without +/// its transfer to linear light; the chromaticity-derived matrices (12, 13), which need the colour primaries, +/// SMPTE ST 2085 (11) and ICtCp (14), as every unspecified or unknown value, take BT.709 from 720 lines up and BT.601 +/// below. None of them comes from the phones and services Febe meets. +/// /// internal static class YuvToRgb { @@ -53,6 +60,11 @@ internal static class YuvToRgb { internal bool Identity { get; init; } + /// YCgCo (matrix 8): G = Y + Cg, R = Y − Cg + Co, B = Y − Cg − Co, Cg and Co scaled by . + internal bool YCgCo { get; init; } + + internal int ChromaScale { get; init; } + internal int LumaScale { get; init; } internal int LumaOffset { get; init; } @@ -74,8 +86,8 @@ internal static class YuvToRgb } /// - /// The coefficients for (matrix_coeffs; unspecified or unknown: BT.709 from 720 lines up, - /// BT.601 below), and the bit depths of the samples. + /// The coefficients for (matrix_coeffs; unspecified, unknown or approximated as the class + /// says: BT.709 from 720 lines up, BT.601 below), and the bit depths of the samples. /// internal static Coefficients For(int matrix, bool fullRange, int bitDepthY, int bitDepthC, int height) { @@ -84,6 +96,19 @@ internal static class YuvToRgb return new Coefficients { Identity = true, IdentityShiftY = Math.Max(0, bitDepthY - 8), IdentityShiftC = Math.Max(0, bitDepthC - 8) }; } + if (matrix == 8) + { + // Cg and Co are quantised as Cb and Cr are, with the same ranges (H.273, MatrixCoefficients 8). + return new Coefficients + { + YCgCo = true, + LumaScale = (int)Math.Round((fullRange ? 1.0 : 255.0 / 219.0) / (1 << Math.Max(0, bitDepthY - 8)) * One), + LumaOffset = fullRange ? 0 : 16 << Math.Max(0, bitDepthY - 8), + ChromaMiddle = 1 << (bitDepthC - 1), + ChromaScale = (int)Math.Round((fullRange ? 1.0 : 255.0 / 224.0) / (1 << Math.Max(0, bitDepthC - 8)) * One), + }; + } + var (kr, kb) = matrix switch { 1 => (0.2126, 0.0722), @@ -161,6 +186,17 @@ internal static class YuvToRgb var l = (luma - k.LumaOffset) * k.LumaScale; u -= k.ChromaMiddle; v -= k.ChromaMiddle; + if (k.YCgCo) + { + var cg = u * k.ChromaScale; + var co = v * k.ChromaScale; + var t = l - cg; + r += Clip((t + co + Half) >> Shift); + g += Clip((l + cg + Half) >> Shift); + b += Clip((t - co + Half) >> Shift); + continue; + } + 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); diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md index d2cdf24..2f89fcf 100644 --- a/src/Febe.Core/Import/LEGGIMI.md +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -160,9 +160,9 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per ## Limiti noti - 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. + decodificatore HEVC): immagine singola o griglia di riquadri, `clap`, `irot`/`imir`, trasparenza. La data di scatto + si legge dall'oggetto `Exif` del box `meta` 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. diff --git a/tests/Febe.Tests/Media/H265/H265RobustnessTests.cs b/tests/Febe.Tests/Media/H265/H265RobustnessTests.cs new file mode 100644 index 0000000..f606ce1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265RobustnessTests.cs @@ -0,0 +1,242 @@ +using Febe.Core.Codecs.H265; +using static Febe.Tests.Codecs.H265.H265SyntheticStreams; +using Pps = Febe.Core.Codecs.H265.Pps; +using Sps = Febe.Core.Codecs.H265.Sps; + +namespace Febe.Tests.Codecs.H265; + +/// +/// The HEVC decoder on streams written for the purpose (): what bounds its memory +/// against damaged streams, parameter sets repeated inside a picture, the extensions it refuses, the range of weighted +/// prediction offsets. +/// +[TestClass] +public sealed class H265RobustnessTests +{ + private static readonly SequenceSettings Small = new(); + private static readonly PictureSettings Plain = new(); + + [TestMethod] + public void TheSyntheticStreamsDecode() + { + // The control for every test below: an I picture and three P pictures, each referring to the one before, all + // at the middle of the range (intra prediction from nothing, then skipped blocks). + var frames = Decode(AnnexB( + Sps(Small), + Pps(Plain), + Slice(new SliceSettings(Cra, 0), Small, Plain), + Slice(new SliceSettings(TrailR, 1) { Negative = [(-1, true)] }, Small, Plain), + Slice(new SliceSettings(TrailR, 2) { Negative = [(-1, true)] }, Small, Plain), + Slice(new SliceSettings(TrailR, 3) { Negative = [(-1, true)] }, Small, Plain))); + + Assert.HasCount(4, frames); + foreach (var frame in frames) + { + Assert.AreEqual((16, 16), (frame.Width, frame.Height)); + Assert.IsTrue(frame.Y.All(v => v == 128) && frame.Cb.All(v => v == 128) && frame.Cr.All(v => v == 128)); + } + } + + [TestMethod] + [DataRow(416, 240, 15, true)] + [DataRow(4096, 2160, 15, true)] + [DataRow(8192, 4320, 5, true)] + [DataRow(8192, 4320, 6, false)] + [DataRow(7680, 4320, 7, false)] + [DataRow(5120, 2880, 11, true)] + [DataRow(5120, 2880, 12, false)] + public void TheBufferMustFitTheLargestLevel(int width, int height, int maxDecPicBufferingMinus1, bool accepted) + { + // A.4.2 at level 6.2: 16 pictures up to a quarter of MaxLumaPs (8 912 896 samples), 12 up to half, 8 up to three + // quarters, then 6. Sixteen pictures of the largest size would be gigabytes. + var nal = Sps(new SequenceSettings(width, height, maxDecPicBufferingMinus1)); + byte[]? buffer = null; + if (accepted) + { + var sps = Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader()); + Assert.AreEqual(maxDecPicBufferingMinus1, sps.MaxDecPicBufferingMinus1[0]); + } + else + { + Assert.ThrowsExactly(() => Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader())); + } + } + + [TestMethod] + public void MissingReferencesShareOneGeneratedPicture() + { + // A P picture whose 15 short-term and 16 long-term references are all missing: one generated picture stands for + // all of them, each entry of the lists keeping its own POC. + var sequence = new SequenceSettings(2048, 1024, LongTermRefsPresent: true); + var p = new SliceSettings(TrailR, 40) + { + Negative = [.. Enumerable.Range(1, 15).Select(d => (-d, true))], + LongTerm = [.. Enumerable.Range(100, 16).Select(lsb => (lsb, true))], + ActiveRefs = 15, + }; + var decoder = new H265Decoder(); + Picture? decoded = null; + decoder.PictureDecoded += picture => decoded = picture; + decoder.DecodeAccessUnitAnnexB(AnnexB(Sps(sequence), Pps(Plain), Slice(new SliceSettings(Cra, 0), sequence, Plain))); + var pictureBytes = (2048L * 1024 * 2 * 3 / 2) + (512L * 256 * 10); + + var before = GC.GetAllocatedBytesForCurrentThread(); + decoder.DecodeAccessUnitAnnexB(AnnexB(Slice(p, sequence, Plain))); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + // The new picture and the generated one; one picture each would be 31 more. + Assert.IsLessThan(4 * pictureBytes, allocated, $"{allocated} byte per un'immagine P con 31 riferimenti mancanti"); + Assert.IsNotNull(decoded); + Assert.AreEqual(40, decoded.Poc); + var list = decoded.Slices[0].RefPicList[0]; + var generated = list[0]; + Assert.IsTrue(generated.Generated); + for (var i = 0; i < 15; i++) + { + Assert.AreSame(generated, list[i], $"riferimento {i}"); + Assert.AreEqual(40 - 1 - i, decoded.Slices[0].RefPoc[0][i], $"POC del riferimento {i}"); + } + } + + [TestMethod] + public void TheBufferDoesNotGrowBeyondTheSps() + { + // Room for two pictures, but every P picture keeps all those before it as references: from the fourth picture + // the buffer would have to hold more than it declares, which a damaged stream must not turn into memory. + var sequence = new SequenceSettings(MaxDecPicBufferingMinus1: 1); + var units = new List { Sps(sequence), Pps(Plain), Slice(new SliceSettings(Cra, 0), sequence, Plain) }; + for (var poc = 1; poc < 40; poc++) + { + var negative = Enumerable.Range(1, Math.Min(poc, 16)).Select(d => (-d, d == 1)).ToArray(); + units.Add(Slice(new SliceSettings(TrailR, poc) { Negative = negative }, sequence, Plain)); + } + + var decoder = new H265Decoder(); + var output = 0; + decoder.FrameOutput += _ => output++; + var ex = Assert.ThrowsExactly(() => decoder.DecodeAnnexB(AnnexB([.. units]))); + StringAssert.Contains(ex.Message, "buffer"); + Assert.IsLessThan(6, decoder.PicturesDecoded, "rifiutato appena il buffer non basta"); + + // The same stream keeping only the picture before: every picture decodes. + units.RemoveRange(3, units.Count - 3); + for (var poc = 1; poc < 40; poc++) + { + units.Add(Slice(new SliceSettings(TrailR, poc) { Negative = [(-1, true)] }, sequence, Plain)); + } + + Assert.HasCount(40, Decode(AnnexB([.. units]))); + } + + [TestMethod] + public void ParameterSetsRepeatedInsideAPictureAreAccepted() + { + // Two slices of one picture (two coding tree blocks), the SPS and PPS sent again between them: §7.4.2.4.4 allows + // it as long as the content is the same. + var wide = new SequenceSettings(32, 16); + var first = new SliceSettings(Cra, 0) { CtbCount = 2, WidthInCtbs = 2 }; + var second = first with { First = false, Address = 1 }; + var frames = Decode(AnnexB( + Sps(wide), + Pps(Plain), + Slice(first, wide, Plain), + Sps(wide), + Pps(Plain), + Slice(second, wide, Plain))); + Assert.HasCount(1, frames); + Assert.IsTrue(frames[0].Y.All(v => v == 128)); + } + + [TestMethod] + public void AChangedPpsAppliesFromTheNextPicture() + { + // A PPS with the same ID and another content, between the slices of a picture (not allowed, but met in damaged + // streams) and between two pictures: the picture under way keeps its PPS, the next one takes the new one. Here + // the new PPS has output_flag_present_flag, and the P picture says pic_output_flag 0: it is not output. + var wide = new SequenceSettings(32, 16); + var flagged = new PictureSettings(OutputFlagPresent: true); + var first = new SliceSettings(Cra, 0) { CtbCount = 2, WidthInCtbs = 2 }; + var second = first with { First = false, Address = 1 }; + var p = new SliceSettings(TrailR, 1) { Negative = [(-1, true)], CtbCount = 2, WidthInCtbs = 2, Ctus = 2, OutputFlag = false }; + var inside = Decode(AnnexB(Sps(wide), Pps(Plain), Slice(first, wide, Plain), Pps(flagged), Slice(second, wide, Plain), Slice(p, wide, flagged))); + Assert.HasCount(1, inside, "dentro l'immagine"); + + var between = Decode(AnnexB(Sps(wide), Pps(Plain), Slice(first, wide, Plain), Slice(second, wide, Plain), Pps(flagged), Slice(p, wide, flagged))); + Assert.HasCount(1, between, "fra due immagini"); + } + + [TestMethod] + [DataRow(true, false, 1)] + [DataRow(false, true, 1)] + [DataRow(false, false, 9)] + [DataRow(false, false, 11)] + public void ScreenContentCodingIsRefused(bool spsFlag, bool ppsFlag, int profile) + { + var sequence = new SequenceSettings(SccExtension: spsFlag, ProfileIdc: profile); + var picture = new PictureSettings(SccExtension: ppsFlag); + var stream = AnnexB(Sps(sequence), Pps(picture), Slice(new SliceSettings(Cra, 0), sequence, picture)); + var ex = Assert.ThrowsExactly(() => new H265Decoder().DecodeAnnexB(stream)); + StringAssert.Contains(ex.Message, "SCC"); + } + + [TestMethod] + [DataRow(10, true, 511, true, 511)] + [DataRow(10, true, -512, true, -512)] + [DataRow(10, true, 512, false, 0)] + [DataRow(12, true, 2047, true, 2047)] + [DataRow(12, true, -2049, false, 0)] + [DataRow(10, false, 127, true, 508)] + [DataRow(10, false, 128, false, 0)] + [DataRow(8, true, -128, true, -128)] + [DataRow(8, true, 128, false, 0)] + public void LumaOffsetsFollowTheirRange(int bitDepth, bool highPrecision, int offset, bool accepted, int expected) + { + // WpOffsetHalfRangeY (7-45): 1 << (BitDepthY − 1) with high_precision_offsets_enabled_flag, 128 without, when + // the offset is then scaled to the bit depth. + var sequence = new SequenceSettings(BitDepth: bitDepth, HighPrecisionOffsets: highPrecision); + var picture = new PictureSettings(WeightedPred: true); + byte[]? buffer = null; + var spss = new Sps?[16]; + var ppss = new Pps?[64]; + spss[0] = Sps.Parse(H265NalUnit.Unescape(Sps(sequence), ref buffer).Reader()); + ppss[0] = Pps.Parse(H265NalUnit.Unescape(Pps(picture), ref buffer).Reader()); + var slice = H265NalUnit.Unescape(Slice(new SliceSettings(TrailR, 1) { Negative = [(-1, true)], LumaOffset = offset }, sequence, picture), ref buffer); + if (accepted) + { + var header = SliceHeader.Parse(slice.Reader(), TrailR, spss, ppss, null, out _, out _); + Assert.AreEqual(expected, header.LumaOffset[0][0]); + } + else + { + Assert.ThrowsExactly(() => SliceHeader.Parse(slice.Reader(), TrailR, spss, ppss, null, out _, out _)); + } + } + + [TestMethod] + public void APictureOfAnotherSizeThanExpectedIsRefused() + { + var stream = AnnexB(Sps(Small), Pps(Plain), Slice(new SliceSettings(Cra, 0), Small, Plain)); + var decoder = new H265Decoder { ExpectedFrameSize = (16, 16) }; + var frames = new List(); + decoder.FrameOutput += frames.Add; + decoder.DecodeAnnexB(stream); + Assert.HasCount(1, frames); + + // 2048×1024 where 16×16 is expected: refused before its picture is allocated. + var large = new SequenceSettings(2048, 1024); + var big = AnnexB(Sps(large), Pps(Plain), Slice(new SliceSettings(Cra, 0), large, Plain)); + var refusing = new H265Decoder { ExpectedFrameSize = (16, 16) }; + var before = GC.GetAllocatedBytesForCurrentThread(); + Assert.ThrowsExactly(() => refusing.DecodeAnnexB(big)); + Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before); + } + + private static List Decode(byte[] stream) + { + var frames = new List(); + var decoder = new H265Decoder(); + decoder.FrameOutput += frames.Add; + decoder.DecodeAnnexB(stream); + return frames; + } +} diff --git a/tests/Febe.Tests/Media/H265/H265SyntheticStreams.cs b/tests/Febe.Tests/Media/H265/H265SyntheticStreams.cs new file mode 100644 index 0000000..f413a8c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265SyntheticStreams.cs @@ -0,0 +1,497 @@ +using Febe.Core.Codecs.H265; +using Lps = Febe.Core.Codecs.H264.CabacTables; + +namespace Febe.Tests.Codecs.H265; + +/// +/// Tiny HEVC streams written bit by bit from the syntax of ITU-T H.265 (§7.3), their slice data with a CABAC encoder +/// that mirrors the decoding engine of §9.3.4.3: 4:2:0 parameter sets with 16×16 coding tree blocks, I pictures whose +/// coding tree units are one intra coding unit predicted from nothing (every sample at the middle of its range) and P +/// pictures whose coding tree units are skipped. A picture can stop after its first coding tree unit, so pictures of +/// any size cost a few bytes. They reach what the conformance streams do not: missing references, reference picture +/// sets larger than the buffer, parameter sets repeated inside a picture, the screen content extensions, large weighted +/// prediction offsets. +/// +internal static class H265SyntheticStreams +{ + internal const int Cra = 21; + internal const int TrailR = 1; + + /// Settings of the sequence parameter set. + internal sealed record SequenceSettings( + int Width = 16, + int Height = 16, + int MaxDecPicBufferingMinus1 = 4, + int BitDepth = 8, + bool LongTermRefsPresent = false, + bool HighPrecisionOffsets = false, + bool SccExtension = false, + int ProfileIdc = 1); + + /// Settings of the picture parameter set. + internal sealed record PictureSettings( + bool OutputFlagPresent = false, + bool WeightedPred = false, + bool SccExtension = false, + int InitQpMinus26 = 0); + + /// A slice segment: its NAL unit type and the syntax elements of its header that the tests vary. + internal sealed record SliceSettings(int NalType, int PocLsb) + { + public bool First { get; init; } = true; + + /// slice_segment_address of a segment that is not the first. + public int Address { get; init; } + + /// Picture size in coding tree blocks (for the bits of the address and to know the last one). + public int CtbCount { get; init; } = 1; + + /// Coding tree units coded in the segment, from its address; the slice ends after them. + public int Ctus { get; init; } = 1; + + /// Coding tree blocks per row (for the contexts of cu_skip_flag). + public int WidthInCtbs { get; init; } = 1; + + /// The negative deltas of the short-term set, each with used_by_curr_pic_s0_flag. + public (int Delta, bool Used)[] Negative { get; init; } = []; + + /// poc_lsb_lt and used_by_curr_pic_lt_flag of the long-term entries (the SPS must allow them). + public (int PocLsb, bool Used)[] LongTerm { get; init; } = []; + + /// num_ref_idx_l0_active_minus1 + 1, written with the override flag when it is not 1. + public int ActiveRefs { get; init; } = 1; + + /// pic_output_flag, written when the PPS has output_flag_present_flag. + public bool? OutputFlag { get; init; } + + /// luma_offset_l0 of reference 0, with a weight table, when the PPS has weighted_pred_flag. + public int? LumaOffset { get; init; } + } + + /// A sequence parameter set NAL unit (§7.3.2.2), without start code. + internal static byte[] Sps(SequenceSettings s) + { + var bits = new BitWriter(); + bits.Bits(0, 4); // sps_video_parameter_set_id + bits.Bits(0, 3); // sps_max_sub_layers_minus1 + bits.Bits(1, 1); // sps_temporal_id_nesting_flag + + // profile_tier_level(1, 0): space, tier, profile, 32 compatibility flags, 48 bits of constraints, level. + bits.Bits(0, 3); + bits.Bits((uint)s.ProfileIdc, 5); + bits.Bits(1u << (31 - s.ProfileIdc), 32); + bits.Bits(0, 24); + bits.Bits(0, 24); + bits.Bits(186, 8); // general_level_idc: 6.2 + + bits.Ue(0); // sps_seq_parameter_set_id + bits.Ue(1); // chroma_format_idc: 4:2:0 + bits.Ue((uint)s.Width); + bits.Ue((uint)s.Height); + bits.Bits(0, 1); // conformance_window_flag + bits.Ue((uint)s.BitDepth - 8); + bits.Ue((uint)s.BitDepth - 8); + bits.Ue(4); // log2_max_pic_order_cnt_lsb_minus4: 8 bits + bits.Bits(1, 1); // sps_sub_layer_ordering_info_present_flag + bits.Ue((uint)s.MaxDecPicBufferingMinus1); + bits.Ue(0); // sps_max_num_reorder_pics + bits.Ue(0); // sps_max_latency_increase_plus1 + bits.Ue(0); // log2_min_luma_coding_block_size_minus3: 8×8 + bits.Ue(1); // log2_diff_max_min_luma_coding_block_size: 16×16 coding tree blocks + bits.Ue(0); // log2_min_luma_transform_block_size_minus2: 4×4 + bits.Ue(2); // log2_diff_max_min_luma_transform_block_size: 16×16 + bits.Ue(0); // max_transform_hierarchy_depth_inter + bits.Ue(0); // max_transform_hierarchy_depth_intra + bits.Bits(0, 1); // scaling_list_enabled_flag + bits.Bits(0, 1); // amp_enabled_flag + bits.Bits(0, 1); // sample_adaptive_offset_enabled_flag + bits.Bits(0, 1); // pcm_enabled_flag + bits.Ue(0); // num_short_term_ref_pic_sets + bits.Bits(s.LongTermRefsPresent ? 1u : 0u, 1); + if (s.LongTermRefsPresent) + { + bits.Ue(0); // num_long_term_ref_pics_sps + } + + bits.Bits(0, 1); // sps_temporal_mvp_enabled_flag + bits.Bits(0, 1); // strong_intra_smoothing_enabled_flag + bits.Bits(0, 1); // vui_parameters_present_flag + var extension = s.HighPrecisionOffsets || s.SccExtension; + bits.Bits(extension ? 1u : 0u, 1); + if (extension) + { + bits.Bits(s.HighPrecisionOffsets ? 1u : 0u, 1); // sps_range_extension_flag + bits.Bits(0, 2); // sps_multilayer_extension_flag, sps_3d_extension_flag + bits.Bits(s.SccExtension ? 1u : 0u, 1); + bits.Bits(0, 4); // sps_extension_4bits + if (s.HighPrecisionOffsets) + { + // Range extension flags: only high_precision_offsets_enabled_flag (the seventh). + bits.Bits(0b0000_0010_0, 9); + } + + // sps_scc_extension() is not written: the decoder refuses the stream before it would need it. + } + + return Nal(33, bits); + } + + /// A picture parameter set NAL unit (§7.3.2.3), without start code: deblocking off, no tiles or wavefronts. + internal static byte[] Pps(PictureSettings p) + { + var bits = new BitWriter(); + bits.Ue(0); // pps_pic_parameter_set_id + bits.Ue(0); // pps_seq_parameter_set_id + bits.Bits(0, 1); // dependent_slice_segments_enabled_flag + bits.Bits(p.OutputFlagPresent ? 1u : 0u, 1); + bits.Bits(0, 3); // num_extra_slice_header_bits + bits.Bits(0, 1); // sign_data_hiding_enabled_flag + bits.Bits(0, 1); // cabac_init_present_flag + bits.Ue(0); // num_ref_idx_l0_default_active_minus1 + bits.Ue(0); // num_ref_idx_l1_default_active_minus1 + bits.Se(p.InitQpMinus26); + bits.Bits(0, 1); // constrained_intra_pred_flag + bits.Bits(0, 1); // transform_skip_enabled_flag + bits.Bits(0, 1); // cu_qp_delta_enabled_flag + bits.Se(0); // pps_cb_qp_offset + bits.Se(0); // pps_cr_qp_offset + bits.Bits(0, 1); // pps_slice_chroma_qp_offsets_present_flag + bits.Bits(p.WeightedPred ? 1u : 0u, 1); + bits.Bits(0, 1); // weighted_bipred_flag + bits.Bits(0, 1); // transquant_bypass_enabled_flag + bits.Bits(0, 1); // tiles_enabled_flag + bits.Bits(0, 1); // entropy_coding_sync_enabled_flag + bits.Bits(0, 1); // pps_loop_filter_across_slices_enabled_flag + bits.Bits(1, 1); // deblocking_filter_control_present_flag + bits.Bits(0, 1); // deblocking_filter_override_enabled_flag + bits.Bits(1, 1); // pps_deblocking_filter_disabled_flag + bits.Bits(0, 1); // pps_scaling_list_data_present_flag + bits.Bits(0, 1); // lists_modification_present_flag + bits.Ue(0); // log2_parallel_merge_level_minus2 + bits.Bits(0, 1); // slice_segment_header_extension_present_flag + bits.Bits(p.SccExtension ? 1u : 0u, 1); + if (p.SccExtension) + { + bits.Bits(0, 3); // pps_range_extension_flag, pps_multilayer_extension_flag, pps_3d_extension_flag + bits.Bits(1, 1); // pps_scc_extension_flag + bits.Bits(0, 4); // pps_extension_4bits; pps_scc_extension() is not written + } + + return Nal(34, bits); + } + + /// A slice segment NAL unit (§7.3.6, §7.3.8), without start code, for the parameter sets above. + internal static byte[] Slice(SliceSettings s, SequenceSettings sequence, PictureSettings picture) + { + var bits = new BitWriter(); + bits.Bits(s.First ? 1u : 0u, 1); + if (s.NalType is >= 16 and <= 23) + { + bits.Bits(0, 1); // no_output_of_prior_pics_flag + } + + bits.Ue(0); // slice_pic_parameter_set_id + if (!s.First) + { + var addressBits = 0; + while ((1 << addressBits) < s.CtbCount) + { + addressBits++; + } + + bits.Bits((uint)s.Address, addressBits); + } + + var intra = s.NalType is >= 16 and <= 23; + bits.Ue(intra ? 2u : 1u); // slice_type: I or P + if (picture.OutputFlagPresent) + { + bits.Bits(s.OutputFlag ?? true ? 1u : 0u, 1); + } + + bits.Bits((uint)s.PocLsb, 8); + bits.Bits(0, 1); // short_term_ref_pic_set_sps_flag: the set follows + bits.Ue((uint)s.Negative.Length); + bits.Ue(0); // num_positive_pics + var previous = 0; + foreach (var (delta, used) in s.Negative) + { + bits.Ue((uint)(previous - delta - 1)); // delta_poc_s0_minus1, from the previous entry + bits.Bits(used ? 1u : 0u, 1); + previous = delta; + } + + if (sequence.LongTermRefsPresent) + { + bits.Ue((uint)s.LongTerm.Length); + foreach (var (pocLsb, used) in s.LongTerm) + { + bits.Bits((uint)pocLsb, 8); + bits.Bits(used ? 1u : 0u, 1); + bits.Bits(0, 1); // delta_poc_msb_present_flag + } + } + + if (!intra) + { + bits.Bits(s.ActiveRefs != 1 ? 1u : 0u, 1); // num_ref_idx_active_override_flag + if (s.ActiveRefs != 1) + { + bits.Ue((uint)s.ActiveRefs - 1); + } + + if (picture.WeightedPred) + { + bits.Ue(6); // luma_log2_weight_denom + bits.Se(0); // delta_chroma_log2_weight_denom + for (var i = 0; i < s.ActiveRefs; i++) + { + bits.Bits(i == 0 ? 1u : 0u, 1); // luma_weight_l0_flag + } + + bits.Bits(0, s.ActiveRefs); // chroma_weight_l0_flag + bits.Se(0); // delta_luma_weight_l0 + bits.Se(s.LumaOffset ?? 0); + } + + bits.Ue(4); // five_minus_max_num_merge_cand: one candidate, no merge_idx + } + + bits.Se(0); // slice_qp_delta + bits.Bits(1, 1); // byte_alignment() + bits.Align(); + + var cabac = new CabacWriter(bits, intra ? 0 : 1, 26 + picture.InitQpMinus26); + for (var k = 0; k < s.Ctus; k++) + { + var address = s.Address + k; + cabac.Decision(CabacTables.SplitCuFlag, 0); + if (intra) + { + cabac.Decision(CabacTables.PrevIntraLumaPredFlag, 1); + cabac.Bypass(0); // mpm_idx 0 + cabac.Decision(CabacTables.IntraChromaPredMode, 0); // the luma mode + cabac.Decision(CabacTables.CbfChroma, 0); + cabac.Decision(CabacTables.CbfChroma, 0); + cabac.Decision(CabacTables.CbfLuma + 1, 0); + } + else + { + // cu_skip_flag: one more for each neighbour (left, above) of the same slice, all skipped. + var x = address % s.WidthInCtbs; + var y = address / s.WidthInCtbs; + var ctx = (x > 0 && address > s.Address ? 1 : 0) + (y > 0 && address - s.WidthInCtbs >= s.Address ? 1 : 0); + cabac.Decision(CabacTables.CuSkipFlag + ctx, 1); + } + + cabac.Terminate(k == s.Ctus - 1 ? 1 : 0); // end_of_slice_segment_flag + } + + bits.Align(); + return Nal(s.NalType, bits, stopBit: false); + } + + /// NAL units with start codes, one after the other. + internal static byte[] AnnexB(params byte[][] units) => [.. units.SelectMany(u => (byte[])[0, 0, 0, 1, .. u])]; + + private static byte[] Nal(int type, BitWriter bits, bool stopBit = true) + { + if (stopBit) + { + bits.Bits(1, 1); // rbsp_stop_one_bit + bits.Align(); + } + + return [(byte)(type << 1), 1, .. bits.ToArray()]; + } + + /// + /// The arithmetic encoder that matches the decoding engine bit for bit (the encoding flowcharts of ITU-T H.264 + /// §9.3.4, whose arithmetic HEVC keeps), with the context variables initialised by the decoder's own code. + /// + private sealed class CabacWriter + { + private readonly BitWriter bits; + private readonly byte[] contexts; + private int low; + private int range = 510; + private int outstanding; + private bool firstBit = true; + + public CabacWriter(BitWriter bits, int initType, int sliceQp) + { + this.bits = bits; + var engine = new CabacEngine(); + engine.InitContexts(initType, sliceQp); + contexts = (byte[])engine.Contexts.Clone(); + } + + public void Decision(int ctx, int bin) + { + int s = contexts[ctx]; + var p = s >> 1; + var mps = s & 1; + int lps = Lps.RangeLps[(p << 2) + ((range >> 6) & 3)]; + range -= lps; + if (bin != mps) + { + low += range; + range = lps; + if (p == 0) + { + mps ^= 1; + } + + contexts[ctx] = (byte)((Lps.NextStateLps[p] << 1) | mps); + } + else if (p < 62) + { + contexts[ctx] = (byte)(s + 2); + } + + Renormalise(); + } + + public void Bypass(int bin) + { + low <<= 1; + if (bin != 0) + { + low += range; + } + + if (low >= 1024) + { + Put(1); + low -= 1024; + } + else if (low < 512) + { + Put(0); + } + else + { + low -= 512; + outstanding++; + } + } + + public void Terminate(int bin) + { + range -= 2; + if (bin == 0) + { + Renormalise(); + return; + } + + // EncodeFlush: the last bit written is the stop bit of the slice data. + low += range; + range = 2; + Renormalise(); + Put((low >> 9) & 1); + bits.Bits((uint)(((low >> 7) & 3) | 1), 2); + } + + private void Renormalise() + { + while (range < 256) + { + if (low < 256) + { + Put(0); + } + else if (low >= 512) + { + low -= 512; + Put(1); + } + else + { + low -= 256; + outstanding++; + } + + range <<= 1; + low <<= 1; + } + } + + private void Put(int bit) + { + if (firstBit) + { + firstBit = false; + } + else + { + bits.Bits((uint)bit, 1); + } + + for (; outstanding > 0; outstanding--) + { + bits.Bits((uint)(1 - bit), 1); + } + } + } + + private sealed class BitWriter + { + private readonly List bits = []; + + public void Bits(uint value, int count) + { + for (var i = count - 1; i >= 0; i--) + { + bits.Add(((value >> i) & 1) != 0); + } + } + + public void Ue(uint value) + { + var code = value + 1; + var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code); + Bits(0, length - 1); + Bits(code, length); + } + + public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1)); + + public void Align() + { + while (bits.Count % 8 != 0) + { + bits.Add(false); + } + } + + public byte[] ToArray() + { + var bytes = new byte[(bits.Count + 7) / 8]; + for (var i = 0; i < bits.Count; i++) + { + if (bits[i]) + { + bytes[i / 8] |= (byte)(0x80 >> (i % 8)); + } + } + + // Emulation prevention (§7.4.2): never two zero bytes followed by a byte up to 3. + var output = new List(); + var zeros = 0; + foreach (var b in bytes) + { + if (zeros >= 2 && b <= 3) + { + output.Add(3); + zeros = 0; + } + + output.Add(b); + zeros = b == 0 ? zeros + 1 : 0; + } + + return [.. output]; + } + } +} diff --git a/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs b/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs index 0e38eb9..31c104a 100644 --- a/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs +++ b/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs @@ -341,6 +341,161 @@ public sealed class HeifDecoderTests Assert.IsGreaterThan(0, decoded, "nessuna variante decodificata"); } + [TestMethod] + public void ACodedImageMustHaveTheSizeOfItsIspe() + { + // A 416×240 picture behind an ispe of 64×64: the decoder would allocate the picture the SPS says, however small + // the ispe, and the result was cut silently. + var picture = CodedPicture.First(Tiles[0]); + var builder = new HeifBuilder(); + var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC)); + builder.Item(1, "hvc1", picture.Data, -hvcC, builder.Property(HeifBuilder.Ispe(64, 64))); + var file = builder.Build(); + var ex = Assert.ThrowsExactly(() => HeifDecoder.Decode(file)); + StringAssert.Contains(ex.Message, "dimensioni diverse"); + using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file)); + Assert.IsNull(bitmap); + } + + [TestMethod] + public void GridTilesMustHaveTheSizeOfTheirIspe() + { + // Tiles declared 208×120 that are pictures of 416×240, in a grid whose output the declared size covers. + var pictures = Tiles.Select(CodedPicture.First).ToArray(); + var (tw, th) = (pictures[0].Frame.Width / 2, pictures[0].Frame.Height / 2); + var builder = new HeifBuilder(); + var ispe = builder.Property(HeifBuilder.Ispe(tw, th)); + builder.Item(1, "grid", HeifBuilder.GridData(2, 2, (2 * tw) - 4, (2 * th) - 4)); + for (var i = 0; i < 4; i++) + { + builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe); + } + + builder.Reference("dimg", 1, 10, 11, 12, 13); + Assert.ThrowsExactly(() => HeifDecoder.Decode(builder.Build())); + } + + [TestMethod] + [DataRow(0x5000_0000, 240)] + [DataRow(416, 0x5000_0000)] + [DataRow(100, 240)] + [DataRow(0, 240)] + public void TilesThatDoNotFitTheGridAreRefused(int tileWidth, int tileHeight) + { + // A row of four tiles for an image 800 wide: tiles 0x50000000 wide made the offset of the fourth overflow and + // the exception escaped the decoder from its parallel loop; 100 wide do not cover the image; 0 is no size. + var pictures = Tiles.Select(CodedPicture.First).ToArray(); + var builder = new HeifBuilder(); + var ispe = builder.Property(HeifBuilder.Ispe(tileWidth, tileHeight)); + builder.Item(1, "grid", HeifBuilder.GridData(1, 4, 800, 240)); + for (var i = 0; i < 4; i++) + { + builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe); + } + + builder.Reference("dimg", 1, 10, 11, 12, 13); + var file = builder.Build(); + Assert.ThrowsExactly(() => HeifDecoder.Decode(file)); + using var bitmap = ImageDecoding.DecodeUpright(new MemoryStream(file)); + Assert.IsNull(bitmap, "nessuna eccezione fuori dalla decodifica"); + } + + [TestMethod] + public void TilesThatShareTheirBytesCannotMultiplyThem() + { + // Four tile items whose extents are the same bytes: read as four, they would be four times what the file holds + // (with thousands of tiles, gigabytes from a small file). + var picture = CodedPicture.First(Tiles[0]); + var (tw, th) = (picture.Frame.Width, picture.Frame.Height); + var shared = new HeifBuilder(); + var hvcC = shared.Property(HeifBuilder.HvcCProperty(picture.HvcC)); + var ispe = shared.Property(HeifBuilder.Ispe(tw, th)); + shared.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th)).Item(10, "hvc1", picture.Data, -hvcC, ispe); + for (var i = 1; i < 4; i++) + { + shared.ItemSharing((uint)(10 + i), "hvc1", 10, -hvcC, ispe); + } + + shared.Reference("dimg", 1, 10, 11, 12, 13); + var ex = Assert.ThrowsExactly(() => HeifDecoder.Decode(shared.Build())); + StringAssert.Contains(ex.Message, "più dati"); + + // The same tile named four times is read once: the grid is that picture four times. + var repeated = new HeifBuilder(); + hvcC = repeated.Property(HeifBuilder.HvcCProperty(picture.HvcC)); + ispe = repeated.Property(HeifBuilder.Ispe(tw, th)); + repeated.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th)).Item(10, "hvc1", picture.Data, -hvcC, ispe).Reference("dimg", 1, 10, 10, 10, 10); + var image = HeifDecoder.Decode(repeated.Build()); + var tile = Rgba(picture.Frame); + for (var y = 0; y < 2 * th; y++) + { + for (var half = 0; half < 2; half++) + { + var row = image.Pixels.AsSpan(((y * 2 * tw) + (half * tw)) * 4, tw * 4); + Assert.IsTrue(row.SequenceEqual(tile.AsSpan(y % th * tw * 4, tw * 4)), $"riga {y}, metà {half}"); + } + } + } + + [TestMethod] + public void TheBytesOfAllTilesHaveALimit() + { + var pictures = Tiles.Select(CodedPicture.First).ToArray(); + var (tw, th) = (pictures[0].Frame.Width, pictures[0].Frame.Height); + var builder = new HeifBuilder(); + var ispe = builder.Property(HeifBuilder.Ispe(tw, th)); + builder.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th)); + for (var i = 0; i < 4; i++) + { + builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe); + } + + builder.Reference("dimg", 1, 10, 11, 12, 13); + var file = builder.Build(); + long total = pictures.Sum(p => p.Data.Length); + Assert.AreEqual(2 * tw, HeifDecoder.Decode(file, new HeifLimits { MaxTotalBytes = total }).Width); + Assert.ThrowsExactly(() => HeifDecoder.Decode(file, new HeifLimits { MaxTotalBytes = total - 1 })); + } + + [TestMethod] + [DataRow(6201)] + [DataRow(6202)] + public void DamagedTilesDecodedInParallelOnlyRaiseHeifException(int seed) + { + // The data of the tiles after the first, which are decoded on several threads: whatever goes wrong there leaves + // the decoder as a HeifException, not as the AggregateException of the parallel loop. + var pictures = Tiles.Select(CodedPicture.First).ToArray(); + var (tw, th) = (pictures[0].Frame.Width, pictures[0].Frame.Height); + var builder = new HeifBuilder(); + var ispe = builder.Property(HeifBuilder.Ispe(tw, th)); + builder.Item(1, "grid", HeifBuilder.GridData(2, 2, 2 * tw, 2 * th)); + for (var i = 0; i < 4; i++) + { + builder.Item((uint)(10 + i), "hvc1", pictures[i].Data, -builder.Property(HeifBuilder.HvcCProperty(pictures[i].HvcC)), ispe); + } + + builder.Reference("dimg", 1, 10, 11, 12, 13); + var file = builder.Build(); + var rest = pictures.Skip(1).Sum(p => p.Data.Length); + var random = new Random(seed); + for (var trial = 0; trial < 40; trial++) + { + var copy = (byte[])file.Clone(); + for (var k = random.Next(1, 30); k > 0; k--) + { + copy[copy.Length - 1 - random.Next(rest)] = (byte)random.Next(256); + } + + try + { + _ = HeifDecoder.Decode(copy); + } + catch (HeifException) + { + } + } + } + private static byte[] WithExif(CodedPicture picture, byte[] tiff) { var builder = new HeifBuilder(); diff --git a/tests/Febe.Tests/Media/Heif/HeifFiles.cs b/tests/Febe.Tests/Media/Heif/HeifFiles.cs index 7ef5226..2c213df 100644 --- a/tests/Febe.Tests/Media/Heif/HeifFiles.cs +++ b/tests/Febe.Tests/Media/Heif/HeifFiles.cs @@ -108,6 +108,13 @@ internal sealed class HeifBuilder return this; } + /// Adds an item whose only extent is that of item : the same bytes of the file. + public HeifBuilder ItemSharing(uint id, string type, uint dataOf, params int[] properties) + { + items.Add(new Entry(id, type, [], properties) { SharesWith = dataOf }); + return this; + } + /// Adds a property box and returns its 1-based index. public int Property(byte[] box) { @@ -156,7 +163,7 @@ internal sealed class HeifBuilder var meta = Meta(0); var mdatStart = ftyp.Length + meta.Length + 8; meta = Meta(mdatStart); - var payload = InIdat ? [] : items.SelectMany(i => i.Data).ToArray(); + var payload = InIdat ? [] : items.Where(i => i.SharesWith is null).SelectMany(i => i.Data).ToArray(); return [.. ftyp, .. meta, .. Box("mdat", payload)]; } @@ -171,15 +178,22 @@ internal sealed class HeifBuilder var iloc = new List { 0x44, 0x00 }; iloc.AddRange(U16((ushort)items.Count)); var offset = InIdat ? 0 : mdatStart; + var extents = new Dictionary(); + foreach (var item in items.Where(i => i.SharesWith is null)) + { + extents[item.Id] = (offset, item.Data.Length); + offset += item.Data.Length; + } + foreach (var item in items) { + var (start, length) = extents[item.SharesWith ?? item.Id]; 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; + iloc.AddRange(U32((uint)start)); + iloc.AddRange(U32((uint)length)); } var ipma = new List(); @@ -214,7 +228,7 @@ internal sealed class HeifBuilder children.Add(iprp); if (InIdat) { - children.Add(Box("idat", [.. items.SelectMany(i => i.Data)])); + children.Add(Box("idat", [.. items.Where(i => i.SharesWith is null).SelectMany(i => i.Data)])); } return FullBox("meta", 0, [.. children.SelectMany(b => b)]); @@ -235,5 +249,8 @@ internal sealed class HeifBuilder 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); + private sealed record Entry(uint Id, string Type, byte[] Data, int[] Properties) + { + public uint? SharesWith { get; init; } + } } diff --git a/tests/Febe.Tests/Media/YuvToRgbTests.cs b/tests/Febe.Tests/Media/YuvToRgbTests.cs new file mode 100644 index 0000000..ab2e7ce --- /dev/null +++ b/tests/Febe.Tests/Media/YuvToRgbTests.cs @@ -0,0 +1,37 @@ +using Febe.Core.Codecs; + +namespace Febe.Tests.Codecs; + +/// The shared Y′CbCr to RGB conversion: the matrices that are not Y′CbCr ones. +[TestClass] +public sealed class YuvToRgbTests +{ + [TestMethod] + [DataRow(128, 148, 128, true, 8, 108, 148, 108)] + [DataRow(100, 128, 150, true, 8, 122, 100, 78)] + [DataRow(200, 100, 160, true, 8, 255, 172, 196)] + [DataRow(512, 592, 512, true, 10, 108, 148, 108)] + [DataRow(16, 128, 128, false, 8, 0, 0, 0)] + [DataRow(235, 128, 128, false, 8, 255, 255, 255)] + [DataRow(126, 151, 128, false, 8, 102, 154, 102)] + public void YCgCoIsNotConvertedAsYCbCr(int y, int cg, int co, bool fullRange, int bitDepth, int r, int g, int b) + { + // matrix_coeffs 8 (H.273): G = Y + Cg, R = Y − Cg + Co, B = Y − Cg − Co, Cg and Co around the middle of their + // range and, in limited range, scaled as Cb and Cr are (224 steps), Y as luma (219 steps from 16). + var k = YuvToRgb.For(8, fullRange, bitDepth, bitDepth, 1080); + var planes = new YuvPlanes([(ushort)y], [(ushort)cg], [(ushort)co], 1, 1, 0, 0, false, bitDepth, bitDepth); + var rgb = new byte[3]; + YuvToRgb.Convert(planes, k, 1, rgb, 3, 3, 1, 1); + Assert.AreEqual((r, g, b), (rgb[0], rgb[1], rgb[2])); + } + + [TestMethod] + public void YCgCoGreyStaysGrey() + { + var k = YuvToRgb.For(8, false, 8, 8, 1080); + var planes = new YuvPlanes([16, 126, 235], [128, 128, 128], [128, 128, 128], 3, 1, 0, 0, false, 8, 8); + var rgb = new byte[9]; + YuvToRgb.Convert(planes, k, 1, rgb, 9, 3, 3, 1); + CollectionAssert.AreEqual(new byte[] { 0, 0, 0, 128, 128, 128, 255, 255, 255 }, rgb); + } +}