diff --git a/docs/decisioni.md b/docs/decisioni.md index f757f23..99b9c8d 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -500,4 +500,16 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Nella CI resta zero il numero di prove saltate ammesse, con una sola eccezione, la categoria «da fare»: le inconclusive di `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: » subito dopo la cornice di MSTest. `riepilogo-prove.sh` vincola sia il nome della prova sia l'inizio del motivo; i due flussi MVC senza ricostruzione ufficiale passano da «da verificare: …» a «da fare: …» | Con lo schema di prima (`Inconclusive.*da fare: ` in qualunque punto del messaggio) qualunque prova poteva saltarsi in silenzio scrivendo quelle parole, e i due flussi MVC, che non le avevano, contavano come saltate e facevano fallire ogni verifica del ramo. Ora `PipelineTests` prova lo script su file `.trx` con le cornici inglese e italiana | | 2026-11-18 | Provenienza del filtro di deblocking per campi e coppie MBAFF: la riga del 18 novembre che dice «come lo fa il decodificatore di riferimento dell'ITU-T» va letta come «come vuole §8.7 (§8.7.1, `fieldModeInFrameFilteringFlag`, `mixedModeEdgeFlag`), confermato dalla ricostruzione ufficiale dei flussi MBAFF»: il codice cita §8.7 e non nasce da sorgenti di terzi. Le uscite che H.264 non fissa (due byte little-endian oltre gli 8 bit, crominanza al valore medio per il 4:0:0, righe grigie per un campo senza compagno) seguono i file di ricostruzione ufficiali della serie H.264.1 o, per il campo solo, la scelta di non inventare righe; i commenti nel codice ora lo dicono così | Le regole sono «dalle specifiche pubbliche, mai copiando sorgenti di terzi»: citare il decodificatore di riferimento faceva pensare il contrario. Se nelle sessioni precedenti siano stati letti sorgenti di JM, JSVM o JMVC non si ricava dal repository (nessun identificatore di JM nel codice): lo può dire solo chi ha scritto il codice | | 2026-11-18 | Correzioni dopo la revisione del decodificatore H.264 e dei lettori FLV: una partizione B o C si copia solo se `slice_id` e `redundant_pic_cnt` sono quelli della slice in attesa e se arriva nell'ordine A, B, C (una sperduta non tocca più le partizioni già tenute); le viste MVC tengono insieme al massimo due volte `MaxDpbMbs` di immagini (il fattore 2 dell'allegato H) e il decodificatore di una vista nuova si tiene solo dopo il controllo dell'SPS di sottoinsieme; `Wanted` vale per ogni vista, ciascuna con il suo indice di decodifica, e una componente con `inter_view_flag` si ricostruisce sempre; senza durata nei metadati un FLV dura fino alla fine dell'ultimo fotogramma (l'ultimo tag video più l'intervallo dal precedente, l'audio solo senza video), come fa il lettore MPEG; un FLV è di solo audio solo se la testa ha un tag audio intero, nessun tag video e arriva alla fine del file, a cinque secondi d'audio o a 4096 tag | Erano difetti veri: residui di un'altra slice in una slice con la partizione A persa, memoria moltiplicata per il numero di viste da un SPS rovinato, il filtro ignorato dalle viste non base, durate di un fotogramma più corte di quelle dei metadati, e video veri scartati come «Non riconosciuto» quando un `onMetaData` grande riempiva la testa. Ogni correzione ha una prova che fallisce con il codice di prima | +| 2026-11-18 | Per il decodificatore HEVC si tengono nel repository 146 flussi della serie di conformità ITU-T H.265.1 (136 Main, Main 10 e Main Still Picture, 10 RExt), circa 29 MB, in `tests/Febe.Tests/Media/H265/Conformita`: flusso, `readme` originale e `riferimento.md5` con l'MD5 di tutto il YUV ufficiale e, per i 15 flussi che hanno il YUV nello zip, di ogni fotogramma. Le prove di decodifica sono inconcludenti finché il decodificatore non c'è, e quelle RExt finché Alberto non decide se servono; gli hash SEI delle immagini si leggono già con un lettore scritto dalla norma (D.3.19) | Un riferimento ufficiale per ogni strumento di HEVC prima di scriverne il decodificatore, senza i YUV (centinaia di MB) e senza i flussi grandi già coperti da altri (elenco in LEGGIMI.md). Le 146 prove inconcludenti sono saltate per la CI, che oggi non ne ammette nessuna: il ramo non passa la verifica finché il decodificatore o una regola diversa non le toglie | +| 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 | +| 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) | +| 2026-11-25 | Unione della catena della 0.3.0 nel ramo HEVC: le foto HEIC passano dalla facciata dei codec di casa (`ImageDecoder`, `HeifImageDecoder`): l'`HeifImage` diventa un `RgbaImage` senza copia e `irot`/`imir` l'orientamento dei metadati, così `ImageDecoding`, miniature e impronte le trattano come JPEG e PNG; la misura di un HEIC più grande dei primi 256 KB si legge dai soli box (`HeifDecoder.ReadInfo`). Un HEIC senza immagine non si dice «File danneggiato o incompleto»: il decodificatore HEIF non distingue un file rovinato da un HEIF che non gestisce (AV1, JPEG, una proprietà essenziale sconosciuta). I fotogrammi H.264 sopra gli 8 bit passano dal convertitore comune `YuvToRgb` come quelli HEVC, copiati una volta in valori a 16 bit; dell'MVC solo la vista di base | Una sola immagine RGBA per tutti i codec, come voleva il ramo HEVC; dire danneggiato un HEIC di un tipo non gestito sarebbe falso, e i fotogrammi decodificati per una miniatura sono pochi | +| 2026-11-25 | Flusso di programma MPEG con HEVC: con il tipo 0x24 nella mappa del flusso, codec e dimensioni (dopo la finestra di conformità) vengono dall'SPS dell'HEVC (`H265StreamInfo`), come per l'H.264. Senza mappa un HEVC non si riconosce (niente dimensioni). Come per l'H.264, i campioni non si elencano e non c'è miniatura | Il lettore MPEG del ramo H.264 lo rendeva facile; distinguere un HEVC senza mappa dall'H.264 o da altro video vorrebbe un'euristica sui byte che nessun campione chiede | | 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana | diff --git a/docs/docker.md b/docs/docker.md index f7e8f7f..005f214 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -74,7 +74,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 riquadri, rotazione, trasparenza, EXIF). ## Porte diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs index 79ad9f7..822574a 100644 --- a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -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 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, }; } diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs index f04168e..2493752 100644 --- a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -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, diff --git a/src/Febe.Core/Codecs/Containers/MediaContainer.cs b/src/Febe.Core/Codecs/Containers/MediaContainer.cs index 442d177..b1b7337 100644 --- a/src/Febe.Core/Codecs/Containers/MediaContainer.cs +++ b/src/Febe.Core/Codecs/Containers/MediaContainer.cs @@ -22,7 +22,7 @@ public enum ContainerFormat MpegPs, } -/// Video codecs recognised in a container; only can be decoded. +/// Video codecs recognised in a container; and can be decoded. public enum VideoCodec { Unknown, @@ -115,6 +115,13 @@ public sealed class VideoTrack : MediaTrack /// The AVCDecoderConfigurationRecord (avcC) of an H.264 track stored with length prefixes. public byte[]? AvcConfiguration { get; init; } + /// + /// The HEVCDecoderConfigurationRecord (hvcC, ISO/IEC 14496-15 §8.3.3) of an HEVC track stored with length + /// prefixes: the hvcC box of an hvc1 or hev1 sample entry, the CodecPrivate of a Matroska + /// V_MPEGH/ISO/HEVC track. + /// + public byte[]? HevcConfiguration { get; init; } + /// True when the samples are an Annex B byte stream (start codes), as in AVI. public bool AnnexB { get; init; } diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs index 9cf4406..4c3838f 100644 --- a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -6,7 +6,10 @@ namespace Febe.Core.Codecs.Containers; /// A sample to write: its size, its times in track units, whether it is a sync sample. public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key); -/// A track to write: H.264 video (with its avcC) or AAC audio (with its AudioSpecificConfig). +/// +/// A track to write: H.264 video (with its avcC), HEVC video (with its hvcC, as an hvc1 sample entry) or +/// AAC audio (with its AudioSpecificConfig). +/// public sealed class Mp4OutputTrack { public required bool IsVideo { get; init; } @@ -27,6 +30,9 @@ public sealed class Mp4OutputTrack public byte[]? AvcConfiguration { get; init; } + /// The hvcC of an HEVC video track (then stays null). + 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; } diff --git a/src/Febe.Core/Codecs/Containers/MpegPsReader.cs b/src/Febe.Core/Codecs/Containers/MpegPsReader.cs index 736a015..a082b43 100644 --- a/src/Febe.Core/Codecs/Containers/MpegPsReader.cs +++ b/src/Febe.Core/Codecs/Containers/MpegPsReader.cs @@ -2,6 +2,7 @@ using System.Buffers; using System.Buffers.Binary; using System.Globalization; using Febe.Core.Codecs.H264; +using Febe.Core.Codecs.H265; namespace Febe.Core.Codecs.Containers; @@ -524,6 +525,13 @@ public static class MpegPsReader return; } + // HEVC only with its stream type (0x24) in the stream map: without one, the H.264 look above has the stream. + if (type == 0x24 && H265StreamInfo.TryPictureSizeFromAnnexB(data, whole, out width, out height)) + { + (Codec, Width, Height, VideoDone) = (VideoCodec.Hevc, width, height, true); + return; + } + if (final) { Codec = type switch @@ -620,7 +628,7 @@ public static class MpegPsReader : Codec.ToString(), Width = Width, Height = Height, - AnnexB = Codec == VideoCodec.H264, + AnnexB = Codec is VideoCodec.H264 or VideoCodec.Hevc, Timescale = ClockRate, Duration = ticks ?? 0, }; diff --git a/src/Febe.Core/Codecs/H265/BitReader.cs b/src/Febe.Core/Codecs/H265/BitReader.cs new file mode 100644 index 0000000..9310df5 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/BitReader.cs @@ -0,0 +1,174 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Codecs.H265; + +/// A malformed or unsupported HEVC stream. +public sealed class H265Exception(string message) : Exception(message); + +/// +/// Reads the bits of a raw byte sequence payload (ITU-T H.265 §7.2, §7.4.2): a NAL unit with its emulation prevention +/// bytes removed. The buffer carries sixteen zero bytes past the end (see ), so reads never +/// need a bounds check; reading past the payload gives zeros and is detected through . +/// +internal sealed class BitReader +{ + private readonly byte[] data; + private readonly int length; + private int position; + + /// The payload, followed by at least sixteen bytes of zero padding. + /// Bytes of payload. + /// First byte to read (after the two-byte NAL unit header). + internal BitReader(byte[] data, int length, int startByte) + { + this.data = data; + this.length = length; + position = startByte * 8; + } + + internal byte[] Data => data; + + internal int Length => length; + + internal int Position + { + get => position; + set => position = value; + } + + internal int BitsLeft => (length * 8) - position; + + internal bool ByteAligned => (position & 7) == 0; + + /// more_rbsp_data() (§7.2): true while bits remain before the rbsp_stop_one_bit. + internal bool MoreRbspData + { + get + { + var last = length - 1; + while (last >= 0 && data[last] == 0) + { + last--; + } + + if (last < 0) + { + return false; + } + + var stopBit = (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(data[last]); + return position < stopBit; + } + } + + internal uint Peek(int count) + { + var index = position >> 3; + if (index + 8 > data.Length) + { + throw new H265Exception("Flusso HEVC troncato."); + } + + var word = BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(index, 8)); + return (uint)((word << (position & 7)) >> (64 - count)); + } + + /// u(n), 0 to 32 bits. + internal uint Read(int count) + { + if (count == 0) + { + return 0; + } + + var value = Peek(count); + position += count; + return value; + } + + internal int ReadInt(int count) => (int)Read(count); + + internal void Skip(int count) => position += count; + + internal bool ReadFlag() + { + if ((position >> 3) >= data.Length) + { + throw new H265Exception("Flusso HEVC troncato."); + } + + var bit = (data[position >> 3] >> (7 - (position & 7))) & 1; + position++; + return bit != 0; + } + + /// ue(v): Exp-Golomb code (§9.2). + internal uint ReadUe() + { + var zeros = 0; + while (!ReadFlag()) + { + if (++zeros > 31 || position > (length * 8) + 32) + { + throw new H265Exception("Codice Exp-Golomb non valido."); + } + } + + return zeros == 0 ? 0 : (uint)(((1UL << zeros) - 1) + Read(zeros)); + } + + /// A ue(v) value that must not exceed . + internal int ReadUe(int max) + { + var value = ReadUe(); + if (value > (uint)max) + { + throw new H265Exception("Valore fuori dall'intervallo ammesso."); + } + + return (int)value; + } + + /// se(v): signed Exp-Golomb code (§9.2.2). + internal int ReadSe() + { + var code = ReadUe(); + var magnitude = (int)((code + 1) >> 1); + return (code & 1) != 0 ? magnitude : -magnitude; + } + + /// A se(v) value inside [, ]. + internal int ReadSe(int min, int max) + { + var value = ReadSe(); + if (value < min || value > max) + { + throw new H265Exception("Valore fuori dall'intervallo ammesso."); + } + + return value; + } + + /// Moves to the next byte boundary (byte_alignment() and the alignment bits before PCM samples). + internal void AlignToByte() => position = (position + 7) & ~7; +} + +/// One HEVC NAL unit, with its RBSP (the two-byte header included at its start). +internal readonly record struct H265NalUnit(int Type, int LayerId, int TemporalId, byte[] Rbsp, int Length) +{ + /// A reader positioned after the two-byte NAL unit header (§7.3.1.2). + internal BitReader Reader() => new(Rbsp, Length, 2); + + /// Removes the emulation prevention bytes of one NAL unit into , grown when needed. + internal static H265NalUnit Unescape(ReadOnlySpan nal, ref byte[]? buffer) + { + if (nal.Length < 2) + { + throw new H265Exception("Unità NAL HEVC troppo corta."); + } + + var unit = NalUnits.Unescape(nal, ref buffer); + return new H265NalUnit((nal[0] >> 1) & 63, ((nal[0] & 1) << 5) | (nal[1] >> 3), (nal[1] & 7) - 1, unit.Rbsp, unit.Length); + } +} diff --git a/src/Febe.Core/Codecs/H265/CabacEngine.cs b/src/Febe.Core/Codecs/H265/CabacEngine.cs new file mode 100644 index 0000000..d958c30 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/CabacEngine.cs @@ -0,0 +1,201 @@ +using System.Buffers.Binary; +using System.Numerics; +using Lps = Febe.Core.Codecs.H264.CabacTables; + +namespace Febe.Core.Codecs.H265; + +/// +/// The arithmetic decoding engine of HEVC CABAC (ITU-T H.265 §9.3.4.3) with the context variables of the slice segment. +/// Each context is one byte, (pStateIdx << 1) | valMps, so the storage and synchronisation of §9.3.2.3 and §9.3.2.4 +/// (wavefronts, dependent slice segments) are plain copies. The data is read through a 64-bit window and +/// renormalisation shifts all its bits at once: the arithmetic is that of the Recommendation, bit for bit. +/// +internal sealed class CabacEngine +{ + internal readonly byte[] Contexts = new byte[CabacTables.ContextCount]; + + private byte[] data = []; + private int range; + private int offset; + private ulong window; + private int bits; + private int next; + private int end; + + /// Initialises every context variable for an initType and the slice QP (§9.3.2.2). + internal void InitContexts(int initType, int sliceQp) + { + var values = CabacTables.InitValues[initType]; + var qp = Math.Clamp(sliceQp, 0, 51); + for (var i = 0; i < Contexts.Length; i++) + { + int initValue = values[i]; + var m = ((initValue >> 4) * 5) - 45; + var n = ((initValue & 15) << 3) - 16; + var pre = Math.Clamp(((m * qp) >> 4) + n, 1, 126); + Contexts[i] = pre <= 63 ? (byte)((63 - pre) << 1) : (byte)(((pre - 64) << 1) | 1); + } + } + + /// + /// Initialises the arithmetic decoder (§9.3.2.5) at a bit position of ; reading stops at + /// (the end of the slice segment data), past which the decoder sees zeros. + /// + internal void Start(byte[] source, int bitPosition, int endByte) + { + data = source; + end = endByte; + next = bitPosition >> 3; + window = 0; + bits = 0; + Refill(); + var skip = bitPosition & 7; + window <<= skip; + bits -= skip; + range = 510; + offset = Take(9); + if (offset >= range) + { + throw new H265Exception("Dati CABAC non validi."); + } + } + + /// The bit position right after the last bit the decoder has read (after a terminating bin equal to 1). + internal int BitPosition => (next * 8) - bits; + + /// DecodeDecision (§9.3.4.3.2). + internal int Decision(int ctx) + { + int s = Contexts[ctx]; + var p = s >> 1; + var mps = s & 1; + int lps = Lps.RangeLps[(p << 2) + ((range >> 6) & 3)]; + range -= lps; + int bin; + if (offset >= range) + { + bin = mps ^ 1; + offset -= range; + range = lps; + if (p == 0) + { + mps ^= 1; + } + + Contexts[ctx] = (byte)((Lps.NextStateLps[p] << 1) | mps); + } + else + { + bin = mps; + if (p < 62) + { + Contexts[ctx] = (byte)(s + 2); + } + } + + if (range < 256) + { + var shift = BitOperations.LeadingZeroCount((uint)range) - 23; + range <<= shift; + offset = (offset << shift) | Take(shift); + } + + return bin; + } + + internal bool Flag(int ctx) => Decision(ctx) != 0; + + /// DecodeBypass (§9.3.4.3.4). + internal int Bypass() + { + offset = (offset << 1) | Take(1); + if (offset >= range) + { + offset -= range; + return 1; + } + + return 0; + } + + /// bypass bins (at most 16), the first one in the most significant bit. + internal int BypassBits(int count) + { + var value = 0; + for (var i = 0; i < count; i++) + { + offset = (offset << 1) | Take(1); + value <<= 1; + if (offset >= range) + { + offset -= range; + value |= 1; + } + } + + return value; + } + + /// + /// DecodeTerminate (§9.3.4.3.5). After a bin equal to 1 (end of slice segment, of a substream, PCM samples) the last + /// bit read is the final bit of the encoder's flush and is where the bitstream goes on. + /// + internal int Terminate() + { + range -= 2; + if (offset >= range) + { + return 1; + } + + if (range < 256) + { + range <<= 1; + offset = (offset << 1) | Take(1); + } + + return 0; + } + + private int Take(int count) + { + if (bits < count) + { + Refill(); + } + + var value = (int)(window >> (64 - count)); + window <<= count; + bits -= count; + return value; + } + + private void Refill() + { + while (bits <= 32) + { + uint word; + if (next + 4 <= end) + { + word = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)); + } + else + { + if (next > end + 64) + { + throw new H265Exception("Dati CABAC oltre la fine della slice."); + } + + word = 0; + for (var k = 0; k < 4; k++) + { + word = (word << 8) | (next + k < end ? data[next + k] : 0u); + } + } + + window |= (ulong)word << (32 - bits); + next += 4; + bits += 32; + } + } +} diff --git a/src/Febe.Core/Codecs/H265/CabacTables.cs b/src/Febe.Core/Codecs/H265/CabacTables.cs new file mode 100644 index 0000000..506dafd --- /dev/null +++ b/src/Febe.Core/Codecs/H265/CabacTables.cs @@ -0,0 +1,141 @@ +namespace Febe.Core.Codecs.H265; + +/// +/// The context variables of HEVC CABAC (ITU-T H.265 §9.3.2.2): where each syntax element's contexts start in the +/// decoder's array and their initValue for the three initTypes (0 for I slices, 1 and 2 for P and B slices, swapped by +/// cabac_init_flag), transcribed from the tables of 9.3.2.2 of the Recommendation. Contexts that a slice type never uses +/// (for instance cu_skip_flag in I slices) have no value in the Recommendation and take 154 here, which is never read. +/// rangeTabLps and transIdxLps (9.3.4.3.2) are those of H.264 (). +/// +internal static class CabacTables +{ + internal const int SaoMergeFlag = 0; + internal const int SaoTypeIdx = SaoMergeFlag + 1; + internal const int SplitCuFlag = SaoTypeIdx + 1; + internal const int CuTransquantBypassFlag = SplitCuFlag + 3; + internal const int CuSkipFlag = CuTransquantBypassFlag + 1; + internal const int PredModeFlag = CuSkipFlag + 3; + internal const int PartMode = PredModeFlag + 1; + internal const int PrevIntraLumaPredFlag = PartMode + 4; + internal const int IntraChromaPredMode = PrevIntraLumaPredFlag + 1; + internal const int RqtRootCbf = IntraChromaPredMode + 1; + internal const int MergeFlag = RqtRootCbf + 1; + internal const int MergeIdx = MergeFlag + 1; + internal const int InterPredIdc = MergeIdx + 1; + internal const int RefIdx = InterPredIdc + 5; + internal const int MvpFlag = RefIdx + 2; + internal const int SplitTransformFlag = MvpFlag + 1; + internal const int CbfLuma = SplitTransformFlag + 3; + internal const int CbfChroma = CbfLuma + 2; + internal const int AbsMvdGreater0Flag = CbfChroma + 5; + internal const int AbsMvdGreater1Flag = AbsMvdGreater0Flag + 1; + internal const int CuQpDeltaAbs = AbsMvdGreater1Flag + 1; + internal const int TransformSkipFlag = CuQpDeltaAbs + 2; + internal const int LastSigCoeffXPrefix = TransformSkipFlag + 2; + internal const int LastSigCoeffYPrefix = LastSigCoeffXPrefix + 18; + internal const int CodedSubBlockFlag = LastSigCoeffYPrefix + 18; + internal const int SigCoeffFlag = CodedSubBlockFlag + 4; + internal const int CoeffAbsLevelGreater1Flag = SigCoeffFlag + 44; + internal const int CoeffAbsLevelGreater2Flag = CoeffAbsLevelGreater1Flag + 24; + internal const int ExplicitRdpcmFlag = CoeffAbsLevelGreater2Flag + 6; + internal const int ExplicitRdpcmDirFlag = ExplicitRdpcmFlag + 2; + internal const int Log2ResScaleAbsPlus1 = ExplicitRdpcmDirFlag + 2; + internal const int ResScaleSignFlag = Log2ResScaleAbsPlus1 + 8; + internal const int CuChromaQpOffsetFlag = ResScaleSignFlag + 2; + internal const int CuChromaQpOffsetIdx = CuChromaQpOffsetFlag + 1; + + /// Number of context variables kept by the decoder. + internal const int ContextCount = CuChromaQpOffsetIdx + 1; + + /// + /// The syntax elements in the order of the layout above, each with its initValues for initType 0, 1 and 2 (as many + /// values per initType as the element has contexts). + /// + internal static readonly (string Name, byte[] I, byte[] P, byte[] B)[] Elements = + [ + ("sao_merge_left_flag", [153], [153], [153]), + ("sao_type_idx", [200], [185], [160]), + ("split_cu_flag", [139, 141, 157], [107, 139, 126], [107, 139, 126]), + ("cu_transquant_bypass_flag", [154], [154], [154]), + ("cu_skip_flag", [154, 154, 154], [197, 185, 201], [197, 185, 201]), + ("pred_mode_flag", [154], [149], [134]), + ("part_mode", [184, 154, 154, 154], [154, 139, 154, 154], [154, 139, 154, 154]), + ("prev_intra_luma_pred_flag", [184], [154], [183]), + ("intra_chroma_pred_mode", [63], [152], [152]), + ("rqt_root_cbf", [154], [79], [79]), + ("merge_flag", [154], [110], [154]), + ("merge_idx", [154], [122], [137]), + ("inter_pred_idc", [154, 154, 154, 154, 154], [95, 79, 63, 31, 31], [95, 79, 63, 31, 31]), + ("ref_idx", [154, 154], [153, 153], [153, 153]), + ("mvp_flag", [154], [168], [168]), + ("split_transform_flag", [153, 138, 138], [124, 138, 94], [224, 167, 122]), + ("cbf_luma", [111, 141], [153, 111], [153, 111]), + ("cbf_cb_cr", [94, 138, 182, 154, 154], [149, 107, 167, 154, 154], [149, 92, 167, 154, 154]), + ("abs_mvd_greater0_flag", [154], [140], [169]), + ("abs_mvd_greater1_flag", [154], [198], [198]), + ("cu_qp_delta_abs", [154, 154], [154, 154], [154, 154]), + ("transform_skip_flag", [139, 139], [139, 139], [139, 139]), + ( + "last_sig_coeff_x_prefix", + [110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63], + [125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108], + [125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93]), + ( + "last_sig_coeff_y_prefix", + [110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63], + [125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108], + [125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93]), + ("coded_sub_block_flag", [91, 171, 134, 141], [121, 140, 61, 154], [121, 140, 61, 154]), + ( + "sig_coeff_flag", // the last two of each initType are those of transform_skip_context_enabled_flag + [ + 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 107, + 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 141, 111, + ], + [ + 155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, + 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140, + ], + [ + 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, + 183, 140, 136, 153, 154, 170, 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140, + ]), + ( + "coeff_abs_level_greater1_flag", + [140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, 140, 179, 166, 182, 140, 227, 122, 197], + [154, 196, 196, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182], + [154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122, 169, 208, 166, 167, 154, 152, 167, 182]), + ("coeff_abs_level_greater2_flag", [138, 153, 136, 167, 152, 152], [107, 167, 91, 122, 107, 167], [107, 167, 91, 107, 107, 167]), + ("explicit_rdpcm_flag", [139, 139], [139, 139], [139, 139]), + ("explicit_rdpcm_dir_flag", [139, 139], [139, 139], [139, 139]), + ("log2_res_scale_abs_plus1", [154, 154, 154, 154, 154, 154, 154, 154], [154, 154, 154, 154, 154, 154, 154, 154], [154, 154, 154, 154, 154, 154, 154, 154]), + ("res_scale_sign_flag", [154, 154], [154, 154], [154, 154]), + ("cu_chroma_qp_offset_flag", [154], [154], [154]), + ("cu_chroma_qp_offset_idx", [154], [154], [154]), + ]; + + /// initValue of every context by initType: InitValues[initType][ctx]. + internal static readonly byte[][] InitValues = BuildInitValues(); + + private static byte[][] BuildInitValues() + { + var tables = new byte[3][]; + for (var t = 0; t < 3; t++) + { + var values = new List(ContextCount); + foreach (var element in Elements) + { + values.AddRange(t == 0 ? element.I : t == 1 ? element.P : element.B); + } + + if (values.Count != ContextCount) + { + throw new InvalidOperationException("Tabelle CABAC HEVC incoerenti."); + } + + tables[t] = [.. values]; + } + + return tables; + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs new file mode 100644 index 0000000..b57d60d --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Decoder.Filters.cs @@ -0,0 +1,543 @@ +namespace Febe.Core.Codecs.H265; + +/// The in-loop filters (§8.7): deblocking (§8.7.2) then sample adaptive offset (§8.7.3), on the whole picture. +public sealed partial class H265Decoder +{ + private ushort[] saoSource = []; + + /// The left and top edges of a coding block, unless filterEdgeFlag of §8.7.2.3 is 0 for them. + private void MarkCodingUnitEdges(int x0, int y0, int size) + { + if (x0 > 0 && FilterAcross(x0 - 1, y0)) + { + MarkVertical(x0, y0, size, 2); + } + + if (y0 > 0 && FilterAcross(x0, y0 - 1)) + { + MarkHorizontal(x0, y0, size, 2); + } + } + + /// Whether deblocking may cross into the block at (xN, yN) from the current one: slice and tile boundaries. + private bool FilterAcross(int xN, int yN) + { + var log2 = sps.Log2CtbSize; + var ctbN = ((yN >> log2) * widthInCtbs) + (xN >> log2); + if (ctbN == ctbAddrRs) + { + return true; + } + + if (!pps.LoopFilterAcrossTilesEnabled && pps.TileIdRs[ctbN] != pps.TileIdRs[ctbAddrRs]) + { + return false; + } + + return slice.LoopFilterAcrossSlices || ctbSlice[ctbN] == sliceIdx; + } + + /// The edges between the prediction blocks of an inter coding unit (§8.7.2.3). + private void MarkPredictionEdges(int x0, int y0, int size) + { + if (cuIntra) + { + return; + } + + int half = size >> 1, quarter = size >> 2; + switch (cuPartMode) + { + case PartNx2N: + MarkVertical(x0 + half, y0, size, 1); + break; + case PartnLx2N: + MarkVertical(x0 + quarter, y0, size, 1); + break; + case PartnRx2N: + MarkVertical(x0 + size - quarter, y0, size, 1); + break; + case Part2NxN: + MarkHorizontal(x0, y0 + half, size, 1); + break; + case Part2NxnU: + MarkHorizontal(x0, y0 + quarter, size, 1); + break; + case Part2NxnD: + MarkHorizontal(x0, y0 + size - quarter, size, 1); + break; + case PartNxN: + MarkVertical(x0 + half, y0, size, 1); + MarkHorizontal(x0, y0 + half, size, 1); + break; + } + } + + private void MarkVertical(int x, int y0, int length, byte kind) + { + if (slice.DeblockingDisabled || (x & 7) != 0) + { + return; + } + + var gx = x >> 2; + var end = Math.Min((y0 + length) >> 2, h4); + for (var gy = y0 >> 2; gy < end; gy++) + { + ref var e = ref edgeV[(gy * w4) + gx]; + e = Math.Max(e, kind); + } + } + + private void MarkHorizontal(int x0, int y, int length, byte kind) + { + if (slice.DeblockingDisabled || (y & 7) != 0) + { + return; + } + + var row = (y >> 2) * w4; + var end = Math.Min((x0 + length) >> 2, w4); + for (var gx = x0 >> 2; gx < end; gx++) + { + ref var e = ref edgeH[row + gx]; + e = Math.Max(e, kind); + } + } + + private void ApplyInLoopFilters(Picture picture) + { + Deblock(picture, true); + Deblock(picture, false); + foreach (var header in slices) + { + if (header.SaoLuma || header.SaoChroma) + { + ApplySao(picture); + break; + } + } + } + + /// + /// bS of §8.7.2.4 between the 4×4 blocks and of the grid, in the CTBs + /// and . + /// + private int BoundaryStrength(Picture picture, int p, int q, int kind, int ctbP, int ctbQ) + { + if (predMode[p] == ModeIntra || predMode[q] == ModeIntra) + { + return 2; + } + + if (kind == 2 && ((blockFlags[p] | blockFlags[q]) & FlagCoded) != 0) + { + return 1; + } + + // The motion: the pictures referred to (whichever the list), how many vectors, how far apart (4 = one sample). + var mp = picture.Motion[p]; + var mq = picture.Motion[q]; + if (mp.Ref0 < 0 && mp.Ref1 < 0) + { + // A block of a CTB that no slice decoded. + return 0; + } + + var sliceP = slices[ctbSlice[ctbP]]; + var sliceQ = ctbP == ctbQ ? sliceP : slices[ctbSlice[ctbQ]]; + var p0 = mp.Ref0 >= 0 ? sliceP.RefPicList[0][mp.Ref0] : null; + var p1 = mp.Ref1 >= 0 ? sliceP.RefPicList[1][mp.Ref1] : null; + var q0 = mq.Ref0 >= 0 ? sliceQ.RefPicList[0][mq.Ref0] : null; + var q1 = mq.Ref1 >= 0 ? sliceQ.RefPicList[1][mq.Ref1] : null; + var countP = (p0 is null ? 0 : 1) + (p1 is null ? 0 : 1); + var countQ = (q0 is null ? 0 : 1) + (q1 is null ? 0 : 1); + if (countP != countQ) + { + return 1; + } + + if (countP == 1) + { + if (!ReferenceEquals(p0 ?? p1, q0 ?? q1)) + { + return 1; + } + + int pX = p0 is null ? mp.X1 : mp.X0, pY = p0 is null ? mp.Y1 : mp.Y0; + int qX = q0 is null ? mq.X1 : mq.X0, qY = q0 is null ? mq.Y1 : mq.Y0; + return Far(pX, pY, qX, qY) ? 1 : 0; + } + + var straight = ReferenceEquals(p0, q0) && ReferenceEquals(p1, q1); + var crossed = ReferenceEquals(p0, q1) && ReferenceEquals(p1, q0); + if (!straight && !crossed) + { + return 1; + } + + if (!ReferenceEquals(p0, p1)) + { + // Two different pictures: the vectors that refer to the same picture are compared. + return straight + ? (Far(mp.X0, mp.Y0, mq.X0, mq.Y0) || Far(mp.X1, mp.Y1, mq.X1, mq.Y1) ? 1 : 0) + : (Far(mp.X0, mp.Y0, mq.X1, mq.Y1) || Far(mp.X1, mp.Y1, mq.X0, mq.Y0) ? 1 : 0); + } + + // Both vectors of both blocks refer to one picture: bS 1 only when both pairings differ. + return (Far(mp.X0, mp.Y0, mq.X0, mq.Y0) || Far(mp.X1, mp.Y1, mq.X1, mq.Y1)) + && (Far(mp.X0, mp.Y0, mq.X1, mq.Y1) || Far(mp.X1, mp.Y1, mq.X0, mq.Y0)) ? 1 : 0; + } + + private static bool Far(int ax, int ay, int bx, int by) => Math.Abs(ax - bx) >= 4 || Math.Abs(ay - by) >= 4; + + /// Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 8×8 grid of chroma samples. + private void Deblock(Picture picture, bool vertical) + { + var edges = vertical ? edgeV : edgeH; + var luma = picture.Planes[0]; + var stride = picture.Width; + var maxY = (1 << sps.BitDepthY) - 1; + var scaleY = 1 << (sps.BitDepthY - 8); + var log2Ctb = sps.Log2CtbSize; + var checkFlags = pictureHasUnfilteredBlocks; + + // Chroma edges (§8.7.2.5.5) lie on the 8×8 grid of chroma samples and are filtered in segments of 4 chroma + // samples, each taking bS and QP from the luma segment at its start: a vertical edge every 8 << sx luma columns, + // a segment every 4 << sy luma rows (and the other way round for horizontal edges). + var chroma = sps.ChromaArrayType != 0; + int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY; + int edgeMask = vertical ? (8 << sx) - 1 : (8 << sy) - 1; + int segmentMask = vertical ? (4 << sy) - 1 : (4 << sx) - 1; + for (var gy = 0; gy < h4; gy++) + { + for (var gx = 0; gx < w4; gx++) + { + var q = (gy * w4) + gx; + int kind = edges[q]; + if (kind == 0) + { + continue; + } + + var p = vertical ? q - 1 : q - w4; + var ctbQ = ((gy << 2 >> log2Ctb) * widthInCtbs) + (gx << 2 >> log2Ctb); + var ctbP = vertical ? ((gy << 2 >> log2Ctb) * widthInCtbs) + ((gx - 1) << 2 >> log2Ctb) : (((gy - 1) << 2 >> log2Ctb) * widthInCtbs) + (gx << 2 >> log2Ctb); + var bS = BoundaryStrength(picture, p, q, kind, ctbP, ctbQ); + if (bS == 0) + { + continue; + } + + var header = slices[ctbSlice[ctbQ]]; + int qpP = qpMap[p], qpQ = qpMap[q]; + var qpL = (qpQ + qpP + 1) >> 1; + var beta = H265Tables.Beta[Math.Clamp(qpL + (header.BetaOffsetDiv2 * 2), 0, 51)] * scaleY; + var tc = H265Tables.Tc[Math.Clamp(qpL + (2 * (bS - 1)) + (header.TcOffsetDiv2 * 2), 0, 53)] * scaleY; + var noP = checkFlags && (blockFlags[p] & FlagNoFilter) != 0; + var noQ = checkFlags && (blockFlags[q] & FlagNoFilter) != 0; + var x = gx << 2; + var y = gy << 2; + var origin = (y * stride) + x; + if (tc > 0 || beta > 0) + { + FilterLuma(luma, origin, vertical ? 1 : stride, vertical ? stride : 1, beta, tc, noP, noQ, maxY); + } + + // Chroma: bS 2 only. + if (bS == 2 && chroma && (vertical ? (x & edgeMask) == 0 && (y & segmentMask) == 0 : (y & edgeMask) == 0 && (x & segmentMask) == 0)) + { + FilterChromaEdge(picture, x >> sx, y >> sy, vertical, qpL, header.TcOffsetDiv2, noP, noQ); + } + } + } + } + + private void FilterChromaEdge(Picture picture, int xc, int yc, bool vertical, int qpL, int tcOffsetDiv2, bool noP, bool noQ) + { + var stride = picture.ChromaWidth; + var max = (1 << sps.BitDepthC) - 1; + var scale = 1 << (sps.BitDepthC - 8); + var lines = Math.Min(4, vertical ? picture.ChromaHeight - yc : picture.ChromaWidth - xc); + for (var c = 1; c <= 2; c++) + { + var qpC = H265Tables.ChromaQp(qpL + (c == 1 ? pps.CbQpOffset : pps.CrQpOffset), sps.ChromaArrayType); + var tc = H265Tables.Tc[Math.Clamp(qpC + 2 + (tcOffsetDiv2 * 2), 0, 53)] * scale; + if (tc == 0) + { + continue; + } + + var s = picture.Planes[c]; + var across = vertical ? 1 : stride; + var along = vertical ? stride : 1; + var origin = (yc * stride) + xc; + for (var k = 0; k < lines; k++) + { + var q0At = origin + (k * along); + int p0 = s[q0At - across], p1 = s[q0At - (2 * across)], q0 = s[q0At], q1 = s[q0At + across]; + var delta = Math.Clamp(((((q0 - p0) << 2) + p1 - q1 + 4) >> 3), -tc, tc); + if (!noP) + { + s[q0At - across] = (ushort)Math.Clamp(p0 + delta, 0, max); + } + + if (!noQ) + { + s[q0At] = (ushort)Math.Clamp(q0 - delta, 0, max); + } + } + } + } + + /// The luma decisions (§8.7.2.5.3, §8.7.2.5.6) and filtering (§8.7.2.5.7) of one 4-line edge segment. + private static void FilterLuma(ushort[] s, int origin, int across, int along, int beta, int tc, bool noP, bool noQ, int max) + { + var line3 = origin + (3 * along); + var dp0 = Math.Abs(s[origin - (3 * across)] - (2 * s[origin - (2 * across)]) + s[origin - across]); + var dp3 = Math.Abs(s[line3 - (3 * across)] - (2 * s[line3 - (2 * across)]) + s[line3 - across]); + var dq0 = Math.Abs(s[origin + (2 * across)] - (2 * s[origin + across]) + s[origin]); + var dq3 = Math.Abs(s[line3 + (2 * across)] - (2 * s[line3 + across]) + s[line3]); + var dpq0 = dp0 + dq0; + var dpq3 = dp3 + dq3; + var dp = dp0 + dp3; + var dq = dq0 + dq3; + if (dpq0 + dpq3 >= beta) + { + return; + } + + var strong = StrongDecision(s, origin, across, 2 * dpq0, beta, tc) && StrongDecision(s, line3, across, 2 * dpq3, beta, tc); + var side = (beta + (beta >> 1)) >> 3; + var dEp = dp < side; + var dEq = dq < side; + for (var k = 0; k < 4; k++) + { + var at = origin + (k * along); + int p0 = s[at - across], p1 = s[at - (2 * across)], p2 = s[at - (3 * across)], p3 = s[at - (4 * across)]; + int q0 = s[at], q1 = s[at + across], q2 = s[at + (2 * across)], q3 = s[at + (3 * across)]; + if (strong) + { + var tc2 = 2 * tc; + if (!noP) + { + s[at - across] = (ushort)Math.Clamp((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3, p0 - tc2, p0 + tc2); + s[at - (2 * across)] = (ushort)Math.Clamp((p2 + p1 + p0 + q0 + 2) >> 2, p1 - tc2, p1 + tc2); + s[at - (3 * across)] = (ushort)Math.Clamp(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3, p2 - tc2, p2 + tc2); + } + + if (!noQ) + { + s[at] = (ushort)Math.Clamp((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3, q0 - tc2, q0 + tc2); + s[at + across] = (ushort)Math.Clamp((p0 + q0 + q1 + q2 + 2) >> 2, q1 - tc2, q1 + tc2); + s[at + (2 * across)] = (ushort)Math.Clamp((p0 + q0 + q1 + (3 * q2) + (2 * q3) + 4) >> 3, q2 - tc2, q2 + tc2); + } + } + else + { + var delta = ((9 * (q0 - p0)) - (3 * (q1 - p1)) + 8) >> 4; + if (Math.Abs(delta) >= tc * 10) + { + continue; + } + + delta = Math.Clamp(delta, -tc, tc); + if (!noP) + { + s[at - across] = (ushort)Math.Clamp(p0 + delta, 0, max); + if (dEp) + { + var deltaP = Math.Clamp((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1, -(tc >> 1), tc >> 1); + s[at - (2 * across)] = (ushort)Math.Clamp(p1 + deltaP, 0, max); + } + } + + if (!noQ) + { + s[at] = (ushort)Math.Clamp(q0 - delta, 0, max); + if (dEq) + { + var deltaQ = Math.Clamp((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1, -(tc >> 1), tc >> 1); + s[at + across] = (ushort)Math.Clamp(q1 + deltaQ, 0, max); + } + } + } + } + } + + /// dSam of §8.7.2.5.6 for one line. + private static bool StrongDecision(ushort[] s, int at, int across, int dpq, int beta, int tc) + { + int p0 = s[at - across], p3 = s[at - (4 * across)], q0 = s[at], q3 = s[at + (3 * across)]; + return dpq < (beta >> 2) && Math.Abs(p3 - p0) + Math.Abs(q0 - q3) < (beta >> 3) && Math.Abs(p0 - q0) < (((5 * tc) + 1) >> 1); + } + + /// Sample adaptive offset (§8.7.3) of every CTB, from a copy of the deblocked picture. + private void ApplySao(Picture picture) + { + var log2Ctb = sps.Log2CtbSize; + var heightInCtbs = sps.HeightInCtbs; + Span neighbours = stackalloc bool[9]; + var components = sps.ChromaArrayType == 0 ? 1 : 3; + for (var c = 0; c < components; c++) + { + var plane = picture.Planes[c]; + var width = c == 0 ? picture.Width : picture.ChromaWidth; + var height = c == 0 ? picture.Height : picture.ChromaHeight; + int sx = c == 0 ? 0 : sps.ChromaShiftX, sy = c == 0 ? 0 : sps.ChromaShiftY; + int ctbWidth = (1 << log2Ctb) >> sx, ctbHeight = (1 << log2Ctb) >> sy; + var bitDepth = c == 0 ? sps.BitDepthY : sps.BitDepthC; + var max = (1 << bitDepth) - 1; + if (saoSource.Length < plane.Length) + { + saoSource = new ushort[plane.Length]; + } + + var copied = false; + for (var rs = 0; rs < sps.CtbCount; rs++) + { + var at = (rs * 3) + c; + int type = saoType[at]; + if (type == 0 || ctbSlice[rs] < 0) + { + continue; + } + + if (!copied) + { + plane.AsSpan().CopyTo(saoSource); + copied = true; + } + + int cx = rs % widthInCtbs, cy = rs / widthInCtbs; + int x0 = cx * ctbWidth, y0 = cy * ctbHeight; + int x1 = Math.Min(x0 + ctbWidth, width), y1 = Math.Min(y0 + ctbHeight, height); + var offsets = saoOffset.AsSpan(at * 4, 4); + if (type == 1) + { + SaoBand(plane, width, x0, y0, x1, y1, saoClass[at], offsets, bitDepth, max, sx, sy); + } + else + { + for (var dy = -1; dy <= 1; dy++) + { + for (var dx = -1; dx <= 1; dx++) + { + neighbours[((dy + 1) * 3) + dx + 1] = SaoNeighbourAvailable(rs, cx + dx, cy + dy, heightInCtbs); + } + } + + SaoEdge(plane, width, x0, y0, x1, y1, saoClass[at], offsets, max, sx, sy, neighbours); + } + } + } + } + + /// Whether the samples of the CTB at (nx, ny) can be used by the edge offset of the CTB . + private bool SaoNeighbourAvailable(int rs, int nx, int ny, int heightInCtbs) + { + if (nx < 0 || ny < 0 || nx >= widthInCtbs || ny >= heightInCtbs) + { + return false; + } + + var nb = (ny * widthInCtbs) + nx; + if (nb == rs) + { + return true; + } + + int sliceN = ctbSlice[nb], sliceC = ctbSlice[rs]; + if (sliceN < 0) + { + return false; + } + + if (sliceN != sliceC) + { + // The flag of the slice that comes later in decoding order decides. + var later = sliceN > sliceC ? slices[sliceN] : slices[sliceC]; + if (!later.LoopFilterAcrossSlices) + { + return false; + } + } + + return pps.LoopFilterAcrossTilesEnabled || pps.TileIdRs[nb] == pps.TileIdRs[rs]; + } + + private void SaoBand(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int position, ReadOnlySpan offsets, int bitDepth, int max, int sx, int sy) + { + Span table = stackalloc int[32]; + for (var k = 0; k < 4; k++) + { + table[(k + position) & 31] = offsets[k]; + } + + var bandShift = bitDepth - 5; + var check = pictureHasUnfilteredBlocks; + for (var y = y0; y < y1; y++) + { + var row = y * stride; + for (var x = x0; x < x1; x++) + { + if (check && (blockFlags[Grid(x << sx, y << sy)] & FlagNoFilter) != 0) + { + continue; + } + + int value = saoSource[row + x]; + var offset = table[value >> bandShift]; + if (offset != 0) + { + plane[row + x] = (ushort)Math.Clamp(value + offset, 0, max); + } + } + } + } + + private void SaoEdge(ushort[] plane, int stride, int x0, int y0, int x1, int y1, int eoClass, ReadOnlySpan offsets, int max, int sx, int sy, ReadOnlySpan neighbours) + { + // hPos and vPos of table 8-14 (the second neighbour is the opposite of the first). + int dx = eoClass switch { 0 => -1, 1 => 0, 2 => -1, _ => 1 }; + int dy = eoClass == 0 ? 0 : -1; + Span byEdge = [offsets[0], offsets[1], 0, offsets[2], offsets[3]]; + var check = pictureHasUnfilteredBlocks; + var width = stride; + var height = plane.Length / stride; + for (var y = y0; y < y1; y++) + { + var row = y * stride; + int ya = y + dy, yb = y - dy; + var cellA = (ya < y0 ? 0 : ya >= y1 ? 2 : 1) * 3; + var cellB = (yb < y0 ? 0 : yb >= y1 ? 2 : 1) * 3; + var rowOutside = ya < 0 || yb < 0 || ya >= height || yb >= height; + for (var x = x0; x < x1; x++) + { + int xa = x + dx, xb = x - dx; + if (rowOutside || xa < 0 || xb < 0 || xa >= width || xb >= width) + { + continue; + } + + if (!neighbours[cellA + (xa < x0 ? 0 : xa >= x1 ? 2 : 1)] || !neighbours[cellB + (xb < x0 ? 0 : xb >= x1 ? 2 : 1)]) + { + continue; + } + + if (check && (blockFlags[Grid(x << sx, y << sy)] & FlagNoFilter) != 0) + { + continue; + } + + int value = saoSource[row + x]; + var edge = 2 + Math.Sign(value - saoSource[(ya * stride) + xa]) + Math.Sign(value - saoSource[(yb * stride) + xb]); + var offset = byEdge[edge]; + if (offset != 0) + { + plane[row + x] = (ushort)Math.Clamp(value + offset, 0, max); + } + } + } + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs new file mode 100644 index 0000000..0f0c4ab --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Decoder.Inter.cs @@ -0,0 +1,966 @@ +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace Febe.Core.Codecs.H265; + +/// +/// Inter prediction (§8.5.3): reference picture lists (§8.3.4), merge mode and AMVP with their spatial and temporal +/// candidates, fractional sample interpolation and weighted sample prediction. +/// +public sealed partial class H265Decoder +{ + /// fL of table 8-11 (luma, quarter samples 1 to 3), taps at −3 to +4. + private static readonly sbyte[] s_lumaFilter = + [ + 0, 0, 0, 64, 0, 0, 0, 0, + -1, 4, -10, 58, 17, -5, 1, 0, + -1, 4, -11, 40, 40, -11, 4, -1, + 0, 1, -5, 17, 58, -10, 4, -1, + ]; + + /// fC of table 8-12 (chroma, eighth samples 1 to 7), taps at −1 to +2. + private static readonly sbyte[] s_chromaFilter = + [ + 0, 64, 0, 0, + -2, 58, 10, -2, + -4, 54, 16, -2, + -6, 46, 28, -4, + -4, 36, 36, -4, + -4, 28, 46, -6, + -2, 16, 54, -4, + -2, 10, 58, -2, + ]; + + /// l0CandIdx and l1CandIdx of table 8-7 (combined bi-predictive merging candidates). + private static readonly byte[] s_combinedL0 = [0, 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3]; + + private static readonly byte[] s_combinedL1 = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2]; + + /// predSamplesL0 and predSamplesL1 of the block being predicted, at 14-bit precision. + private readonly short[] predL0 = new short[64 * 64]; + + private readonly short[] predL1 = new short[64 * 64]; + + /// The reference samples a block needs, padded at the picture edges (8-228, 8-229). + private readonly ushort[] refBlock = new ushort[(64 + 7) * (64 + 7)]; + + /// The horizontal pass of a block filtered in both directions. + private readonly short[] filterTemp = new short[(64 + 7) * 64]; + + /// RefPicList0 and RefPicList1 of a P or B slice (§8.3.4), its collocated picture and NoBackwardPredFlag. + private void BuildReferencePictureLists(SliceHeader h) + { + var total = refStCurrBefore.Count + refStCurrAfter.Count + refLtCurr.Count; + if (total == 0 || total != h.NumPicTotalCurr) + { + throw new H265Exception("Insieme di riferimento che non corrisponde alla slice."); + } + + Span temp = stackalloc int[Math.Max(16, total)]; + var lists = h.Type == SliceType.B ? 2 : 1; + h.NoBackwardPred = true; + for (var list = 0; list < lists; list++) + { + // RefPicListTemp0 is StCurrBefore, StCurrAfter, LtCurr; RefPicListTemp1 swaps the first two; both repeat + // until they hold Max(num_ref_idx_active, NumPicTotalCurr) entries. An entry is its index in that order. + var active = h.NumRefIdxActive[list]; + var length = Math.Max(active, total); + if (temp.Length < length) + { + temp = new int[length]; + } + + int before = refStCurrBefore.Count, after = refStCurrAfter.Count; + var r = 0; + while (r < length) + { + for (var i = 0; i < (list == 0 ? before : after) && r < length; i++) + { + temp[r++] = list == 0 ? i : before + i; + } + + for (var i = 0; i < (list == 0 ? after : before) && r < length; i++) + { + temp[r++] = list == 0 ? before + i : i; + } + + for (var i = 0; i < refLtCurr.Count && r < length; i++) + { + temp[r++] = before + after + i; + } + } + + for (var i = 0; i < active; i++) + { + var entry = temp[h.ListModification[list] ? h.ListEntry[list][i] : i]; + var longTerm = 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] = refPoc; + h.RefIsLongTerm[list][i] = longTerm; + h.NoBackwardPred &= refPoc <= cur!.Poc; + } + } + + h.ColPic = null; + if (h.TemporalMvpEnabled) + { + var list = h.Type == SliceType.B && !h.CollocatedFromL0 ? 1 : 0; + if (h.CollocatedRefIdx >= h.NumRefIdxActive[list]) + { + throw new H265Exception("Immagine co-locata fuori dalla lista."); + } + + h.ColPic = h.RefPicList[list][h.CollocatedRefIdx]; + } + } + + /// + /// The prediction block availability (§6.4.2) of the neighbour (xN, yN) of a prediction block of the current coding + /// unit, false also when the neighbour is intra. + /// + private bool NeighbourAvailable(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int xN, int yN) + { + var size = 1 << cuLog2; + bool available; + if (xN >= cuX && yN >= cuY && xN < cuX + size && yN < cuY + size) + { + // In the same coding block: everything decoded before, except partition 2 seen from partition 1 of NxN. + available = !((nPbW << 1) == size && (nPbH << 1) == size && partIdx == 1 && cuY + nPbH <= yN && cuX + nPbW > xN); + } + else + { + available = Available(xPb, yPb, xN, yN); + } + + return available && predMode[Grid(xN, yN)] != ModeIntra; + } + + /// The motion of a merged prediction unit (§8.5.3.2.2 to §8.5.3.2.5). + private MvField MergeMotion(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int mergeIdx) + { + var originalSize = nPbW + nPbH; + var level = pps.Log2ParallelMergeLevel; + if (level > 2 && cuLog2 == 3) + { + // singleMCLFlag: every prediction unit of an 8×8 coding unit shares the list of the 2N×2N one. + xPb = cuX; + yPb = cuY; + nPbW = nPbH = 8; + partIdx = 0; + } + + var motion = cur!.Motion; + Span list = stackalloc MvField[5]; + var count = 0; + + // Spatial candidates (§8.5.3.2.3), in the order A1, B1, B0, A0, B2. + int xA1 = xPb - 1, yA1 = yPb + nPbH - 1; + var availableA1 = !SameMergeRegion(xPb, yPb, xA1, yA1, level) + && !(partIdx == 1 && cuPartMode is PartNx2N or PartnLx2N or PartnRx2N) + && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA1, yA1); + var a1 = availableA1 ? motion[Grid(xA1, yA1)] : default; + if (availableA1) + { + list[count++] = a1; + } + + int xB1 = xPb + nPbW - 1, yB1 = yPb - 1; + var availableB1 = !SameMergeRegion(xPb, yPb, xB1, yB1, level) + && !(partIdx == 1 && cuPartMode is Part2NxN or Part2NxnU or Part2NxnD) + && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB1, yB1); + var b1 = availableB1 ? motion[Grid(xB1, yB1)] : default; + var flagB1 = availableB1 && !(availableA1 && a1.SameAs(b1)); + if (flagB1) + { + list[count++] = b1; + } + + if (mergeIdx < count) + { + return Restricted(list[mergeIdx], originalSize); + } + + int xB0 = xPb + nPbW, yB0 = yPb - 1; + var availableB0 = !SameMergeRegion(xPb, yPb, xB0, yB0, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB0, yB0); + var flagB0 = false; + if (availableB0) + { + var b0 = motion[Grid(xB0, yB0)]; + flagB0 = !(availableB1 && b1.SameAs(b0)); + if (flagB0) + { + list[count++] = b0; + } + } + + int xA0 = xPb - 1, yA0 = yPb + nPbH; + var availableA0 = !SameMergeRegion(xPb, yPb, xA0, yA0, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA0); + var flagA0 = false; + if (availableA0) + { + var a0 = motion[Grid(xA0, yA0)]; + flagA0 = !(availableA1 && a1.SameAs(a0)); + if (flagA0) + { + list[count++] = a0; + } + } + + if (count < 4) + { + // B2 only when one of the four others is missing. + int xB2 = xPb - 1, yB2 = yPb - 1; + if (!SameMergeRegion(xPb, yPb, xB2, yB2, level) && NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB2, yB2)) + { + var b2 = motion[Grid(xB2, yB2)]; + if (!(availableA1 && a1.SameAs(b2)) && !(availableB1 && b1.SameAs(b2))) + { + list[count++] = b2; + } + } + } + + if (mergeIdx < count) + { + return Restricted(list[mergeIdx], originalSize); + } + + // The temporal candidate (§8.5.3.2.8), reference index 0 in each list. + if (slice.TemporalMvpEnabled) + { + var candidate = MvField.Intra; + if (TemporalMotionVector(xPb, yPb, nPbW, nPbH, 0, 0, out var x0, out var y0)) + { + candidate.Ref0 = 0; + candidate.X0 = x0; + candidate.Y0 = y0; + } + + if (slice.Type == SliceType.B && TemporalMotionVector(xPb, yPb, nPbW, nPbH, 1, 0, out var x1, out var y1)) + { + candidate.Ref1 = 0; + candidate.X1 = x1; + candidate.Y1 = y1; + } + + if (candidate.Ref0 >= 0 || candidate.Ref1 >= 0) + { + list[count++] = candidate; + } + } + + if (mergeIdx < count) + { + return Restricted(list[mergeIdx], originalSize); + } + + var max = slice.MaxNumMergeCand; + + // Combined bi-predictive candidates (§8.5.3.2.4). + if (slice.Type == SliceType.B && count > 1 && count < max) + { + var original = count; + for (var combIdx = 0; combIdx < original * (original - 1) && count < max; combIdx++) + { + var l0 = list[s_combinedL0[combIdx]]; + var l1 = list[s_combinedL1[combIdx]]; + if (l0.Ref0 >= 0 && l1.Ref1 >= 0 + && (!ReferenceEquals(slice.RefPicList[0][l0.Ref0], slice.RefPicList[1][l1.Ref1]) || l0.X0 != l1.X1 || l0.Y0 != l1.Y1)) + { + list[count++] = new MvField { Ref0 = l0.Ref0, X0 = l0.X0, Y0 = l0.Y0, Ref1 = l1.Ref1, X1 = l1.X1, Y1 = l1.Y1 }; + } + } + } + + if (mergeIdx < count) + { + return Restricted(list[mergeIdx], originalSize); + } + + // Zero candidates (§8.5.3.2.5). + var numRefIdx = slice.Type == SliceType.P ? slice.NumRefIdxActive[0] : Math.Min(slice.NumRefIdxActive[0], slice.NumRefIdxActive[1]); + var zeroIdx = mergeIdx - count; + var refIdx = (sbyte)(zeroIdx < numRefIdx ? zeroIdx : 0); + var zero = new MvField { Ref0 = refIdx, Ref1 = slice.Type == SliceType.B ? refIdx : (sbyte)-1 }; + return Restricted(zero, originalSize); + } + + private static bool SameMergeRegion(int xPb, int yPb, int xN, int yN, int level) => + xPb >> level == xN >> level && yPb >> level == yN >> level; + + /// 8×4 and 4×8 prediction units are never bi-predicted (8-118): list 1 is dropped. + private static MvField Restricted(MvField motion, int originalSize) + { + if (originalSize == 12 && motion.Ref0 >= 0 && motion.Ref1 >= 0) + { + motion.Ref1 = -1; + motion.X1 = motion.Y1 = 0; + } + + return motion; + } + + /// mvpLX of AMVP (§8.5.3.2.6, §8.5.3.2.7) for list and a reference index. + private (int X, int Y) PredictedMotionVector(int xPb, int yPb, int nPbW, int nPbH, int partIdx, int x, int refIdx, int mvpFlag) + { + 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. + int xA0 = xPb - 1, yA0 = yPb + nPbH, yA1 = yPb + nPbH - 1; + var availableA0 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA0); + var availableA1 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xA0, yA1); + var isScaled = availableA0 || availableA1; + var flagA = false; + int ax = 0, ay = 0; + for (var k = 0; k < 2 && !flagA; k++) + { + if (k == 0 ? availableA0 : availableA1) + { + flagA = SameReference(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, target, out ax, out ay); + } + } + + for (var k = 0; k < 2 && !flagA; k++) + { + if (k == 0 ? availableA0 : availableA1) + { + flagA = ScaledCandidate(motion[Grid(xA0, k == 0 ? yA0 : yA1)], x, targetPoc, targetLongTerm, poc, out ax, out ay); + } + } + + // B: B0, B1 then B2. + int xB0 = xPb + nPbW, xB1 = xPb + nPbW - 1, xB2 = xPb - 1, yB = yPb - 1; + var availableB0 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB0, yB); + var availableB1 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB1, yB); + var availableB2 = NeighbourAvailable(xPb, yPb, nPbW, nPbH, partIdx, xB2, yB); + var flagB = false; + int bx = 0, by = 0; + for (var k = 0; k < 3 && !flagB; k++) + { + if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2) + { + flagB = SameReference(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, target, out bx, out by); + } + } + + if (!isScaled) + { + if (flagB) + { + flagA = true; + ax = bx; + ay = by; + } + + flagB = false; + for (var k = 0; k < 3 && !flagB; k++) + { + if (k == 0 ? availableB0 : k == 1 ? availableB1 : availableB2) + { + flagB = ScaledCandidate(motion[Grid(k == 0 ? xB0 : k == 1 ? xB1 : xB2, yB)], x, targetPoc, targetLongTerm, poc, out bx, out by); + } + } + } + + // mvpListLX (8-182): A, B unless equal to A, then the temporal candidate, then zeros. + Span candidates = stackalloc int[4]; + var count = 0; + if (flagA) + { + candidates[0] = ax; + candidates[1] = ay; + count = 1; + } + + if (flagB && !(flagA && ax == bx && ay == by)) + { + candidates[count * 2] = bx; + candidates[(count * 2) + 1] = by; + count++; + } + + if (count < 2 && mvpFlag >= count && slice.TemporalMvpEnabled + && TemporalMotionVector(xPb, yPb, nPbW, nPbH, x, refIdx, out var cx, out var cy)) + { + candidates[count * 2] = cx; + candidates[(count * 2) + 1] = cy; + count++; + } + + return mvpFlag < count ? (candidates[mvpFlag * 2], candidates[(mvpFlag * 2) + 1]) : (0, 0); + } + + /// The first conditions of §8.5.3.2.7: the neighbour refers to the same picture, in list X or in list Y. + private bool SameReference(in MvField n, int x, Picture target, out int mx, out int my) + { + if (x == 0) + { + if (n.Ref0 >= 0 && ReferenceEquals(slice.RefPicList[0][n.Ref0], target)) + { + (mx, my) = (n.X0, n.Y0); + return true; + } + + if (n.Ref1 >= 0 && ReferenceEquals(slice.RefPicList[1][n.Ref1], target)) + { + (mx, my) = (n.X1, n.Y1); + return true; + } + } + else + { + if (n.Ref1 >= 0 && ReferenceEquals(slice.RefPicList[1][n.Ref1], target)) + { + (mx, my) = (n.X1, n.Y1); + return true; + } + + if (n.Ref0 >= 0 && ReferenceEquals(slice.RefPicList[0][n.Ref0], target)) + { + (mx, my) = (n.X0, n.Y0); + return true; + } + } + + mx = my = 0; + return false; + } + + /// + /// 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, int targetPoc, bool targetLongTerm, int poc, out int mx, out int my) + { + for (var pass = 0; pass < 2; pass++) + { + var list = pass == 0 ? x : 1 - x; + var refIdx = list == 0 ? n.Ref0 : n.Ref1; + if (refIdx < 0 || slice.RefIsLongTerm[list][refIdx] != targetLongTerm) + { + continue; + } + + mx = list == 0 ? n.X0 : n.X1; + my = list == 0 ? n.Y0 : n.Y1; + if (!targetLongTerm) + { + var td = Math.Clamp(poc - slice.RefPoc[list][refIdx], -128, 127); + var tb = Math.Clamp(poc - targetPoc, -128, 127); + if (td != 0) + { + mx = ScaleMv(mx, td, tb); + my = ScaleMv(my, td, tb); + } + } + + return true; + } + + mx = my = 0; + return false; + } + + /// The scaling of a motion vector by POC distances (8-179 to 8-181, 8-205 to 8-207). + private static int ScaleMv(int mv, int td, int tb) + { + var tx = (16384 + (Math.Abs(td) >> 1)) / td; + var distScaleFactor = Math.Clamp(((tb * tx) + 32) >> 6, -4096, 4095); + var product = distScaleFactor * mv; + return Math.Clamp(Math.Sign(product) * ((Math.Abs(product) + 127) >> 8), -32768, 32767); + } + + /// + /// The temporal luma motion vector prediction (§8.5.3.2.8): the collocated block at the bottom right of the + /// prediction block (inside the same CTB row) or else at its centre, on the 16×16 grid of the collocated picture. + /// + private bool TemporalMotionVector(int xPb, int yPb, int nPbW, int nPbH, int x, int refIdx, out short mx, out short my) + { + var col = slice.ColPic; + if (col is null || !col.Fits(sps)) + { + mx = my = 0; + return false; + } + + int xBr = xPb + nPbW, yBr = yPb + nPbH; + if (yPb >> sps.Log2CtbSize == yBr >> sps.Log2CtbSize && yBr < sps.Height && xBr < sps.Width + && CollocatedMotionVector(col, (xBr >> 4) << 4, (yBr >> 4) << 4, x, refIdx, out mx, out my)) + { + return true; + } + + int xCtr = xPb + (nPbW >> 1), yCtr = yPb + (nPbH >> 1); + return CollocatedMotionVector(col, (xCtr >> 4) << 4, (yCtr >> 4) << 4, x, refIdx, out mx, out my); + } + + /// The collocated motion vectors (§8.5.3.2.9). + private bool CollocatedMotionVector(Picture col, int xCol, int yCol, int x, int refIdx, out short mx, out short my) + { + mx = my = 0; + var n = col.Motion[Grid(xCol, yCol)]; + if (n.Ref0 < 0 && n.Ref1 < 0) + { + return false; + } + + int listCol = n.Ref0 < 0 ? 1 : n.Ref1 < 0 ? 0 : slice.NoBackwardPred ? x : slice.CollocatedFromL0 ? 1 : 0; + var refIdxCol = listCol == 0 ? n.Ref0 : n.Ref1; + var ctb = ((yCol >> col.Sps.Log2CtbSize) * col.Sps.WidthInCtbs) + (xCol >> col.Sps.Log2CtbSize); + if (ctb >= col.CtbSlice.Length || col.CtbSlice[ctb] < 0 || col.CtbSlice[ctb] >= col.Slices.Count) + { + return false; + } + + var colSlice = col.Slices[col.CtbSlice[ctb]]; + var longTerm = slice.RefIsLongTerm[x][refIdx]; + if (colSlice.RefIsLongTerm[listCol][refIdxCol] != longTerm) + { + return false; + } + + int vx = listCol == 0 ? n.X0 : n.X1, vy = listCol == 0 ? n.Y0 : n.Y1; + var colPocDiff = col.Poc - colSlice.RefPoc[listCol][refIdxCol]; + var currPocDiff = cur!.Poc - slice.RefPoc[x][refIdx]; + if (!longTerm && colPocDiff != currPocDiff && colPocDiff != 0) + { + var td = Math.Clamp(colPocDiff, -128, 127); + var tb = Math.Clamp(currPocDiff, -128, 127); + vx = ScaleMv(vx, td, tb); + vy = ScaleMv(vy, td, tb); + } + + mx = (short)vx; + my = (short)vy; + return true; + } + + /// The decoding process for inter sample prediction (§8.5.3.3) of one prediction block, written into the picture. + private void PredictInter(int xPb, int yPb, int width, int height, in MvField motion) + { + var weighted = slice.Type == SliceType.P ? pps.WeightedPred : pps.WeightedBipred; + var picture = cur!; + var components = sps.ChromaArrayType == 0 ? 1 : 3; + for (var c = 0; c < components; c++) + { + int x0 = xPb, y0 = yPb, w = width, h = height; + int mx0 = motion.X0, my0 = motion.Y0, mx1 = motion.X1, my1 = motion.Y1; + if (c > 0) + { + // Chroma vectors in eighths of a chroma sample (8-228, 8-229): mvCLX = mvLX * 2 / SubWidthC (SubHeightC). + int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY; + x0 >>= sx; + y0 >>= sy; + w >>= sx; + h >>= sy; + mx0 <<= 1 - sx; + mx1 <<= 1 - sx; + my0 <<= 1 - sy; + my1 <<= 1 - sy; + } + + var bitDepth = c == 0 ? sps.BitDepthY : sps.BitDepthC; + if (motion.Ref0 >= 0) + { + Interpolate(slice.RefPicList[0][motion.Ref0], c, x0, y0, w, h, mx0, my0, bitDepth, predL0); + } + + if (motion.Ref1 >= 0) + { + Interpolate(slice.RefPicList[1][motion.Ref1], c, x0, y0, w, h, mx1, my1, bitDepth, predL1); + } + + var plane = picture.Planes[c]; + var stride = picture.Stride(c); + if (weighted) + { + ExplicitWeights(plane, stride, x0, y0, w, h, c, motion, bitDepth); + } + else + { + DefaultWeights(plane, stride, x0, y0, w, h, motion, bitDepth); + } + } + } + + /// The default weighted sample prediction (§8.5.3.3.4.2): a rounded shift, or the rounded mean of both lists. + private void DefaultWeights(ushort[] plane, int stride, int x0, int y0, int w, int h, in MvField motion, int bitDepth) + { + var max = (1 << bitDepth) - 1; + if (motion.Ref0 >= 0 && motion.Ref1 >= 0) + { + var shift = 15 - bitDepth; + var offset = 1 << (shift - 1); + for (var y = 0; y < h; y++) + { + var row = plane.AsSpan(((y0 + y) * stride) + x0, w); + var a = predL0.AsSpan(y * w, w); + var b = predL1.AsSpan(y * w, w); + for (var x = 0; x < row.Length; x++) + { + row[x] = (ushort)Math.Clamp((a[x] + b[x] + offset) >> shift, 0, max); + } + } + } + else + { + var source = motion.Ref0 >= 0 ? predL0 : predL1; + var shift = 14 - bitDepth; + var offset = shift > 0 ? 1 << (shift - 1) : 0; + for (var y = 0; y < h; y++) + { + var row = plane.AsSpan(((y0 + y) * stride) + x0, w); + var a = source.AsSpan(y * w, w); + for (var x = 0; x < row.Length; x++) + { + row[x] = (ushort)Math.Clamp((a[x] + offset) >> shift, 0, max); + } + } + } + } + + /// The explicit weighted sample prediction (§8.5.3.3.4.3) with the weights and offsets of the slice header. + private void ExplicitWeights(ushort[] plane, int stride, int x0, int y0, int w, int h, int c, in MvField motion, int bitDepth) + { + var max = (1 << bitDepth) - 1; + var shift1 = 14 - bitDepth; + var log2Wd = (c == 0 ? slice.LumaLog2WeightDenom : slice.ChromaLog2WeightDenom) + shift1; + int w0 = 0, o0 = 0, w1 = 0, o1 = 0; + if (motion.Ref0 >= 0) + { + w0 = c == 0 ? slice.LumaWeight[0][motion.Ref0] : slice.ChromaWeight[0][(motion.Ref0 * 2) + c - 1]; + o0 = c == 0 ? slice.LumaOffset[0][motion.Ref0] : slice.ChromaOffset[0][(motion.Ref0 * 2) + c - 1]; + } + + if (motion.Ref1 >= 0) + { + w1 = c == 0 ? slice.LumaWeight[1][motion.Ref1] : slice.ChromaWeight[1][(motion.Ref1 * 2) + c - 1]; + o1 = c == 0 ? slice.LumaOffset[1][motion.Ref1] : slice.ChromaOffset[1][(motion.Ref1 * 2) + c - 1]; + } + + if (motion.Ref0 >= 0 && motion.Ref1 >= 0) + { + var round = (o0 + o1 + 1) << log2Wd; + var shift = log2Wd + 1; + for (var y = 0; y < h; y++) + { + var row = plane.AsSpan(((y0 + y) * stride) + x0, w); + var a = predL0.AsSpan(y * w, w); + var b = predL1.AsSpan(y * w, w); + for (var x = 0; x < row.Length; x++) + { + row[x] = (ushort)Math.Clamp(((a[x] * w0) + (b[x] * w1) + round) >> shift, 0, max); + } + } + + return; + } + + var source = motion.Ref0 >= 0 ? predL0 : predL1; + var weight = motion.Ref0 >= 0 ? w0 : w1; + var add = motion.Ref0 >= 0 ? o0 : o1; + for (var y = 0; y < h; y++) + { + var row = plane.AsSpan(((y0 + y) * stride) + x0, w); + var a = source.AsSpan(y * w, w); + if (log2Wd >= 1) + { + var rounding = 1 << (log2Wd - 1); + for (var x = 0; x < row.Length; x++) + { + row[x] = (ushort)Math.Clamp((((a[x] * weight) + rounding) >> log2Wd) + add, 0, max); + } + } + else + { + for (var x = 0; x < row.Length; x++) + { + row[x] = (ushort)Math.Clamp((a[x] * weight) + add, 0, max); + } + } + } + } + + /// + /// The fractional sample interpolation (§8.5.3.3.3) of one component of a block from a reference picture, at 14-bit + /// precision: 8 taps for luma in quarter samples, 4 taps for chroma in eighth samples. + /// + private void Interpolate(Picture reference, int c, int x0, int y0, int w, int h, int mvX, int mvY, int bitDepth, short[] output) + { + var luma = c == 0; + var taps = luma ? 8 : 4; + var before = luma ? 3 : 1; + var fracBits = luma ? 2 : 3; + var fracX = mvX & ((1 << fracBits) - 1); + var fracY = mvY & ((1 << fracBits) - 1); + var xInt = x0 + (mvX >> fracBits); + var yInt = y0 + (mvY >> fracBits); + var plane = reference.Planes[c]; + var planeWidth = luma ? reference.Width : reference.ChromaWidth; + var planeHeight = luma ? reference.Height : reference.ChromaHeight; + + // The reference samples, from (xInt − before, yInt − before): straight from the picture when they are all in it, + // otherwise copied with the coordinates clamped to the picture. + int left = xInt - before, top = yInt - before, rw = w + taps - 1, rh = h + taps - 1; + ushort[] source; + int origin, stride; + if (left >= 0 && top >= 0 && left + rw <= planeWidth && top + rh <= planeHeight) + { + source = plane; + stride = planeWidth; + origin = (top * stride) + left; + } + else + { + source = refBlock; + stride = rw; + origin = 0; + // The columns inside the picture are copied, those outside repeat the edge sample. + var inStart = Math.Clamp(-left, 0, rw); + var inEnd = Math.Clamp(planeWidth - left, inStart, rw); + for (var y = 0; y < rh; y++) + { + var sourceRow = plane.AsSpan(Math.Clamp(top + y, 0, planeHeight - 1) * planeWidth, planeWidth); + var row = refBlock.AsSpan(y * rw, rw); + if (inEnd > inStart) + { + sourceRow.Slice(left + inStart, inEnd - inStart).CopyTo(row[inStart..]); + } + + row[..inStart].Fill(sourceRow[0]); + row[inEnd..].Fill(sourceRow[^1]); + } + } + + var shift1 = bitDepth - 8; + var shift3 = 14 - bitDepth; + var filters = luma ? s_lumaFilter : s_chromaFilter; + if (fracX == 0 && fracY == 0) + { + for (var y = 0; y < h; y++) + { + var row = source.AsSpan(origin + ((y + before) * stride) + before, w); + var o = output.AsSpan(y * w, w); + var x = 0; + if (Vector128.IsHardwareAccelerated) + { + for (; x + 8 <= w; x += 8) + { + (Vector128.Create(row.Slice(x, 8)).AsInt16() << shift3).CopyTo(o.Slice(x, 8)); + } + } + + for (; x < w; x++) + { + o[x] = (short)(row[x] << shift3); + } + } + + return; + } + + if (fracY == 0) + { + var f = filters.AsSpan(fracX * taps, taps); + for (var y = 0; y < h; y++) + { + FilterRow(source, origin + ((y + before) * stride), 1, f, w, shift1, output.AsSpan(y * w, w)); + } + + return; + } + + if (fracX == 0) + { + var f = filters.AsSpan(fracY * taps, taps); + for (var y = 0; y < h; y++) + { + FilterRow(source, origin + (y * stride) + before, stride, f, w, shift1, output.AsSpan(y * w, w)); + } + + return; + } + + // Both: the horizontal pass on every row the vertical one needs, then the vertical pass with a shift of 6. + var fx = filters.AsSpan(fracX * taps, taps); + for (var y = 0; y < rh; y++) + { + FilterRow(source, origin + (y * stride), 1, fx, w, shift1, filterTemp.AsSpan(y * w, w)); + } + + var fy = filters.AsSpan(fracY * taps, taps); + for (var y = 0; y < h; y++) + { + FilterColumn(filterTemp, y * w, w, fy, w, output.AsSpan(y * w, w)); + } + } + + /// + /// One row of a filter over samples, apart (1 horizontally, the stride vertically): 8 outputs + /// at a time in vectors where the processor has them, the rest one by one. + /// + private static void FilterRow(ushort[] source, int start, int step, ReadOnlySpan f, int w, int shift, Span output) + { + var x = 0; + var taps = f.Length; + var src = source.AsSpan(start); + if (src.Length < w + ((taps - 1) * step) || output.Length < w) + { + throw new ArgumentOutOfRangeException(nameof(source)); + } + + if (Vector128.IsHardwareAccelerated && w >= 8) + { + ref var s0 = ref MemoryMarshal.GetReference(src); + ref var o0 = ref MemoryMarshal.GetReference(output); + var st = (nuint)step; + if (shift == 0) + { + // 8-bit samples: every product and every partial sum fits in 16 bits (at most 88 × 255). + Vector128 c0 = Vector128.Create((short)f[0]), c1 = Vector128.Create((short)f[1]); + Vector128 c2 = Vector128.Create((short)f[2]), c3 = Vector128.Create((short)f[3]); + if (taps == 8) + { + Vector128 c4 = Vector128.Create((short)f[4]), c5 = Vector128.Create((short)f[5]); + Vector128 c6 = Vector128.Create((short)f[6]), c7 = Vector128.Create((short)f[7]); + for (; x + 8 <= w; x += 8) + { + var at = (nuint)x; + var sum = (Vector128.LoadUnsafe(ref s0, at).AsInt16() * c0) + (Vector128.LoadUnsafe(ref s0, at + st).AsInt16() * c1) + + (Vector128.LoadUnsafe(ref s0, at + (2 * st)).AsInt16() * c2) + (Vector128.LoadUnsafe(ref s0, at + (3 * st)).AsInt16() * c3) + + (Vector128.LoadUnsafe(ref s0, at + (4 * st)).AsInt16() * c4) + (Vector128.LoadUnsafe(ref s0, at + (5 * st)).AsInt16() * c5) + + (Vector128.LoadUnsafe(ref s0, at + (6 * st)).AsInt16() * c6) + (Vector128.LoadUnsafe(ref s0, at + (7 * st)).AsInt16() * c7); + sum.StoreUnsafe(ref o0, at); + } + } + else + { + for (; x + 8 <= w; x += 8) + { + var at = (nuint)x; + var sum = (Vector128.LoadUnsafe(ref s0, at).AsInt16() * c0) + (Vector128.LoadUnsafe(ref s0, at + st).AsInt16() * c1) + + (Vector128.LoadUnsafe(ref s0, at + (2 * st)).AsInt16() * c2) + (Vector128.LoadUnsafe(ref s0, at + (3 * st)).AsInt16() * c3); + sum.StoreUnsafe(ref o0, at); + } + } + } + else + { + for (; x + 8 <= w; x += 8) + { + var at = (nuint)x; + Vector128 lo = Vector128.Zero, hi = Vector128.Zero; + for (var k = 0; k < taps; k++) + { + var (a, b) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + ((nuint)k * st))); + var c = Vector128.Create((int)f[k]); + lo += a.AsInt32() * c; + hi += b.AsInt32() * c; + } + + Vector128.Narrow(lo >> shift, hi >> shift).StoreUnsafe(ref o0, at); + } + } + } + + if (taps == 8) + { + int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3], f4 = f[4], f5 = f[5], f6 = f[6], f7 = f[7]; + for (; x < w; x++) + { + var sum = (f0 * src[x]) + (f1 * src[x + step]) + (f2 * src[x + (2 * step)]) + (f3 * src[x + (3 * step)]) + + (f4 * src[x + (4 * step)]) + (f5 * src[x + (5 * step)]) + (f6 * src[x + (6 * step)]) + (f7 * src[x + (7 * step)]); + output[x] = (short)(sum >> shift); + } + } + else + { + int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3]; + for (; x < w; x++) + { + var sum = (f0 * src[x]) + (f1 * src[x + step]) + (f2 * src[x + (2 * step)]) + (f3 * src[x + (3 * step)]); + output[x] = (short)(sum >> shift); + } + } + } + + /// The vertical pass over the 14-bit rows of the horizontal one (8-236, 8-246), shifted by 6. + private static void FilterColumn(short[] source, int start, int stride, ReadOnlySpan f, int w, Span output) + { + var x = 0; + var taps = f.Length; + var src = source.AsSpan(start); + if (src.Length < w + ((taps - 1) * stride) || output.Length < w) + { + throw new ArgumentOutOfRangeException(nameof(source)); + } + + if (Vector128.IsHardwareAccelerated && w >= 8) + { + ref var s0 = ref MemoryMarshal.GetReference(src); + ref var o0 = ref MemoryMarshal.GetReference(output); + var st = (nuint)stride; + Vector128 c0 = Vector128.Create((int)f[0]), c1 = Vector128.Create((int)f[1]); + Vector128 c2 = Vector128.Create((int)f[2]), c3 = Vector128.Create((int)f[3]); + if (taps == 8) + { + Vector128 c4 = Vector128.Create((int)f[4]), c5 = Vector128.Create((int)f[5]); + Vector128 c6 = Vector128.Create((int)f[6]), c7 = Vector128.Create((int)f[7]); + for (; x + 8 <= w; x += 8) + { + var at = (nuint)x; + var (a0, b0) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at)); + var (a1, b1) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + st)); + var (a2, b2) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (2 * st))); + var (a3, b3) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (3 * st))); + var (a4, b4) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (4 * st))); + var (a5, b5) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (5 * st))); + var (a6, b6) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (6 * st))); + var (a7, b7) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (7 * st))); + var lo = (a0 * c0) + (a1 * c1) + (a2 * c2) + (a3 * c3) + (a4 * c4) + (a5 * c5) + (a6 * c6) + (a7 * c7); + var hi = (b0 * c0) + (b1 * c1) + (b2 * c2) + (b3 * c3) + (b4 * c4) + (b5 * c5) + (b6 * c6) + (b7 * c7); + Vector128.Narrow(lo >> 6, hi >> 6).StoreUnsafe(ref o0, at); + } + } + else + { + for (; x + 8 <= w; x += 8) + { + var at = (nuint)x; + var (a0, b0) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at)); + var (a1, b1) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + st)); + var (a2, b2) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (2 * st))); + var (a3, b3) = Vector128.Widen(Vector128.LoadUnsafe(ref s0, at + (3 * st))); + var lo = (a0 * c0) + (a1 * c1) + (a2 * c2) + (a3 * c3); + var hi = (b0 * c0) + (b1 * c1) + (b2 * c2) + (b3 * c3); + Vector128.Narrow(lo >> 6, hi >> 6).StoreUnsafe(ref o0, at); + } + } + } + + if (taps == 8) + { + int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3], f4 = f[4], f5 = f[5], f6 = f[6], f7 = f[7]; + for (; x < w; x++) + { + var sum = (f0 * src[x]) + (f1 * src[x + stride]) + (f2 * src[x + (2 * stride)]) + (f3 * src[x + (3 * stride)]) + + (f4 * src[x + (4 * stride)]) + (f5 * src[x + (5 * stride)]) + (f6 * src[x + (6 * stride)]) + (f7 * src[x + (7 * stride)]); + output[x] = (short)(sum >> 6); + } + } + else + { + int f0 = f[0], f1 = f[1], f2 = f[2], f3 = f[3]; + for (; x < w; x++) + { + var sum = (f0 * src[x]) + (f1 * src[x + stride]) + (f2 * src[x + (2 * stride)]) + (f3 * src[x + (3 * stride)]); + output[x] = (short)(sum >> 6); + } + } + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs new file mode 100644 index 0000000..d9c5bd7 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Decoder.Intra.cs @@ -0,0 +1,271 @@ +namespace Febe.Core.Codecs.H265; + +/// Intra sample prediction (§8.4.4.2): reference samples, their substitution and filtering, planar, DC and angular. +public sealed partial class H265Decoder +{ + /// + /// The reference samples of a block of size N as one line of 4N + 1 values, from p[−1][2N − 1] up to p[−1][−1] (at + /// index 2N) and on to p[2N − 1][−1]: the order of the substitution process of §8.4.4.2.2. + /// + private readonly int[] refLine = new int[(4 * 32) + 1]; + + private readonly int[] refFiltered = new int[(4 * 32) + 1]; + private readonly bool[] refAvailable = new bool[(4 * 32) + 1]; + private readonly int[] refMain = new int[(3 * 32) + 1]; + + /// Predicts a block of component at (, ) in its own samples. + private void PredictIntra(int cIdx, int x0, int y0, int log2, int mode) + { + var picture = cur!; + var plane = picture.Planes[cIdx]; + var stride = picture.Stride(cIdx); + var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC; + var n = 1 << log2; + var n2 = 2 * n; + // Neighbours are looked up in luma locations; availability is known by 4×4 luma blocks. + int sx = cIdx == 0 ? 0 : sps.ChromaShiftX, sy = cIdx == 0 ? 0 : sps.ChromaShiftY; + int unitV = 4 >> sy, unitH = 4 >> sx; + int xL = x0 << sx, yL = y0 << sy; + var line = refLine.AsSpan(0, (4 * n) + 1); + var available = refAvailable.AsSpan(0, (4 * n) + 1); + var constrained = pps.ConstrainedIntraPred; + var any = false; + + // Left and below-left, top to bottom. + for (var k = 0; k < n2; k += unitV) + { + var ok = IntraNeighbour(xL, yL, (x0 - 1) << sx, (y0 + k) << sy, constrained); + for (var j = 0; j < unitV; j++) + { + var index = n2 - 1 - (k + j); + available[index] = ok; + if (ok) + { + line[index] = plane[((y0 + k + j) * stride) + x0 - 1]; + } + } + + any |= ok; + } + + var corner = IntraNeighbour(xL, yL, (x0 - 1) << sx, (y0 - 1) << sy, constrained); + available[n2] = corner; + if (corner) + { + line[n2] = plane[((y0 - 1) * stride) + x0 - 1]; + any = true; + } + + // Above and above-right, left to right. + for (var k = 0; k < n2; k += unitH) + { + var ok = IntraNeighbour(xL, yL, (x0 + k) << sx, (y0 - 1) << sy, constrained); + if (ok) + { + plane.AsSpan(((y0 - 1) * stride) + x0 + k, unitH).CopyTo(refRow); + for (var j = 0; j < unitH; j++) + { + line[n2 + 1 + k + j] = refRow[j]; + } + } + + for (var j = 0; j < unitH; j++) + { + available[n2 + 1 + k + j] = ok; + } + + any |= ok; + } + + // Substitution (§8.4.4.2.2). + if (!any) + { + line.Fill(1 << (bitDepth - 1)); + } + else + { + if (!available[0]) + { + for (var i = 1; i < line.Length; i++) + { + if (available[i]) + { + line[0] = line[i]; + break; + } + } + } + + for (var i = 1; i < line.Length; i++) + { + if (!available[i]) + { + line[i] = line[i - 1]; + } + } + } + + // Filtering (§8.4.4.2.3): luma, and chroma in 4:4:4, unless intra_smoothing_disabled_flag. + Span p = line; + if ((cIdx == 0 || sps.ChromaArrayType == 3) && !sps.IntraSmoothingDisabled && mode != 1 && n != 4) + { + var minDistVerHor = Math.Min(Math.Abs(mode - 26), Math.Abs(mode - 10)); + var threshold = n == 8 ? 7 : n == 16 ? 1 : 0; + if (minDistVerHor > threshold) + { + var filtered = refFiltered.AsSpan(0, line.Length); + var last = 4 * n; + var limit = 1 << (bitDepth - 5); + if (cIdx == 0 && sps.StrongIntraSmoothing && n == 32 + && Math.Abs(line[n2] + line[last] - (2 * line[n2 + n])) < limit + && Math.Abs(line[n2] + line[0] - (2 * line[n2 - n])) < limit) + { + filtered[0] = line[0]; + filtered[n2] = line[n2]; + filtered[last] = line[last]; + for (var i = 0; i < 63; i++) + { + filtered[n2 - 1 - i] = (((63 - i) * line[n2]) + ((i + 1) * line[0]) + 32) >> 6; + filtered[n2 + 1 + i] = (((63 - i) * line[n2]) + ((i + 1) * line[last]) + 32) >> 6; + } + } + else + { + filtered[0] = line[0]; + filtered[last] = line[last]; + for (var i = 1; i < last; i++) + { + filtered[i] = (line[i - 1] + (2 * line[i]) + line[i + 1] + 2) >> 2; + } + } + + p = filtered; + } + } + + var max = (1 << bitDepth) - 1; + if (mode == 0) + { + // Planar (§8.4.4.2.5). + var topRight = p[n2 + 1 + n]; + var bottomLeft = p[n2 - 1 - n]; + for (var y = 0; y < n; y++) + { + var row = ((y0 + y) * stride) + x0; + var left = p[n2 - 1 - y]; + for (var x = 0; x < n; x++) + { + plane[row + x] = (ushort)((((n - 1 - x) * left) + ((x + 1) * topRight) + ((n - 1 - y) * p[n2 + 1 + x]) + ((y + 1) * bottomLeft) + n) >> (log2 + 1)); + } + } + } + else if (mode == 1) + { + // DC (§8.4.4.2.6), with the edge filter for luma blocks below 32×32. + var sum = n; + for (var i = 0; i < n; i++) + { + sum += p[n2 + 1 + i] + p[n2 - 1 - i]; + } + + var dc = sum >> (log2 + 1); + for (var y = 0; y < n; y++) + { + plane.AsSpan(((y0 + y) * stride) + x0, n).Fill((ushort)dc); + } + + if (cIdx == 0 && n < 32) + { + plane[(y0 * stride) + x0] = (ushort)((p[n2 - 1] + (2 * dc) + p[n2 + 1] + 2) >> 2); + for (var x = 1; x < n; x++) + { + plane[(y0 * stride) + x0 + x] = (ushort)((p[n2 + 1 + x] + (3 * dc) + 2) >> 2); + } + + for (var y = 1; y < n; y++) + { + plane[((y0 + y) * stride) + x0] = (ushort)((p[n2 - 1 - y] + (3 * dc) + 2) >> 2); + } + } + } + else + { + // Angular (§8.4.4.2.6): ref[x] for x from −N to 2N, at refMain[N + x]. + int angle = H265Tables.IntraPredAngle[mode]; + var refs = refMain.AsSpan(0, (3 * n) + 1); + var vertical = mode >= 18; + for (var x = 0; x <= n; x++) + { + refs[n + x] = vertical ? p[n2 + x] : p[n2 - x]; + } + + if (angle < 0) + { + var invAngle = H265Tables.InvAngle[mode - 11]; + var lowest = (n * angle) >> 5; + if (lowest < -1) + { + for (var x = lowest; x <= -1; x++) + { + var offset = ((x * invAngle) + 128) >> 8; + refs[n + x] = vertical ? p[n2 - offset] : p[n2 + offset]; + } + } + } + else + { + for (var x = n + 1; x <= n2; x++) + { + refs[n + x] = vertical ? p[n2 + x] : p[n2 - x]; + } + } + + for (var j = 0; j < n; j++) + { + var iIdx = ((j + 1) * angle) >> 5; + var iFact = ((j + 1) * angle) & 31; + for (var i = 0; i < n; i++) + { + var a = n + i + iIdx + 1; + var value = iFact != 0 ? (((32 - iFact) * refs[a]) + (iFact * refs[a + 1]) + 16) >> 5 : refs[a]; + + // For vertical modes j is the row and i the column; for horizontal ones the other way round. + var position = vertical ? ((y0 + j) * stride) + x0 + i : ((y0 + i) * stride) + x0 + j; + plane[position] = (ushort)value; + } + } + + // disableIntraBoundaryFilter (§8.4.4.2.6): implicit RDPCM of a coding unit without transform and quantisation. + if (cIdx == 0 && n < 32 && !(sps.ImplicitRdpcmEnabled && cuTransquantBypass)) + { + if (mode == 26) + { + for (var y = 0; y < n; y++) + { + plane[((y0 + y) * stride) + x0] = (ushort)Math.Clamp(p[n2 + 1] + ((p[n2 - 1 - y] - p[n2]) >> 1), 0, max); + } + } + else if (mode == 10) + { + for (var x = 0; x < n; x++) + { + plane[(y0 * stride) + x0 + x] = (ushort)Math.Clamp(p[n2 - 1] + ((p[n2 + 1 + x] - p[n2]) >> 1), 0, max); + } + } + } + } + } + + private readonly ushort[] refRow = new ushort[4]; + + /// Whether a neighbouring sample can be used for intra prediction (§8.4.4.2.2), in luma locations. + private bool IntraNeighbour(int xCur, int yCur, int xN, int yN, bool constrained) + { + if (!Available(xCur, yCur, xN, yN)) + { + return false; + } + + return !constrained || predMode[Grid(xN, yN)] == ModeIntra; + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs new file mode 100644 index 0000000..36d82c6 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Decoder.Residual.cs @@ -0,0 +1,597 @@ +namespace Febe.Core.Codecs.H265; + +/// residual_coding() (§7.3.8.11) and the scaling, transformation and reconstruction of §8.6. +public sealed partial class H265Decoder +{ + /// ctxIdxMap of sig_coeff_flag in 4×4 blocks (9-55), by raster position. + private static readonly byte[] s_sigCtxMap4x4 = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8]; + + /// No residual DPCM; horizontal; vertical (§8.6.8, the direction of explicit_rdpcm_dir_flag + 1). + private const int RdpcmNone = 0; + + private const int RdpcmHorizontal = 1; + private const int RdpcmVertical = 2; + + /// TransCoeffLevel of the block being decoded, raster order (y << log2) + x; zero outside it. + private readonly int[] coefficients = new int[32 * 32]; + + /// Raster positions of the nonzero entries of . + private readonly short[] nonzero = new short[32 * 32]; + + private readonly int[] residual = new int[32 * 32]; + private readonly int[] transformTemp = new int[32 * 32]; + private readonly byte[] codedSubBlocks = new byte[64]; + + /// The luma residual of the transform unit, for the cross-component prediction of its chroma (§8.6.6). + private readonly int[] lumaResidual = new int[32 * 32]; + + /// Decodes the residual of one transform block and adds it to the prediction in the picture. + /// Colour component. + /// Left of the block, in samples of the component. + /// Top of the block, in samples of the component. + /// Log2 of the block size. + /// The intra prediction mode of the block, −1 for inter. + /// ResScaleVal of the cross-component prediction of a chroma block, 0 for none. + private void Residual(int cIdx, int x0, int y0, int log2, int predModeIntra, int resScale) + { + var count = ParseResidual(cIdx, log2, predModeIntra, out var transformSkip, out var maxX, out var maxY, out var rdpcm); + var size = 1 << log2; + var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC; + var total = size * size; + + // transform_skip_rotation_enabled_flag: the residual of 4×4 intra blocks without a transform is rotated by 180°. + var rotate = sps.TransformSkipRotationEnabled && log2 == 2 && cuIntra && (transformSkip || cuTransquantBypass); + if (cuTransquantBypass) + { + if (rotate) + { + for (var i = 0; i < total; i++) + { + residual[i] = coefficients[total - 1 - i]; + } + } + else + { + Array.Copy(coefficients, residual, total); + } + } + else + { + Dequantise(cIdx, log2, count, bitDepth, transformSkip); + if (transformSkip) + { + // §8.6.4.2: r = d << tsShift, then the same rounding as after a transform. + var tsShift = 5 + log2; + var bdShift = 20 - bitDepth; + var add = 1 << (bdShift - 1); + for (var i = 0; i < total; i++) + { + residual[i] = ((coefficients[rotate ? total - 1 - i : i] << tsShift) + add) >> bdShift; + } + } + else if (count == 1 && nonzero[0] == 0 && !(cuIntra && cIdx == 0 && log2 == 2)) + { + // Only the DC coefficient of a DCT: the two passes give one value everywhere. + var bdShift = 20 - bitDepth; + var first = Math.Clamp(((coefficients[0] * 64) + 64) >> 7, short.MinValue, short.MaxValue); + var value = ((first * 64) + (1 << (bdShift - 1))) >> bdShift; + residual.AsSpan(0, total).Fill(value); + } + else + { + Transform.Inverse(coefficients, residual, transformTemp, log2, cIdx == 0 && cuIntra && log2 == 2, maxX, maxY, bitDepth); + } + } + + if (rdpcm != RdpcmNone) + { + AccumulateResidual(log2, rdpcm == RdpcmVertical); + } + + // Clear the coefficients for the next block. + for (var i = 0; i < count; i++) + { + coefficients[nonzero[i]] = 0; + } + + if (cIdx == 0) + { + if (pps.CrossComponentPredictionEnabled) + { + Array.Copy(residual, lumaResidual, total); + } + } + else if (resScale != 0) + { + AddCrossComponent(total, resScale); + } + + AddResidual(cIdx, x0, y0, log2, bitDepth); + } + + /// A chroma block without coefficients whose residual is only the cross-component prediction (§8.6.6). + private void CrossComponentResidual(int cIdx, int x0, int y0, int log2, int resScale) + { + var total = 1 << (2 * log2); + residual.AsSpan(0, total).Clear(); + AddCrossComponent(total, resScale); + AddResidual(cIdx, x0, y0, log2, sps.BitDepthC); + } + + /// The residual modification process for transform blocks using cross-component prediction (8-xx of §8.6.6). + private void AddCrossComponent(int total, int resScale) + { + int bitDepthY = sps.BitDepthY, bitDepthC = sps.BitDepthC; + for (var i = 0; i < total; i++) + { + residual[i] += (resScale * ((lumaResidual[i] << bitDepthC) >> bitDepthY)) >> 3; + } + } + + /// The directional residual modification (§8.6.8): each residual sample accumulates the previous ones. + private void AccumulateResidual(int log2, bool vertical) + { + var size = 1 << log2; + if (vertical) + { + for (var y = 1; y < size; y++) + { + var row = y << log2; + for (var x = 0; x < size; x++) + { + residual[row + x] += residual[row - size + x]; + } + } + } + else + { + for (var y = 0; y < size; y++) + { + var row = y << log2; + for (var x = 1; x < size; x++) + { + residual[row + x] += residual[row + x - 1]; + } + } + } + } + + /// The picture construction (§8.6.7): prediction plus residual, clipped to the bit depth. + private void AddResidual(int cIdx, int x0, int y0, int log2, int bitDepth) + { + var size = 1 << log2; + var plane = cur!.Planes[cIdx]; + var stride = cur.Stride(cIdx); + var max = (1 << bitDepth) - 1; + for (var y = 0; y < size; y++) + { + var row = plane.AsSpan(((y0 + y) * stride) + x0, size); + var r = residual.AsSpan(y << log2, size); + for (var x = 0; x < row.Length; x++) + { + row[x] = (ushort)Math.Clamp(row[x] + r[x], 0, max); + } + } + } + + /// The scaling process for transform coefficients (§8.6.3), on the nonzero coefficients. + private void Dequantise(int cIdx, int log2, int count, int bitDepth, bool transformSkip) + { + int qp; + if (cIdx == 0) + { + qp = qpY + sps.QpBdOffsetY; + } + else + { + var offset = cIdx == 1 ? pps.CbQpOffset + slice.CbQpOffset + cuQpOffsetCb : pps.CrQpOffset + slice.CrQpOffset + cuQpOffsetCr; + var qPi = Math.Clamp(qpY + offset, -sps.QpBdOffsetC, 57); + qp = H265Tables.ChromaQp(qPi, sps.ChromaArrayType) + sps.QpBdOffsetC; + } + + var bdShift = bitDepth + log2 - 5; + var add = 1L << (bdShift - 1); + var scale = (long)H265Tables.LevelScale[qp % 6] << (qp / 6); + var list = pps.ScalingList ?? sps.ScalingList; + byte[]? factors = null; + + // m is 16 without scaling lists, and for transform skip blocks larger than 4×4 (8-xx). + if (sps.ScalingListEnabled && list is not null && !(transformSkip && log2 > 2)) + { + factors = list.Factors[((log2 - 2) * 6) + (cuIntra ? 0 : 3) + cIdx]; + } + + for (var i = 0; i < count; i++) + { + int position = nonzero[i]; + long m = factors is null ? 16 : factors[position]; + var value = ((coefficients[position] * m * scale) + add) >> bdShift; + coefficients[position] = (int)Math.Clamp(value, short.MinValue, short.MaxValue); + } + } + + /// + /// residual_coding(): fills and ; returns the number of nonzero + /// coefficients and the largest column and row that hold one, and the residual DPCM of the block (§8.6.8). + /// + private int ParseResidual(int cIdx, int log2, int predModeIntra, out bool transformSkip, out int maxX, out int maxY, out int rdpcm) + { + transformSkip = false; + if (pps.TransformSkipEnabled && !cuTransquantBypass && log2 <= pps.Log2MaxTransformSkipSize) + { + transformSkip = cabac.Flag(CabacTables.TransformSkipFlag + (cIdx == 0 ? 0 : 1)); + } + + // Residual DPCM of blocks without a transform: explicit_rdpcm_flag in inter coding units, implicit in intra ones + // predicted horizontally (mode 10) or vertically (mode 26). + var untransformed = transformSkip || cuTransquantBypass; + rdpcm = RdpcmNone; + var explicitRdpcm = false; + if (untransformed) + { + if (!cuIntra && sps.ExplicitRdpcmEnabled) + { + var c = cIdx == 0 ? 0 : 1; + if (cabac.Flag(CabacTables.ExplicitRdpcmFlag + c)) + { + explicitRdpcm = true; + rdpcm = cabac.Flag(CabacTables.ExplicitRdpcmDirFlag + c) ? RdpcmVertical : RdpcmHorizontal; + } + } + else if (cuIntra && sps.ImplicitRdpcmEnabled && predModeIntra is 10 or 26) + { + rdpcm = predModeIntra == 26 ? RdpcmVertical : RdpcmHorizontal; + } + } + + // last_sig_coeff_x_prefix, last_sig_coeff_y_prefix and their suffixes (§9.3.4.2.3). + int ctxOffset, ctxShift; + if (cIdx == 0) + { + ctxOffset = (3 * (log2 - 2)) + ((log2 - 1) >> 2); + ctxShift = (log2 + 1) >> 2; + } + else + { + ctxOffset = 15; + ctxShift = log2 - 2; + } + + var cMax = (log2 << 1) - 1; + var prefixX = 0; + while (prefixX < cMax && cabac.Flag(CabacTables.LastSigCoeffXPrefix + ctxOffset + (prefixX >> ctxShift))) + { + prefixX++; + } + + var prefixY = 0; + while (prefixY < cMax && cabac.Flag(CabacTables.LastSigCoeffYPrefix + ctxOffset + (prefixY >> ctxShift))) + { + prefixY++; + } + + var lastX = prefixX; + if (prefixX > 3) + { + var bits = (prefixX >> 1) - 1; + lastX = ((2 + (prefixX & 1)) << bits) + cabac.BypassBits(bits); + } + + var lastY = prefixY; + if (prefixY > 3) + { + var bits = (prefixY >> 1) - 1; + lastY = ((2 + (prefixY & 1)) << bits) + cabac.BypassBits(bits); + } + + // scanIdx (§7.4.9.11): mode-dependent scans for intra 4×4 blocks and 8×8 luma blocks. + var scanIdx = 0; + if (predModeIntra >= 0 && (log2 == 2 || (log2 == 3 && (cIdx == 0 || sps.ChromaArrayType == 3)))) + { + if (predModeIntra is >= 6 and <= 14) + { + scanIdx = 2; + } + else if (predModeIntra is >= 22 and <= 30) + { + scanIdx = 1; + } + } + + if (scanIdx == 2) + { + (lastX, lastY) = (lastY, lastX); + } + + var size = 1 << log2; + if (lastX >= size || lastY >= size) + { + throw new H265Exception("Ultimo coefficiente fuori dal blocco."); + } + + var log2Sb = log2 - 2; + var sbWidth = 1 << log2Sb; + var sbScan = H265Tables.ScanOrder[log2Sb][scanIdx]; + var scan4 = H265Tables.ScanOrder[2][scanIdx]; + var lastSubBlock = 0; + var lastPacked = (ushort)((lastX >> 2) | ((lastY >> 2) << 8)); + for (var i = 0; i < sbScan.Length; i++) + { + if (sbScan[i] == lastPacked) + { + lastSubBlock = i; + break; + } + } + + var lastScanPos = H265Tables.ScanPosition4x4[scanIdx][((lastY & 3) << 2) + (lastX & 3)]; + codedSubBlocks.AsSpan(0, sbWidth * sbWidth).Clear(); + + // No sign data hiding without a transform where the residual is accumulated (§7.3.8.11). + var signHidingEnabled = pps.SignDataHidingEnabled && !cuTransquantBypass + && !(cuIntra && sps.ImplicitRdpcmEnabled && transformSkip && predModeIntra is 10 or 26) && !explicitRdpcm; + + // transform_skip_context_enabled_flag: one context for every sig_coeff_flag of a block without a transform. + var singleSigCtx = sps.TransformSkipContextEnabled && untransformed ? (cIdx == 0 ? 42 : 16) : -1; + + // The persistent Rice adaptation (§9.3.3.11): StatCoeff by component and transform, no bound on cRiceParam. + var persistentRice = sps.PersistentRiceAdaptationEnabled; + var sbType = (cIdx == 0 ? 0 : 2) + (untransformed ? 1 : 0); + var riceLimit = persistentRice ? 16 : 4; + var greater1Ctx = 1; + var firstSubBlock = true; + var count = 0; + maxX = 0; + maxY = 0; + Span sigPositions = stackalloc int[16]; + Span levels = stackalloc int[16]; + var ctxBase = CabacTables.SigCoeffFlag + (cIdx == 0 ? 0 : 27); + for (var i = lastSubBlock; i >= 0; i--) + { + var xS = sbScan[i] & 0xFF; + var yS = sbScan[i] >> 8; + var inferSbDcSigCoeff = false; + bool coded; + if (i < lastSubBlock && i > 0) + { + var csbfCtx = 0; + if (xS < sbWidth - 1) + { + csbfCtx += codedSubBlocks[(yS * sbWidth) + xS + 1]; + } + + if (yS < sbWidth - 1) + { + csbfCtx += codedSubBlocks[((yS + 1) * sbWidth) + xS]; + } + + coded = cabac.Flag(CabacTables.CodedSubBlockFlag + Math.Min(csbfCtx, 1) + (cIdx == 0 ? 0 : 2)); + inferSbDcSigCoeff = true; + } + else + { + coded = true; + } + + codedSubBlocks[(yS * sbWidth) + xS] = (byte)(coded ? 1 : 0); + + // prevCsbf for the contexts of sig_coeff_flag (§9.3.4.2.5). + var prevCsbf = 0; + if (xS < sbWidth - 1) + { + prevCsbf += codedSubBlocks[(yS * sbWidth) + xS + 1]; + } + + if (yS < sbWidth - 1) + { + prevCsbf += codedSubBlocks[((yS + 1) * sbWidth) + xS] << 1; + } + + // Significant coefficients, from the last scan position of the sub-block down to 0. + var sigCount = 0; + var start = 15; + if (i == lastSubBlock) + { + start = lastScanPos - 1; + sigPositions[sigCount++] = lastScanPos; + } + + if (coded) + { + for (var n = start; n >= 0; n--) + { + var xP = scan4[n] & 0xFF; + var yP = scan4[n] >> 8; + if (n > 0 || !inferSbDcSigCoeff) + { + int sigCtx; + if (singleSigCtx >= 0) + { + sigCtx = singleSigCtx; + } + else if (log2 == 2) + { + sigCtx = s_sigCtxMap4x4[(yP << 2) + xP]; + } + else if (xS == 0 && yS == 0 && xP == 0 && yP == 0) + { + sigCtx = 0; + } + else + { + sigCtx = prevCsbf switch + { + 0 => xP + yP == 0 ? 2 : xP + yP < 3 ? 1 : 0, + 1 => yP == 0 ? 2 : yP == 1 ? 1 : 0, + 2 => xP == 0 ? 2 : xP == 1 ? 1 : 0, + _ => 2, + }; + if (cIdx == 0) + { + if (xS > 0 || yS > 0) + { + sigCtx += 3; + } + + sigCtx += log2 == 3 ? (scanIdx == 0 ? 9 : 15) : 21; + } + else + { + sigCtx += log2 == 3 ? 9 : 12; + } + } + + if (cabac.Flag(ctxBase + sigCtx)) + { + sigPositions[sigCount++] = n; + inferSbDcSigCoeff = false; + } + } + else + { + // n == 0 with every other flag of a coded sub-block zero: the DC is inferred significant. + sigPositions[sigCount++] = 0; + } + } + } + + if (sigCount == 0) + { + continue; + } + + // coeff_abs_level_greater1_flag for the first 8, then greater2 for the first of them that is 1 (§9.3.4.2.6). + var ctxSet = i == 0 || cIdx > 0 ? 0 : 2; + if (!firstSubBlock && greater1Ctx == 0) + { + ctxSet++; + } + + firstSubBlock = false; + greater1Ctx = 1; + var firstGreater1 = -1; + var g1Base = CabacTables.CoeffAbsLevelGreater1Flag + (cIdx == 0 ? 0 : 16); + var limit = Math.Min(sigCount, 8); + for (var k = 0; k < sigCount; k++) + { + levels[k] = 1; + } + + for (var k = 0; k < limit; k++) + { + var flag = cabac.Flag(g1Base + (ctxSet * 4) + Math.Min(3, greater1Ctx)); + if (flag) + { + levels[k] = 2; + greater1Ctx = 0; + if (firstGreater1 < 0) + { + firstGreater1 = k; + } + } + else if (greater1Ctx > 0) + { + greater1Ctx++; + } + } + + if (firstGreater1 >= 0 && cabac.Flag(CabacTables.CoeffAbsLevelGreater2Flag + ctxSet + (cIdx == 0 ? 0 : 4))) + { + levels[firstGreater1] = 3; + } + + var firstSigScanPos = sigPositions[sigCount - 1]; + var lastSigScanPos = sigPositions[0]; + var signHidden = signHidingEnabled && lastSigScanPos - firstSigScanPos > 3; + var signCount = signHidden ? sigCount - 1 : sigCount; + var signs = cabac.BypassBits(signCount) << (32 - signCount); + if (signCount == 0) + { + signs = 0; + } + + // coeff_abs_level_remaining (§9.3.3.11): the Rice parameter starts at 0 (at StatCoeff / 4 with the + // persistent adaptation, which the first value of the sub-block updates) and grows with the levels. + var rice = persistentRice ? statCoeff[sbType] >> 2 : 0; + var firstRemaining = persistentRice; + var sumAbs = 0; + for (var k = 0; k < sigCount; k++) + { + var baseLevel = levels[k]; + var absolute = baseLevel; + if (baseLevel == (k < 8 ? (k == firstGreater1 ? 3 : 2) : 1)) + { + var remaining = CoeffAbsLevelRemaining(rice); + absolute = baseLevel + remaining; + if (firstRemaining) + { + ref var stat = ref statCoeff[sbType]; + if (remaining >= 3 << (stat >> 2)) + { + stat++; + } + else if (2 * remaining < 1 << (stat >> 2) && stat > 0) + { + stat--; + } + + firstRemaining = false; + } + + if (absolute > 3 * (1 << rice)) + { + rice = Math.Min(rice + 1, riceLimit); + } + } + + var n = sigPositions[k]; + var xC = (xS << 2) + (scan4[n] & 0xFF); + var yC = (yS << 2) + (scan4[n] >> 8); + var value = absolute; + if (k < signCount) + { + if (signs < 0) + { + value = -value; + } + + signs <<= 1; + } + + sumAbs += absolute; + if (signHidden && k == sigCount - 1 && (sumAbs & 1) == 1) + { + value = -value; + } + + var position = (yC << log2) + xC; + coefficients[position] = value; + nonzero[count++] = (short)position; + maxX = Math.Max(maxX, xC); + maxY = Math.Max(maxY, yC); + } + } + + return count; + } + + private int CoeffAbsLevelRemaining(int rice) + { + var prefix = 0; + while (cabac.Bypass() == 1) + { + if (++prefix > 32) + { + throw new H265Exception("coeff_abs_level_remaining non valido."); + } + } + + if (prefix <= 3) + { + return (prefix << rice) + (rice > 0 ? cabac.BypassBits(rice) : 0); + } + + var bits = prefix - 3 + rice; + return (((1 << (prefix - 3)) + 3 - 1) << rice) + ReadBypass(bits); + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs b/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs new file mode 100644 index 0000000..e96b45a --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Decoder.Slice.cs @@ -0,0 +1,1285 @@ +namespace Febe.Core.Codecs.H265; + +/// Slice segment data (§7.3.8): coding tree units, coding quadtree, coding units, prediction units and transform tree. +public sealed partial class H265Decoder +{ + private const byte ModeIntra = 1; + private const byte ModeInter = 2; + private const byte ModeSkip = 3; + + /// Samples that no in-loop filter changes: PCM with pcm_loop_filter_disabled_flag, cu_transquant_bypass_flag. + private const byte FlagNoFilter = 1; + + /// A luma transform block with coefficients (for the boundary strength of §8.7.2.4). + private const byte FlagCoded = 2; + + private const byte FlagPcm = 4; + + private const int Part2Nx2N = 0; + private const int Part2NxN = 1; + private const int PartNx2N = 2; + private const int PartNxN = 3; + private const int Part2NxnU = 4; + private const int Part2NxnD = 5; + private const int PartnLx2N = 6; + private const int PartnRx2N = 7; + + /// Z-scan order of the 4×4 blocks of a CTB (up to 16×16 of them), by (y << 4) | x (§6.5.2). + private static readonly ushort[] s_zOrder = BuildZOrder(); + + private readonly CabacEngine cabac = new(); + private readonly byte[] wppContexts = new byte[CabacTables.ContextCount]; + private readonly byte[] dsContexts = new byte[CabacTables.ContextCount]; + + /// StatCoeff of the persistent Rice adaptation (§9.3.3.11), kept and synchronised with the contexts. + private readonly int[] statCoeff = new int[4]; + + private readonly int[] wppStatCoeff = new int[4]; + private readonly int[] dsStatCoeff = new int[4]; + private List slices = []; + + private Picture? cur; + private Sps sps = null!; + private Pps pps = null!; + private SliceHeader? sliceHeader; + + // Per picture, on the grid of 4×4 luma blocks. + private int w4; + private int h4; + private byte[] predMode = []; + private byte[] ctDepthMap = []; + private byte[] intraModeMap = []; + private sbyte[] qpMap = []; + private byte[] blockFlags = []; + + /// Edges of §8.7.2 at the left (edgeV) and the top (edgeH) of each 4×4 block: 0 none, 1 prediction, 2 transform. + private byte[] edgeV = []; + + private byte[] edgeH = []; + + /// Index in of the slice of each CTB (raster order), −1 while not decoded. + private int[] ctbSlice = []; + + /// SAO parameters by CTB and component: type (0 none, 1 band, 2 edge), class or band position, 4 offsets. + private byte[] saoType = []; + + private byte[] saoClass = []; + private short[] saoOffset = []; + private bool pictureHasUnfilteredBlocks; + + // The slice segment being decoded. + private SliceHeader slice = null!; + private int sliceIdx; + private byte[] data = []; + private int dataEnd; + private int ctbAddrRs; + private int ctbX; + private int ctbY; + private int widthInCtbs; + + // Quantisation (§8.6.1). + private int log2MinCuQpDeltaSize; + private bool isCuQpDeltaCoded; + private int cuQpDeltaVal; + private int qpYPrev; + private int qpYPred; + private int qpY; + private bool resetQpPrev; + private bool isCuChromaQpOffsetCoded; + private int cuQpOffsetCb; + private int cuQpOffsetCr; + + // The coding unit being decoded. + private int cuX; + private int cuY; + private int cuLog2; + private bool cuIntra; + private bool cuTransquantBypass; + private int cuPartMode; + + /// IntraPredModeC of each prediction block (one unless 4:4:4 with NxN), and whether intra_chroma_pred_mode was 4. + private readonly int[] cuChromaModes = new int[4]; + + private readonly bool[] cuChromaDm = new bool[4]; + private int cuMaxTrafoDepth; + private bool cuIntraSplit; + + private void StartPictureData(Sps s, Pps p) + { + sps = s; + pps = p; + slices = cur!.Slices; + slices.Clear(); + cur.Motion.AsSpan().Fill(MvField.Intra); + widthInCtbs = s.WidthInCtbs; + var nw = (s.Width + 3) >> 2; + var nh = (s.Height + 3) >> 2; + if (nw != w4 || nh != h4) + { + w4 = nw; + h4 = nh; + var count = nw * nh; + predMode = new byte[count]; + ctDepthMap = new byte[count]; + intraModeMap = new byte[count]; + qpMap = new sbyte[count]; + blockFlags = new byte[count]; + edgeV = new byte[count]; + edgeH = new byte[count]; + } + else + { + Array.Clear(predMode); + Array.Clear(blockFlags); + Array.Clear(edgeV); + Array.Clear(edgeH); + } + + var ctbs = s.CtbCount; + if (cur.CtbSlice.Length != ctbs) + { + cur.CtbSlice = new int[ctbs]; + } + + ctbSlice = cur.CtbSlice; + if (saoType.Length != ctbs * 3) + { + saoType = new byte[ctbs * 3]; + saoClass = new byte[ctbs * 3]; + saoOffset = new short[ctbs * 12]; + } + + Array.Fill(ctbSlice, -1); + Array.Clear(saoType); + pictureHasUnfilteredBlocks = false; + log2MinCuQpDeltaSize = s.Log2CtbSize - p.DiffCuQpDeltaDepth; + } + + private void DecodeSliceData(H265NalUnit nal, SliceHeader h) + { + slice = h; + if (!h.Dependent) + { + sliceIdx = slices.Count - 1; + resetQpPrev = true; + cuQpOffsetCb = 0; + cuQpOffsetCr = 0; + } + + data = nal.Rbsp; + dataEnd = nal.Length; + ctbAddrRs = h.SegmentAddress; + if (ctbSlice[ctbAddrRs] >= 0) + { + throw new H265Exception("Segmento di slice sovrapposto a uno già decodificato."); + } + + var ctbAddrTs = pps.CtbAddrRsToTs[ctbAddrRs]; + cabac.Start(data, h.DataOffset * 8, dataEnd); + var firstInSegment = true; + var initType = h.InitType; + while (true) + { + ctbX = ctbAddrRs % widthInCtbs; + ctbY = ctbAddrRs / widthInCtbs; + var tile = pps.TileIdRs[ctbAddrRs]; + var colStart = pps.ColBd[tile % pps.NumTileColumns]; + var rowStart = pps.RowBd[tile / pps.NumTileColumns]; + var tileStart = ctbX == colStart && ctbY == rowStart; + var wppRowStart = pps.EntropyCodingSyncEnabled && ctbX == colStart; + if (firstInSegment || tileStart || wppRowStart) + { + // Initialisation of the context variables (§9.3.2.2 to §9.3.2.4). + if (tileStart) + { + InitEntropy(initType, h.SliceQpY); + } + else if (wppRowStart) + { + var topRight = ctbAddrRs - widthInCtbs + 1; + var available = ctbY > 0 && ctbX + 1 < widthInCtbs && ctbSlice[topRight] == sliceIdx && pps.TileIdRs[topRight] == tile; + if (available) + { + LoadEntropy(wppContexts, wppStatCoeff); + } + else + { + InitEntropy(initType, h.SliceQpY); + } + } + else if (h.Dependent) + { + LoadEntropy(dsContexts, dsStatCoeff); + } + else + { + InitEntropy(initType, h.SliceQpY); + } + } + + if (tileStart || wppRowStart) + { + resetQpPrev = true; + } + + ctbSlice[ctbAddrRs] = sliceIdx; + CodingTreeUnit(); + if (pps.EntropyCodingSyncEnabled && ctbX - colStart <= 1) + { + SaveEntropy(wppContexts, wppStatCoeff); + } + + var end = cabac.Terminate() == 1; + ctbAddrTs++; + if (end) + { + if (pps.DependentSliceSegmentsEnabled) + { + SaveEntropy(dsContexts, dsStatCoeff); + } + + return; + } + + if (ctbAddrTs >= sps.CtbCount) + { + throw new H265Exception("Slice che continua oltre l'ultimo CTB."); + } + + var nextRs = pps.CtbAddrTsToRs[ctbAddrTs]; + var nextTile = pps.TileIdRs[nextRs]; + var nextX = nextRs % widthInCtbs; + if ((pps.TilesEnabled && nextTile != tile) + || (pps.EntropyCodingSyncEnabled && nextX == pps.ColBd[nextTile % pps.NumTileColumns])) + { + // end_of_subset_one_bit, byte_alignment() and a new substream (§9.3.2.5). + if (cabac.Terminate() != 1) + { + throw new H265Exception("Fine di un sottoflusso CABAC non valida."); + } + + var position = (cabac.BitPosition + 7) & ~7; + cabac.Start(data, position, dataEnd); + } + + ctbAddrRs = nextRs; + firstInSegment = false; + } + } + + /// The initialisation of §9.3.2.2: the context variables, and StatCoeff to 0. + private void InitEntropy(int initType, int sliceQp) + { + cabac.InitContexts(initType, sliceQp); + Array.Clear(statCoeff); + } + + /// The synchronisation process of §9.3.2.4: contexts and StatCoeff from a stored state. + private void LoadEntropy(byte[] contexts, int[] stat) + { + contexts.CopyTo(cabac.Contexts, 0); + stat.CopyTo(statCoeff, 0); + } + + /// The storage process of §9.3.2.3. + private void SaveEntropy(byte[] contexts, int[] stat) + { + cabac.Contexts.CopyTo(contexts, 0); + statCoeff.CopyTo(stat, 0); + } + + private void CodingTreeUnit() + { + var log2 = sps.Log2CtbSize; + if (slice.SaoLuma || slice.SaoChroma) + { + ParseSao(); + } + + CodingQuadtree(ctbX << log2, ctbY << log2, log2, 0); + } + + /// sao() (§7.3.8.3). + private void ParseSao() + { + var rs = ctbAddrRs; + var merge = -1; + if (ctbX > 0 && rs > slice.SliceAddress && pps.TileIdRs[rs] == pps.TileIdRs[rs - 1] && cabac.Flag(CabacTables.SaoMergeFlag)) + { + merge = rs - 1; + } + + if (merge < 0 && ctbY > 0 && rs - widthInCtbs >= slice.SliceAddress && pps.TileIdRs[rs] == pps.TileIdRs[rs - widthInCtbs] + && cabac.Flag(CabacTables.SaoMergeFlag)) + { + merge = rs - widthInCtbs; + } + + if (merge >= 0) + { + Array.Copy(saoType, merge * 3, saoType, rs * 3, 3); + Array.Copy(saoClass, merge * 3, saoClass, rs * 3, 3); + Array.Copy(saoOffset, merge * 12, saoOffset, rs * 12, 12); + return; + } + + Span magnitude = stackalloc int[4]; + for (var cIdx = 0; cIdx < 3; cIdx++) + { + var at = (rs * 3) + cIdx; + if (!(cIdx == 0 ? slice.SaoLuma : slice.SaoChroma)) + { + saoType[at] = 0; + continue; + } + + if (cIdx == 2) + { + saoType[at] = saoType[at - 1]; + saoClass[at] = saoClass[at - 1]; + } + else + { + // sao_type_idx: TR with cMax 2, the first bin with its context, the second bypass. + saoType[at] = (byte)(!cabac.Flag(CabacTables.SaoTypeIdx) ? 0 : cabac.Bypass() == 0 ? 1 : 2); + } + + if (saoType[at] == 0) + { + continue; + } + + var bitDepth = cIdx == 0 ? sps.BitDepthY : sps.BitDepthC; + var cMax = (1 << (Math.Min(bitDepth, 10) - 5)) - 1; + for (var i = 0; i < 4; i++) + { + var value = 0; + while (value < cMax && cabac.Bypass() == 1) + { + value++; + } + + magnitude[i] = value; + } + + var scale = cIdx == 0 ? pps.Log2SaoOffsetScaleLuma : pps.Log2SaoOffsetScaleChroma; + if (saoType[at] == 1) + { + for (var i = 0; i < 4; i++) + { + if (magnitude[i] != 0 && cabac.Bypass() == 1) + { + magnitude[i] = -magnitude[i]; + } + } + + saoClass[at] = (byte)cabac.BypassBits(5); + for (var i = 0; i < 4; i++) + { + saoOffset[(at * 4) + i] = (short)(magnitude[i] << scale); + } + } + else + { + if (cIdx < 2) + { + saoClass[at] = (byte)cabac.BypassBits(2); + } + + // Edge offsets: the first two are positive, the last two negative. + saoOffset[(at * 4) + 0] = (short)(magnitude[0] << scale); + saoOffset[(at * 4) + 1] = (short)(magnitude[1] << scale); + saoOffset[(at * 4) + 2] = (short)(-(magnitude[2] << scale)); + saoOffset[(at * 4) + 3] = (short)(-(magnitude[3] << scale)); + } + } + } + + private void CodingQuadtree(int x0, int y0, int log2, int depth) + { + var size = 1 << log2; + bool split; + if (x0 + size <= sps.Width && y0 + size <= sps.Height && log2 > sps.Log2MinCbSize) + { + var ctx = 0; + if (Available(x0, y0, x0 - 1, y0) && ctDepthMap[Grid(x0 - 1, y0)] > depth) + { + ctx++; + } + + if (Available(x0, y0, x0, y0 - 1) && ctDepthMap[Grid(x0, y0 - 1)] > depth) + { + ctx++; + } + + split = cabac.Flag(CabacTables.SplitCuFlag + ctx); + } + else + { + split = log2 > sps.Log2MinCbSize; + } + + if (pps.CuQpDeltaEnabled && log2 >= log2MinCuQpDeltaSize) + { + isCuQpDeltaCoded = false; + cuQpDeltaVal = 0; + } + + if (slice.CuChromaQpOffsetEnabled && log2 >= sps.Log2CtbSize - pps.DiffCuChromaQpOffsetDepth) + { + isCuChromaQpOffsetCoded = false; + } + + if (split) + { + var half = size >> 1; + CodingQuadtree(x0, y0, log2 - 1, depth + 1); + if (x0 + half < sps.Width) + { + CodingQuadtree(x0 + half, y0, log2 - 1, depth + 1); + } + + if (y0 + half < sps.Height) + { + CodingQuadtree(x0, y0 + half, log2 - 1, depth + 1); + } + + if (x0 + half < sps.Width && y0 + half < sps.Height) + { + CodingQuadtree(x0 + half, y0 + half, log2 - 1, depth + 1); + } + } + else + { + CodingUnit(x0, y0, log2, depth); + } + } + + private void CodingUnit(int x0, int y0, int log2, int depth) + { + var size = 1 << log2; + cuX = x0; + cuY = y0; + cuLog2 = log2; + + // The predicted QP of a quantisation group (§8.6.1), at its first coding unit. + var qgMask = (1 << log2MinCuQpDeltaSize) - 1; + if ((x0 & qgMask) == 0 && (y0 & qgMask) == 0) + { + if (resetQpPrev) + { + qpYPrev = slice.SliceQpY; + resetQpPrev = false; + } + + var ctbMask = ~((1 << sps.Log2CtbSize) - 1); + var qpA = (x0 & ~ctbMask) != 0 ? qpMap[Grid(x0 - 1, y0)] : qpYPrev; + var qpB = (y0 & ~ctbMask) != 0 ? qpMap[Grid(x0, y0 - 1)] : qpYPrev; + qpYPred = (qpA + qpB + 1) >> 1; + } + + UpdateQpY(); + cuTransquantBypass = pps.TransquantBypassEnabled && cabac.Flag(CabacTables.CuTransquantBypassFlag); + var skip = false; + if (!slice.IsIntra) + { + var ctx = 0; + if (Available(x0, y0, x0 - 1, y0) && predMode[Grid(x0 - 1, y0)] == ModeSkip) + { + ctx++; + } + + if (Available(x0, y0, x0, y0 - 1) && predMode[Grid(x0, y0 - 1)] == ModeSkip) + { + ctx++; + } + + skip = cabac.Flag(CabacTables.CuSkipFlag + ctx); + } + + FillGrid(ctDepthMap, x0, y0, size, size, (byte)depth); + var pcm = false; + cuPartMode = Part2Nx2N; + cuIntraSplit = false; + if (skip) + { + cuIntra = false; + FillGrid(predMode, x0, y0, size, size, ModeSkip); + PredictionUnit(x0, y0, size, size, true, depth, 0); + } + else + { + cuIntra = slice.IsIntra || cabac.Flag(CabacTables.PredModeFlag); + FillGrid(predMode, x0, y0, size, size, cuIntra ? ModeIntra : ModeInter); + if (!cuIntra || log2 == sps.Log2MinCbSize) + { + cuPartMode = ParsePartMode(log2); + } + + var mergeFirst = false; + if (cuIntra) + { + cuIntraSplit = cuPartMode == PartNxN; + if (cuPartMode == Part2Nx2N && sps.PcmEnabled && log2 >= sps.Log2MinPcmCbSize && log2 <= sps.Log2MaxPcmCbSize) + { + pcm = cabac.Terminate() == 1; + } + + if (pcm) + { + PcmSamples(x0, y0, log2); + } + else + { + ParseIntraModes(x0, y0, log2); + } + } + else + { + mergeFirst = PredictionUnits(x0, y0, size, depth); + } + + if (!pcm) + { + var rqtRootCbf = true; + if (!cuIntra && !(cuPartMode == Part2Nx2N && mergeFirst)) + { + rqtRootCbf = cabac.Flag(CabacTables.RqtRootCbf); + } + + MarkPredictionEdges(x0, y0, size); + if (rqtRootCbf) + { + cuMaxTrafoDepth = cuIntra ? sps.MaxTransformHierarchyDepthIntra + (cuIntraSplit ? 1 : 0) : sps.MaxTransformHierarchyDepthInter; + TransformTree(x0, y0, x0, y0, log2, 0, 0, 0); + } + } + } + + // QpY of the coding unit (for the prediction of the next ones and for deblocking), and its flags. + FillGrid(qpMap, x0, y0, size, size, (sbyte)qpY); + qpYPrev = qpY; + var flags = (byte)((pcm ? FlagPcm : 0) | ((pcm && sps.PcmLoopFilterDisabled) || cuTransquantBypass ? FlagNoFilter : 0)); + if (flags != 0) + { + OrGrid(blockFlags, x0, y0, size, size, flags); + pictureHasUnfilteredBlocks |= (flags & FlagNoFilter) != 0; + } + + MarkCodingUnitEdges(x0, y0, size); + } + + /// QpY from the predicted QP and CuQpDeltaVal (8-283). + private void UpdateQpY() + { + var offset = sps.QpBdOffsetY; + qpY = ((qpYPred + cuQpDeltaVal + 52 + (2 * offset)) % (52 + offset)) - offset; + } + + /// part_mode (§9.3.3.7): bins 0 and 1 with contexts 0 and 1, then context 2 or 3, then bypass. + private int ParsePartMode(int log2) + { + if (cabac.Flag(CabacTables.PartMode)) + { + return Part2Nx2N; + } + + if (cuIntra) + { + return PartNxN; + } + + if (log2 == sps.Log2MinCbSize) + { + if (cabac.Flag(CabacTables.PartMode + 1)) + { + return Part2NxN; + } + + if (log2 == 3) + { + return PartNx2N; + } + + return cabac.Flag(CabacTables.PartMode + 2) ? PartNx2N : PartNxN; + } + + var horizontal = cabac.Flag(CabacTables.PartMode + 1); + if (!sps.AmpEnabled) + { + return horizontal ? Part2NxN : PartNx2N; + } + + if (cabac.Flag(CabacTables.PartMode + 3)) + { + return horizontal ? Part2NxN : PartNx2N; + } + + var second = cabac.Bypass() == 1; + return horizontal ? (second ? Part2NxnD : Part2NxnU) : (second ? PartnRx2N : PartnLx2N); + } + + /// The intra prediction modes of a coding unit (§7.3.8.5, §8.4.2, §8.4.3). + private void ParseIntraModes(int x0, int y0, int log2) + { + var count = cuIntraSplit ? 4 : 1; + var pbSize = cuIntraSplit ? 1 << (log2 - 1) : 1 << log2; + Span prev = stackalloc bool[4]; + Span list = stackalloc int[3]; + Span lumaModes = stackalloc int[4]; + for (var i = 0; i < count; i++) + { + prev[i] = cabac.Flag(CabacTables.PrevIntraLumaPredFlag); + } + + for (var i = 0; i < count; i++) + { + var xPb = x0 + ((i & 1) * pbSize); + var yPb = y0 + ((i >> 1) * pbSize); + var candA = NeighbourIntraMode(xPb, yPb, xPb - 1, yPb, false); + var candB = NeighbourIntraMode(xPb, yPb, xPb, yPb - 1, true); + if (candA == candB) + { + if (candA < 2) + { + list[0] = 0; + list[1] = 1; + list[2] = 26; + } + else + { + list[0] = candA; + list[1] = 2 + ((candA + 29) % 32); + list[2] = 2 + ((candA - 2 + 1) % 32); + } + } + else + { + list[0] = candA; + list[1] = candB; + list[2] = candA != 0 && candB != 0 ? 0 : candA != 1 && candB != 1 ? 1 : 26; + } + + int mode; + if (prev[i]) + { + // mpm_idx: TR with cMax 2, bypass. + var mpm = cabac.Bypass() == 0 ? 0 : cabac.Bypass() == 0 ? 1 : 2; + mode = list[mpm]; + } + else + { + mode = cabac.BypassBits(5); + list.Sort(); + for (var k = 0; k < 3; k++) + { + if (mode >= list[k]) + { + mode++; + } + } + } + + FillGrid(intraModeMap, xPb, yPb, pbSize, pbSize, (byte)mode); + lumaModes[i] = mode; + } + + if (sps.ChromaArrayType == 0) + { + return; + } + + // intra_chroma_pred_mode (§8.4.3, table 8-2): 4 is the luma mode, 0 to 3 are planar, vertical, horizontal and DC, + // replaced by mode 34 when they equal the luma mode. One for each prediction block in 4:4:4, one for the coding + // unit otherwise (with the mode of its first block); in 4:2:2 the mode is then mapped by table 8-3. + var chromaCount = sps.ChromaArrayType == 3 ? count : 1; + for (var i = 0; i < chromaCount; i++) + { + var luma = lumaModes[i]; + var chroma = !cabac.Flag(CabacTables.IntraChromaPredMode) ? 4 : cabac.BypassBits(2); + var mode = chroma switch + { + 0 => luma == 0 ? 34 : 0, + 1 => luma == 26 ? 34 : 26, + 2 => luma == 10 ? 34 : 10, + 3 => luma == 1 ? 34 : 1, + _ => luma, + }; + cuChromaModes[i] = sps.ChromaArrayType == 2 ? H265Tables.ChromaMode422[mode] : mode; + cuChromaDm[i] = chroma == 4; + } + } + + /// candIntraPredModeX of §8.4.2. + private int NeighbourIntraMode(int xPb, int yPb, int xN, int yN, bool above) + { + if (!Available(xPb, yPb, xN, yN)) + { + return 1; + } + + var g = Grid(xN, yN); + if (predMode[g] != ModeIntra || (blockFlags[g] & FlagPcm) != 0) + { + return 1; + } + + if (above && yN < ((yPb >> sps.Log2CtbSize) << sps.Log2CtbSize)) + { + return 1; + } + + return intraModeMap[g]; + } + + /// pcm_sample() (§7.3.8.7) and its reconstruction (§8.4.4.1): the CABAC engine restarts after the samples. + private void PcmSamples(int x0, int y0, int log2) + { + var reader = new BitReader(data, dataEnd, 0) { Position = (cabac.BitPosition + 7) & ~7 }; + var size = 1 << log2; + var plane = cur!.Planes[0]; + var stride = cur.Width; + int shift = sps.BitDepthY - sps.PcmBitDepthY, bits = sps.PcmBitDepthY; + for (var y = 0; y < size; y++) + { + for (var x = 0; x < size; x++) + { + plane[((y0 + y) * stride) + x0 + x] = (ushort)(reader.Read(bits) << shift); + } + } + + shift = sps.BitDepthC - sps.PcmBitDepthC; + bits = sps.PcmBitDepthC; + int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY; + int chromaWidth = size >> sx, chromaHeight = size >> sy, xc = x0 >> sx, yc = y0 >> sy; + for (var c = 1; c <= 2 && sps.ChromaArrayType != 0; c++) + { + plane = cur.Planes[c]; + stride = cur.ChromaWidth; + for (var y = 0; y < chromaHeight; y++) + { + for (var x = 0; x < chromaWidth; x++) + { + plane[((yc + y) * stride) + xc + x] = (ushort)(reader.Read(bits) << shift); + } + } + } + + if (reader.BitsLeft < 0) + { + throw new H265Exception("Campioni PCM troncati."); + } + + cabac.Start(data, reader.Position, dataEnd); + } + + /// The prediction units of an inter coding unit by part_mode; true when the first one is merged. + private bool PredictionUnits(int x0, int y0, int size, int depth) + { + int half = size >> 1, quarter = size >> 2; + switch (cuPartMode) + { + case Part2Nx2N: + return PredictionUnit(x0, y0, size, size, false, depth, 0); + case Part2NxN: + { + var merge = PredictionUnit(x0, y0, size, half, false, depth, 0); + PredictionUnit(x0, y0 + half, size, half, false, depth, 1); + return merge; + } + + case PartNx2N: + { + var merge = PredictionUnit(x0, y0, half, size, false, depth, 0); + PredictionUnit(x0 + half, y0, half, size, false, depth, 1); + return merge; + } + + case Part2NxnU: + { + var merge = PredictionUnit(x0, y0, size, quarter, false, depth, 0); + PredictionUnit(x0, y0 + quarter, size, size - quarter, false, depth, 1); + return merge; + } + + case Part2NxnD: + { + var merge = PredictionUnit(x0, y0, size, size - quarter, false, depth, 0); + PredictionUnit(x0, y0 + size - quarter, size, quarter, false, depth, 1); + return merge; + } + + case PartnLx2N: + { + var merge = PredictionUnit(x0, y0, quarter, size, false, depth, 0); + PredictionUnit(x0 + quarter, y0, size - quarter, size, false, depth, 1); + return merge; + } + + case PartnRx2N: + { + var merge = PredictionUnit(x0, y0, size - quarter, size, false, depth, 0); + PredictionUnit(x0 + size - quarter, y0, quarter, size, false, depth, 1); + return merge; + } + + default: + { + var merge = PredictionUnit(x0, y0, half, half, false, depth, 0); + PredictionUnit(x0 + half, y0, half, half, false, depth, 1); + PredictionUnit(x0, y0 + half, half, half, false, depth, 2); + PredictionUnit(x0 + half, y0 + half, half, half, false, depth, 3); + return merge; + } + } + } + + /// + /// prediction_unit() (§7.3.8.6) and mvd_coding() (§7.3.8.9), then the motion of the unit (merge or AMVP, §8.5.3.2) + /// and its inter prediction samples (§8.5.3.3), to which the residual is added later. + /// + private bool PredictionUnit(int x0, int y0, int width, int height, bool skip, int depth, int partIdx) + { + MvField motion; + var merge = skip || cabac.Flag(CabacTables.MergeFlag); + if (merge) + { + var mergeIdx = 0; + if (slice.MaxNumMergeCand > 1 && cabac.Flag(CabacTables.MergeIdx)) + { + mergeIdx = 1; + while (mergeIdx < slice.MaxNumMergeCand - 1 && cabac.Bypass() == 1) + { + mergeIdx++; + } + } + + motion = MergeMotion(x0, y0, width, height, partIdx, mergeIdx); + } + else + { + var interPredIdc = 0; // PRED_L0 + if (slice.Type == SliceType.B) + { + if (width + height != 12 && cabac.Flag(CabacTables.InterPredIdc + depth)) + { + interPredIdc = 2; // PRED_BI + } + else + { + interPredIdc = cabac.Flag(CabacTables.InterPredIdc + 4) ? 1 : 0; + } + } + + Span refIdx = [-1, -1]; + Span mvd = [0, 0, 0, 0]; + Span mvpFlag = [0, 0]; + for (var list = 0; list < 2; list++) + { + if (interPredIdc == 1 - list) + { + continue; + } + + var count = slice.NumRefIdxActive[list]; + var index = 0; + if (count > 1) + { + while (index < count - 1 && (index >= 2 ? cabac.Bypass() == 1 : cabac.Flag(CabacTables.RefIdx + index))) + { + index++; + } + } + + refIdx[list] = index; + if (!(list == 1 && slice.MvdL1Zero && interPredIdc == 2)) + { + MvdCoding(out mvd[list * 2], out mvd[(list * 2) + 1]); + } + + mvpFlag[list] = cabac.Flag(CabacTables.MvpFlag) ? 1 : 0; + } + + motion = MvField.Intra; + if (refIdx[0] >= 0) + { + var (x, y) = PredictedMotionVector(x0, y0, width, height, partIdx, 0, refIdx[0], mvpFlag[0]); + motion.Ref0 = (sbyte)refIdx[0]; + motion.X0 = (short)(x + mvd[0]); + motion.Y0 = (short)(y + mvd[1]); + } + + if (refIdx[1] >= 0) + { + var (x, y) = PredictedMotionVector(x0, y0, width, height, partIdx, 1, refIdx[1], mvpFlag[1]); + motion.Ref1 = (sbyte)refIdx[1]; + motion.X1 = (short)(x + mvd[2]); + motion.Y1 = (short)(y + mvd[3]); + } + } + + FillGrid(cur!.Motion, x0, y0, width, height, motion); + PredictInter(x0, y0, width, height, motion); + return merge; + } + + /// mvd_coding() (§7.3.8.9): MvdLX, horizontal then vertical. + private void MvdCoding(out int x, out int y) + { + var greater0X = cabac.Flag(CabacTables.AbsMvdGreater0Flag); + var greater0Y = cabac.Flag(CabacTables.AbsMvdGreater0Flag); + var greater1X = greater0X && cabac.Flag(CabacTables.AbsMvdGreater1Flag); + var greater1Y = greater0Y && cabac.Flag(CabacTables.AbsMvdGreater1Flag); + x = 0; + y = 0; + if (greater0X) + { + x = greater1X ? ExpGolombBypass(1) + 2 : 1; + if (cabac.Bypass() == 1) + { + x = -x; + } + } + + if (greater0Y) + { + y = greater1Y ? ExpGolombBypass(1) + 2 : 1; + if (cabac.Bypass() == 1) + { + y = -y; + } + } + } + + /// A k-th order Exp-Golomb value in bypass bins (§9.3.3.3). + private int ExpGolombBypass(int k) + { + var value = 0; + while (cabac.Bypass() == 1) + { + value += 1 << k; + k++; + if (k > 31) + { + throw new H265Exception("Codice Exp-Golomb CABAC non valido."); + } + } + + return k > 0 ? value + ReadBypass(k) : value; + } + + private int ReadBypass(int count) + { + var value = 0; + while (count > 16) + { + value = (value << 16) | cabac.BypassBits(16); + count -= 16; + } + + return (value << count) | cabac.BypassBits(count); + } + + /// + /// transform_tree() (§7.3.8.8). holds the chroma coded block flags of the parent: bit 0 + /// cbf_cb, bit 1 the cbf_cb of the second (lower) 4:2:2 block, bits 2 and 3 the same for cbf_cr. + /// + private void TransformTree(int x0, int y0, int xBase, int yBase, int log2, int depth, int blkIdx, int parentCbf) + { + bool split; + var interSplit = sps.MaxTransformHierarchyDepthInter == 0 && !cuIntra && cuPartMode != Part2Nx2N && depth == 0; + if (log2 <= sps.Log2MaxTbSize && log2 > sps.Log2MinTbSize && depth < cuMaxTrafoDepth && !(cuIntraSplit && depth == 0)) + { + split = cabac.Flag(CabacTables.SplitTransformFlag + 5 - log2); + } + else + { + split = log2 > sps.Log2MaxTbSize || (cuIntraSplit && depth == 0) || interSplit; + } + + var chromaType = sps.ChromaArrayType; + var cbf = 0; + if ((log2 > 2 && chromaType != 0) || chromaType == 3) + { + // In 4:2:2 a block that is not split further (or splits into 4×4 luma blocks) has two chroma blocks per + // component, one above the other, each with its flag. + var second = chromaType == 2 && (!split || log2 == 3); + if (depth == 0 || (parentCbf & 1) != 0) + { + cbf |= cabac.Flag(CabacTables.CbfChroma + depth) ? 1 : 0; + cbf |= second && cabac.Flag(CabacTables.CbfChroma + depth) ? 2 : 0; + } + + if (depth == 0 || (parentCbf & 4) != 0) + { + cbf |= cabac.Flag(CabacTables.CbfChroma + depth) ? 4 : 0; + cbf |= second && cabac.Flag(CabacTables.CbfChroma + depth) ? 8 : 0; + } + } + else if (chromaType != 0) + { + // 4×4 luma blocks in 4:2:0 and 4:2:2: the chroma of the four is coded once, with the parent's flags (§7.4.9.8). + cbf = parentCbf; + } + + if (split) + { + var half = 1 << (log2 - 1); + TransformTree(x0, y0, x0, y0, log2 - 1, depth + 1, 0, cbf); + TransformTree(x0 + half, y0, x0, y0, log2 - 1, depth + 1, 1, cbf); + TransformTree(x0, y0 + half, x0, y0, log2 - 1, depth + 1, 2, cbf); + TransformTree(x0 + half, y0 + half, x0, y0, log2 - 1, depth + 1, 3, cbf); + return; + } + + var cbfLuma = true; + if (cuIntra || depth != 0 || cbf != 0) + { + cbfLuma = cabac.Flag(CabacTables.CbfLuma + (depth == 0 ? 1 : 0)); + } + + TransformUnit(x0, y0, xBase, yBase, log2, blkIdx, cbfLuma, cbf); + } + + private void TransformUnit(int x0, int y0, int xBase, int yBase, int log2, int blkIdx, bool cbfLuma, int cbf) + { + var size = 1 << log2; + var cbfChroma = cbf != 0; + if (cbfLuma || cbfChroma) + { + if (pps.CuQpDeltaEnabled && !isCuQpDeltaCoded) + { + // cu_qp_delta_abs: TR prefix of up to 5 bins (the first with context 0, the others with context 1), + // then an EG0 suffix in bypass; cu_qp_delta_sign_flag in bypass. + var prefix = 0; + while (prefix < 5 && cabac.Flag(CabacTables.CuQpDeltaAbs + (prefix == 0 ? 0 : 1))) + { + prefix++; + } + + var value = prefix == 5 ? 5 + ExpGolombBypass(0) : prefix; + if (value != 0 && cabac.Bypass() == 1) + { + value = -value; + } + + var offset = sps.QpBdOffsetY; + if (value < -(26 + (offset / 2)) || value > 25 + (offset / 2)) + { + throw new H265Exception("cu_qp_delta fuori dall'intervallo."); + } + + isCuQpDeltaCoded = true; + cuQpDeltaVal = value; + UpdateQpY(); + } + + if (slice.CuChromaQpOffsetEnabled && cbfChroma && !cuTransquantBypass && !isCuChromaQpOffsetCoded) + { + var on = cabac.Flag(CabacTables.CuChromaQpOffsetFlag); + var index = 0; + if (on && pps.ChromaQpOffsetListLength > 1) + { + while (index < pps.ChromaQpOffsetListLength - 1 && cabac.Flag(CabacTables.CuChromaQpOffsetIdx)) + { + index++; + } + } + + cuQpOffsetCb = on ? pps.CbQpOffsetList[index] : 0; + cuQpOffsetCr = on ? pps.CrQpOffsetList[index] : 0; + isCuChromaQpOffsetCoded = true; + } + } + + var lumaMode = cuIntra ? intraModeMap[Grid(x0, y0)] : -1; + if (cuIntra) + { + PredictIntra(0, x0, y0, log2, lumaMode); + } + + if (cbfLuma) + { + Residual(0, x0, y0, log2, lumaMode, 0); + FillGrid(blockFlags, x0, y0, size, size, FlagCoded, true); + } + + if (x0 > cuX) + { + MarkVertical(x0, y0, size, 2); + } + + if (y0 > cuY) + { + MarkHorizontal(x0, y0, size, 2); + } + + var chromaType = sps.ChromaArrayType; + if (chromaType == 0) + { + return; + } + + int sx = sps.ChromaShiftX, sy = sps.ChromaShiftY; + if (log2 > 2 || chromaType == 3) + { + // In 4:4:4 an NxN coding unit has a chroma mode for each of its four blocks. + var part = 0; + if (cuIntraSplit && chromaType == 3) + { + var half = 1 << (cuLog2 - 1); + part = (y0 >= cuY + half ? 2 : 0) + (x0 >= cuX + half ? 1 : 0); + } + + ChromaBlocks(x0 >> sx, y0 >> sy, chromaType == 3 ? log2 : log2 - 1, cbf, part, cbfLuma); + } + else if (blkIdx == 3) + { + ChromaBlocks(xBase >> sx, yBase >> sy, 2, cbf, 0, false); + } + } + + /// + /// The chroma blocks of a transform unit (two per component in 4:2:2, one above the other): prediction, then the + /// residual, with cross_comp_pred() (§7.3.8.12) when the luma block has coefficients. + /// + private void ChromaBlocks(int xc, int yc, int log2, int cbf, int part, bool lumaCoded) + { + var mode = cuIntra ? cuChromaModes[part] : -1; + var crossComponent = lumaCoded && pps.CrossComponentPredictionEnabled && (!cuIntra || cuChromaDm[part]); + var blocks = sps.ChromaArrayType == 2 ? 2 : 1; + for (var c = 1; c <= 2; c++) + { + var resScale = crossComponent ? CrossComponentPrediction(c - 1) : 0; + for (var t = 0; t < blocks; t++) + { + var y = yc + (t << log2); + if (cuIntra) + { + PredictIntra(c, xc, y, log2, mode); + } + + if ((cbf & (1 << (((c - 1) * 2) + t))) != 0) + { + Residual(c, xc, y, log2, mode, resScale); + } + else if (resScale != 0) + { + CrossComponentResidual(c, xc, y, log2, resScale); + } + } + } + } + + /// log2_res_scale_abs_plus1 and res_scale_sign_flag of one chroma component, as ResScaleVal (7.4.9.12). + private int CrossComponentPrediction(int c) + { + var value = 0; + while (value < 4 && cabac.Flag(CabacTables.Log2ResScaleAbsPlus1 + (4 * c) + value)) + { + value++; + } + + if (value == 0) + { + return 0; + } + + return cabac.Flag(CabacTables.ResScaleSignFlag + c) ? -(1 << (value - 1)) : 1 << (value - 1); + } + + /// + /// availableN of the z-scan order (§6.4.1), for luma locations: inside the picture, already decoded, in the same + /// slice and the same tile. + /// + private bool Available(int xCur, int yCur, int xN, int yN) + { + if (xN < 0 || yN < 0 || xN >= sps.Width || yN >= sps.Height) + { + return false; + } + + var log2 = sps.Log2CtbSize; + var ctbN = ((yN >> log2) * widthInCtbs) + (xN >> log2); + var ctbC = ((yCur >> log2) * widthInCtbs) + (xCur >> log2); + if (ctbN != ctbC) + { + return ctbSlice[ctbN] == sliceIdx && pps.TileIdRs[ctbN] == pps.TileIdRs[ctbC]; + } + + var mask = (1 << log2) - 1; + return s_zOrder[(((yN & mask) >> 2) << 4) | ((xN & mask) >> 2)] < s_zOrder[(((yCur & mask) >> 2) << 4) | ((xCur & mask) >> 2)]; + } + + private int Grid(int x, int y) => ((y >> 2) * w4) + (x >> 2); + + private void FillGrid(T[] grid, int x0, int y0, int width, int height, T value) + { + int gx = x0 >> 2, gy = y0 >> 2; + int gw = Math.Min((width + 3) >> 2, w4 - gx), gh = Math.Min((height + 3) >> 2, h4 - gy); + for (var y = 0; y < gh; y++) + { + grid.AsSpan(((gy + y) * w4) + gx, gw).Fill(value); + } + } + + private void FillGrid(byte[] grid, int x0, int y0, int width, int height, byte bits, bool or) + { + if (or) + { + OrGrid(grid, x0, y0, width, height, bits); + } + else + { + FillGrid(grid, x0, y0, width, height, bits); + } + } + + private void OrGrid(byte[] grid, int x0, int y0, int width, int height, byte bits) + { + int gx = x0 >> 2, gy = y0 >> 2; + int gw = Math.Min((width + 3) >> 2, w4 - gx), gh = Math.Min((height + 3) >> 2, h4 - gy); + for (var y = 0; y < gh; y++) + { + var row = ((gy + y) * w4) + gx; + for (var x = 0; x < gw; x++) + { + grid[row + x] |= bits; + } + } + } + + private void FillPlane(int cIdx, int x0, int y0, int width, int height, ushort value) + { + var plane = cur!.Planes[cIdx]; + var stride = cur.Stride(cIdx); + var rows = cIdx == 0 ? cur.Height : cur.ChromaHeight; + width = Math.Min(width, stride - x0); + height = Math.Min(height, rows - y0); + for (var y = 0; y < height; y++) + { + plane.AsSpan(((y0 + y) * stride) + x0, width).Fill(value); + } + } + + private static ushort[] BuildZOrder() + { + var table = new ushort[256]; + for (var y = 0; y < 16; y++) + { + for (var x = 0; x < 16; x++) + { + var z = 0; + for (var b = 0; b < 4; b++) + { + z |= ((x >> b) & 1) << (2 * b); + z |= ((y >> b) & 1) << ((2 * b) + 1); + } + + table[(y << 4) | x] = (ushort)z; + } + } + + return table; + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Decoder.cs b/src/Febe.Core/Codecs/H265/H265Decoder.cs new file mode 100644 index 0000000..bf61065 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Decoder.cs @@ -0,0 +1,778 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Codecs.H265; + +/// What an access unit offers to start decoding from (see ). +public enum H265AccessPoint +{ + /// A picture that is not IRAP, or no picture: decoding cannot start here. + None, + + /// A CRA picture: decoding starts here, but its RASL pictures (shown before it) are skipped. + Cra, + + /// An IDR or BLA picture: nothing decoded after it refers to anything before. + Idr, +} + +/// +/// 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, +/// dependent slice segments, PCM, transform skip, sign data hiding, scaling lists, inter prediction (merge, AMVP, temporal +/// 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, 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 +{ + private readonly Sps?[] spss = new Sps?[16]; + private readonly Pps?[] ppss = new Pps?[64]; + private readonly List dpb = []; + private readonly Stack pool = new(); + private byte[]? rbsp; + + /// No picture decoded yet: the next IRAP picture is "picture 0" of C.5.2.2. + private bool firstPicture = true; + + /// At the start of the bitstream or after an end of sequence: the next CRA picture has NoRaslOutputFlag 1. + private bool afterEndOfSequence = true; + + private bool seenIrap; + + /// NoRaslOutputFlag of the IRAP picture the current pictures are associated with. + private bool irapNoRaslOutput; + + /// PicOrderCntVal of prevTid0Pic (§8.3.1). + private int prevTid0Poc; + + private long codedPictures; + + /// The slices of the current picture are skipped (a RASL picture that cannot be decoded, no IRAP yet). + private bool skipping; + + /// + /// 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<(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; + + /// + /// Raised for each picture once decoded and filtered, in decoding order and cropped, when 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. + /// + public event Action? FrameDecoded; + + /// Which pictures hands out, by decoding index; null hands out all of them. + public Func? Wanted { get; set; } + + /// Raised for each picture once decoded and filtered, in decoding order (for the decoded picture hash). + internal event Action? PictureDecoded; + + /// 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) + { + var position = 0; + while (NalUnits.NextAnnexB(stream, ref position, out var unit)) + { + Decode(stream[unit]); + } + + Flush(); + } + + /// + /// Reads the parameter sets of an hvcC box (HEVCDecoderConfigurationRecord, ISO/IEC 14496-15 §8.3.3); returns + /// the size of the NAL length fields of the samples. + /// + public int ConfigureHvcC(ReadOnlySpan hvcC) + { + if (hvcC.Length < 23 || hvcC[0] != 1) + { + throw new H265Exception("Configurazione hvcC non valida."); + } + + var lengthSize = (hvcC[21] & 3) + 1; + var arrays = hvcC[22]; + var offset = 23; + for (var a = 0; a < arrays; a++) + { + if (offset + 3 > hvcC.Length) + { + throw new H265Exception("Configurazione hvcC troncata."); + } + + var count = (hvcC[offset + 1] << 8) | hvcC[offset + 2]; + offset += 3; + for (var i = 0; i < count; i++) + { + if (offset + 2 > hvcC.Length) + { + throw new H265Exception("Configurazione hvcC troncata."); + } + + var size = (hvcC[offset] << 8) | hvcC[offset + 1]; + offset += 2; + if (size == 0 || offset + size > hvcC.Length) + { + throw new H265Exception("Configurazione hvcC troncata."); + } + + Decode(hvcC.Slice(offset, size)); + offset += size; + } + } + + return lengthSize; + } + + /// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture. + public void DecodeSample(ReadOnlySpan sample, int lengthSize) + { + var position = 0; + while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit)) + { + Decode(sample[unit]); + } + + FinishPicture(); + } + + /// Decodes one access unit in Annex B form (an AVI chunk, a PES packet) and finishes its picture. + public void DecodeAccessUnitAnnexB(ReadOnlySpan accessUnit) + { + var position = 0; + while (NalUnits.NextAnnexB(accessUnit, ref position, out var unit)) + { + Decode(accessUnit[unit]); + } + + FinishPicture(); + } + + /// + /// 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. + /// is the size of the NAL length fields, 0 for Annex B. + /// + public static H265AccessPoint AccessPoint(ReadOnlySpan 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, + }; + } + } + + /// Finishes the picture being decoded and outputs every picture still waiting, in output order. + public void Flush() + { + FinishPicture(); + while (Bump()) + { + } + } + + private void Decode(ReadOnlySpan bytes) + { + if (bytes.Length < 2 || (bytes[0] & 0x80) != 0) + { + return; + } + + var type = (bytes[0] >> 1) & 63; + var layer = ((bytes[0] & 1) << 5) | (bytes[1] >> 3); + if (layer != 0) + { + return; + } + + try + { + switch (type) + { + case <= 9: + case >= 16 and <= 21: + DecodeSlice(H265NalUnit.Unescape(bytes, ref rbsp)); + break; + case 33: + InstallSps(Sps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader())); + break; + case 34: + InstallPps(Pps.Parse(H265NalUnit.Unescape(bytes, ref rbsp).Reader())); + break; + + case 35: // access unit delimiter + FinishPicture(); + break; + case 36: // end of sequence + case 37: // end of bitstream + FinishPicture(); + afterEndOfSequence = true; + break; + } + } + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException) + { + throw new H265Exception("Flusso HEVC troncato o danneggiato."); + } + } + + private void DecodeSlice(H265NalUnit nal) + { + var first = (nal.Rbsp[2] & 0x80) != 0; + if (first) + { + FinishPicture(); + } + else if (skipping || cur is null) + { + // A segment of a picture that is skipped, or whose first segment is missing. + return; + } + + var reader = nal.Reader(); + var header = SliceHeader.Parse(reader, nal.Type, spss, ppss, first ? null : sliceHeader, out var s, out var p); + if (first) + { + StartPicture(nal, header, s, p); + if (skipping) + { + return; + } + } + else if (!s.SameContent(sps) || !p.SameContent(pps)) + { + throw new H265Exception("Parametri diversi fra le slice di un'immagine."); + } + + if (!header.Dependent) + { + if (!header.IsIntra) + { + BuildReferencePictureLists(header); + } + + sliceHeader = header; + slices.Add(header); + } + + DecodeSliceData(nal, header); + } + + private void StartPicture(H265NalUnit nal, SliceHeader h, Sps s, Pps p) + { + var index = codedPictures++; + var type = nal.Type; + var irap = type is >= 16 and <= 23; + var idr = type is 19 or 20; + skipping = false; + sliceHeader = null; + var noRaslOutput = false; + if (irap) + { + noRaslOutput = idr || type <= 18 || afterEndOfSequence; + irapNoRaslOutput = noRaslOutput; + seenIrap = true; + } + else if (!seenIrap || (type is 8 or 9 && irapNoRaslOutput)) + { + // Decoding cannot start here, or a RASL picture of a CRA that starts the sequence (§8.1.3): not decoded. + skipping = true; + return; + } + + if (s.SeparateColourPlane || s.BitDepthY > 12 || s.BitDepthC > 12) + { + throw new H265Exception("Solo video HEVC fino a 12 bit, senza piani di colore separati."); + } + + if (s.UsesUnsupportedTools) + { + 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). + var maxLsb = 1 << s.Log2MaxPocLsb; + int msb; + if (irap && noRaslOutput) + { + msb = 0; + } + else + { + var prevLsb = prevTid0Poc & (maxLsb - 1); + var prevMsb = prevTid0Poc - prevLsb; + if (h.PocLsb < prevLsb && prevLsb - h.PocLsb >= maxLsb / 2) + { + msb = prevMsb + maxLsb; + } + else if (h.PocLsb > prevLsb && h.PocLsb - prevLsb > maxLsb / 2) + { + msb = prevMsb - maxLsb; + } + else + { + msb = prevMsb; + } + } + + var poc = msb + h.PocLsb; + var subLayerNonReference = type <= 14 && type % 2 == 0; + if (nal.TemporalId == 0 && type is not (>= 6 and <= 9) && !subLayerNonReference) + { + prevTid0Poc = poc; + } + + ApplyReferencePictureSet(h, s, poc, irap && noRaslOutput, idr); + + // Removal of pictures from the DPB before the current one is decoded (C.5.2.2). + if (irap && noRaslOutput && !firstPicture) + { + var noOutputOfPriorPics = type == 21 || h.NoOutputOfPriorPics; + if (!noOutputOfPriorPics) + { + while (Bump()) + { + } + } + + foreach (var picture in dpb) + { + pool.Push(picture); + } + + dpb.Clear(); + } + else + { + RemoveUnused(); + var t = s.HighestTid; + while (OutputWanted(s, t) || dpb.Count >= s.MaxDecPicBufferingMinus1[t] + 1) + { + if (!Bump()) + { + 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; + afterEndOfSequence = false; + cur = NewPicture(s); + cur.Poc = poc; + cur.DecodeIndex = index; + cur.OutputFlag = h.PicOutputFlag; + StartPictureData(s, p); + } + + /// The decoding process for the reference picture set (§8.3.2), and the marking of the DPB it implies. + private void ApplyReferencePictureSet(SliceHeader h, Sps s, int poc, bool irapNoRasl, bool idr) + { + refStCurrBefore.Clear(); + refStCurrAfter.Clear(); + refLtCurr.Clear(); + if (irapNoRasl) + { + foreach (var picture in dpb) + { + picture.ShortTerm = picture.LongTerm = false; + } + } + + if (idr) + { + foreach (var picture in dpb) + { + picture.ShortTerm = picture.LongTerm = false; + } + + return; + } + + var maxLsb = 1 << s.Log2MaxPocLsb; + Span keep = stackalloc bool[dpb.Count]; + + // Long-term pictures first: a picture they take is no longer a short-term candidate. + var total = h.PocLsbLt.Length; + for (var i = 0; i < total; i++) + { + var pocLt = h.PocLsbLt[i]; + if (h.DeltaPocMsbPresent[i]) + { + pocLt += poc - (h.DeltaPocMsbCycleLt[i] * maxLsb) - (poc & (maxLsb - 1)); + } + + var found = -1; + for (var k = 0; k < dpb.Count; k++) + { + var candidate = dpb[k]; + if (candidate.IsReference && (h.DeltaPocMsbPresent[i] ? candidate.Poc == pocLt : (candidate.Poc & (maxLsb - 1)) == pocLt)) + { + found = k; + break; + } + } + + if (found >= 0) + { + keep[found] = true; + dpb[found].LongTerm = true; + dpb[found].ShortTerm = false; + } + + if (h.UsedByCurrPicLt[i]) + { + refLtCurr.Add(found >= 0 ? (dpb[found], dpb[found].Poc) : (MissingReference(s), pocLt)); + } + } + + if (h.StRps is { } rps) + { + for (var i = 0; i < rps.NumNegative; i++) + { + var picture = FindShortTerm(poc + rps.DeltaPocS0[i], keep); + if (rps.UsedS0[i]) + { + refStCurrBefore.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS0[i])); + } + } + + for (var i = 0; i < rps.NumPositive; i++) + { + var picture = FindShortTerm(poc + rps.DeltaPocS1[i], keep); + if (rps.UsedS1[i]) + { + refStCurrAfter.Add((picture ?? MissingReference(s), poc + rps.DeltaPocS1[i])); + } + } + } + + // Every reference picture that is in none of the five lists is no longer used for reference. + for (var k = 0; k < dpb.Count; k++) + { + if (!keep[k]) + { + dpb[k].ShortTerm = dpb[k].LongTerm = false; + } + } + } + + /// + /// 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 Picture MissingReference(Sps s) + { + 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++) + { + if (dpb[k].ShortTerm && !dpb[k].LongTerm && dpb[k].Poc == poc) + { + keep[k] = true; + return dpb[k]; + } + } + + return null; + } + + /// The conditions of C.5.2.2 and C.5.2.3 on the pictures waiting for output. + private bool OutputWanted(Sps s, int t) + { + var waiting = 0; + var late = false; + var maxLatency = s.MaxNumReorderPics[t] + (long)s.MaxLatencyIncreasePlus1[t] - 1; + foreach (var picture in dpb) + { + if (picture.NeededForOutput) + { + waiting++; + late |= s.MaxLatencyIncreasePlus1[t] != 0 && picture.LatencyCount >= maxLatency; + } + } + + return waiting > s.MaxNumReorderPics[t] || late; + } + + private void RemoveUnused() + { + for (var k = dpb.Count - 1; k >= 0; k--) + { + if (!dpb[k].NeededForOutput && !dpb[k].IsReference) + { + pool.Push(dpb[k]); + dpb.RemoveAt(k); + } + } + } + + /// The bumping process (C.5.2.4): outputs the waiting picture with the smallest POC; false when none waits. + private bool Bump() + { + Picture? best = null; + foreach (var picture in dpb) + { + if (picture.NeededForOutput && (best is null || picture.Poc < best.Poc)) + { + best = picture; + } + } + + if (best is null) + { + return false; + } + + best.NeededForOutput = false; + FrameOutput?.Invoke(best.ToFrame()); + if (!best.IsReference) + { + dpb.Remove(best); + pool.Push(best); + } + + return true; + } + + private Picture NewPicture(Sps s) + { + while (pool.Count > 0) + { + var picture = pool.Pop(); + if (picture.Fits(s)) + { + picture.Sps = s; + picture.ShortTerm = picture.LongTerm = picture.NeededForOutput = picture.Generated = false; + picture.LatencyCount = 0; + return picture; + } + } + + return new Picture(s); + } + + /// + /// Finishes the current picture: in-loop filters, then the marking and the "additional bumping" of C.5.2.3. A damaged + /// picture whose filtering fails raises an and is dropped. + /// + private void FinishPicture() + { + if (cur is null) + { + return; + } + + var picture = cur; + cur = null; + InstallPending(); + picture.IntraOnly = true; + foreach (var header in slices) + { + picture.IntraOnly &= header.IsIntra; + } + + try + { + ApplyInLoopFilters(picture); + } + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException) + { + throw new H265Exception("Flusso HEVC troncato o danneggiato."); + } + + PictureDecoded?.Invoke(picture); + if (FrameDecoded is { } decoded && (Wanted?.Invoke(picture.DecodeIndex) ?? true)) + { + decoded(picture.ToFrame()); + } + + foreach (var other in dpb) + { + if (other.NeededForOutput) + { + other.LatencyCount++; + } + } + + picture.NeededForOutput = picture.OutputFlag; + picture.LatencyCount = 0; + picture.ShortTerm = true; + dpb.Add(picture); + var s = picture.Sps; + while (OutputWanted(s, s.HighestTid)) + { + if (!Bump()) + { + break; + } + } + } +} diff --git a/src/Febe.Core/Codecs/H265/H265StreamInfo.cs b/src/Febe.Core/Codecs/H265/H265StreamInfo.cs new file mode 100644 index 0000000..8531e66 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265StreamInfo.cs @@ -0,0 +1,77 @@ +namespace Febe.Core.Codecs.H265; + +/// +/// What the sequence parameter set of an HEVC stream says without decoding it: the size of the pictures shown, after +/// the conformance window (§7.4.3.2.1). Used by the container readers whose headers do not carry the size (MPEG program +/// streams), as H264StreamInfo is for H.264. +/// +public static class H265StreamInfo +{ + /// nal_unit_type of a sequence parameter set (table 7-1). + private const int SpsType = 33; + + /// The picture size of an SPS NAL unit (two-byte header included); false when it is not an SPS or is damaged. + public static bool TryPictureSize(ReadOnlySpan nal, out int width, out int height) + { + width = height = 0; + if (nal.Length < 4 || (nal[0] & 0x80) != 0 || ((nal[0] >> 1) & 63) != SpsType) + { + return false; // forbidden_zero_bit set, or not an SPS + } + + try + { + byte[]? buffer = null; + var sps = Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader()); + var w = sps.Width - sps.ConfLeft - sps.ConfRight; + var h = sps.Height - sps.ConfTop - sps.ConfBottom; + if (w <= 0 || h <= 0) + { + return false; + } + + (width, height) = (w, h); + return true; + } + catch (Exception ex) when (ex is H265Exception or IndexOutOfRangeException or ArgumentException or OverflowException) + { + return false; + } + } + + /// + /// The picture size of the first whole SPS of an Annex B byte stream; an SPS that the end of + /// cuts counts only when says nothing follows. + /// + public static bool TryPictureSizeFromAnnexB(ReadOnlySpan stream, bool complete, out int width, out int height) + { + width = height = 0; + ReadOnlySpan startCode = [0, 0, 1]; + var found = stream.IndexOf(startCode); + while (found >= 0) + { + var start = found + 3; + var next = stream[start..].IndexOf(startCode); + if (next < 0 && !complete) + { + return false; // the last unit may be cut short + } + + var end = next < 0 ? stream.Length : start + next; + var nal = stream[start..end]; + while (nal.Length > 0 && nal[^1] == 0) + { + nal = nal[..^1]; // the zero byte of a four-byte start code belongs to the next unit + } + + if (TryPictureSize(nal, out width, out height)) + { + return true; + } + + found = next < 0 ? -1 : end; + } + + return false; + } +} diff --git a/src/Febe.Core/Codecs/H265/H265Tables.cs b/src/Febe.Core/Codecs/H265/H265Tables.cs new file mode 100644 index 0000000..a7850a8 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/H265Tables.cs @@ -0,0 +1,190 @@ +namespace Febe.Core.Codecs.H265; + +/// +/// Constant tables of ITU-T H.265, transcribed from the text of the Recommendation: scan orders (§6.5.3–6.5.5), default +/// scaling lists (table 7-6), intra prediction angles (tables 8-4 and 8-5), the 4:2:2 chroma intra modes (table 8-3), the chroma QP mapping (table 8-10), the +/// thresholds of the deblocking filter (table 8-12) and the transform matrices (§8.6.4.2). +/// +internal static class H265Tables +{ + /// intraPredAngle by intra prediction mode (table 8-4); modes 0 (planar) and 1 (DC) have none. + internal static readonly sbyte[] IntraPredAngle = + [ + 0, 0, 32, 26, 21, 17, 13, 9, 5, 2, 0, -2, -5, -9, -13, -17, -21, -26, + -32, -26, -21, -17, -13, -9, -5, -2, 0, 2, 5, 9, 13, 17, 21, 26, 32, + ]; + + /// invAngle of the modes 11 to 25 (table 8-5), indexed by mode − 11. + internal static readonly short[] InvAngle = [-4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096]; + + /// QpC as a function of qPi for ChromaArrayType 1 (table 8-10), for qPi from 30 to 43. + internal static readonly byte[] ChromaQp30To43 = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37]; + + /// + /// The 4:2:2 intra prediction mode of chroma (table 8-3) from modeIdc, the mode table 8-2 gives: for chroma samples + /// twice as tall as they are wide, the mode whose angle is closest to the luma one with the horizontal displacement + /// halved (horizontal modes: the vertical one doubled; past 45° a mode of the other direction). + /// + internal static readonly byte[] ChromaMode422 = + [ + 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, + 21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31, + ]; + + /// QpC of chroma from qPi (8-258 to 8-261, table 8-10): the table for 4:2:0, Min(qPi, 51) otherwise. + internal static int ChromaQp(int qPi, int chromaArrayType) => + chromaArrayType != 1 ? Math.Min(qPi, 51) : qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : ChromaQp30To43[qPi - 30]; + + /// β′ for Q from 0 to 51 (table 8-12). + internal static readonly byte[] Beta = + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, + 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, + ]; + + /// tC′ for Q from 0 to 53 (table 8-12). + internal static readonly byte[] Tc = + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, + 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, + ]; + + /// levelScale[qP % 6] of the scaling process (§8.6.3). + internal static readonly int[] LevelScale = [40, 45, 51, 57, 64, 72]; + + /// Default values of ScalingList[1..3][0..2] (intra), in up-right diagonal order (table 7-6). + internal static readonly byte[] DefaultScalingIntra = + [ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20, 21, 20, 19, 21, 24, 22, 22, 24, + 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31, 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115, + ]; + + /// Default values of ScalingList[1..3][3..5] (inter), in up-right diagonal order (table 7-6). + internal static readonly byte[] DefaultScalingInter = + [ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20, 20, 20, 20, 20, 24, 24, 24, 24, + 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28, 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91, + ]; + + /// + /// Scan orders of blocks from 1×1 to 32×32 (index log2 size, 0 to 5) for scanIdx 0 (up-right diagonal, §6.5.3), 1 + /// (horizontal, §6.5.4) and 2 (vertical, §6.5.5): each entry is x | (y << 8). + /// + internal static readonly ushort[][][] ScanOrder = BuildScans(); + + /// For the 4×4 scans: position in scan order of each raster position (y * 4 + x), by scanIdx. + internal static readonly byte[][] ScanPosition4x4 = BuildInverse4x4(); + + /// + /// Magnitudes of the coefficients of the 32-point DCT of §8.6.4.2 by angle index a (cos(aπ/64) scaled), for a from 0 to + /// 32: the odd rows of the 32-point matrix are 90, 90, 88, 85, …, 4, the odd rows of the 16-point one 90, 87, 80, …, 9, + /// those of the 8-point one 89, 75, 50, 18 and of the 4-point one 83, 36. + /// + internal static readonly byte[] DctCosines = + [ + 64, 90, 90, 90, 89, 88, 87, 85, 83, 82, 80, 78, 75, 73, 70, 67, 64, 61, 57, 54, 50, 46, 43, 38, 36, 31, 25, 22, 18, 13, 9, 4, 0, + ]; + + /// + /// The 32×32 inverse DCT matrix of §8.6.4.2, as transMatrix[k][n] = DctMatrix[k * 32 + n] with k the frequency and n + /// the sample: the 4-, 8- and 16-point matrices are its rows 32/N·k and first N columns. + /// + internal static readonly short[] DctMatrix = BuildDct(); + + /// The 4×4 DST matrix of §8.6.4.2 (trType 1), transMatrix[k][n] = DstMatrix[k * 4 + n]. + internal static readonly short[] DstMatrix = [29, 55, 74, 84, 74, 74, 0, -74, 84, -29, -74, 55, 55, -84, 74, -29]; + + private static short[] BuildDct() + { + var m = new short[32 * 32]; + for (var k = 0; k < 32; k++) + { + for (var n = 0; n < 32; n++) + { + if (k == 0) + { + m[n] = 64; + continue; + } + + // The entry is cos((2n + 1)kπ/64) on the scale of the table: fold the angle into the first quadrant. + var a = ((2 * n) + 1) * k % 128; + int value = a switch + { + <= 32 => DctCosines[a], + <= 64 => -DctCosines[64 - a], + <= 96 => -DctCosines[a - 64], + _ => DctCosines[128 - a], + }; + m[(k * 32) + n] = (short)value; + } + } + + return m; + } + + private static ushort[][][] BuildScans() + { + var scans = new ushort[6][][]; + for (var log2 = 0; log2 < 6; log2++) + { + var size = 1 << log2; + var diagonal = new ushort[size * size]; + int i = 0, x = 0, y = 0; + var stop = false; + while (!stop) + { + while (y >= 0) + { + if (x < size && y < size) + { + diagonal[i++] = (ushort)(x | (y << 8)); + } + + y--; + x++; + } + + y = x; + x = 0; + if (i >= size * size) + { + stop = true; + } + } + + var horizontal = new ushort[size * size]; + var vertical = new ushort[size * size]; + i = 0; + for (y = 0; y < size; y++) + { + for (x = 0; x < size; x++) + { + horizontal[i] = (ushort)(x | (y << 8)); + vertical[i] = (ushort)(y | (x << 8)); + i++; + } + } + + scans[log2] = [diagonal, horizontal, vertical]; + } + + return scans; + } + + private static byte[][] BuildInverse4x4() + { + var inverse = new byte[3][]; + for (var s = 0; s < 3; s++) + { + inverse[s] = new byte[16]; + for (var n = 0; n < 16; n++) + { + var p = ScanOrder[2][s][n]; + inverse[s][((p >> 8) * 4) + (p & 0xFF)] = (byte)n; + } + } + + return inverse; + } +} diff --git a/src/Febe.Core/Codecs/H265/ParameterSets.cs b/src/Febe.Core/Codecs/H265/ParameterSets.cs new file mode 100644 index 0000000..243bd6e --- /dev/null +++ b/src/Febe.Core/Codecs/H265/ParameterSets.cs @@ -0,0 +1,1025 @@ +namespace Febe.Core.Codecs.H265; + +/// A short-term reference picture set (§7.3.7, §7.4.8): the POC deltas of the negative and positive pictures. +internal sealed class ShortTermRps +{ + /// At most sps_max_dec_pic_buffering_minus1 + 1 ≤ 16 pictures in each half. + internal const int MaxPictures = 16; + + internal int NumNegative; + internal int NumPositive; + internal readonly int[] DeltaPocS0 = new int[MaxPictures]; + internal readonly int[] DeltaPocS1 = new int[MaxPictures]; + internal readonly bool[] UsedS0 = new bool[MaxPictures]; + internal readonly bool[] UsedS1 = new bool[MaxPictures]; + + internal int NumDeltaPocs => NumNegative + NumPositive; + + /// + /// st_ref_pic_set(stRpsIdx): is stRpsIdx, the sets already read + /// from the SPS (all of them when the set is in a slice header, where equals their number). + /// + internal static ShortTermRps Parse(BitReader r, int index, int spsCount, IReadOnlyList spsSets) + { + var rps = new ShortTermRps(); + var interPrediction = index != 0 && r.ReadFlag(); + if (interPrediction) + { + var deltaIdx = index == spsCount ? r.ReadUe(index - 1) + 1 : 1; + var reference = spsSets[index - deltaIdx]; + var sign = r.ReadFlag(); + var deltaRps = (r.ReadUe(32767) + 1) * (sign ? -1 : 1); + var count = reference.NumDeltaPocs; + Span used = stackalloc bool[(MaxPictures * 2) + 1]; + Span useDelta = stackalloc bool[(MaxPictures * 2) + 1]; + for (var j = 0; j <= count; j++) + { + used[j] = r.ReadFlag(); + useDelta[j] = used[j] || r.ReadFlag(); + } + + // (7-61) and (7-62). + var i = 0; + for (var j = reference.NumPositive - 1; j >= 0; j--) + { + var dPoc = reference.DeltaPocS1[j] + deltaRps; + if (dPoc < 0 && useDelta[reference.NumNegative + j]) + { + rps.Add0(ref i, dPoc, used[reference.NumNegative + j]); + } + } + + if (deltaRps < 0 && useDelta[count]) + { + rps.Add0(ref i, deltaRps, used[count]); + } + + for (var j = 0; j < reference.NumNegative; j++) + { + var dPoc = reference.DeltaPocS0[j] + deltaRps; + if (dPoc < 0 && useDelta[j]) + { + rps.Add0(ref i, dPoc, used[j]); + } + } + + rps.NumNegative = i; + i = 0; + for (var j = reference.NumNegative - 1; j >= 0; j--) + { + var dPoc = reference.DeltaPocS0[j] + deltaRps; + if (dPoc > 0 && useDelta[j]) + { + rps.Add1(ref i, dPoc, used[j]); + } + } + + if (deltaRps > 0 && useDelta[count]) + { + rps.Add1(ref i, deltaRps, used[count]); + } + + for (var j = 0; j < reference.NumPositive; j++) + { + var dPoc = reference.DeltaPocS1[j] + deltaRps; + if (dPoc > 0 && useDelta[reference.NumNegative + j]) + { + rps.Add1(ref i, dPoc, used[reference.NumNegative + j]); + } + } + + rps.NumPositive = i; + } + else + { + rps.NumNegative = r.ReadUe(MaxPictures); + rps.NumPositive = r.ReadUe(MaxPictures); + if (rps.NumDeltaPocs > MaxPictures) + { + throw new H265Exception("Insieme di riferimento con troppe immagini."); + } + + var poc = 0; + for (var i = 0; i < rps.NumNegative; i++) + { + poc -= r.ReadUe(32767) + 1; + rps.DeltaPocS0[i] = poc; + rps.UsedS0[i] = r.ReadFlag(); + } + + poc = 0; + for (var i = 0; i < rps.NumPositive; i++) + { + poc += r.ReadUe(32767) + 1; + rps.DeltaPocS1[i] = poc; + rps.UsedS1[i] = r.ReadFlag(); + } + } + + return rps; + } + + private void Add0(ref int i, int dPoc, bool used) + { + if (i >= MaxPictures) + { + throw new H265Exception("Insieme di riferimento con troppe immagini."); + } + + DeltaPocS0[i] = dPoc; + UsedS0[i++] = used; + } + + private void Add1(ref int i, int dPoc, bool used) + { + if (i >= MaxPictures) + { + throw new H265Exception("Insieme di riferimento con troppe immagini."); + } + + DeltaPocS1[i] = dPoc; + UsedS1[i++] = used; + } +} + +/// +/// Scaling factors (§7.3.4, §7.4.5): ScalingFactor[sizeId][matrixId] as raster arrays (y * size + x), sizeId 0 to 3 for +/// 4×4 to 32×32 and matrixId 0 to 5 (intra Y, Cb, Cr, then inter Y, Cb, Cr). +/// +internal sealed class ScalingList +{ + private ScalingList() + { + } + + /// Factors[sizeId * 6 + matrixId]. + internal byte[][] Factors { get; } = new byte[24][]; + + /// The lists when scaling_list_enabled_flag is 1 and no list is sent: table 7-5 and table 7-6. + internal static ScalingList Default() + { + var lists = new byte[24][]; + var dc = new int[24]; + for (var sizeId = 0; sizeId < 4; sizeId++) + { + for (var matrixId = 0; matrixId < 6; matrixId++) + { + SetDefault(lists, dc, sizeId, matrixId); + } + } + + return Build(lists, dc); + } + + /// scaling_list_data(). + internal static ScalingList Parse(BitReader r) + { + var lists = new byte[24][]; + var dc = new int[24]; + for (var sizeId = 0; sizeId < 4; sizeId++) + { + var coefNum = Math.Min(64, 1 << (4 + (sizeId << 1))); + for (var matrixId = 0; matrixId < 6; matrixId += sizeId == 3 ? 3 : 1) + { + var id = (sizeId * 6) + matrixId; + if (!r.ReadFlag()) + { + // scaling_list_pred_matrix_id_delta: 0 is the default list, otherwise a copy of an earlier one. + var step = sizeId == 3 ? 3 : 1; + var delta = r.ReadUe(matrixId / step); + if (delta == 0) + { + SetDefault(lists, dc, sizeId, matrixId); + } + else + { + var reference = (sizeId * 6) + matrixId - (delta * step); + lists[id] = lists[reference]; + dc[id] = dc[reference]; + } + } + else + { + var list = new byte[coefNum]; + var nextCoef = 8; + if (sizeId > 1) + { + nextCoef = r.ReadSe(-7, 247) + 8; + dc[id] = nextCoef; + } + + for (var i = 0; i < coefNum; i++) + { + var delta = r.ReadSe(-128, 127); + nextCoef = (nextCoef + delta + 256) % 256; + list[i] = (byte)nextCoef; + } + + lists[id] = list; + if (sizeId <= 1) + { + dc[id] = list[0]; + } + } + } + } + + // 32×32 chroma lists exist only for ChromaArrayType 3 (§7.3.4): they are those of the 16×16 ones. + foreach (var matrixId in (ReadOnlySpan)[1, 2, 4, 5]) + { + lists[18 + matrixId] = lists[12 + matrixId]; + dc[18 + matrixId] = dc[12 + matrixId]; + } + + return Build(lists, dc); + } + + private static void SetDefault(byte[][] lists, int[] dc, int sizeId, int matrixId) + { + var id = (sizeId * 6) + matrixId; + if (sizeId == 0) + { + lists[id] = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16]; + } + else + { + lists[id] = matrixId < 3 ? H265Tables.DefaultScalingIntra : H265Tables.DefaultScalingInter; + } + + dc[id] = 16; + } + + /// ScalingFactor from the lists (7-40 to 7-44): lists in diagonal order, upsampled beyond 8×8, with the DC. + private static ScalingList Build(byte[][] lists, int[] dc) + { + var result = new ScalingList(); + for (var sizeId = 0; sizeId < 4; sizeId++) + { + var size = 4 << sizeId; + var scan = sizeId == 0 ? H265Tables.ScanOrder[2][0] : H265Tables.ScanOrder[3][0]; + var ratio = sizeId <= 1 ? 1 : size / 8; + for (var matrixId = 0; matrixId < 6; matrixId++) + { + var id = (sizeId * 6) + matrixId; + var list = lists[id]; + var factors = new byte[size * size]; + for (var i = 0; i < list.Length; i++) + { + var x = scan[i] & 0xFF; + var y = scan[i] >> 8; + for (var j = 0; j < ratio; j++) + { + for (var k = 0; k < ratio; k++) + { + factors[((y * ratio) + j) * size + (x * ratio) + k] = list[i]; + } + } + } + + if (sizeId >= 2) + { + factors[0] = (byte)dc[id]; + } + + result.Factors[id] = factors; + } + } + + return result; + } +} + +/// A sequence parameter set (§7.3.2.2), with what decoding needs. +internal sealed class Sps +{ + /// MaxLumaPs of level 6.2 (table A.8): the largest picture of any level. + internal const int MaxLumaPs = 35_651_584; + + /// 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; + internal int ChromaFormatIdc; + internal bool SeparateColourPlane; + internal int Width; + internal int Height; + internal int ConfLeft, ConfRight, ConfTop, ConfBottom; + internal int BitDepthY; + internal int BitDepthC; + internal int Log2MaxPocLsb; + internal readonly int[] MaxDecPicBufferingMinus1 = new int[8]; + internal readonly int[] MaxNumReorderPics = new int[8]; + internal readonly int[] MaxLatencyIncreasePlus1 = new int[8]; + internal int Log2MinCbSize; + internal int Log2CtbSize; + internal int Log2MinTbSize; + internal int Log2MaxTbSize; + internal int MaxTransformHierarchyDepthInter; + internal int MaxTransformHierarchyDepthIntra; + internal bool ScalingListEnabled; + internal ScalingList? ScalingList; + internal bool AmpEnabled; + internal bool SaoEnabled; + internal bool PcmEnabled; + internal int PcmBitDepthY; + internal int PcmBitDepthC; + internal int Log2MinPcmCbSize; + internal int Log2MaxPcmCbSize; + internal bool PcmLoopFilterDisabled; + internal readonly List ShortTermRpsList = []; + internal bool LongTermRefsPresent; + internal int NumLongTermRefPicsSps; + internal readonly int[] LtRefPicPocLsbSps = new int[32]; + internal readonly bool[] UsedByCurrPicLtSps = new bool[32]; + internal bool TemporalMvpEnabled; + internal bool StrongIntraSmoothing; + + // Range extension (§7.3.2.2.2): every tool is decoded except extended precision and the bypass alignment. + internal bool TransformSkipRotationEnabled; + internal bool TransformSkipContextEnabled; + internal bool ImplicitRdpcmEnabled; + internal bool ExplicitRdpcmEnabled; + internal bool ExtendedPrecisionProcessing; + internal bool IntraSmoothingDisabled; + internal bool HighPrecisionOffsetsEnabled; + internal bool PersistentRiceAdaptationEnabled; + internal bool CabacBypassAlignmentEnabled; + + /// VUI colour description: matrix_coeffs (2 = unspecified) and video_full_range_flag. + internal int MatrixCoefficients = 2; + + internal bool FullRange; + + internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc; + + internal int SubWidthC => ChromaFormatIdc is 1 or 2 ? 2 : 1; + + internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1; + + internal int CtbSize => 1 << Log2CtbSize; + + internal int WidthInCtbs => (Width + CtbSize - 1) >> Log2CtbSize; + + internal int HeightInCtbs => (Height + CtbSize - 1) >> Log2CtbSize; + + internal int CtbCount => WidthInCtbs * HeightInCtbs; + + internal int QpBdOffsetY => 6 * (BitDepthY - 8); + + internal int QpBdOffsetC => 6 * (BitDepthC - 8); + + 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; + + internal int ChromaShiftY => SubHeightC - 1; + + internal static Sps Parse(BitReader r) + { + var s = new Sps { Raw = RawOf(r) }; + r.Skip(4); // sps_video_parameter_set_id + s.MaxSubLayersMinus1 = r.ReadInt(3); + if (s.MaxSubLayersMinus1 > 6) + { + throw new H265Exception("SPS con troppi sottolivelli temporali."); + } + + r.Skip(1); // sps_temporal_id_nesting_flag + s.ProfileIdc = ProfileTierLevel.Skip(r, true, s.MaxSubLayersMinus1); + s.Id = r.ReadUe(15); + s.ChromaFormatIdc = r.ReadUe(3); + if (s.ChromaFormatIdc == 3) + { + s.SeparateColourPlane = r.ReadFlag(); + } + + s.Width = r.ReadUe(MaxDimension); + s.Height = r.ReadUe(MaxDimension); + if (s.Width == 0 || s.Height == 0 || (long)s.Width * s.Height > MaxLumaPs) + { + throw new H265Exception("Dimensioni dell'immagine HEVC non valide."); + } + + if (r.ReadFlag()) + { + s.ConfLeft = r.ReadUe(MaxDimension) * s.SubWidthC; + s.ConfRight = r.ReadUe(MaxDimension) * s.SubWidthC; + s.ConfTop = r.ReadUe(MaxDimension) * s.SubHeightC; + s.ConfBottom = r.ReadUe(MaxDimension) * s.SubHeightC; + if (s.ConfLeft + s.ConfRight >= s.Width || s.ConfTop + s.ConfBottom >= s.Height) + { + throw new H265Exception("Finestra di conformità che non lascia immagine."); + } + } + + s.BitDepthY = r.ReadUe(8) + 8; + 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); + } + + if (!orderingInfo) + { + for (var i = 0; i < s.MaxSubLayersMinus1; i++) + { + s.MaxDecPicBufferingMinus1[i] = s.MaxDecPicBufferingMinus1[s.MaxSubLayersMinus1]; + s.MaxNumReorderPics[i] = s.MaxNumReorderPics[s.MaxSubLayersMinus1]; + s.MaxLatencyIncreasePlus1[i] = s.MaxLatencyIncreasePlus1[s.MaxSubLayersMinus1]; + } + } + + s.Log2MinCbSize = r.ReadUe(3) + 3; + s.Log2CtbSize = s.Log2MinCbSize + r.ReadUe(3); + s.Log2MinTbSize = r.ReadUe(3) + 2; + s.Log2MaxTbSize = s.Log2MinTbSize + r.ReadUe(3); + if (s.Log2CtbSize > 6 || s.Log2CtbSize < 4 || s.Log2MinTbSize >= s.Log2MinCbSize || s.Log2MaxTbSize > Math.Min(s.Log2CtbSize, 5) + || s.Width % (1 << s.Log2MinCbSize) != 0 || s.Height % (1 << s.Log2MinCbSize) != 0) + { + throw new H265Exception("Dimensioni dei blocchi HEVC non valide."); + } + + s.MaxTransformHierarchyDepthInter = r.ReadUe(s.Log2CtbSize - s.Log2MinTbSize); + s.MaxTransformHierarchyDepthIntra = r.ReadUe(s.Log2CtbSize - s.Log2MinTbSize); + s.ScalingListEnabled = r.ReadFlag(); + if (s.ScalingListEnabled) + { + s.ScalingList = r.ReadFlag() ? ScalingList.Parse(r) : ScalingList.Default(); + } + + s.AmpEnabled = r.ReadFlag(); + s.SaoEnabled = r.ReadFlag(); + s.PcmEnabled = r.ReadFlag(); + if (s.PcmEnabled) + { + s.PcmBitDepthY = r.ReadInt(4) + 1; + s.PcmBitDepthC = r.ReadInt(4) + 1; + s.Log2MinPcmCbSize = r.ReadUe(2) + 3; + s.Log2MaxPcmCbSize = s.Log2MinPcmCbSize + r.ReadUe(2); + s.PcmLoopFilterDisabled = r.ReadFlag(); + if (s.PcmBitDepthY > s.BitDepthY || s.PcmBitDepthC > s.BitDepthC || s.Log2MaxPcmCbSize > Math.Min(s.Log2CtbSize, 5)) + { + throw new H265Exception("Parametri PCM non validi."); + } + } + + var count = r.ReadUe(64); + for (var i = 0; i < count; i++) + { + s.ShortTermRpsList.Add(ShortTermRps.Parse(r, i, count, s.ShortTermRpsList)); + } + + s.LongTermRefsPresent = r.ReadFlag(); + if (s.LongTermRefsPresent) + { + s.NumLongTermRefPicsSps = r.ReadUe(32); + for (var i = 0; i < s.NumLongTermRefPicsSps; i++) + { + s.LtRefPicPocLsbSps[i] = r.ReadInt(s.Log2MaxPocLsb); + s.UsedByCurrPicLtSps[i] = r.ReadFlag(); + } + } + + s.TemporalMvpEnabled = r.ReadFlag(); + s.StrongIntraSmoothing = r.ReadFlag(); + if (r.ReadFlag()) + { + Vui.Parse(r, s); + } + + if (r.ReadFlag()) + { + var range = r.ReadFlag(); + 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(); + s.TransformSkipContextEnabled = r.ReadFlag(); + s.ImplicitRdpcmEnabled = r.ReadFlag(); + s.ExplicitRdpcmEnabled = r.ReadFlag(); + s.ExtendedPrecisionProcessing = r.ReadFlag(); + s.IntraSmoothingDisabled = r.ReadFlag(); + s.HighPrecisionOffsetsEnabled = r.ReadFlag(); + s.PersistentRiceAdaptationEnabled = r.ReadFlag(); + s.CabacBypassAlignmentEnabled = r.ReadFlag(); + } + + // 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; + } +} + +/// profile_tier_level() (§7.3.3): skipped, except general_profile_idc. +internal static class ProfileTierLevel +{ + internal static int Skip(BitReader r, bool profilePresent, int maxSubLayersMinus1) + { + var profileIdc = 0; + if (profilePresent) + { + r.Skip(3); // general_profile_space, general_tier_flag + profileIdc = r.ReadInt(5); + r.Skip(32 + 48); // compatibility flags, constraint flags + } + + r.Skip(8); // general_level_idc + Span profile = stackalloc bool[8]; + Span level = stackalloc bool[8]; + for (var i = 0; i < maxSubLayersMinus1; i++) + { + profile[i] = r.ReadFlag(); + level[i] = r.ReadFlag(); + } + + if (maxSubLayersMinus1 > 0) + { + r.Skip(2 * (8 - maxSubLayersMinus1)); + } + + for (var i = 0; i < maxSubLayersMinus1; i++) + { + if (profile[i]) + { + r.Skip(88); + } + + if (level[i]) + { + r.Skip(8); + } + } + + return profileIdc; + } +} + +/// vui_parameters() (Annex E): only the colour description is kept. +internal static class Vui +{ + internal static void Parse(BitReader r, Sps s) + { + if (r.ReadFlag() && r.ReadInt(8) == 255) + { + r.Skip(32); // sar_width, sar_height + } + + if (r.ReadFlag()) + { + r.Skip(1); // overscan_appropriate_flag + } + + if (r.ReadFlag()) + { + r.Skip(3); // video_format + s.FullRange = r.ReadFlag(); + if (r.ReadFlag()) + { + r.Skip(16); // colour_primaries, transfer_characteristics + s.MatrixCoefficients = r.ReadInt(8); + } + } + + if (r.ReadFlag()) + { + r.ReadUe(); + r.ReadUe(); + } + + r.Skip(3); // neutral_chroma_indication_flag, field_seq_flag, frame_field_info_present_flag + if (r.ReadFlag()) + { + for (var i = 0; i < 4; i++) + { + r.ReadUe(); // default display window + } + } + + if (r.ReadFlag()) + { + r.Skip(64); // vui_num_units_in_tick, vui_time_scale + if (r.ReadFlag()) + { + r.ReadUe(); // vui_num_ticks_poc_diff_one_minus1 + } + + if (r.ReadFlag()) + { + Hrd(r, true, s.MaxSubLayersMinus1); + } + } + + if (r.ReadFlag()) + { + r.Skip(3); // tiles_fixed_structure_flag, motion_vectors_over_pic_boundaries_flag, restricted_ref_pic_lists_flag + for (var i = 0; i < 5; i++) + { + r.ReadUe(); + } + } + } + + /// hrd_parameters() (E.2.2), skipped. + internal static void Hrd(BitReader r, bool commonInfo, int maxSubLayersMinus1) + { + bool nal = false, vcl = false, subPic = false; + if (commonInfo) + { + nal = r.ReadFlag(); + vcl = r.ReadFlag(); + if (nal || vcl) + { + subPic = r.ReadFlag(); + if (subPic) + { + r.Skip(8 + 5 + 1 + 5); + } + + r.Skip(8); // bit_rate_scale, cpb_size_scale + if (subPic) + { + r.Skip(4); + } + + r.Skip(15); + } + } + + for (var i = 0; i <= maxSubLayersMinus1; i++) + { + var fixedGeneral = r.ReadFlag(); + var fixedWithinCvs = fixedGeneral || r.ReadFlag(); + var lowDelay = false; + if (fixedWithinCvs) + { + r.ReadUe(); + } + else + { + lowDelay = r.ReadFlag(); + } + + var cpbCount = lowDelay ? 1 : r.ReadUe(31) + 1; + for (var k = (nal ? 1 : 0) + (vcl ? 1 : 0); k > 0; k--) + { + for (var j = 0; j < cpbCount; j++) + { + r.ReadUe(); + r.ReadUe(); + if (subPic) + { + r.ReadUe(); + r.ReadUe(); + } + + r.Skip(1); + } + } + } + } +} + +/// A picture parameter set (§7.3.2.3), with what decoding needs. +internal sealed class Pps +{ + internal int Id; + internal int SpsId; + internal bool DependentSliceSegmentsEnabled; + internal bool OutputFlagPresent; + internal int NumExtraSliceHeaderBits; + internal bool SignDataHidingEnabled; + internal bool CabacInitPresent; + internal int NumRefIdxL0DefaultActive; + internal int NumRefIdxL1DefaultActive; + internal int InitQp; + internal bool ConstrainedIntraPred; + internal bool TransformSkipEnabled; + internal bool CuQpDeltaEnabled; + internal int DiffCuQpDeltaDepth; + internal int CbQpOffset; + internal int CrQpOffset; + internal bool SliceChromaQpOffsetsPresent; + internal bool WeightedPred; + internal bool WeightedBipred; + internal bool TransquantBypassEnabled; + internal bool TilesEnabled; + internal bool EntropyCodingSyncEnabled; + internal int NumTileColumns = 1; + internal int NumTileRows = 1; + internal bool UniformSpacing = true; + internal int[] ColumnWidths = []; + internal int[] RowHeights = []; + internal bool LoopFilterAcrossTilesEnabled = true; + internal bool LoopFilterAcrossSlicesEnabled; + internal bool DeblockingFilterOverrideEnabled; + internal bool DeblockingFilterDisabled; + internal int BetaOffsetDiv2; + internal int TcOffsetDiv2; + internal ScalingList? ScalingList; + internal bool ListsModificationPresent; + internal int Log2ParallelMergeLevel; + internal bool SliceSegmentHeaderExtensionPresent; + + // Range extension (§7.3.2.3.2). + internal int Log2MaxTransformSkipSize = 2; + internal bool CrossComponentPredictionEnabled; + internal bool ChromaQpOffsetListEnabled; + internal int DiffCuChromaQpOffsetDepth; + internal int ChromaQpOffsetListLength; + internal readonly int[] CbQpOffsetList = new int[6]; + internal readonly int[] CrQpOffsetList = new int[6]; + 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; + + /// CtbAddrRsToTs, CtbAddrTsToRs and TileId (by raster address) of §6.5.1. + internal int[] CtbAddrRsToTs = []; + + internal int[] CtbAddrTsToRs = []; + internal int[] TileIdRs = []; + + /// colBd and rowBd: the first CTB column and row of each tile, with one more entry for the end. + internal int[] ColBd = []; + + internal int[] RowBd = []; + + internal static Pps Parse(BitReader r) + { + var p = new Pps + { + Raw = Sps.RawOf(r), + Id = r.ReadUe(63), + SpsId = r.ReadUe(15), + DependentSliceSegmentsEnabled = r.ReadFlag(), + OutputFlagPresent = r.ReadFlag(), + NumExtraSliceHeaderBits = r.ReadInt(3), + SignDataHidingEnabled = r.ReadFlag(), + CabacInitPresent = r.ReadFlag(), + NumRefIdxL0DefaultActive = r.ReadUe(14) + 1, + NumRefIdxL1DefaultActive = r.ReadUe(14) + 1, + InitQp = 26 + r.ReadSe(-26 - 36, 25), + ConstrainedIntraPred = r.ReadFlag(), + TransformSkipEnabled = r.ReadFlag(), + CuQpDeltaEnabled = r.ReadFlag(), + }; + if (p.CuQpDeltaEnabled) + { + p.DiffCuQpDeltaDepth = r.ReadUe(3); + } + + p.CbQpOffset = r.ReadSe(-12, 12); + p.CrQpOffset = r.ReadSe(-12, 12); + p.SliceChromaQpOffsetsPresent = r.ReadFlag(); + p.WeightedPred = r.ReadFlag(); + p.WeightedBipred = r.ReadFlag(); + p.TransquantBypassEnabled = r.ReadFlag(); + p.TilesEnabled = r.ReadFlag(); + p.EntropyCodingSyncEnabled = r.ReadFlag(); + if (p.TilesEnabled) + { + p.NumTileColumns = r.ReadUe(1055) + 1; + p.NumTileRows = r.ReadUe(1055) + 1; + p.UniformSpacing = r.ReadFlag(); + if (!p.UniformSpacing) + { + p.ColumnWidths = new int[p.NumTileColumns]; + p.RowHeights = new int[p.NumTileRows]; + for (var i = 0; i < p.NumTileColumns - 1; i++) + { + p.ColumnWidths[i] = r.ReadUe(1055) + 1; + } + + for (var i = 0; i < p.NumTileRows - 1; i++) + { + p.RowHeights[i] = r.ReadUe(1055) + 1; + } + } + + p.LoopFilterAcrossTilesEnabled = r.ReadFlag(); + } + + p.LoopFilterAcrossSlicesEnabled = r.ReadFlag(); + if (r.ReadFlag()) + { + p.DeblockingFilterOverrideEnabled = r.ReadFlag(); + p.DeblockingFilterDisabled = r.ReadFlag(); + if (!p.DeblockingFilterDisabled) + { + p.BetaOffsetDiv2 = r.ReadSe(-6, 6); + p.TcOffsetDiv2 = r.ReadSe(-6, 6); + } + } + + if (r.ReadFlag()) + { + p.ScalingList = ScalingList.Parse(r); + } + + p.ListsModificationPresent = r.ReadFlag(); + p.Log2ParallelMergeLevel = r.ReadUe(4) + 2; + p.SliceSegmentHeaderExtensionPresent = r.ReadFlag(); + if (r.ReadFlag()) + { + var range = r.ReadFlag(); + 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) + { + p.Log2MaxTransformSkipSize = r.ReadUe(3) + 2; + } + + p.CrossComponentPredictionEnabled = r.ReadFlag(); + p.ChromaQpOffsetListEnabled = r.ReadFlag(); + if (p.ChromaQpOffsetListEnabled) + { + p.DiffCuChromaQpOffsetDepth = r.ReadUe(3); + p.ChromaQpOffsetListLength = r.ReadUe(5) + 1; + for (var i = 0; i < p.ChromaQpOffsetListLength; i++) + { + p.CbQpOffsetList[i] = r.ReadSe(-12, 12); + p.CrQpOffsetList[i] = r.ReadSe(-12, 12); + } + } + + p.Log2SaoOffsetScaleLuma = r.ReadUe(6); + p.Log2SaoOffsetScaleChroma = r.ReadUe(6); + } + } + + return p; + } + + /// Computes the tile layout and the scan conversions of §6.5.1 for , once. + internal void Activate(Sps sps) + { + if (ReferenceEquals(layoutSps, sps)) + { + return; + } + + int w = sps.WidthInCtbs, h = sps.HeightInCtbs; + if (NumTileColumns > w || NumTileRows > h) + { + throw new H265Exception("Più tile che CTB."); + } + + var colWidth = new int[NumTileColumns]; + var rowHeight = new int[NumTileRows]; + if (UniformSpacing) + { + for (var i = 0; i < NumTileColumns; i++) + { + colWidth[i] = ((i + 1) * w / NumTileColumns) - (i * w / NumTileColumns); + } + + for (var j = 0; j < NumTileRows; j++) + { + rowHeight[j] = ((j + 1) * h / NumTileRows) - (j * h / NumTileRows); + } + } + else + { + var rest = w; + for (var i = 0; i < NumTileColumns - 1; i++) + { + colWidth[i] = ColumnWidths[i]; + rest -= colWidth[i]; + } + + colWidth[NumTileColumns - 1] = rest; + rest = h; + for (var j = 0; j < NumTileRows - 1; j++) + { + rowHeight[j] = RowHeights[j]; + rest -= rowHeight[j]; + } + + rowHeight[NumTileRows - 1] = rest; + if (colWidth[NumTileColumns - 1] <= 0 || rowHeight[NumTileRows - 1] <= 0) + { + throw new H265Exception("Tile più larghe dell'immagine."); + } + } + + ColBd = new int[NumTileColumns + 1]; + RowBd = new int[NumTileRows + 1]; + for (var i = 0; i < NumTileColumns; i++) + { + ColBd[i + 1] = ColBd[i] + colWidth[i]; + } + + for (var j = 0; j < NumTileRows; j++) + { + RowBd[j + 1] = RowBd[j] + rowHeight[j]; + } + + var count = w * h; + CtbAddrRsToTs = new int[count]; + CtbAddrTsToRs = new int[count]; + TileIdRs = new int[count]; + for (var rs = 0; rs < count; rs++) + { + int tbX = rs % w, tbY = rs / w; + int tileX = 0, tileY = 0; + for (var i = 0; i < NumTileColumns; i++) + { + if (tbX >= ColBd[i]) + { + tileX = i; + } + } + + for (var j = 0; j < NumTileRows; j++) + { + if (tbY >= RowBd[j]) + { + tileY = j; + } + } + + var v = 0; + for (var i = 0; i < tileX; i++) + { + v += rowHeight[tileY] * colWidth[i]; + } + + for (var j = 0; j < tileY; j++) + { + v += w * rowHeight[j]; + } + + v += ((tbY - RowBd[tileY]) * colWidth[tileX]) + tbX - ColBd[tileX]; + CtbAddrRsToTs[rs] = v; + CtbAddrTsToRs[v] = rs; + TileIdRs[rs] = (tileY * NumTileColumns) + tileX; + } + + layoutSps = sps; + } +} diff --git a/src/Febe.Core/Codecs/H265/Picture.cs b/src/Febe.Core/Codecs/H265/Picture.cs new file mode 100644 index 0000000..fd90641 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/Picture.cs @@ -0,0 +1,189 @@ +namespace Febe.Core.Codecs.H265; + +/// +/// A decoded HEVC picture in the decoded picture buffer: its sample arrays at full size (pic_width_in_luma_samples × +/// pic_height_in_luma_samples, before the conformance window), one 16-bit value per sample whatever the bit depth, and +/// its state for reference and output (§8.3.2, C.5.2). +/// +internal sealed class Picture +{ + internal Picture(Sps sps) + { + Sps = sps; + Width = sps.Width; + Height = sps.Height; + ChromaWidth = sps.ChromaArrayType == 0 ? 0 : Width / sps.SubWidthC; + ChromaHeight = sps.ChromaArrayType == 0 ? 0 : Height / sps.SubHeightC; + Planes = + [ + new ushort[Width * Height], + new ushort[ChromaWidth * ChromaHeight], + new ushort[ChromaWidth * ChromaHeight], + ]; + Motion = new MvField[((Width + 3) >> 2) * ((Height + 3) >> 2)]; + } + + /// The SPS of the picture: a picture of the pool is reused for another SPS of the same size. + internal Sps Sps { get; set; } + + internal int Width { get; } + + internal int Height { get; } + + internal int ChromaWidth { get; } + + internal int ChromaHeight { get; } + + /// Y, Cb and Cr; the chroma arrays are empty for 4:0:0. + internal ushort[][] Planes { get; } + + internal int Poc; + + internal bool ShortTerm; + + internal bool LongTerm; + + /// Marked "needed for output" (C.5.2). + internal bool NeededForOutput; + + internal bool OutputFlag; + + internal int LatencyCount; + + /// Position of the coded picture in decoding order, counting the pictures that are skipped too. + internal long DecodeIndex; + + /// A picture generated for a missing reference (§8.3.3): never output, its samples are not meaningful. + internal bool Generated; + + /// Every slice of the picture is an I slice: it does not depend on other pictures. + internal bool IntraOnly; + + /// The motion of every 4×4 luma block (§8.5.3), kept for the pictures that take this one as collocated (TMVP). + internal MvField[] Motion { get; } + + /// Index in of the slice of each CTB (raster order), −1 where none was decoded. + internal int[] CtbSlice = []; + + /// The independent slice segment headers of the picture, with their reference picture lists. + internal List Slices { get; } = []; + + internal bool IsReference => ShortTerm || LongTerm; + + internal int Stride(int cIdx) => cIdx == 0 ? Width : ChromaWidth; + + internal int BitDepth(int cIdx) => cIdx == 0 ? Sps.BitDepthY : Sps.BitDepthC; + + internal bool Fits(Sps sps) => Width == sps.Width && Height == sps.Height && ChromaWidth == (sps.ChromaArrayType == 0 ? 0 : sps.Width / sps.SubWidthC) + && ChromaHeight == (sps.ChromaArrayType == 0 ? 0 : sps.Height / sps.SubHeightC); + + /// The picture cropped to the conformance window. + internal H265Frame ToFrame() + { + var s = Sps; + var width = Width - s.ConfLeft - s.ConfRight; + var height = Height - s.ConfTop - s.ConfBottom; + var y = Crop(Planes[0], Width, s.ConfLeft, s.ConfTop, width, height); + ushort[] cb = [], cr = []; + if (s.ChromaArrayType != 0) + { + int cx = s.ConfLeft / s.SubWidthC, cy = s.ConfTop / s.SubHeightC; + int cw = width / s.SubWidthC, ch = height / s.SubHeightC; + cb = Crop(Planes[1], ChromaWidth, cx, cy, cw, ch); + cr = Crop(Planes[2], ChromaWidth, cx, cy, cw, ch); + } + + return new H265Frame(width, height, s.ChromaArrayType, s.BitDepthY, s.BitDepthC, y, cb, cr, Poc, DecodeIndex, s.MatrixCoefficients, s.FullRange); + } + + private static ushort[] Crop(ushort[] plane, int stride, int x0, int y0, int width, int height) + { + var result = GC.AllocateUninitializedArray(width * height); + for (var y = 0; y < height; y++) + { + plane.AsSpan(((y0 + y) * stride) + x0, width).CopyTo(result.AsSpan(y * width, width)); + } + + return result; + } +} + +/// +/// The motion of a prediction block: a motion vector in quarter luma samples and a reference index for each list, the +/// index −1 when the list is not used (both −1 for an intra block). An unused list always has a zero vector, so that +/// equal motion means equal fields. +/// +internal struct MvField +{ + internal static readonly MvField Intra = new() { Ref0 = -1, Ref1 = -1 }; + + internal short X0; + internal short Y0; + internal short X1; + internal short Y1; + internal sbyte Ref0; + internal sbyte Ref1; + + internal readonly bool SameAs(in MvField other) => + X0 == other.X0 && Y0 == other.Y0 && X1 == other.X1 && Y1 == other.Y1 && Ref0 == other.Ref0 && Ref1 == other.Ref1; +} + +/// A decoded HEVC frame, cropped to the conformance window, with one 16-bit value per sample. +/// Luma width after cropping. +/// Luma height after cropping. +/// ChromaArrayType: 0 (only luma), 1 (4:2:0), 2 (4:2:2), 3 (4:4:4). +/// Bits per luma sample. +/// Bits per chroma sample. +/// Luma, × . +/// Blue-difference chroma (empty for 4:0:0). +/// Red-difference chroma, same size as . +/// Picture order count. +/// Position of the coded picture in decoding order. +/// matrix_coeffs of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified). +/// video_full_range_flag of the VUI. +public sealed record H265Frame( + int Width, + int Height, + int ChromaFormat, + int BitDepthLuma, + int BitDepthChroma, + ushort[] Y, + ushort[] Cb, + ushort[] Cr, + int Poc, + long DecodeIndex, + int MatrixCoefficients, + bool FullRange) +{ + /// + /// The frame as reference decoders write it: Y, Cb and Cr one after the other, one byte per sample up to 8 bits, + /// otherwise two bytes (the low one first) for every plane. + /// + public byte[] ToYuvFile() + { + var wide = Math.Max(BitDepthLuma, BitDepthChroma) > 8; + var count = Y.Length + Cb.Length + Cr.Length; + var buffer = new byte[wide ? count * 2 : count]; + var position = 0; + foreach (var plane in (ReadOnlySpan)[Y, Cb, Cr]) + { + if (wide) + { + foreach (var sample in plane) + { + buffer[position++] = (byte)sample; + buffer[position++] = (byte)(sample >> 8); + } + } + else + { + foreach (var sample in plane) + { + buffer[position++] = (byte)sample; + } + } + } + + return buffer; + } +} diff --git a/src/Febe.Core/Codecs/H265/SliceHeader.cs b/src/Febe.Core/Codecs/H265/SliceHeader.cs new file mode 100644 index 0000000..ae87d82 --- /dev/null +++ b/src/Febe.Core/Codecs/H265/SliceHeader.cs @@ -0,0 +1,498 @@ +namespace Febe.Core.Codecs.H265; + +/// slice_type (§7.4.7.1). +internal enum SliceType +{ + B = 0, + P = 1, + I = 2, +} + +/// +/// A slice segment header (§7.3.6). A dependent slice segment starts as a copy of the header of the independent slice +/// segment before it (§7.4.7.1) and only reads its own address and entry points. +/// +internal sealed class SliceHeader +{ + internal bool FirstSliceSegmentInPic; + internal bool NoOutputOfPriorPics; + internal int PpsId; + internal bool Dependent; + internal int SegmentAddress; + + /// SliceAddrRs: the address of the first CTB of the slice (of its independent slice segment). + internal int SliceAddress; + + internal SliceType Type; + internal bool PicOutputFlag = true; + internal int ColourPlaneId; + internal int PocLsb; + internal ShortTermRps? StRps; + internal int NumLongTermSps; + internal int NumLongTermPics; + internal int[] PocLsbLt = []; + internal bool[] UsedByCurrPicLt = []; + internal bool[] DeltaPocMsbPresent = []; + internal int[] DeltaPocMsbCycleLt = []; + internal bool TemporalMvpEnabled; + internal bool SaoLuma; + internal bool SaoChroma; + internal readonly int[] NumRefIdxActive = new int[2]; + internal readonly bool[] ListModification = new bool[2]; + internal readonly int[][] ListEntry = [new int[16], new int[16]]; + internal bool MvdL1Zero; + internal bool CabacInit; + internal bool CollocatedFromL0 = true; + internal int CollocatedRefIdx; + internal int LumaLog2WeightDenom; + internal int ChromaLog2WeightDenom; + + /// LumaWeightLX and luma_offset_lX by [list][refIdx] (§7.4.7.3). + internal readonly int[][] LumaWeight = [new int[16], new int[16]]; + + internal readonly int[][] LumaOffset = [new int[16], new int[16]]; + + /// ChromaWeightLX and ChromaOffsetLX by [list][refIdx * 2 + (cIdx − 1)]. + internal readonly int[][] ChromaWeight = [new int[32], new int[32]]; + + internal readonly int[][] ChromaOffset = [new int[32], new int[32]]; + internal int MaxNumMergeCand = 5; + internal int SliceQpY; + internal int CbQpOffset; + internal int CrQpOffset; + internal bool CuChromaQpOffsetEnabled; + internal bool DeblockingDisabled; + internal int BetaOffsetDiv2; + internal int TcOffsetDiv2; + internal bool LoopFilterAcrossSlices; + internal int NumEntryPoints; + internal int[] EntryPointOffsets = []; + + /// RefPicList0 and RefPicList1 (§8.3.4) of the slice, by [list][refIdx]. + internal readonly Picture[][] RefPicList = [new Picture[16], new Picture[16]]; + + /// PicOrderCntVal of each entry of , kept for the pictures that use this one as collocated. + internal readonly int[][] RefPoc = [new int[16], new int[16]]; + + /// Whether each entry of is a long-term reference picture (LongTermRefPic of §8.5.3.2.8). + internal readonly bool[][] RefIsLongTerm = [new bool[16], new bool[16]]; + + /// ColPic (§8.5.3.2.8), when slice_temporal_mvp_enabled_flag is 1. + internal Picture? ColPic; + + /// NoBackwardPredFlag (§8.5.3.2.9): no reference picture follows the current one in output order. + internal bool NoBackwardPred; + + /// NumPicTotalCurr (7-55). + internal int NumPicTotalCurr; + + /// The byte where slice_segment_data() starts in the RBSP. + internal int DataOffset; + + internal bool IsIntra => Type == SliceType.I; + + internal int InitType => Type switch + { + SliceType.I => 0, + SliceType.P => CabacInit ? 2 : 1, + _ => CabacInit ? 1 : 2, + }; + + /// + /// Reads a slice segment header. is the header of the last independent slice segment of + /// the current picture (for a dependent one); and are those it refers to. + /// + internal static SliceHeader Parse( + BitReader r, int nalType, Sps?[] spss, Pps?[] ppss, SliceHeader? previous, out Sps sps, out Pps pps) + { + var first = r.ReadFlag(); + var noOutputOfPriorPics = nalType is >= 16 and <= 23 && r.ReadFlag(); + var ppsId = r.ReadUe(63); + pps = ppss[ppsId] ?? throw new H265Exception("Slice con un PPS sconosciuto."); + sps = spss[pps.SpsId] ?? throw new H265Exception("PPS con un SPS sconosciuto."); + var dependent = false; + var address = 0; + if (!first) + { + if (pps.DependentSliceSegmentsEnabled) + { + dependent = r.ReadFlag(); + } + + var bits = CeilLog2(sps.CtbCount); + address = r.ReadInt(bits); + if (address >= sps.CtbCount) + { + throw new H265Exception("Indirizzo di slice fuori dall'immagine."); + } + } + + SliceHeader h; + if (dependent) + { + if (previous is null || previous.PpsId != ppsId) + { + throw new H265Exception("Segmento di slice dipendente senza la sua slice."); + } + + h = previous.CloneForDependent(); + h.Dependent = true; + h.FirstSliceSegmentInPic = false; + h.SegmentAddress = address; + } + else + { + h = new SliceHeader + { + FirstSliceSegmentInPic = first, + NoOutputOfPriorPics = noOutputOfPriorPics, + PpsId = ppsId, + SegmentAddress = address, + SliceAddress = address, + }; + h.ParseIndependent(r, nalType, sps, pps); + } + + h.NumEntryPoints = 0; + h.EntryPointOffsets = []; + if (pps.TilesEnabled || pps.EntropyCodingSyncEnabled) + { + h.NumEntryPoints = r.ReadUe(sps.CtbCount); + if (h.NumEntryPoints > 0) + { + var length = r.ReadUe(31) + 1; + h.EntryPointOffsets = new int[h.NumEntryPoints]; + for (var i = 0; i < h.NumEntryPoints; i++) + { + h.EntryPointOffsets[i] = (int)Math.Min(r.Read(length) + 1L, int.MaxValue); + } + } + } + + if (pps.SliceSegmentHeaderExtensionPresent) + { + var length = r.ReadUe(256); + r.Skip(length * 8); + } + + // byte_alignment(): a one, then zeros up to the byte boundary. + if (!r.ReadFlag()) + { + throw new H265Exception("Allineamento dell'intestazione di slice non valido."); + } + + r.AlignToByte(); + if (r.BitsLeft <= 0) + { + throw new H265Exception("Slice senza dati."); + } + + h.DataOffset = r.Position >> 3; + return h; + } + + private static int CeilLog2(int value) + { + var bits = 0; + while ((1 << bits) < value) + { + bits++; + } + + return bits; + } + + private SliceHeader CloneForDependent() => (SliceHeader)MemberwiseClone(); + + private void ParseIndependent(BitReader r, int nalType, Sps sps, Pps pps) + { + r.Skip(pps.NumExtraSliceHeaderBits); + var type = r.ReadUe(2); + Type = (SliceType)type; + if (pps.OutputFlagPresent) + { + PicOutputFlag = r.ReadFlag(); + } + + if (sps.SeparateColourPlane) + { + ColourPlaneId = r.ReadInt(2); + } + + if (nalType != 19 && nalType != 20) + { + PocLsb = r.ReadInt(sps.Log2MaxPocLsb); + var count = sps.ShortTermRpsList.Count; + if (!r.ReadFlag()) + { + StRps = ShortTermRps.Parse(r, count, count, sps.ShortTermRpsList); + } + else + { + if (count == 0) + { + throw new H265Exception("Insieme di riferimento dell'SPS che non c'è."); + } + + var index = count > 1 ? r.ReadInt(CeilLog2(count)) : 0; + if (index >= count) + { + throw new H265Exception("Insieme di riferimento dell'SPS che non c'è."); + } + + StRps = sps.ShortTermRpsList[index]; + } + + if (sps.LongTermRefsPresent) + { + if (sps.NumLongTermRefPicsSps > 0) + { + NumLongTermSps = r.ReadUe(sps.NumLongTermRefPicsSps); + } + + NumLongTermPics = r.ReadUe(32); + var total = NumLongTermSps + NumLongTermPics; + if (total > 32) + { + throw new H265Exception("Troppi riferimenti a lungo termine."); + } + + PocLsbLt = new int[total]; + UsedByCurrPicLt = new bool[total]; + DeltaPocMsbPresent = new bool[total]; + DeltaPocMsbCycleLt = new int[total]; + for (var i = 0; i < total; i++) + { + if (i < NumLongTermSps) + { + var index = sps.NumLongTermRefPicsSps > 1 ? r.ReadInt(CeilLog2(sps.NumLongTermRefPicsSps)) : 0; + if (index >= sps.NumLongTermRefPicsSps) + { + throw new H265Exception("Riferimento a lungo termine dell'SPS che non c'è."); + } + + PocLsbLt[i] = sps.LtRefPicPocLsbSps[index]; + UsedByCurrPicLt[i] = sps.UsedByCurrPicLtSps[index]; + } + else + { + PocLsbLt[i] = r.ReadInt(sps.Log2MaxPocLsb); + UsedByCurrPicLt[i] = r.ReadFlag(); + } + + DeltaPocMsbPresent[i] = r.ReadFlag(); + var cycle = DeltaPocMsbPresent[i] ? (int)Math.Min(r.ReadUe(), 1u << 24) : 0; + + // (7-52): the cycles accumulate, separately for the SPS candidates and the others. + DeltaPocMsbCycleLt[i] = i == 0 || i == NumLongTermSps ? cycle : cycle + DeltaPocMsbCycleLt[i - 1]; + } + } + + if (sps.TemporalMvpEnabled) + { + TemporalMvpEnabled = r.ReadFlag(); + } + } + + if (sps.SaoEnabled) + { + SaoLuma = r.ReadFlag(); + if (sps.ChromaArrayType != 0) + { + SaoChroma = r.ReadFlag(); + } + } + + NumPicTotalCurr = 0; + if (StRps is { } rps) + { + for (var i = 0; i < rps.NumNegative; i++) + { + NumPicTotalCurr += rps.UsedS0[i] ? 1 : 0; + } + + for (var i = 0; i < rps.NumPositive; i++) + { + NumPicTotalCurr += rps.UsedS1[i] ? 1 : 0; + } + } + + foreach (var used in UsedByCurrPicLt) + { + NumPicTotalCurr += used ? 1 : 0; + } + + if (Type != SliceType.I) + { + NumRefIdxActive[0] = pps.NumRefIdxL0DefaultActive; + NumRefIdxActive[1] = Type == SliceType.B ? pps.NumRefIdxL1DefaultActive : 0; + if (r.ReadFlag()) + { + NumRefIdxActive[0] = r.ReadUe(14) + 1; + if (Type == SliceType.B) + { + NumRefIdxActive[1] = r.ReadUe(14) + 1; + } + } + + if (NumPicTotalCurr == 0) + { + throw new H265Exception("Slice P o B senza immagini di riferimento."); + } + + if (pps.ListsModificationPresent && NumPicTotalCurr > 1) + { + var bits = CeilLog2(NumPicTotalCurr); + for (var list = 0; list < (Type == SliceType.B ? 2 : 1); list++) + { + ListModification[list] = r.ReadFlag(); + if (ListModification[list]) + { + for (var i = 0; i < NumRefIdxActive[list]; i++) + { + ListEntry[list][i] = r.ReadInt(bits); + if (ListEntry[list][i] >= NumPicTotalCurr) + { + throw new H265Exception("Modifica della lista di riferimento non valida."); + } + } + } + } + } + + if (Type == SliceType.B) + { + MvdL1Zero = r.ReadFlag(); + } + + if (pps.CabacInitPresent) + { + CabacInit = r.ReadFlag(); + } + + if (TemporalMvpEnabled) + { + if (Type == SliceType.B) + { + CollocatedFromL0 = r.ReadFlag(); + } + + if (NumRefIdxActive[CollocatedFromL0 ? 0 : 1] > 1) + { + CollocatedRefIdx = r.ReadUe(NumRefIdxActive[CollocatedFromL0 ? 0 : 1] - 1); + } + } + + if ((pps.WeightedPred && Type == SliceType.P) || (pps.WeightedBipred && Type == SliceType.B)) + { + ParsePredWeightTable(r, sps); + } + + MaxNumMergeCand = 5 - r.ReadUe(4); + } + + SliceQpY = pps.InitQp + r.ReadSe(-87, 51); + if (SliceQpY < -sps.QpBdOffsetY || SliceQpY > 51) + { + throw new H265Exception("QP di slice fuori dall'intervallo."); + } + + if (pps.SliceChromaQpOffsetsPresent) + { + CbQpOffset = r.ReadSe(-12, 12); + CrQpOffset = r.ReadSe(-12, 12); + } + + if (pps.ChromaQpOffsetListEnabled) + { + CuChromaQpOffsetEnabled = r.ReadFlag(); + } + + var overrideDeblocking = pps.DeblockingFilterOverrideEnabled && r.ReadFlag(); + DeblockingDisabled = pps.DeblockingFilterDisabled; + BetaOffsetDiv2 = pps.BetaOffsetDiv2; + TcOffsetDiv2 = pps.TcOffsetDiv2; + if (overrideDeblocking) + { + DeblockingDisabled = r.ReadFlag(); + if (!DeblockingDisabled) + { + BetaOffsetDiv2 = r.ReadSe(-6, 6); + TcOffsetDiv2 = r.ReadSe(-6, 6); + } + } + + LoopFilterAcrossSlices = pps.LoopFilterAcrossSlicesEnabled; + if (pps.LoopFilterAcrossSlicesEnabled && (SaoLuma || SaoChroma || !DeblockingDisabled)) + { + LoopFilterAcrossSlices = r.ReadFlag(); + } + } + + /// pred_weight_table() (§7.3.6.3), as the weights and offsets of §7.4.7.3. + private void ParsePredWeightTable(BitReader r, Sps sps) + { + LumaLog2WeightDenom = r.ReadUe(7); + var chroma = sps.ChromaArrayType != 0; + if (chroma) + { + ChromaLog2WeightDenom = LumaLog2WeightDenom + r.ReadSe(-LumaLog2WeightDenom, 7 - LumaLog2WeightDenom); + } + + 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]; + for (var list = 0; list < (Type == SliceType.B ? 2 : 1); list++) + { + var count = NumRefIdxActive[list]; + for (var i = 0; i < count; i++) + { + lumaFlags[i] = r.ReadFlag(); + } + + for (var i = 0; i < count; i++) + { + chromaFlags[i] = chroma && r.ReadFlag(); + } + + for (var i = 0; i < count; i++) + { + LumaWeight[list][i] = 1 << LumaLog2WeightDenom; + LumaOffset[list][i] = 0; + if (lumaFlags[i]) + { + LumaWeight[list][i] += r.ReadSe(-128, 127); + LumaOffset[list][i] = r.ReadSe(-wpOffsetHalfY, wpOffsetHalfY - 1) << offsetShift; + } + + for (var j = 0; j < 2; j++) + { + ChromaWeight[list][(i * 2) + j] = 1 << ChromaLog2WeightDenom; + ChromaOffset[list][(i * 2) + j] = 0; + } + + if (chromaFlags[i]) + { + for (var j = 0; j < 2; j++) + { + var weight = (1 << ChromaLog2WeightDenom) + r.ReadSe(-128, 127); + var deltaOffset = r.ReadSe(-4 * wpOffsetHalfC, (4 * wpOffsetHalfC) - 1); + + // (7-56): the offset is predicted from the weight. + var offset = Math.Clamp( + (wpOffsetHalfC - ((wpOffsetHalfC * weight) >> ChromaLog2WeightDenom)) + deltaOffset, + -wpOffsetHalfC, + wpOffsetHalfC - 1); + ChromaWeight[list][(i * 2) + j] = weight; + ChromaOffset[list][(i * 2) + j] = offset << offsetShiftC; + } + } + } + } + } +} diff --git a/src/Febe.Core/Codecs/H265/Transform.cs b/src/Febe.Core/Codecs/H265/Transform.cs new file mode 100644 index 0000000..48209bc --- /dev/null +++ b/src/Febe.Core/Codecs/H265/Transform.cs @@ -0,0 +1,58 @@ +namespace Febe.Core.Codecs.H265; + +/// +/// The two-stage inverse transform of §8.6.4.2: columns first, clipped to 16 bits after a 7-bit shift, then rows, with +/// the final shift of 20 − BitDepth. Columns and rows past the last nonzero coefficient are not computed, since their +/// contribution is zero. +/// +internal static class Transform +{ + /// Scaled coefficients d, raster (y << log2) + x. + /// Residual samples, raster. + /// Intermediate values, at least the block size. + /// Log2 of the block size. + /// trType 1: the 4×4 DST of intra luma blocks. + /// Largest column with a nonzero coefficient. + /// Largest row with a nonzero coefficient. + /// Bit depth of the component. + internal static void Inverse(int[] coefficients, int[] output, int[] temp, int log2, bool dst, int maxX, int maxY, int bitDepth) + { + var size = 1 << log2; + ReadOnlySpan matrix = dst ? H265Tables.DstMatrix : H265Tables.DctMatrix; + var rowStep = dst ? 4 : 32 << (5 - log2); // matrix row of frequency k: k * rowStep + + // First stage: each column x up to maxX, e[x][y] = Σk transMatrix[k][y] · d[x][k]. + for (var x = 0; x <= maxX; x++) + { + for (var y = 0; y < size; y++) + { + // At most 32 products of a 16-bit coefficient and a matrix entry below 91: no overflow in 32 bits. + var sum = 0; + for (var k = 0; k <= maxY; k++) + { + sum += matrix[(k * rowStep) + y] * coefficients[(k << log2) + x]; + } + + temp[(y << log2) + x] = Math.Clamp((sum + 64) >> 7, short.MinValue, short.MaxValue); + } + } + + // Second stage: each row y, r[x][y] = Σk transMatrix[k][x] · g[k][y], then the bdShift of §8.6.2. + var bdShift = 20 - bitDepth; + var add = 1 << (bdShift - 1); + for (var y = 0; y < size; y++) + { + var row = y << log2; + for (var x = 0; x < size; x++) + { + var sum = 0; + for (var k = 0; k <= maxX; k++) + { + sum += matrix[(k * rowStep) + x] * temp[row + k]; + } + + output[row + x] = (sum + add) >> bdShift; + } + } + } +} diff --git a/src/Febe.Core/Codecs/Heif/HeifDecoder.cs b/src/Febe.Core/Codecs/Heif/HeifDecoder.cs new file mode 100644 index 0000000..b9823db --- /dev/null +++ b/src/Febe.Core/Codecs/Heif/HeifDecoder.cs @@ -0,0 +1,698 @@ +using System.Buffers.Binary; +using System.Text; +using Febe.Core.Codecs.H265; + +namespace Febe.Core.Codecs.Heif; + +/// +/// Decoder of HEIF still images with HEVC pictures (HEIC, ISO/IEC 23008-12), written from the standard on the HEVC +/// decoder of : the primary item, coded (hvc1) or a grid of coded tiles (grid, as +/// phones write their photos), its colour (colr nclx, otherwise the VUI of the pictures), its alpha plane (an +/// auxiliary image), the clean aperture (clap), rotation and mirroring (irot, imir, returned as an +/// orientation), and the EXIF block (Exif item). Not handled (a ): images of other +/// codecs (AVIF, JPEG), derived images other than grids (overlays, identity), image sequences (moov only), +/// protected items, and essential properties Febe does not know. +/// +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"; + + /// Properties Febe knows: an essential property outside these makes an item undecodable (§6.5.2). + private static readonly HashSet 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' + ]; + + /// True when the first bytes are those of a HEIF file of still images (an ftyp with a HEIF brand). + public static bool Looks(ReadOnlySpan start) => HeifFile.Looks(start); + + /// Size, orientation and alpha of the primary image, without decoding it. + 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); + }); + } + + /// Decodes the primary image of a seekable stream. + public static HeifImage Decode(Stream stream, HeifLimits? limits = null) + { + ArgumentNullException.ThrowIfNull(stream); + limits ??= HeifLimits.Default; + return Guard(() => DecodePrimary(stream, limits)); + } + + /// Decodes the primary image of a whole file in memory. + public static HeifImage Decode(byte[] data, HeifLimits? limits = null) + { + ArgumentNullException.ThrowIfNull(data); + using var stream = new MemoryStream(data, writable: false); + return Decode(stream, limits); + } + + /// + /// The EXIF block (a TIFF structure) of the primary image of a HEIF file whose first bytes are + /// ; null when there is none, the file is not HEIF, or the block lies past those bytes. + /// + public static byte[]? FindExif(ReadOnlySpan 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; + } + } + + /// Runs , turning every sign of a damaged file into a . + private static T Guard(Func work) + { + try + { + return work(); + } + catch (H265Exception ex) + { + throw new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.Message); + } + catch (AggregateException ex) + { + throw Unwrap(ex); + } + catch (Exception ex) when (ex is EndOfStreamException or ArgumentException or IndexOutOfRangeException or OverflowException + or InvalidOperationException) + { + throw new HeifException("File HEIF troncato o danneggiato."); + } + } + + /// + /// 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."); + 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."); + } + } + } + + /// The grid description of §6.6.2.3.1: rows, columns, output size. + 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("Riquadri della griglia HEIF mancanti o in eccesso."); + } + + return (rows, columns, width, height); + } + + /// The size of an image before the clean aperture: of the grid output, or of the coded picture. + 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 (Exception ex) when (ex is HeifException or H265Exception) + { + // 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), + }; + } + + /// + /// 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, 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 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 (rows, columns, width, height) = GridOf(stream, file, item, limits); + var tiles = new HeifItem[item.DerivedFrom.Count]; + (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("Riquadro della griglia HEIF mancante."); + if (tiles[i].Type != HeifFile.Hvc1) + { + throw new HeifException("Riquadro della griglia HEIF non HEVC."); + } + + CheckDecodable(file, tiles[i]); + + // 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."); + } + } + } + + // 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)) + { + 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 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)); + decoder.DecodeSample(data, lengthSize); + decoder.Flush(); + } + finally + { + decoder.FrameDecoded -= Take; + } + + return frame ?? throw new HeifException("Nessuna immagine nei dati HEVC dell'oggetto HEIF."); + } + + private static YuvPlanes 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); + } + + /// The luma of an alpha picture into the alpha bytes: full range as is, limited range stretched. + 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); + } + } + } + + /// The alpha plane of an image: an item that is its auxiliary image (auxl) of the alpha type. + 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; + } + + /// matrix_coefficients and full_range_flag of an nclx colr property, of the image or its first tile. + 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 ColourCarriers(HeifFile file, HeifItem image) + { + yield return image; + if (image.DerivedFrom.Count > 0 && file.Item(image.DerivedFrom[0]) is { } tile) + { + yield return tile; + } + } + + /// + /// 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. + /// + 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; + + /// + /// The rotations (irot: quarter turns anticlockwise) and mirrors (imir: 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. + /// + 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 }; + } + + /// The EXIF item describing the image (or the only EXIF item of the file), without its offset prefix. + 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 + } + } + + /// The Orientation tag (0x0112) of the first IFD of a TIFF structure; 1 without it or when damaged. + internal static int ExifOrientationOf(ReadOnlySpan 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 b, bool little) => + little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b); + + private static uint U32(ReadOnlySpan b, bool little) => + little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b); +} diff --git a/src/Febe.Core/Codecs/Heif/HeifFile.cs b/src/Febe.Core/Codecs/Heif/HeifFile.cs new file mode 100644 index 0000000..746d80d --- /dev/null +++ b/src/Febe.Core/Codecs/Heif/HeifFile.cs @@ -0,0 +1,571 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Containers; + +namespace Febe.Core.Codecs.Heif; + +/// An item of a HEIF file (ISO/IEC 23008-12 §6.2, the iinf, iloc and ipma entries of one ID). +internal sealed class HeifItem(uint id) +{ + internal uint Id { get; } = id; + + /// item_type of the infe box: hvc1, grid, Exif, mime, ...; 0 when unknown. + internal uint Type { get; set; } + + /// construction_method of iloc: 0 from the file, 1 from the idat box. + internal int ConstructionMethod { get; set; } + + /// The extents of the item's data: offset (base_offset added) and length (0: to the end of the file). + internal List<(long Offset, long Length)> Extents { get; } = []; + + /// Whether iloc lists the item at all. + internal bool Located { get; set; } + + /// The associated properties, in the order of ipma: index in , essential. + internal List<(int Index, bool Essential)> Properties { get; } = []; + + /// The items this one is derived from (dimg), in order: the tiles of a grid. + internal List DerivedFrom { get; } = []; + + /// The items this one is an auxiliary image of (auxl). + internal List AuxiliaryOf { get; } = []; + + /// The items this one describes (cdsc): an Exif item and its image. + internal List Describes { get; } = []; +} + +/// A property of the ipco box: its type and where its body lies in . +internal readonly record struct HeifProperty(uint Type, int Start, int Length); + +/// +/// The structure of a HEIF file, read from the boxes of its file-level meta box (ISO/IEC 23008-12 §6 and +/// ISO/IEC 14496-12 §8.11): primary item, items with their locations, properties and references. Only the +/// meta box is kept in memory; item data is read from the stream when asked for. +/// +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 items = []; + + private HeifFile(byte[] meta, long fileLength) + { + Meta = meta; + FileLength = fileLength; + } + + /// The body of the meta box. + internal byte[] Meta { get; } + + internal long FileLength { get; } + + internal uint PrimaryId { get; private set; } + + internal List Properties { get; } = []; + + /// The body of the idat box (start and length in ); length −1 without one. + internal (int Start, int Length) Idat { get; private set; } = (0, -1); + + internal IEnumerable Items => items.Values; + + internal HeifItem? Item(uint id) => items.GetValueOrDefault(id); + + /// True when the file starts with an ftyp box naming a HEIF brand of still images with HEVC. + internal static bool Looks(ReadOnlySpan 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 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); + + /// Reads the top-level boxes of a seekable stream up to its file-level meta box and parses it. + internal static HeifFile Read(Stream stream, HeifLimits limits) + { + var length = stream.Length; + long position = 0; + Span 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 oggetti 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 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 oggetti 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 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 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 + } + } + } + } + } + + /// The first property of associated with , or null. + 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 Body(HeifProperty property) => Meta.AsSpan(property.Start, property.Length); + + /// The bytes of an item, its extents one after the other. + internal byte[] ReadItem(Stream stream, HeifItem item, HeifLimits limits) + { + var spans = Locate(item, limits, out var total); + 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; + } + + /// 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 new file mode 100644 index 0000000..ca766cc --- /dev/null +++ b/src/Febe.Core/Codecs/Heif/HeifImage.cs @@ -0,0 +1,100 @@ +namespace Febe.Core.Codecs.Heif; + +/// A HEIF file that cannot be decoded: damaged, truncated, or of a kind Febe does not handle. +public sealed class HeifException(string message) : Exception(message); + +/// +/// The still image of a HEIF file (HEIC: ISO/IEC 23008-12 with HEVC pictures), decoded: × +/// pixels, top row first, four bytes each R, G, B, A (8 bits, alpha not premultiplied, 255 without +/// an alpha plane). The clean aperture (clap) is already applied; the rotation and mirroring are not: they are in +/// , as an EXIF orientation, for the caller to apply. +/// +/// +/// The same layout as RgbaImage of the image codecs (branch funzione/codec-immagini, not merged here): when that +/// branch is merged, becomes the buffer of an RgbaImage and its +/// ImageMetadata.Orientation, so that ImageOrientation.Apply turns it upright. +/// +public sealed class HeifImage +{ + internal HeifImage(int width, int height, byte[] pixels) + { + Width = width; + Height = height; + Pixels = pixels; + } + + /// Width in pixels as stored (orientation not applied). + public int Width { get; } + + /// Height in pixels as stored. + public int Height { get; } + + /// The pixels, R, G, B, A, row after row. + public byte[] Pixels { get; } + + /// + /// 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 irot and imir 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 . + /// + public int Orientation { get; init; } = 1; + + /// Whether an alpha plane (an auxiliary image) filled the alpha of . + public bool HasAlpha { get; init; } + + /// Bits per luma sample of the coded pictures (8, 10, 12); the pixels have 8 whatever this is. + public int BitDepth { get; init; } = 8; + + /// The EXIF block of the image (its Exif item) as a TIFF structure, or null. + public byte[]? Exif { get; init; } + + /// The Orientation tag of , 1-8; 1 without it. Informative only: see . + public int ExifOrientation { get; init; } = 1; + + /// The ICC profile of a colr property of type prof or rICC, or null. + public byte[]? IccProfile { get; init; } + + /// The image as shown: and swapped when the orientation turns it a quarter. + public (int Width, int Height) DisplaySize => Orientation >= 5 ? (Height, Width) : (Width, Height); +} + +/// What a HEIF file says about its primary image, read without decoding any picture. +/// Width as stored, after the clean aperture. +/// Height as stored, after the clean aperture. +/// As . +/// Whether an alpha plane goes with the image. +/// Coded pictures of the image: 1, or the tiles of a grid. +public sealed record HeifInfo(int Width, int Height, int Orientation, bool HasAlpha, int Tiles) +{ + /// The size as shown (orientation applied). + public (int Width, int Height) DisplaySize => Orientation >= 5 ? (Height, Width) : (Width, Height); +} + +/// Bounds that keep a damaged or hostile file from taking the memory or the processors. +public sealed record HeifLimits +{ + /// The default limits. + public static HeifLimits Default { get; } = new(); + + /// Pixels of the image at most (100 megapixels: 400 MB of RGBA). + public long MaxPixels { get; init; } = 100_000_000; + + /// Bytes of the meta box at most. + public int MaxMetaBytes { get; init; } = 32 * 1024 * 1024; + + /// 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; + + /// Tiles decoded at the same time at most. + public int MaxParallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4); +} diff --git a/src/Febe.Core/Codecs/Images/HeifImageDecoder.cs b/src/Febe.Core/Codecs/Images/HeifImageDecoder.cs new file mode 100644 index 0000000..dde3e00 --- /dev/null +++ b/src/Febe.Core/Codecs/Images/HeifImageDecoder.cs @@ -0,0 +1,74 @@ +using System.Runtime.InteropServices; +using Febe.Core.Codecs.Heif; + +namespace Febe.Core.Codecs.Images; + +/// +/// HEIC/HEIF photos through the image facade (): the decoder written in house +/// (, on the HEVC decoder) gives straight RGBA8, which becomes an +/// without a copy; the irot/imir properties become , so that +/// turns the picture upright as it does for the EXIF orientation of a JPEG. +/// +internal static class HeifImageDecoder +{ + /// Size, alpha and orientation of the primary image, without decoding it. + public static ImageInfo Identify(ReadOnlyMemory data, ImageLimits? limits) + { + limits ??= ImageLimits.Default; + using var stream = Open(data); + var info = ReadInfo(stream); + limits.CheckSize(info.Width, info.Height); + return ToInfo(info.Width, info.Height, info.HasAlpha, new ImageMetadata { Orientation = info.Orientation }); + } + + /// Decodes the primary image; the pixels are the decoder's own array, never pooled. + public static RgbaImage Decode(ReadOnlyMemory data, out ImageInfo info, ImageLimits? limits) + { + limits ??= ImageLimits.Default; + using var stream = Open(data); + + // The size first, from the boxes alone: a picture over the limits is refused as such, before any tile is decoded. + var header = ReadInfo(stream); + limits.CheckSize(header.Width, header.Height); + stream.Position = 0; + HeifImage image; + try + { + image = HeifDecoder.Decode(stream, HeifLimits.Default with { MaxPixels = limits.MaxPixels }); + } + catch (HeifException ex) + { + throw new ImageDecodeException(ex.Message, ex); + } + + info = ToInfo(image.Width, image.Height, image.HasAlpha, new ImageMetadata + { + Orientation = image.Orientation, + Exif = image.Exif, + IccProfile = image.IccProfile, + }) with { BitsPerSample = image.BitDepth }; + return new RgbaImage(image.Width, image.Height, image.Pixels); + } + + private static HeifInfo ReadInfo(Stream stream) + { + try + { + // The facade's limits are checked on the clean size; the decoder's own bound is only the memory of a process. + return HeifDecoder.ReadInfo(stream, HeifLimits.Default with { MaxPixels = long.MaxValue }); + } + catch (HeifException ex) + { + throw new ImageDecodeException(ex.Message, ex); + } + } + + private static ImageInfo ToInfo(int width, int height, bool hasAlpha, ImageMetadata metadata) => + new(ImageFormat.Heif, width, height, 1, hasAlpha, metadata); + + /// A read-only stream over the bytes, without copying them when they are an array. + private static MemoryStream Open(ReadOnlyMemory data) => + MemoryMarshal.TryGetArray(data, out var segment) && segment.Array is not null + ? new MemoryStream(segment.Array, segment.Offset, segment.Count, writable: false) + : new MemoryStream(data.ToArray(), writable: false); +} diff --git a/src/Febe.Core/Codecs/Images/ImageDecoder.cs b/src/Febe.Core/Codecs/Images/ImageDecoder.cs index 372eaf2..0edcd1e 100644 --- a/src/Febe.Core/Codecs/Images/ImageDecoder.cs +++ b/src/Febe.Core/Codecs/Images/ImageDecoder.cs @@ -6,8 +6,12 @@ namespace Febe.Core.Codecs.Images; /// public static class ImageDecoder { - /// Whether Febe has a decoder for . - public static bool CanDecode(ImageFormat format) => format is ImageFormat.Png or ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp or ImageFormat.WebP; + /// + /// Whether Febe has a decoder for . For only the HEVC + /// pictures (HEIC) decode: a HEIF of other pictures (AV1, JPEG) raises . + /// + public static bool CanDecode(ImageFormat format) => + format is ImageFormat.Png or ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp or ImageFormat.WebP or ImageFormat.Heif; /// Size, frames and metadata of an image, without decoding the pixels. /// The format is not known or has no decoder yet. @@ -20,6 +24,7 @@ public static class ImageDecoder ImageFormat.Gif => GifDecoder.Identify(data, limits), ImageFormat.Bmp => BmpDecoder.Identify(data, limits), ImageFormat.WebP => WebPDecoder.Identify(data, limits), + ImageFormat.Heif => HeifImageDecoder.Identify(data, limits), var other => throw NotSupported(other), }; @@ -35,6 +40,7 @@ public static class ImageDecoder ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled), ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled), ImageFormat.WebP => WebPDecoder.Decode(data, limits, pooled), + ImageFormat.Heif => HeifImageDecoder.Decode(data, out _, limits), var other => throw NotSupported(other), }; @@ -56,6 +62,8 @@ public static class ImageDecoder return BmpDecoder.Decode(data, out info, limits, pooled); case ImageFormat.WebP: return WebPDecoder.Decode(data, out info, limits, pooled); + case ImageFormat.Heif: + return HeifImageDecoder.Decode(data, out info, limits); case var other: throw NotSupported(other); } diff --git a/src/Febe.Core/Codecs/YuvToRgb.cs b/src/Febe.Core/Codecs/YuvToRgb.cs new file mode 100644 index 0000000..3b93c15 --- /dev/null +++ b/src/Febe.Core/Codecs/YuvToRgb.cs @@ -0,0 +1,229 @@ +using System.Numerics; + +namespace Febe.Core.Codecs; + +/// +/// The sample planes of a decoded picture, whatever its codec: luma × , chroma +/// subsampled by 1 << ChromaShiftX and 1 << ChromaShiftY (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). +/// +internal readonly struct YuvPlanes( + T[] y, T[] cb, T[] cr, int width, int height, int chromaShiftX, int chromaShiftY, bool monochrome, int bitDepthY, int bitDepthC) + where T : unmanaged, IBinaryInteger +{ + 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; + + /// Width of a chroma row (rounded up, as for odd H.264 widths). + internal int ChromaWidth => (Width + (1 << ChromaShiftX) - 1) >> ChromaShiftX; +} + +/// +/// 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 (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 +{ + private const int Shift = 16; + private const double One = 1 << Shift; + private const int Half = 1 << (Shift - 1); + + /// The integer coefficients for one matrix, range and bit depth. + internal readonly struct Coefficients + { + 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; } + + 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; } + + /// Right shift that brings an identity-matrix sample to 8 bits, luma and chroma. + internal int IdentityShiftY { get; init; } + + internal int IdentityShiftC { get; init; } + } + + /// + /// 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) + { + if (matrix == 0) + { + 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), + 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), + }; + } + + /// + /// Converts the picture reduced by (each output pixel the mean of factor × factor converted + /// pixels) into : × pixels of + /// bytes (3: R, G, B; 4: R, G, B and an alpha of 255), rows + /// bytes apart. The output must fit in the picture: width × factor ≤ its width, height × factor ≤ its height. + /// + internal static void Convert(in YuvPlanes p, in Coefficients k, int factor, Span target, int stride, int pixelSize, int width, int height) + where T : unmanaged, IBinaryInteger + { + var area = factor * factor; + var cw = p.ChromaWidth; + var sx = p.ChromaShiftX; + var sy = p.ChromaShiftY; + ReadOnlySpan 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; + 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); + } + } + + 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; +} diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index a5b215c..bb5cd49 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -81,7 +81,7 @@ internal static class ContentAnalysis return new ContentFacts(type, length, sha, width, height, null, hash, date, null); } - /// Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. HEIC). + /// Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. AVIF). private static (int? Width, int? Height, ulong? Hash) Decode(byte[] bytes) { try @@ -121,7 +121,7 @@ internal static class ContentAnalysis } catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException) { - return (null, null, null); // formats Febe cannot decode (e.g. HEIC) already give nulls: no size, no hash + return (null, null, null); // a format no decoder reads (e.g. AVIF): no size, no hash } } diff --git a/src/Febe.Core/Import/ExifDateReader.cs b/src/Febe.Core/Import/ExifDateReader.cs index 12eb775..1af71e2 100644 --- a/src/Febe.Core/Import/ExifDateReader.cs +++ b/src/Febe.Core/Import/ExifDateReader.cs @@ -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. /// /// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (eXIf chunk), WebP (EXIF chunk). -/// HEIC keeps its EXIF in an item of the meta 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 meta box (): read when the +/// item lies within the first bytes read. Every offset is checked: a damaged block gives no date, never an exception. /// /// public static class ExifDateReader @@ -46,7 +47,7 @@ public static class ExifDateReader } } - /// The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none. + /// The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG, WebP or HEIC; empty when there is none. internal static ReadOnlySpan FindTiff(ReadOnlySpan 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 []; } diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md index 7914be4..44387ef 100644 --- a/src/Febe.Core/Import/LEGGIMI.md +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -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, AVI, WMV, FLV e MPEG (null: la stessa, predefinita) SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, @@ -164,12 +164,14 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per trasmissione), dei flussi (codec, dimensioni, audio, anche dentro l'estensione dell'intestazione), il titolo e `WM/EncodingTime` quando manca la data; di un FLV `onMetaData` (durata, dimensioni, `creationdate`), le dimensioni dall'SPS dell'H.264 o dall'intestazione dell'H.263 di Sorenson, e senza durata nei metadati quella fino alla fine dell'ultimo fotogramma (l'ultimo tag video più l'intervallo dal precedente; l'audio solo se non c'è video); di un MPEG - (MPEG-1 e MPEG-2, anche VOB) codec e dimensioni dall'intestazione di sequenza o dall'SPS dell'H.264 e la durata dal + (MPEG-1 e MPEG-2, anche VOB) codec e dimensioni dall'intestazione di sequenza o dall'SPS dell'H.264 o dell'HEVC (tipo 0x24 nella mappa) e la durata dal primo all'ultimo tempo di presentazione, leggendo solo i primi 2 MB e l'ultimo MB. Un MPEG non ha data. La miniatura viene solo dagli FLV H.264: WMV (VC-1) e MPEG-2 non si decodificano, e i campioni di un MPEG, spezzati nei - pacchetti PES, non si elencano, nemmeno se H.264. -- HEIC/HEIF: si riconoscono, ma i codec di Febe (PNG, JPEG, GIF, BMP, WebP) non li decodificano: niente dimensioni, - impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica. + pacchetti PES, non si elencano, nemmeno se H.264 o HEVC. +- HEIC/HEIF: dimensioni, impronta e miniatura vengono dal decodificatore scritto in casa (`Febe.Core.Codecs.Heif`, sul + 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/src/Febe.Core/Library/DamagedImage.cs b/src/Febe.Core/Library/DamagedImage.cs index af2ac28..b095e89 100644 --- a/src/Febe.Core/Library/DamagedImage.cs +++ b/src/Febe.Core/Library/DamagedImage.cs @@ -14,7 +14,7 @@ public static class DamagedImage { /// /// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or - /// truncated; false for a photo that decodes, for a format Febe does not read (HEIC, an unknown one) and for a + /// truncated; false for a photo that decodes, for a format Febe does not read (AVIF, an unknown one), for HEIC (see ImageDecoding.IsDamaged) and for a /// picture too large to decode. /// public static bool IsDamaged(ReadOnlyMemory data) => ImageDecoding.IsDamaged(data); diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs index 45f9c9e..21d35d1 100644 --- a/src/Febe.Core/Library/ImageDecoding.cs +++ b/src/Febe.Core/Library/ImageDecoding.cs @@ -1,11 +1,12 @@ +using Febe.Core.Codecs.Heif; using Febe.Core.Codecs.Images; namespace Febe.Core.Library; /// -/// Decodes images with the in-house codecs (: JPEG, PNG, GIF, BMP, WebP), applying the -/// EXIF orientation (photos from phones) and, for JPEG, decoding directly at a reduced size when a smaller picture is -/// enough, which saves memory and time. +/// Decodes images with the in-house codecs (: JPEG, PNG, GIF, BMP, WebP and HEIC through +/// ), applying the EXIF orientation (photos from phones; for HEIC its irot/imir) +/// and, for JPEG, decoding directly at a reduced size when a smaller picture is enough, which saves memory and time. /// internal static class ImageDecoding { @@ -23,7 +24,7 @@ internal static class ImageDecoding /// /// Decodes an image upright, as straight RGBA. When is given the codec may decode /// at a lower resolution, but never below that long side (unless the image is smaller). Returns null when the - /// content is not a decodable image (unknown format, HEIC, damaged or truncated file, too large). + /// content is not a decodable image (unknown format, AVIF, damaged or truncated file, too large). /// public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null) { @@ -78,12 +79,15 @@ internal static class ImageDecoding /// /// True when is in a format Febe decodes but cannot be decoded because it is damaged or /// truncated (spec §8.4, «File danneggiato o incompleto»). False for a picture that decodes, for what Febe does not - /// read (unknown formats, HEIC, the JPEG processes it leaves out) and for a picture over the limits: those are not - /// damaged, Febe just has no picture of them. + /// read (unknown formats, the JPEG processes it leaves out) and for a picture over the limits: those are not + /// damaged, Febe just has no picture of them. HEIC is never said damaged: its decoder does not tell a damaged file + /// from a HEIF it does not handle (AV1 or JPEG pictures, an unknown essential property), so a HEIC without a + /// picture only gets the neutral tile. /// internal static bool IsDamaged(ReadOnlyMemory data) { - if (data.IsEmpty || !ImageDecoder.CanDecode(ImageFormatSniffer.Detect(data.Span))) + var format = data.IsEmpty ? ImageFormat.Unknown : ImageFormatSniffer.Detect(data.Span); + if (format == ImageFormat.Heif || !ImageDecoder.CanDecode(format)) { return false; } @@ -114,7 +118,7 @@ internal static class ImageDecoding /// /// Bytes read first by for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is /// at most 64 KiB) fit; when they do not (large ICC profiles) the rest of the file is read as well. PNG and WebP - /// are always read whole. + /// are always read whole; HEIC only its boxes (), never its pictures. /// internal const int HeaderBytes = 256 * 1024; @@ -138,8 +142,23 @@ internal static class ImageDecoding return ReadSize(ReadAll(stream)); } + var start = stream.Position; var data = new byte[HeaderBytes]; stream.ReadExactly(data); + if (ImageFormatSniffer.Detect(data) == ImageFormat.Heif) + { + // A HEIC keeps its boxes at the start and its pictures after them: the boxes alone give the size. + stream.Position = start; + try + { + return HeifDecoder.ReadInfo(stream).DisplaySize; + } + catch (HeifException) + { + return null; + } + } + if (ImageFormatSniffer.Detect(data) is not (ImageFormat.Jpeg or ImageFormat.Gif or ImageFormat.Bmp)) { // PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 817c061..5496967 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -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 /// /// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover): -/// the container readers of and the H.264 decoder written in house -/// (). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the -/// neutral tile. +/// the container readers of and the H.264 and HEVC decoders written in house +/// (, ). Videos in other codecs (VP9, AV1, ...) give no frame: the +/// interface shows the neutral tile. /// 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; - /// The H.264 video track of a container with its samples; null for other codecs or without video. + /// The H.264 or HEVC video track of a container with its samples; null for other codecs or without video. 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,98 @@ public sealed class VideoFrameDecoder return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys]; } + /// Where decoding can start, whatever the codec. + private enum StartPoint + { + /// Decoding cannot start here. + None, + + /// Close: an H.264 picture of I slices that is not IDR, an HEVC CRA picture (its RASL pictures are lost). + Intra, + + /// Exact: an H.264 IDR picture, an HEVC IDR or BLA picture. + Idr, + } + + /// Size of the NAL length fields of the samples (0: Annex B), from the configuration record. + 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; + } + + /// A decoded frame of either codec. + private sealed class Frame(H264Frame? avc, H265Frame? hevc) + { + internal H264Frame? Avc { get; } = avc; + + internal H265Frame? Hevc { get; } = hevc; + } + + /// The decoder of the track's codec, configured from its configuration record. + private sealed class Runner + { + private readonly H264Decoder? avc; + private readonly H265Decoder? hevc; + private readonly int lengthSize; + + internal Runner(VideoTrack video, Func wanted, Action 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 + { + // Of an MVC stream only the base view: it is the 2D video, and the other views would add frames. + avc = new H264Decoder { Wanted = _ => wanted(), DecodeAllViews = false }; + avc.FrameDecoded += frame => found(new Frame(frame, null)); + lengthSize = video.AnnexB ? 0 : avc.ConfigureAvcC(video.AvcConfiguration); + } + } + + internal void Decode(ReadOnlySpan 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); + } + } + } + /// /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. /// private sealed class Decoding(Stream stream, VideoTrack video, int maxRun) { - private readonly Dictionary found = []; + private readonly Dictionary found = []; private readonly HashSet wanted = []; private readonly int[] keys = KeyIndices(video); - private readonly Dictionary accessPoints = []; + private readonly Dictionary accessPoints = []; + private readonly int lengthSize = LengthSize(video); private byte[] buffer = new byte[64 * 1024]; /// The sample being decoded: the picture it finishes is that sample's frame. @@ -360,9 +452,9 @@ public sealed class VideoFrameDecoder /// The sample where decoding for 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. /// internal int RunStart(int index) { @@ -378,91 +470,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 Decode(int[] targets, CancellationToken ct) + internal Dictionary 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. - // Of an MVC stream only the base view: it is the 2D video, and the other views would add frames. - decoder = new H264Decoder { Wanted = _ => wanted.Contains(current), DecodeAllViews = false }; - 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,57 +562,52 @@ public sealed class VideoFrameDecoder } } + /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise. + private static double[] Grid(Frame frame) => + frame.Hevc is { } h ? Grid(Planes(h)) : frame.Avc!.BytesPerSample == 2 ? Grid(WidePlanes(frame.Avc)) : Grid(Planes(frame.Avc)); + /// - /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise; values on the - /// 8-bit scale whatever the bit depth, the chroma at any sampling (its own grid over its own plane). + /// 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). /// - private static double[] Grid(H264Frame frame) + private static double[] Grid(in YuvPlanes frame) + where T : unmanaged, IBinaryInteger { var grid = new double[GridSize * GridSize * 2]; var counts = new int[GridSize * GridSize]; - var wide = frame.BytesPerSample == 2; - ReadOnlySpan y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Y) : default; - var lumaShift = frame.BitDepthLuma - 8; + var lumaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthY - 8)); + ReadOnlySpan luma = frame.Y; for (var y = 0; y < frame.Height; y++) { var gy = y * GridSize / frame.Height; - var start = y * frame.Width; - for (var x = 0; x < frame.Width; x++) + 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] += wide ? y16[start + x] >> lumaShift : frame.Y[start + x]; + grid[cell] += int.CreateTruncating(row[x]) * lumaScale; counts[cell]++; } } - var cw = frame.ChromaWidth; - var ch = frame.ChromaHeight; - ReadOnlySpan cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cb) : default; - ReadOnlySpan cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cr) : default; - var chromaShift = frame.BitDepthChroma - 8; - var middle = 1 << (frame.BitDepthChroma - 1); 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 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; - int u, v; - if (wide) + var gy = y * GridSize / ch; + for (var x = 0; x < cw; x++) { - u = Math.Abs(cb16[i] - middle) >> chromaShift; - v = Math.Abs(cr16[i] - middle) >> chromaShift; + 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]++; } - else - { - u = Math.Abs(frame.Cb[i] - 128); - v = Math.Abs(frame.Cr[i] - 128); - } - - grid[(GridSize * GridSize) + cell] += (u + v) / 2.0; - chromaCounts[cell]++; } } @@ -535,101 +622,94 @@ public sealed class VideoFrameDecoder } /// - /// The frame in RGB: BT.709, BT.601 or BT.2020 coefficients as the stream says (unspecified: BT.709 from 720 lines - /// up), limited or full range at the bit depth of the frame (limited: black at 16 · 2^(n − 8), luma span 219 · 2^(n − 8), - /// chroma 224 · 2^(n − 8) around 2^(n − 1)), any chroma sampling (4:2:0, 4:2:2, 4:4:4; monochrome comes with grey - /// chroma), reduced by an integer factor to fit , then rotated clockwise. + /// The planes of an H.264 frame of 8-bit samples, at any chroma sampling. A monochrome frame comes with grey 4:2:0 + /// chroma planes (), which the conversion does not read. /// - internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) + private static YuvPlanes Planes(H264Frame frame) { - 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; - int lumaBits = frame.BitDepthLuma - 8, chromaBits = frame.BitDepthChroma - 8; - var yScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthLuma) - 1) : 255.0 / (219 << lumaBits); - var cScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthChroma) - 1) : 255.0 / (224 << chromaBits); - var yOffset = frame.FullRange ? 0 : 16 << lumaBits; - var middle = 1 << (frame.BitDepthChroma - 1); - 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); + var (sx, sy) = ChromaShifts(frame.ChromaFormat); + return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma); + } + /// + /// The planes of an H.264 frame above 8 bits (two bytes a sample, little-endian), as 16-bit values: copied once, + /// for the few frames a thumbnail or a stillness check decodes. + /// + private static YuvPlanes WidePlanes(H264Frame frame) + { + static ushort[] Wide(byte[] plane) + { + var values = new ushort[plane.Length / 2]; + for (var i = 0; i < values.Length; i++) + { + values[i] = BinaryPrimitives.ReadUInt16LittleEndian(plane.AsSpan(2 * i)); + } + + return values; + } + + var (sx, sy) = ChromaShifts(frame.ChromaFormat); + return new(Wide(frame.Y), Wide(frame.Cb), Wide(frame.Cr), frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, + frame.BitDepthLuma, frame.BitDepthChroma); + } + + /// Chroma subsampling of chroma_format_idc (0, monochrome, as 4:2:0: the planes H.264 gives it are that size). + private static (int X, int Y) ChromaShifts(int chromaFormat) => chromaFormat switch + { + 0 or 1 => (1, 1), + 2 => (1, 0), + _ => (0, 0), + }; + + private static YuvPlanes 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); + + /// + /// 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 , then rotated clockwise. + /// + internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) => + frame.BytesPerSample == 2 + ? ToImage(WidePlanes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide) + : ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide); + + /// + /// An HEVC frame in RGB, as : any chroma format (4:0:0 in grey) and bit + /// depth, brought to 8 bits. + /// + internal static VideoImage ToImage(H265Frame frame, int rotation, int maxLongSide) => + ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide); + + private static VideoImage ToImage(in YuvPlanes planes, int matrix, bool fullRange, int rotation, int maxLongSide) + where T : unmanaged, IBinaryInteger + { 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.ChromaWidth; - var shiftX = frame.ChromaFormat == 3 ? 0 : 1; - var shiftY = frame.ChromaFormat is 2 or 3 ? 0 : 1; - var wide = frame.BytesPerSample == 2; - ReadOnlySpan y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Y) : default; - ReadOnlySpan cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cb) : default; - ReadOnlySpan cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cr) : default; - 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 >> shiftY) * cw; - for (var dx = 0; dx < factor; dx++) - { - var x = (ox * factor) + dx; - var ci = chromaRow + (x >> shiftX); - int l, u, v; - if (wide) - { - l = (y16[lumaRow + x] - yOffset) * cy; - u = cb16[ci] - middle; - v = cr16[ci] - middle; - } - else - { - l = (frame.Y[lumaRow + x] - yOffset) * cy; - u = frame.Cb[ci] - middle; - v = frame.Cr[ci] - middle; - } - - 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; diff --git a/tests/Febe.Tests/Febe.Tests.csproj b/tests/Febe.Tests/Febe.Tests.csproj index 18936ce..0dacc75 100644 --- a/tests/Febe.Tests/Febe.Tests.csproj +++ b/tests/Febe.Tests/Febe.Tests.csproj @@ -20,6 +20,7 @@ + diff --git a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs index 61e94a4..f90f48f 100644 --- a/tests/Febe.Tests/Imaging/ImagingBaseTests.cs +++ b/tests/Febe.Tests/Imaging/ImagingBaseTests.cs @@ -126,6 +126,7 @@ public sealed class ImagingBaseTests Assert.Contains("TIFF", error.Message); Assert.ThrowsExactly(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi"))); Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Png) && ImageDecoder.CanDecode(ImageFormat.Gif) && ImageDecoder.CanDecode(ImageFormat.Bmp) && ImageDecoder.CanDecode(ImageFormat.Jpeg) && ImageDecoder.CanDecode(ImageFormat.WebP)); - Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Tiff) || ImageDecoder.CanDecode(ImageFormat.Heif) || ImageDecoder.CanDecode(ImageFormat.Unknown)); + Assert.IsTrue(ImageDecoder.CanDecode(ImageFormat.Heif), "HEIC, con il decodificatore HEIF sull'HEVC"); + Assert.IsFalse(ImageDecoder.CanDecode(ImageFormat.Tiff) || ImageDecoder.CanDecode(ImageFormat.Avif) || ImageDecoder.CanDecode(ImageFormat.Unknown)); } } diff --git a/tests/Febe.Tests/Library/DamagedImageTests.cs b/tests/Febe.Tests/Library/DamagedImageTests.cs index 78fda9e..b1cd219 100644 --- a/tests/Febe.Tests/Library/DamagedImageTests.cs +++ b/tests/Febe.Tests/Library/DamagedImageTests.cs @@ -29,7 +29,7 @@ public sealed class DamagedImageTests Assert.IsFalse(DamagedImage.IsDamaged(ReadOnlyMemory.Empty)); Assert.IsFalse(DamagedImage.IsDamaged(new byte[100]), "un formato sconosciuto"); byte[] heic = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. new byte[64]]; - Assert.IsFalse(DamagedImage.IsDamaged(heic), "HEIC: Febe non lo legge, ma non è rovinato"); + Assert.IsFalse(DamagedImage.IsDamaged(heic), "HEIC senza immagine: il suo decodificatore non distingue un file rovinato da uno che non gestisce"); } [TestMethod] diff --git a/tests/Febe.Tests/Media/Containers/HevcVideoTests.cs b/tests/Febe.Tests/Media/Containers/HevcVideoTests.cs new file mode 100644 index 0000000..addac91 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/HevcVideoTests.cs @@ -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; + +/// +/// 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). +/// +[TestClass] +public sealed class HevcVideoTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + + /// 416×240, 8 bit, 60 frames shown in another order than they are decoded. + 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]}"); + } + + /// The frames of a conformance stream in output order, decoded straight from its Annex B form. + private static List Shown(string name) + { + var frames = new List(); + var decoder = new H265Decoder(); + decoder.FrameOutput += frames.Add; + decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(name).BitstreamPath)); + return frames; + } +} diff --git a/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs b/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs index 826bf57..154dd1d 100644 --- a/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs +++ b/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs @@ -275,6 +275,24 @@ public sealed class LegacyContainerTests Assert.IsNull(container.Audio); } + [TestMethod] + [DataRow("INITQP_A_Sony_1")] + [DataRow("CONFWIN_A_Sony_1")] + public void HevcInAProgramStreamTakesItsSizeFromTheSps(string name) + { + // Stream type 0x24 in the stream map; the size is the picture's after the conformance window. + var es = ElementaryStream.LoadHevc(name); + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Video = "hevc", Stream = es, StreamMap = true, Audio = null })); + Assert.AreEqual(VideoCodec.Hevc, container.Video!.Codec); + Assert.AreEqual((es.Width, es.Height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual("0x24", container.Video.CodecTag); + Assert.IsEmpty(container.Video.Samples, "i campioni di un MPEG non si elencano, nemmeno se HEVC"); + + // Without a stream map an HEVC stream is not told from other video: no size, but no error either. + var unmapped = Read(LegacyTestVideos.MpegPs(new PsOptions { Video = "hevc", Stream = es, Audio = null })); + Assert.AreEqual((0, 0), (unmapped.Video!.Width, unmapped.Video.Height)); + } + [TestMethod] public void TheEndOfALongProgramStreamGivesItsDuration() { diff --git a/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs b/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs index 33346bf..83a2fbc 100644 --- a/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs @@ -25,7 +25,7 @@ internal sealed record AsfOptions /// What a test MPEG program stream holds. internal sealed record PsOptions { - /// «mpeg2», «mpeg1» or «h264» (then gives the pictures). + /// «mpeg2», «mpeg1», «h264» or «hevc» (for these two gives the pictures). public string Video { get; init; } = "mpeg2"; public int Width { get; init; } = 720; public int Height { get; init; } = 576; @@ -358,13 +358,14 @@ internal static class LegacyTestVideos /// An MPEG program stream: a pack header before each picture, a system header, optionally a program stream map, the /// pictures as PES packets of at most 2,000 bytes (the first with its presentation time), and audio frames between. /// MPEG-1 and MPEG-2 pictures are a sequence header (with its extension in MPEG-2), a GOP header, a picture header - /// and filler slice bytes; H.264 pictures are the access units of . + /// and filler slice bytes; H.264 and HEVC pictures are the access units of . /// public static byte[] MpegPs(PsOptions o) { var random = new Random(o.Seed); - var frameTicks = o.Video == "h264" ? 3000 : 3600; // 30 or 25 pictures a second - var frames = o.Video == "h264" ? o.Stream!.Count : o.Frames; + var coded = o.Video is "h264" or "hevc"; + var frameTicks = coded ? 3000 : 3600; // 30 or 25 pictures a second + var frames = coded ? o.Stream!.Count : o.Frames; using var output = new MemoryStream(); var audioTime = o.FirstPts; for (var i = 0; i < frames; i++) @@ -376,14 +377,14 @@ internal static class LegacyTestVideos output.Write([0, 0, 1, 0xBB, 0, 12, 0x80, 0x00, 0x01, 0x04, 0xE1, 0xFF, 0xE0, 0xE0, 0xE8, 0xC0, 0xC0, 0x20]); if (o.StreamMap) { - var videoType = o.Video switch { "h264" => (byte)0x1B, "mpeg1" => (byte)0x01, _ => (byte)0x02 }; + var videoType = o.Video switch { "h264" => (byte)0x1B, "hevc" => (byte)0x24, "mpeg1" => (byte)0x01, _ => (byte)0x02 }; byte[] map = [videoType, 0xE0, 0, 0, 0x04, 0xC0, 0, 0]; byte[] body = [0x80, 0x01, 0, 0, .. U16((ushort)map.Length), .. map, 0, 0, 0, 0]; output.Write([0, 0, 1, 0xBC, .. U16((ushort)body.Length), .. body]); } } - var picture = o.Video == "h264" ? o.Stream!.WithStartCodes(i) : MpegPicture(o, i, random); + var picture = coded ? o.Stream!.WithStartCodes(i) : MpegPicture(o, i, random); for (var offset = 0; offset < picture.Length; offset += 2000) { var chunk = picture.AsSpan(offset, Math.Min(2000, picture.Length - offset)).ToArray(); diff --git a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs index d283c7e..10a007a 100644 --- a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs +++ b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs @@ -25,6 +25,8 @@ public sealed class MalformedInputTests [DataRow("flv")] [DataRow("mpg")] [DataRow("h264.mpg")] + [DataRow("hevc.mp4")] + [DataRow("hevc.mkv")] public void TruncatedFilesNeverBreakTheReaders(string kind) { var file = Build(kind); @@ -62,6 +64,9 @@ public sealed class MalformedInputTests [DataRow("wmv", 5815)] [DataRow("flv", 5816)] [DataRow("mpg", 5817)] + [DataRow("hevc.mp4", 5815)] + [DataRow("hevc.mkv", 5816)] + [DataRow("hevc.avi", 5817)] public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed) { var file = Build(kind); @@ -313,7 +318,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), diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs index 879d3b3..a150de8 100644 --- a/tests/Febe.Tests/Media/Containers/TestVideos.cs +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -13,7 +13,7 @@ namespace Febe.Tests.Codecs.Containers; /// internal sealed class ElementaryStream { - private ElementaryStream(string name, List> units, int[] rank, bool[] key, byte[] avcC, int width, int height) + private ElementaryStream(string name, List> 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; } + /// An HEVC stream (of the H.265.1 set): then holds its hvcC record. + public bool Hevc { get; } + /// The NAL units (without start codes) of each access unit, in decoding order. public List> Units { get; } @@ -119,22 +123,74 @@ internal sealed class ElementaryStream return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height); } + /// + /// 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 hvcC 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. + /// + public static ElementaryStream LoadHevc(string name) + { + var annexB = File.ReadAllBytes(H265.H265ConformanceStream.Load(name).BitstreamPath); + var units = new List>(); + List? 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(); + 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(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; + /// The same stream with only its first access unit, repeated: a video of a still picture. 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); } /// - /// 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. /// 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); } /// An access unit with 4-byte length prefixes (MP4, Matroska). @@ -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 { Element(0xE7, [0]) }; for (var i = 0; i < es.Count; i++) { @@ -392,7 +449,7 @@ internal static class TestVideos } var strh = new List(); - 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 { 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) { diff --git a/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.bit b/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.bit new file mode 100644 index 0000000..c57b7f0 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.txt b/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.txt new file mode 100644 index 0000000..baeb2f0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.txt @@ -0,0 +1,9 @@ +Bitstream file name: ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.bit +Conformance point: HM-14.0+RExt7.2 +The purpose of the stream: To exercise all the intra prediction modes at all the block sizes for chroma (35 modes for each of C16x32, C8x16, and C4x8) +Picture size: 1920x1080 +Frame rate: 24fp +Bit depth: 10bpp +The number of pictures: 3 pictures (All slices are coded as I slices.) + +- Checksum SEI messages are included. diff --git a/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/riferimento.md5 new file mode 100644 index 0000000..f463cd5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2/riferimento.md5 @@ -0,0 +1,2 @@ +# ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.yuv 1920x1080 4:2:2 10 bit, 3 fotogrammi, 24883200 byte +tutto b045776950c2e06d35348bd03268c07f diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/AMP_A_Samsung_7.bin b/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/AMP_A_Samsung_7.bin new file mode 100644 index 0000000..41d0473 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/AMP_A_Samsung_7.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/AMP_A_Samsung_7.txt b/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/AMP_A_Samsung_7.txt new file mode 100644 index 0000000..cae29eb --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/AMP_A_Samsung_7.txt @@ -0,0 +1,9 @@ +Category: other coding tools; Sub-category: AMP + +The purpose of the stream is to exercise all AMP modes (2NxnU, 2NxND, nLx2N, nRx2N). + +The bitstream contains I, P, and B slices and one slice per picture. + +Checksum SEI messages are not included. + +Spec. version : HM15.0. diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/riferimento.md5 new file mode 100644 index 0000000..71794c9 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMP_A_Samsung_7/riferimento.md5 @@ -0,0 +1,2 @@ +# AMP_A_Samsung_7.yuv 2560x1600 4:2:0 8 bit, 17 fotogrammi, 104448000 byte +tutto 93a5875d58072db5539c04e1e943ed9d diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/AMP_B_Samsung_7.bin b/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/AMP_B_Samsung_7.bin new file mode 100644 index 0000000..5741362 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/AMP_B_Samsung_7.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/AMP_B_Samsung_7.txt b/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/AMP_B_Samsung_7.txt new file mode 100644 index 0000000..54f5b0e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/AMP_B_Samsung_7.txt @@ -0,0 +1,9 @@ +Category: other coding tools; Sub-category: AMP + +The purpose of the stream is to exercise a constraint for AMP: AMP is only utilized for PUs of which size is lager than minmum CU. + +The bitstream contains I, P, and B slices and one slice per picture. + +Checksum SEI messages are not included. + +Spec. version : HM15.0. diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/riferimento.md5 new file mode 100644 index 0000000..811939c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMP_B_Samsung_7/riferimento.md5 @@ -0,0 +1,2 @@ +# AMP_B_Samsung_7.yuv 2560x1600 4:2:0 8 bit, 17 fotogrammi, 104448000 byte +tutto 4e051fad4145d5127e16ac2999500069 diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/AMVP_A_MTK_4.bit b/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/AMVP_A_MTK_4.bit new file mode 100644 index 0000000..ede5c3d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/AMVP_A_MTK_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/AMVP_A_MTK_4_Descriptions.txt b/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/AMVP_A_MTK_4_Descriptions.txt new file mode 100644 index 0000000..aba0720 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/AMVP_A_MTK_4_Descriptions.txt @@ -0,0 +1,8 @@ +Software version: HM-10.0 + +Description : +All slices are coded as I or P slices. Each picture contains only one slice. +num_ref_idx_l0_default_active_minus1 is equal to 0, num_ref_idx_l1_default_active_minus1 is equal to 0 and num_ref_idx_active_override_flag is equal to 0. + +Purpose : +Check whether motion vector prediction candidate generation and signalling perform correctly when MV scaling is not needed for spatial MVP candidate generation (All inter-coded PUs within the same slice have the same inter_pred_idc and ref_idx_l0). diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/riferimento.md5 new file mode 100644 index 0000000..7d579ec --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMVP_A_MTK_4/riferimento.md5 @@ -0,0 +1,2 @@ +# AMVP_A_MTK_4.yuv 416x240 4:2:0 8 bit, 30 fotogrammi, 4492800 byte +tutto 5dd1b1099391ad659225fbf94965a6c7 diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/AMVP_B_MTK_4.bit b/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/AMVP_B_MTK_4.bit new file mode 100644 index 0000000..2a6d078 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/AMVP_B_MTK_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/AMVP_B_MTK_4.txt b/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/AMVP_B_MTK_4.txt new file mode 100644 index 0000000..2591282 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/AMVP_B_MTK_4.txt @@ -0,0 +1,9 @@ +Software version: HM-10.0 + +Description : +All slices are coded as I or B slices. Each picture contains only one slice. +Multiple reference pictures are used. For GPB slices, num_ref_idx_l0_default_active_minus1 is equal to 3 and num_ref_idx_active_override_flag is equal to 1. +For non-GPB B slices, num_ref_idx_l0_default_active_minus1 is equal to 1, num_ref_idx_l1_default_active_minus1 is equal to 1 and num_ref_idx_active_override_flag is equal to 0 + +Purpose : +Check whether motion vector prediction candidate generation and signalling perform correctly when neighboring PUs have various partition mode (part_mode), prediction mode (pred_mode_flag), reference index (ref_idx_l0, ref_idx_l1), inter_pred_idc. diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/riferimento.md5 new file mode 100644 index 0000000..b55c842 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMVP_B_MTK_4/riferimento.md5 @@ -0,0 +1,2 @@ +# AMVP_B_MTK_4.yuv 416x240 4:2:0 8 bit, 41 fotogrammi, 6140160 byte +tutto 7fecb4fe8ee4d4838f4a9873b062b819 diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/AMVP_C_Samsung_7.bin b/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/AMVP_C_Samsung_7.bin new file mode 100644 index 0000000..0ff83a3 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/AMVP_C_Samsung_7.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/AMVP_C_Samsung_7.txt b/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/AMVP_C_Samsung_7.txt new file mode 100644 index 0000000..f2be8f0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/AMVP_C_Samsung_7.txt @@ -0,0 +1,9 @@ +Category: inter frame coding; Sub-category: AMVP + +The purpose of the stream is to exercise AMVP for low delay condition. + +The bitstream contains I, and P slices and one slice per picture. + +Checksum SEI messages are not included. + +Spec. version : HM15.0. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/riferimento.md5 new file mode 100644 index 0000000..a4fbd7d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/AMVP_C_Samsung_7/riferimento.md5 @@ -0,0 +1,2 @@ +# AMVP_C_Samsung_7.yuv 832x480 4:2:0 8 bit, 60 fotogrammi, 35942400 byte +tutto 75155ad034919a2846bbdcba13b5f733 diff --git a/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/BUMPING_A_ericsson_1.bit b/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/BUMPING_A_ericsson_1.bit new file mode 100644 index 0000000..e857824 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/BUMPING_A_ericsson_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/BUMPING_A_ericsson_1.txt b/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/BUMPING_A_ericsson_1.txt new file mode 100644 index 0000000..e2e4072 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/BUMPING_A_ericsson_1.txt @@ -0,0 +1,8 @@ +BUMPING_A_ericsson_1 + +This stream tests output order conformance, in particular the “bumping” process. Four temporal layers are used and IRAP pictures with no_output_of_prior_pics_flag equal to 1 are present in the bitstream. + + +All pictures with POC 0-65 are to be output except the pictures with the following POC values: +4, 5, 6, 7, 15, 21, 22, 23, 30, 31, 36, 37, 38, 39, 54, 55, 56. Those pictures are not output since they have not been output yet when IRAPs with no_output_of_prior_pics_flag equal to 1 are encountered in the bitstream. + \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/riferimento.md5 new file mode 100644 index 0000000..f6d1d4c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/BUMPING_A_ericsson_1/riferimento.md5 @@ -0,0 +1,2 @@ +# BUMPING_A_ericsson_1.yuv 416x240 4:2:0 8 bit, 49 fotogrammi, 7338240 byte +tutto 64f213eb1cf45614f0eeb50fd1b725bf diff --git a/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/Bitdepth_A_RExt_Sony_1.bin b/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/Bitdepth_A_RExt_Sony_1.bin new file mode 100644 index 0000000..1f123c2 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/Bitdepth_A_RExt_Sony_1.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/Bitdepth_A_RExt_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/Bitdepth_A_RExt_Sony_1.txt new file mode 100644 index 0000000..f1c53bb --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/Bitdepth_A_RExt_Sony_1.txt @@ -0,0 +1,11 @@ +Bitdepth_A_RExt_Sony + +Spec version: HM14.0+RExt-7.2 + +Feature: Test unequal luma and chroma bitdepth setting. The luma bitdepth is higher than the chroma bitdepth. + +Level: 4.1 (1920x1080x60 YUV 444) + +Frame rate: 60 fps + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/riferimento.md5 new file mode 100644 index 0000000..142831e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/Bitdepth_A_RExt_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# Bitdepth_A_RExt_Sony_1.yuv 1920x1080 4:4:4 12/8 bit, 16 fotogrammi, 199065600 byte +tutto 2b65fa2f384085926deb4f9d20fcd798 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/CAINIT_A_SHARP_4.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/CAINIT_A_SHARP_4.bit new file mode 100644 index 0000000..1fd5819 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/CAINIT_A_SHARP_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/CAINIT_A_SHARP_4.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/CAINIT_A_SHARP_4.txt new file mode 100644 index 0000000..f2d1df2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/CAINIT_A_SHARP_4.txt @@ -0,0 +1,14 @@ +CAINIT_A_SHARP_4 +Software version: HM-11.0 + +Description : +All slices are coded as I or B slices. Each picture contains only one slice. There is one picture parameter set. +cabac_init_present_flag is equal to 0 in picture parameter set. + +Purpose : +To verify whether setting cabac_init_present_flag to 0 disables transmission of cabac_init_flag in slice header referring to the picture parameter set. +if( slice_type = = I ) + initType = 0 +if(slice_type = = B ) + initType = 2 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/riferimento.md5 new file mode 100644 index 0000000..294d5ed --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_A_SHARP_4/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_A_SHARP_4.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto 550c5a918fecda6a284aa5f44c0e2f33 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/CAINIT_B_SHARP_4.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/CAINIT_B_SHARP_4.bit new file mode 100644 index 0000000..083be9d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/CAINIT_B_SHARP_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/CAINIT_B_SHARP_4.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/CAINIT_B_SHARP_4.txt new file mode 100644 index 0000000..7d404ee --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/CAINIT_B_SHARP_4.txt @@ -0,0 +1,14 @@ +CAINIT_B_SHARP_4 +Software version: HM-11.0 + +Description : +All slices are coded as I or B slices. Each picture contains only one slice. There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for B slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = B ) + initType = cabac_init_flag ? 1 : 2 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/riferimento.md5 new file mode 100644 index 0000000..46b2d97 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_B_SHARP_4/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_B_SHARP_4.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto 0c633f8ee5a4c5779cff48ca86273685 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/CAINIT_C_SHARP_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/CAINIT_C_SHARP_3.bit new file mode 100644 index 0000000..fff1765 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/CAINIT_C_SHARP_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/CAINIT_C_SHARP_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/CAINIT_C_SHARP_3.txt new file mode 100644 index 0000000..1c6f1d0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/CAINIT_C_SHARP_3.txt @@ -0,0 +1,14 @@ +CAINIT_C_SHARP_3 +Software version: HM-11.0 + +Description : +All slices are coded as I or P slices. Each picture contains only one slice. There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for P slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = P ) + initType = cabac_init_flag ? 2 : 1 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/riferimento.md5 new file mode 100644 index 0000000..487367e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_C_SHARP_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_C_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto 9c6c5363724a8bad54e2869b655fbf3b diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/CAINIT_D_SHARP_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/CAINIT_D_SHARP_3.bit new file mode 100644 index 0000000..106e67a Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/CAINIT_D_SHARP_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/CAINIT_D_SHARP_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/CAINIT_D_SHARP_3.txt new file mode 100644 index 0000000..5881d64 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/CAINIT_D_SHARP_3.txt @@ -0,0 +1,14 @@ +CAINIT_D_SHARP_3 +Software version: HM-11.0 + +Description : +All slices are coded as I or B slices which are uni-directionally predicted. Each picture contains only one slice. There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for B slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = B ) + initType = cabac_init_flag ? 1 : 2 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/riferimento.md5 new file mode 100644 index 0000000..c66bee3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_D_SHARP_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_D_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto 0231e327044e45971fc30a43a1bd8275 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/CAINIT_E_SHARP_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/CAINIT_E_SHARP_3.bit new file mode 100644 index 0000000..f6d0511 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/CAINIT_E_SHARP_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/CAINIT_E_SHARP_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/CAINIT_E_SHARP_3.txt new file mode 100644 index 0000000..0000760 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/CAINIT_E_SHARP_3.txt @@ -0,0 +1,14 @@ +CAINIT_E_SHARP_3 +Software version: HM-11.0 + +Description : +All slices are coded as I or P slices. Each picture contains only one slice. Each slice contains 4 tiles (2 columns of tiles and 2 rows of tiles with uniform spacing). There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for P slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag in presence of four tiles as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = P ) + initType = cabac_init_flag ? 2 : 1 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/riferimento.md5 new file mode 100644 index 0000000..d87aa1a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_E_SHARP_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_E_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto 55af76d5527af999d12ccc37b1f6b7ae diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/CAINIT_F_SHARP_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/CAINIT_F_SHARP_3.bit new file mode 100644 index 0000000..c927d2b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/CAINIT_F_SHARP_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/CAINIT_F_SHARP_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/CAINIT_F_SHARP_3.txt new file mode 100644 index 0000000..5d4a91e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/CAINIT_F_SHARP_3.txt @@ -0,0 +1,14 @@ +CAINIT_F_SHARP_3 +Software version: HM-11.0 + +Description : +All slices are coded as I or uni-directionally predicted B slices. Each picture contains only one slice. Each slice contains 4 tiles (2 columns of tiles and 2 rows of tiles with uniform spacing). There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for uni-directionally predicted B slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag in presence of four tiles as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = B ) + initType = cabac_init_flag ? 1 : 2 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/riferimento.md5 new file mode 100644 index 0000000..895d9f1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_F_SHARP_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_F_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto 88d8cd2d303b662f0a92a25256957b69 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/CAINIT_G_SHARP_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/CAINIT_G_SHARP_3.bit new file mode 100644 index 0000000..120e37b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/CAINIT_G_SHARP_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/CAINIT_G_SHARP_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/CAINIT_G_SHARP_3.txt new file mode 100644 index 0000000..cce5764 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/CAINIT_G_SHARP_3.txt @@ -0,0 +1,14 @@ +CAINIT_G_SHARP_3 +Software version: HM-11.0 + +Description : +All slices are coded as I or P slices. Each picture contains only one slice. Each slice contains multiple dependent slices. Each dependent slice contains 3 CTBs or less. There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for P slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag in presence of dependent slices as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = P ) + initType = cabac_init_flag ? 2 : 1 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/riferimento.md5 new file mode 100644 index 0000000..a60c19c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_G_SHARP_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_G_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto a7036eac7798f6e8691f0975786d6811 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/CAINIT_H_SHARP_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/CAINIT_H_SHARP_3.bit new file mode 100644 index 0000000..a912e55 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/CAINIT_H_SHARP_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/CAINIT_H_SHARP_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/CAINIT_H_SHARP_3.txt new file mode 100644 index 0000000..e6c5214 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/CAINIT_H_SHARP_3.txt @@ -0,0 +1,14 @@ +CAINIT_H_SHARP_3 +Software version: HM-11.0 + +Description : +All slices are coded as I or uni-directionally predicted B slices. Each picture contains only one slice. Each slice contains multiple dependent slices. Each dependent slice contains 3 CTBs or less. There is one picture parameter set. +cabac_init_present_flag is equal to 1 in picture parameter set. cabac_init_flag is signaled for uni-directionally predicted B slices in the slice header referring the picture parameter set. cabac_init_flag can take on values 0 or 1. + +Purpose : +To verify that the CABAC initialization type is correctly determined based on cabac_init_flag in presence of dependent slices as follows: +if( slice_type = = I ) + initType = 0 +if( slice_type = = B ) + initType = cabac_init_flag ? 1 : 2 + diff --git a/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/riferimento.md5 new file mode 100644 index 0000000..b027dde --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CAINIT_H_SHARP_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CAINIT_H_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte +tutto cfdd3ce0f4cf1eafd012dcb266311d06 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/CCP_8bit_RExt_QCOM.bin b/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/CCP_8bit_RExt_QCOM.bin new file mode 100644 index 0000000..ca24edc Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/CCP_8bit_RExt_QCOM.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/CCP_8bit_RExt_QCOM.txt b/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/CCP_8bit_RExt_QCOM.txt new file mode 100644 index 0000000..953143d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/CCP_8bit_RExt_QCOM.txt @@ -0,0 +1,9 @@ +CCP_8bit_RExt_QCOM + +Spec version: HM14.0+RExt-7.2 + +Feature: Test cross-component prediction + +Picture size: 1280x720 YUV 444 8 bit + +Frame rate: 30 fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/riferimento.md5 new file mode 100644 index 0000000..3dfbbc3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CCP_8bit_RExt_QCOM_1/riferimento.md5 @@ -0,0 +1,2 @@ +# CCP_8bit_RExt_QCOM.yuv 1280x720 4:4:4 8 bit, 9 fotogrammi, 24883200 byte +tutto 54231c6f121ca65d8b94a747b9504b8b diff --git a/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/CIP_A_Panasonic_3.bit b/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/CIP_A_Panasonic_3.bit new file mode 100644 index 0000000..47587c0 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/CIP_A_Panasonic_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/CIP_A_Panasonic_3.txt b/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/CIP_A_Panasonic_3.txt new file mode 100644 index 0000000..2f38529 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/CIP_A_Panasonic_3.txt @@ -0,0 +1,14 @@ +CIP_A_Panasonic_3:(CIP_A_Panasonic_3.bit) + +Conformance point: HM-10.0 +(Category: intra coding; Sub-category: constrained intra prediction) + +The purpose of the stream is to exercise the reference sample substitution process for intra sample prediction. + +The bitstream contains one I picture and one B picture. +No. slice per picture = 1 +profile_idc = MAIN +level_idc = LEVEL4 +constrained_intra_pred_flag = 1 +SAO = 0 +DBF = 0 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/riferimento.md5 new file mode 100644 index 0000000..7100822 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CIP_A_Panasonic_3/riferimento.md5 @@ -0,0 +1,2 @@ +# CIP_A_Panasonic_3.yuv 416x240 4:2:0 8 bit, 2 fotogrammi, 299520 byte +tutto 4cbf601ba98d63f642defab5eaa12c8d diff --git a/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/CIP_C_Panasonic_2.bit b/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/CIP_C_Panasonic_2.bit new file mode 100644 index 0000000..3c3fcb9 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/CIP_C_Panasonic_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/CIP_C_Panasonic_2.txt b/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/CIP_C_Panasonic_2.txt new file mode 100644 index 0000000..9805918 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/CIP_C_Panasonic_2.txt @@ -0,0 +1,14 @@ +CIP_C_Panasonic_2:(CIP_C_Panasonic_2.bit) + +Conformance point: HM-10.0 +(Category: intra coding; Sub-category: constrained intra prediction) + +The purpose of the stream is to exercise the reference sample substitution process for intra sample prediction. + +The bitstream contains one I picture and one B picture. +No. slice per picture = 3 +profile_idc = MAIN +level_idc = LEVEL4 +constrained_intra_pred_flag = 1 +SAO = 0 +DBF = 0 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/riferimento.md5 new file mode 100644 index 0000000..1d71841 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CIP_C_Panasonic_2/riferimento.md5 @@ -0,0 +1,2 @@ +# CIP_C_Panasonic_2.yuv 416x240 4:2:0 8 bit, 2 fotogrammi, 299520 byte +tutto ed985932fef2aa8a74ded970070bdab2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/CONFWIN_A_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/CONFWIN_A_Sony_1.bit new file mode 100644 index 0000000..9efad25 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/CONFWIN_A_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/CONFWIN_A_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/CONFWIN_A_Sony_1.txt new file mode 100644 index 0000000..36c7dd7 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/CONFWIN_A_Sony_1.txt @@ -0,0 +1,6 @@ +RaceHorses_416x240_30.yuv +NumOfFrames: 60 +conf_win_bottom_offset = 1 +conf_win_top_offset = 1 +conf_win_left_offset = 1 +conf_win_right_offset = 1 diff --git a/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/riferimento.md5 new file mode 100644 index 0000000..bda8b9d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/CONFWIN_A_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# CONFWIN_A_Sony_1.yuv 412x236 4:2:0 8 bit, 60 fotogrammi, 8750880 byte +tutto a3ce3f936ff69ff1ec2621a622dd37ac diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/DBLK_A_MAIN10_VIXS_4.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/DBLK_A_MAIN10_VIXS_4.bit new file mode 100644 index 0000000..b28db2a Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/DBLK_A_MAIN10_VIXS_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/DBLK_A_MAIN10_VIXS_4.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/DBLK_A_MAIN10_VIXS_4.txt new file mode 100644 index 0000000..a1ebb38 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/DBLK_A_MAIN10_VIXS_4.txt @@ -0,0 +1,7 @@ +DBLK_A_MAIN10_VIXS_4.bit + +Spec version : HM10.0 + +negative QP for deblocking filter (Main10) + +Note: In version 4, the last non zero byte of DBLK_A_MAIN10_VIXS_3 was discarded. diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/riferimento.md5 new file mode 100644 index 0000000..b8e8a2b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_MAIN10_VIXS_4/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_A_MAIN10_VIXS_4.yuv 176x144 4:2:0 10 bit, 8 fotogrammi, 608256 byte +tutto c4594956bb9e8303f1662f9eb1bcdf50 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/DBLK_A_SONY_3.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/DBLK_A_SONY_3.bit new file mode 100644 index 0000000..41fd74d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/DBLK_A_SONY_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/Readme.txt new file mode 100644 index 0000000..55682dd --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/Readme.txt @@ -0,0 +1,15 @@ +DBLK_A_Sony_2: +Spec version: HM10.1 + +Check various combination of beta offset and tc offset + +I, P, B slices +Multi slice per picture +random tc offset (min to max) +random beta offset (min to max) +random QP (22 to 51) + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/riferimento.md5 new file mode 100644 index 0000000..e67e569 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_A_SONY_3/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_A_SONY_3.yuv 832x480 4:2:0 8 bit, 30 fotogrammi, 17971200 byte +tutto 42486a48ea12d5ab6cd98ed2e2807cfe diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/DBLK_B_SONY_3.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/DBLK_B_SONY_3.bit new file mode 100644 index 0000000..9a16c1c Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/DBLK_B_SONY_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/Readme.txt new file mode 100644 index 0000000..82abdef --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/Readme.txt @@ -0,0 +1,15 @@ +DBLK_B_Sony_2: +Spec version: HM10.1 + +Check various combination of chroma QP offset + + +I, P, B slices +Multi slice per picture +random pps_cb_qp_offset, slice_cb_qp_offset +random pps_cr_qp_offset, slice_cr_qp_offset + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/riferimento.md5 new file mode 100644 index 0000000..0042307 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_B_SONY_3/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_B_SONY_3.yuv 832x480 4:2:0 8 bit, 30 fotogrammi, 17971200 byte +tutto cf5de25a94a33e2d4237b8d1c773db06 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/DBLK_C_SONY_3.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/DBLK_C_SONY_3.bit new file mode 100644 index 0000000..f2311a6 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/DBLK_C_SONY_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/Readme.txt new file mode 100644 index 0000000..d146631 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/Readme.txt @@ -0,0 +1,12 @@ +DBLK_C_Sony_2: +Spec version: HM10.1 + +Check random deblock On/Off + + +I, P, B slices +Multi slice per picture +random sps_disable_deblocking_filter_flag ON/OFF +pps_disable_deblocking_filter_flag = 0 + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/riferimento.md5 new file mode 100644 index 0000000..9ca1de6 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_C_SONY_3/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_C_SONY_3.yuv 832x480 4:2:0 8 bit, 30 fotogrammi, 17971200 byte +tutto 41f89edc63b1175ffc1fae909f4fed82 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/DBLK_D_VIXS_2.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/DBLK_D_VIXS_2.bit new file mode 100644 index 0000000..27f339f Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/DBLK_D_VIXS_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/DBLK_D_VIXS_2.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/DBLK_D_VIXS_2.txt new file mode 100644 index 0000000..8c86dec --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/DBLK_D_VIXS_2.txt @@ -0,0 +1,7 @@ +DBLK_D_VIXS_2.bit + +Spec version : HM10.0 + +check loop filter cross slice/tile. slice cover tile + +PPS: loop_filter_across_slices_enabled_flag = 0, loop_filter_across_tiles_enabled_flag = 1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/riferimento.md5 new file mode 100644 index 0000000..3e4573b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_D_VIXS_2/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_D_VIXS_2.yuv 1280x720 4:2:0 8 bit, 8 fotogrammi, 11059200 byte +tutto f6f3075edca573f5dfe4e352d26170f1 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/DBLK_E_VIXS_2.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/DBLK_E_VIXS_2.bit new file mode 100644 index 0000000..92fe365 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/DBLK_E_VIXS_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/DBLK_E_VIXS_2.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/DBLK_E_VIXS_2.txt new file mode 100644 index 0000000..898bd96 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/DBLK_E_VIXS_2.txt @@ -0,0 +1,7 @@ +DBLK_E_VIXS_2.bit + +Spec version : HM10.0 + +check loop filter cross slice/tile. slice cover tile + +PPS: loop_filter_across_slices_enabled_flag = 1, loop_filter_across_tiles_enabled_flag = 0 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/riferimento.md5 new file mode 100644 index 0000000..614177f --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_E_VIXS_2/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_E_VIXS_2.yuv 1280x720 4:2:0 8 bit, 8 fotogrammi, 11059200 byte +tutto 1f94d56d9e462967cad73284ed0f43f9 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/DBKL_F_VIXS_2.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/DBKL_F_VIXS_2.txt new file mode 100644 index 0000000..d505e90 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/DBKL_F_VIXS_2.txt @@ -0,0 +1,7 @@ +DBLK_F_VIXS_2.bit + +Spec version : HM10.0 + +check loop filter cross slice/tile. tile cover slice + +PPS: loop_filter_across_slices_enabled_flag = 0, loop_filter_across_tiles_enabled_flag = 1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/DBLK_F_VIXS_2.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/DBLK_F_VIXS_2.bit new file mode 100644 index 0000000..f281857 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/DBLK_F_VIXS_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/riferimento.md5 new file mode 100644 index 0000000..50e2647 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_F_VIXS_2/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_F_VIXS_2.yuv 1280x720 4:2:0 8 bit, 8 fotogrammi, 11059200 byte +tutto c94d0c0d80c93a2edd372a1fd12f93a1 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/DBLK_G_VIXS_2.bit b/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/DBLK_G_VIXS_2.bit new file mode 100644 index 0000000..92fe365 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/DBLK_G_VIXS_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/DBLK_G_VIXS_2.txt b/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/DBLK_G_VIXS_2.txt new file mode 100644 index 0000000..294f1a8 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/DBLK_G_VIXS_2.txt @@ -0,0 +1,7 @@ +DBLK_G_VIXS_2.bit + +Spec version : HM10.0 + +check loop filter cross slice/tile. tile cover slice + +PPS: loop_filter_across_slices_enabled_flag = 1, loop_filter_across_tiles_enabled_flag = 0 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/riferimento.md5 new file mode 100644 index 0000000..cc9bb8c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DBLK_G_VIXS_2/riferimento.md5 @@ -0,0 +1,2 @@ +# DBLK_G_VIXS_2.yuv 1280x720 4:2:0 8 bit, 8 fotogrammi, 11059200 byte +tutto 1f94d56d9e462967cad73284ed0f43f9 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/DELTAQP_C_SONY_3.bit b/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/DELTAQP_C_SONY_3.bit new file mode 100644 index 0000000..9c9a458 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/DELTAQP_C_SONY_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/Readme.txt new file mode 100644 index 0000000..881fbbc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/Readme.txt @@ -0,0 +1,13 @@ +DELTAQP_C_Sony_2: +Spec version: HM10.1 + +Check if decoder can handle dQP + + +I, P, B slices +Multi slice per picture +random cu_qp_delta +Cbf = 0 in some TU + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/riferimento.md5 new file mode 100644 index 0000000..c00ca36 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DELTAQP_C_SONY_3/riferimento.md5 @@ -0,0 +1,2 @@ +# DELTAQP_C_SONY_3.yuv 832x480 4:2:0 8 bit, 30 fotogrammi, 17971200 byte +tutto 1c2be685b1ae953787e0e93c656ee502 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/DSLICE_A_HHI_5.bin b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/DSLICE_A_HHI_5.bin new file mode 100644 index 0000000..3bb7a91 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/DSLICE_A_HHI_5.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/DSLICE_A_HHI_5.txt b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/DSLICE_A_HHI_5.txt new file mode 100644 index 0000000..ced6162 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/DSLICE_A_HHI_5.txt @@ -0,0 +1,6 @@ +purpose: test correct decoding of independent and dependent slice segments +conformance: HM-10.0 +resolution: 1920x1080 +# of frames: 50 + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/riferimento.md5 new file mode 100644 index 0000000..172d5ac --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_A_HHI_5/riferimento.md5 @@ -0,0 +1,2 @@ +# DSLICE_A_HHI_5.yuv 1920x1080 4:2:0 8 bit, 50 fotogrammi, 155520000 byte +tutto c7caf3164b0a316549ac7244f66f1294 diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/DSLICE_B_HHI_5.bin b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/DSLICE_B_HHI_5.bin new file mode 100644 index 0000000..f937e42 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/DSLICE_B_HHI_5.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/DSLICE_B_HHI_5.txt b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/DSLICE_B_HHI_5.txt new file mode 100644 index 0000000..186d583 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/DSLICE_B_HHI_5.txt @@ -0,0 +1,6 @@ +purpose: test correct decoding of dependent slice segments in combination with substreams (WPP) +conformance: HM-10.0 +resolution: 1920x1080 +# of frames: 50 + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/riferimento.md5 new file mode 100644 index 0000000..3cf7dd0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_B_HHI_5/riferimento.md5 @@ -0,0 +1,2 @@ +# DSLICE_B_HHI_5.yuv 1920x1080 4:2:0 8 bit, 50 fotogrammi, 155520000 byte +tutto 2e072130f116a4d0f7fc69fa76cfcdfb diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/DSLICE_C_HHI_5.bin b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/DSLICE_C_HHI_5.bin new file mode 100644 index 0000000..9775978 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/DSLICE_C_HHI_5.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/DSLICE_C_HHI_5.txt b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/DSLICE_C_HHI_5.txt new file mode 100644 index 0000000..2a9da9c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/DSLICE_C_HHI_5.txt @@ -0,0 +1,6 @@ +purpose: test correct decoding dependent slice segments in combination with tiles +conformance: HM-10.0 +resolution: 1920x1080 +# of frames: 50 + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/riferimento.md5 new file mode 100644 index 0000000..2990e90 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/DSLICE_C_HHI_5/riferimento.md5 @@ -0,0 +1,2 @@ +# DSLICE_C_HHI_5.yuv 1920x1080 4:2:0 8 bit, 50 fotogrammi, 155520000 byte +tutto 505a47c5ce4bc66ef5661aeb778b0f1f diff --git a/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/ENTP_B_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/ENTP_B_Qualcomm_1.bit new file mode 100644 index 0000000..4dd7c22 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/ENTP_B_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/ENTP_B_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/ENTP_B_Qualcomm_1.txt new file mode 100644 index 0000000..2a937b3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/ENTP_B_Qualcomm_1.txt @@ -0,0 +1,20 @@ +ENTP_B_Qualcomm_1 + +Specification version: HM13.0 + +Category: Entry Point +Replacement for ENTP_X_LG_X conformance test bitstreams + +Specification: +- 1080p60 +- 24 frames +- Random access configuration +- One slice per picture +- Six tiles per picture + * num_tiles_columns_minus1 = 1 + * num_tiles_rows_minus1 = 2 + * uniform_spacing_idc = 1 +- MD5 checksum is included in the bitstream +NOTE: There are some pictures (e.g., POC 4, 6, 10, 12, 18, and 20) contains a tile in which emulation prevention bytes occur. + +Purpose: Test entry point signalling in slice header when tile is used and when emulation prevention bytes occur in substream(s) diff --git a/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..d22bed5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ENTP_B_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# ENTP_B_Qualcomm_1.yuv 1920x1080 4:2:0 8 bit, 24 fotogrammi, 74649600 byte +tutto 6577f102b93577eb899e0bff1a20a401 diff --git a/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/ENTP_C_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/ENTP_C_Qualcomm_1.bit new file mode 100644 index 0000000..bc543da Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/ENTP_C_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/ENTP_C_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/ENTP_C_Qualcomm_1.txt new file mode 100644 index 0000000..d2c53ac --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/ENTP_C_Qualcomm_1.txt @@ -0,0 +1,16 @@ +ENTP_C_Qualcomm_1 + +Specification version: HM13.0 + +Category: Entry Point +Replacement for ENTP_X_LG_X conformance test bitstreams + +Specification: +- 1080p60 +- 24 frames +- Low delay main configuration +- One slice per picture +- Wavefront enabled +- MD5 checksum is included in the bitstream + +Purpose: Test entry point signalling in slice header when wavefront is used. diff --git a/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..112f041 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ENTP_C_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# ENTP_C_Qualcomm_1.yuv 1920x1080 4:2:0 8 bit, 24 fotogrammi, 74649600 byte +tutto 0b607e6e7946e6e8d0f92a1a294d135d diff --git a/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/EXT_A_ericsson_4.bit b/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/EXT_A_ericsson_4.bit new file mode 100644 index 0000000..05ab42a Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/EXT_A_ericsson_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/EXT_A_ericsson_4.txt b/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/EXT_A_ericsson_4.txt new file mode 100644 index 0000000..57a89cf --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/EXT_A_ericsson_4.txt @@ -0,0 +1,4 @@ + +EXT_A_ericsson_4 + +This stream contains extension fields in SPS, PPS, and slice header. Note that this bitstream is not a conforming bitstream but conforming decoders are required to be able to ignore the extensions. diff --git a/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/riferimento.md5 new file mode 100644 index 0000000..6a7d2a1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/EXT_A_ericsson_4/riferimento.md5 @@ -0,0 +1,2 @@ +# EXT_A_ericsson_4.yuv 416x240 4:2:0 8 bit, 3 fotogrammi, 449280 byte +tutto 5797b3114fe12daf1ce522ed70ce4078 diff --git a/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/FILLER_A_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/FILLER_A_Sony_1.bit new file mode 100644 index 0000000..198b7ce Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/FILLER_A_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/FILLER_A_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/FILLER_A_Sony_1.txt new file mode 100644 index 0000000..accd5da --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/FILLER_A_Sony_1.txt @@ -0,0 +1,4 @@ +RaceHorses_416x240_30.yuv +NumOfFrames: 60 +nal_unit_type = 38 (filler data) at the end of every AU + diff --git a/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/riferimento.md5 new file mode 100644 index 0000000..163d639 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/FILLER_A_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# FILLER_A_Sony_1.yuv 416x240 4:2:0 8 bit, 60 fotogrammi, 8985600 byte +tutto f92a928770a41b63e7cfc89ea198790f diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/GENERAL_10b_422_RExt_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/GENERAL_10b_422_RExt_Sony_1.bit new file mode 100644 index 0000000..703133d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/GENERAL_10b_422_RExt_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/GENERAL_10b_422_RExt_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/GENERAL_10b_422_RExt_Sony_1.txt new file mode 100644 index 0000000..be219f5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/GENERAL_10b_422_RExt_Sony_1.txt @@ -0,0 +1,11 @@ +Category: general coding tools; Sub-category: "Main 4:2:2 10 Intra" (with general_lower_bit_rate_constraint_flag=1) profile with 10bit 4:2:2 video data + +The purpose of the stream is to exercise some combinations of RExt tools in the specified profile / format +The stream consists of a concatenation of sequences, each containing just one picture: + Sequence 0: chroma_qp_offset_list_enabled_flag=0 + Sequence 1: chroma_qp_offset_list_enabled_flag=1 + +Level=3, tier=main + +Checksum SEI messages are included. +Spec. version : HM16.2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/riferimento.md5 new file mode 100644 index 0000000..a4762d3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_10b_422_RExt_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# GENERAL_10b_422_RExt_Sony_1.yuv 400x384 4:2:2 10 bit, 2 fotogrammi, 1228800 byte +tutto ea5dfb01c95bffb169cd78e549bd39ab diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/GENERAL_12b_420_RExt_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/GENERAL_12b_420_RExt_Sony_1.bit new file mode 100644 index 0000000..c5e0da4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/GENERAL_12b_420_RExt_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/GENERAL_12b_420_RExt_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/GENERAL_12b_420_RExt_Sony_1.txt new file mode 100644 index 0000000..7f5f8da --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/GENERAL_12b_420_RExt_Sony_1.txt @@ -0,0 +1,8 @@ +Category: general coding tools; Sub-category: "Main 12 Intra" (with general_lower_bit_rate_constraint_flag=1) profile with 12bit 4:2:0 video data + +The purpose of the stream is to exercise some combinations of RExt tools in the specified profile / format + +Level=3, tier=main + +Checksum SEI messages are included. +Spec. version : HM16.2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/riferimento.md5 new file mode 100644 index 0000000..ff44430 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_12b_420_RExt_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# GENERAL_12b_420_RExt_Sony_1.yuv 400x384 4:2:0 12 bit, 1 fotogrammi, 460800 byte +tutto 27a2b09b136687f7a391bfdbc50ac964 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/GENERAL_8b_400_RExt_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/GENERAL_8b_400_RExt_Sony_1.bit new file mode 100644 index 0000000..c4e9103 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/GENERAL_8b_400_RExt_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/GENERAL_8b_400_RExt_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/GENERAL_8b_400_RExt_Sony_1.txt new file mode 100644 index 0000000..5bab059 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/GENERAL_8b_400_RExt_Sony_1.txt @@ -0,0 +1,8 @@ +Category: general coding tools; Sub-category: "Monochrome" profile with 8bit 4:0:0 video data + +The purpose of the stream is to exercise some combinations of RExt tools in the specified profile / format + +Level=3, tier=main + +Checksum SEI messages are included. +Spec. version : HM16.2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/riferimento.md5 new file mode 100644 index 0000000..c471c83 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_400_RExt_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# GENERAL_8b_400_RExt_Sony_1.yuv 400x384 4:0:0 8 bit, 1 fotogrammi, 153600 byte +tutto e5223be3da805fb96440dbf2bd170db0 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/GENERAL_8b_420_RExt_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/GENERAL_8b_420_RExt_Sony_1.bit new file mode 100644 index 0000000..c4e6f4c Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/GENERAL_8b_420_RExt_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/GENERAL_8b_420_RExt_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/GENERAL_8b_420_RExt_Sony_1.txt new file mode 100644 index 0000000..c3100df --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/GENERAL_8b_420_RExt_Sony_1.txt @@ -0,0 +1,8 @@ +Category: general coding tools; Sub-category: "Main Intra" (with general_lower_bit_rate_constraint_flag=1) profile with 8bit 4:2:0 video data + +The purpose of the stream is to exercise some combinations of RExt tools in the specified profile / format + +Level=3, tier=main + +Checksum SEI messages are included. +Spec. version : HM16.2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/riferimento.md5 new file mode 100644 index 0000000..9dc3647 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_420_RExt_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# GENERAL_8b_420_RExt_Sony_1.yuv 400x384 4:2:0 8 bit, 1 fotogrammi, 230400 byte +tutto 99eb7a5106988759fd0eaecdb66e2cd2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/GENERAL_8b_444_RExt_Sony_2.bit b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/GENERAL_8b_444_RExt_Sony_2.bit new file mode 100644 index 0000000..d506ab1 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/GENERAL_8b_444_RExt_Sony_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/GENERAL_8b_444_RExt_Sony_2.txt b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/GENERAL_8b_444_RExt_Sony_2.txt new file mode 100644 index 0000000..024ef6b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/GENERAL_8b_444_RExt_Sony_2.txt @@ -0,0 +1,22 @@ +Category: general coding tools; Sub-category: "Main 4:4:4 Intra" (with general_lower_bit_rate_constraint_flag=1) profile with 8bit 4:4:4 video data + +The purpose of the stream is to exercise some combinations of RExt tools in the specified profile / format +The stream consists of a concatenation of sequences, each just two pictures: + the first of each pair has cross_component_prediction_prediction_enabled_flag=0, + the second has cross_component_prediction_prediction_enabled_flag=1. +The concatenated sequences consist of: + Sequence 0: transform_skip_rotation_enabled_flag=0, transform_skip_context_enabled_flag=0, implicit_rdpcm_enabled_flag=0, intra_smoothing_disabled_flag=0, + persistent_rice_adaptation_enabled_flag=0, chroma_qp_offset_list_enabled_flag=0 + Sequence 1: as in sequence 0, but with transform_skip_rotation=1 + Sequence 2: as in sequence 0, but with transform_skip_context=1 + Sequence 3: as in sequence 0, but with implicit_rdpcm=1 + Sequence 4: as in sequence 0, but with intra_smoothing_disabled=1 + Sequence 5: as in sequence 0, but with persistent_rice_adaptation_enabled_flag=1 + Sequence 6: as in sequence 0, but with chroma_qp_offset_list_enabled_flag=1 + +This revision now uses a CRA slice for the second slice of each pair rather than a TRAIL_R + +Level=3, tier=main + +Checksum SEI messages are included. +Spec. version : HM16.3 diff --git a/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/riferimento.md5 new file mode 100644 index 0000000..229e551 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/GENERAL_8b_444_RExt_Sony_2/riferimento.md5 @@ -0,0 +1,2 @@ +# GENERAL_8b_444_RExt_Sony_2.yuv 400x384 4:4:4 8 bit, 14 fotogrammi, 6451200 byte +tutto 3ed16fed34c4ed3ad8fe31962fb77aac diff --git a/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/HRD_A_Fujitsu_3.bin b/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/HRD_A_Fujitsu_3.bin new file mode 100644 index 0000000..c624cf7 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/HRD_A_Fujitsu_3.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/HRD_A_Fujitsu_3.txt b/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/HRD_A_Fujitsu_3.txt new file mode 100644 index 0000000..48842c2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/HRD_A_Fujitsu_3.txt @@ -0,0 +1,12 @@ +HRD_A_Fujitsu_3: +Frame rate: 50 fps +Picture size: 416x240 +Spec version: HM11.0 + +Check DU-based CPB removal time signalling. + +Each AU contains 4 DUs. + +sub_pic_cpb_params_present_flag = 1 +du_common_cpb_removal_delay_flag = 0 +sub_pic_cpb_params_in_pic_timing_sei_flag = 0 diff --git a/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/riferimento.md5 new file mode 100644 index 0000000..7b26d4a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/HRD_A_Fujitsu_3/riferimento.md5 @@ -0,0 +1,2 @@ +# HRD_A_Fujitsu_3.yuv 416x240 4:2:0 8 bit, 96 fotogrammi, 14376960 byte +tutto f6d04dba2ef09bcadbea7b8ab5c8c917 diff --git a/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/INITQP_A_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/INITQP_A_Sony_1.bit new file mode 100644 index 0000000..36c8f43 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/INITQP_A_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/INITQP_A_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/INITQP_A_Sony_1.txt new file mode 100644 index 0000000..e7beddc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/INITQP_A_Sony_1.txt @@ -0,0 +1,3 @@ +RaceHorses_416x240_30.yuv +NumOfFrames: 60 +init_qp_minus26 : -26 tp 25 diff --git a/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/riferimento.md5 new file mode 100644 index 0000000..ca7fb8c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/INITQP_A_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# INITQP_A_Sony_1.yuv 416x240 4:2:0 8 bit, 60 fotogrammi, 8985600 byte +tutto 2716af552e71ef61221b86130ad3d444 diff --git a/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/INITQP_B_Main10_Sony_1.bit b/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/INITQP_B_Main10_Sony_1.bit new file mode 100644 index 0000000..f04fb74 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/INITQP_B_Main10_Sony_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/INITQP_B_Main10_Sony_1.txt b/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/INITQP_B_Main10_Sony_1.txt new file mode 100644 index 0000000..0175ab7 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/INITQP_B_Main10_Sony_1.txt @@ -0,0 +1,3 @@ +RaceHorses_416x240_30.yuv (10bit) +NumOfFrames: 90 +init_qp_minus26 : -38 tp 25 diff --git a/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/riferimento.md5 new file mode 100644 index 0000000..a176201 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/INITQP_B_Main10_Sony_1/riferimento.md5 @@ -0,0 +1,2 @@ +# INITQP_B_Main10_Sony_1.yuv 416x240 4:2:0 10 bit, 90 fotogrammi, 26956800 byte +tutto f63c71e5f6b9c6ddf2b080524f9f14b1 diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/IPCM_A_RExt_NEC.txt b/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/IPCM_A_RExt_NEC.txt new file mode 100644 index 0000000..1bf710e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/IPCM_A_RExt_NEC.txt @@ -0,0 +1,13 @@ +Bitstream file name: IPCM_A_RExt_NEC_1.bit + +Conformance point: HM-14.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. pcm_enabled_flag is equal to 1. Both pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 7. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 0, 1 and 0, respectively. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. Test parsing of 4:2:2 format pcm_sample_luma and pcm_sample_chroma data in PCM sample syntax. + +Purpose: Check that decoder can correctly decode the slice of coded frames containing pcm_flags. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/IPCM_A_RExt_NEC_2.bit b/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/IPCM_A_RExt_NEC_2.bit new file mode 100644 index 0000000..5818959 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/IPCM_A_RExt_NEC_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/riferimento.md5 new file mode 100644 index 0000000..8dbdad7 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPCM_A_RExt_NEC_2/riferimento.md5 @@ -0,0 +1,2 @@ +# IPCM_A_RExt_NEC_2.yuv 416x240 4:2:2 10 bit, 1 fotogrammi, 399360 byte +tutto 8d4eb18812338f9f475035b8da27e74a diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/IPCM_B_RExt_NEC.bit b/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/IPCM_B_RExt_NEC.bit new file mode 100644 index 0000000..499e7fd Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/IPCM_B_RExt_NEC.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/IPCM_B_RExt_NEC.txt b/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/IPCM_B_RExt_NEC.txt new file mode 100644 index 0000000..394cfa2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/IPCM_B_RExt_NEC.txt @@ -0,0 +1,13 @@ +Bitstream file name: IPCM_B_RExt_NEC_1.bit + +Conformance point: HM-14.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. pcm_enabled_flag is equal to 1. Both pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 7. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 0, 1 and 0, respectively. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. Test parsing of 4:4:4 format pcm_sample_luma and pcm_sample_chroma data in PCM sample syntax. + +Purpose: Check that decoder can correctly decode the slice of coded frames containing pcm_flags. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/riferimento.md5 new file mode 100644 index 0000000..a67ec9e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPCM_B_RExt_NEC/riferimento.md5 @@ -0,0 +1,2 @@ +# IPCM_B_RExt_NEC.yuv 416x240 4:4:4 12 bit, 1 fotogrammi, 599040 byte +tutto eea32e6e1f88b7782515e53f8122be7d diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/IPRED_A_docomo_2.bit b/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/IPRED_A_docomo_2.bit new file mode 100644 index 0000000..7833d8c Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/IPRED_A_docomo_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/IPRED_A_docomo_2.txt b/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/IPRED_A_docomo_2.txt new file mode 100644 index 0000000..9993bca --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/IPRED_A_docomo_2.txt @@ -0,0 +1,13 @@ +IPRED_A_docomo_2: +Frame rate: 30 fps +Picture size: 832x480 +Spec version: HM10.1 + +(Category: intra coding; Sub-category: intra prediction) + +The purpose of the stream is to exercise all intra prediction modes (35 modes for each of Y32x32, Y16x16, Y8x8, Y4x4, C16x16, C8x8, and C4x4 for a total of 245 modes). +The bitstream contains only I slices and one slice per picture. Checksum SEI messages are included. + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/riferimento.md5 new file mode 100644 index 0000000..f669589 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPRED_A_docomo_2/riferimento.md5 @@ -0,0 +1,2 @@ +# IPRED_A_docomo_2.yuv 832x480 4:2:0 8 bit, 20 fotogrammi, 11980800 byte +tutto 0e4e9bd00b74e30e400de46ee7ad8023 diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/IPRED_B_Nokia_3.bit b/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/IPRED_B_Nokia_3.bit new file mode 100644 index 0000000..67c1e8d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/IPRED_B_Nokia_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/IPRED_B_Nokia_3.txt b/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/IPRED_B_Nokia_3.txt new file mode 100644 index 0000000..8240913 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/IPRED_B_Nokia_3.txt @@ -0,0 +1,8 @@ +The bitstream: +- is named as IPRED_B_Nokia_3.bit +- is based on HM 10.0 +- exercises all the intra prediction modes at all the block sizes (35 modes for each of Y32x32, Y16x16, Y8x8, Y4x4, C16x16, C8x8, and C4x4 for a total of 245 modes) +- contains one picture of size 1920x1080 samples consisting of one I slice +- general_profile_idc indicating Main Still Picture profile +- general_level_idc indicating Level 4 +- includes an MD5 checksum SEI message diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/riferimento.md5 new file mode 100644 index 0000000..8e6efbc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPRED_B_Nokia_3/riferimento.md5 @@ -0,0 +1,3 @@ +# IPRED_B_Nokia_3.yuv 1920x1080 4:2:0 8 bit, 1 fotogrammi, 3110400 byte +tutto ec3bcad4f9174404e52d132206b6617b +0 ec3bcad4f9174404e52d132206b6617b diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/IPRED_C_Mitsubishi_3.bit b/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/IPRED_C_Mitsubishi_3.bit new file mode 100644 index 0000000..4aed7f5 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/IPRED_C_Mitsubishi_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/IPRED_C_Mitsubishi_3.txt b/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/IPRED_C_Mitsubishi_3.txt new file mode 100644 index 0000000..c840dc5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/IPRED_C_Mitsubishi_3.txt @@ -0,0 +1,8 @@ +Bitstream file name: IPRED_C_Mitsubishi_3.bit +Conformance point: HM-10.0 +The purpose of the stream: To exercise all the intra prediction modes at all the block sizes (35 modes for each of Y32x32, Y16x16, Y8x8, Y4x4, C16x16, C8x8, and C4x4 for a total of 245 modes) +Picture size: 832x480 +Frame rate: 30fp +The number of pictures: 4 pictures (All slices are coded as I slices.) + +- Checksum SEI messages are included. diff --git a/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/riferimento.md5 new file mode 100644 index 0000000..d072e34 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/IPRED_C_Mitsubishi_3/riferimento.md5 @@ -0,0 +1,2 @@ +# IPRED_C_Mitsubishi_3.yuv 832x480 4:2:0 8 bit, 4 fotogrammi, 2396160 byte +tutto 6043c04fecc60ee88f4247aaca96441f diff --git a/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md new file mode 100644 index 0000000..e84fc23 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/LEGGIMI.md @@ -0,0 +1,308 @@ +# Flussi di conformità H.265 (HEVC) + +Questi flussi provano il decodificatore HEVC scritto in casa (`src/Febe.Core/Codecs/H265`), che serve per i video HEVC +e per le foto HEIC (profilo Main Still Picture). Tutti i 146 flussi, i 136 Main, Main 10 e Main Still Picture e i 10 +delle estensioni di formato (RExt), danno esattamente i fotogrammi del YUV ufficiale +(`H265ConformanceTests.FramesMatchTheReference`), e ogni immagine decodificata coincide con l'hash SEI del suo +codificatore dove il flusso lo porta (`H265DecoderTests.EveryPictureMatchesItsHash`). Nessuna prova è inconcludente. + +## Provenienza + +Sono flussi della serie di conformità ufficiale **ITU-T H.265.1** («Conformance specification for ITU-T H.265 high +efficiency video coding»), scaricati il 18/11/2026 dalla cartella pubblica dell'ITU-T +`https://www.itu.int/wftp3/av-arch/jctvc-site/bitstream_exchange/draft_conformance/`, sottocartelle `HEVC_v1` (profili +Main, Main 10 e Main Still Picture) e `RExt` (estensioni di formato). Ogni zip contiene il flusso, il `readme` dei suoi +autori, un file MD5 e, per pochi flussi, la ricostruzione YUV ufficiale. + +Ogni cartella contiene tre file: + +- il flusso così com'è, in Annex B, con il suo nome originale (`.bit` o `.bin`; quello di `SLIST_D_Sony_9` si chiama + `str.bin`); +- il `readme` degli autori, copiato così com'è (git ne cambia al più i fine riga; alcuni sono in Windows-1252, non + in UTF-8); +- `riferimento.md5`, scritto una volta da noi (sotto). + +I file YUV ricostruiti **non sono nel repository**: pesano centinaia di megabyte e basta il loro MD5. L'insieme pesa +circa 29 MB (29.255.690 byte di flussi, più i `readme`). + +## Che cosa contiene `riferimento.md5` + +``` +# .yuv x bit, fotogrammi, byte +tutto +0 +1 +... +``` + +- L'intestazione descrive il file YUV ufficiale: dimensioni dopo il ritaglio della finestra di conformità, formato del + croma, profondità, numero di fotogrammi in uscita e byte. Nel file i fotogrammi sono nell'ordine di uscita, con i + piani Y, Cb e Cr ritagliati; un byte per campione fino a 8 bit, altrimenti due byte (il meno significativo per primo) + per **tutti** i piani. +- `variabile(176x144,320x240,…)` vuol dire che il flusso cambia dimensioni (solo `VPSSPSPPS_A_MainConcept_1`): i + fotogrammi hanno ciascuno la propria. +- `10/9 bit` vuol dire luma a 10 bit e croma a 9 bit (solo `TSUNEQBD_A_MAIN10_Technicolor_2`, scritto a 16 bit come + ogni flusso oltre gli 8); `12/8 bit` è `Bitdepth_A_RExt_Sony_1`. +- `tutto` è l'MD5 dell'intero file YUV ufficiale, quello che lo zip dichiara nel suo file MD5. Gli zip ne danno due (del + flusso e del YUV) senza dire quale sia quale: è del YUV quello diverso dall'MD5 del flusso calcolato da noi, e ce n'è + sempre esattamente uno. Per i 15 flussi con il YUV nello zip l'MD5 dichiarato coincide con quello calcolato. +- Le righe per fotogramma ci sono solo per i **15 flussi** il cui zip conteneva il YUV: `IPRED_B_Nokia_3`, + `TMVP_A_MS_3`, `TSKIP_A_MS_3` e i dodici `WPP_*`. Per questi l'hash SEI di ogni immagine (sotto) è stato confrontato + con il YUV ufficiale e coincide sempre. + +Una prova passerà solo se i fotogrammi decodificati, messi come nel YUV, hanno l'MD5 per fotogramma (quando c'è), il +numero giusto e l'MD5 complessivo di `tutto` (`H265ConformanceStream.Compare`). + +## Hash delle immagini nei flussi + +Quasi tutti i flussi portano in ogni immagine un messaggio SEI «decoded picture hash» (tipo 132, D.2.20 e D.3.19 di +ITU-T H.265): l'MD5 (o un CRC o una somma di controllo) di ogni piano dell'immagine decodificata, **prima** del ritaglio +della finestra di conformità, nell'ordine di decodifica. `H265PictureHashes` li legge senza decodificatore, scritto dal +testo della norma; così anche i flussi senza YUV ufficiale si possono verificare immagine per immagine, comprese quelle +che non escono. Usano la somma di controllo (tipo 2) `HRD_A_Fujitsu_3`, `PICSIZE_C_Bossen_1` e `PICSIZE_D_Bossen_1`; +tutti gli altri l'MD5. Non hanno nessun hash: `AMP_A`, `AMP_B`, `AMVP_A/B/C`, `CONFWIN_A`, i `DBLK_*`, `DELTAQP_C`, +`FILLER_A`, `INITQP_A/B`, `LTRPSPS_A`, i `MAXBINS_*`, `MERGE_F`, `POC_A`, `RAP_A`, `RPS_A`, `RPS_F`, `SAO_C`…`SAO_H`, +`SAODBLK_A`, `STRUCT_A/B`, `TILES_A/B`, `TUSIZE_A`, `VPSSPSPPS_A` e, fra gli RExt, `IPCM_A/B` e `CCP_8bit`. In +`NUT_A_ericsson_5` non hanno hash le due immagini RASL dopo un BLA, che il decodificatore salta. + +## Quanti fotogrammi escono + +Per i flussi senza YUV il numero di fotogrammi dell'intestazione non viene dallo zip: è contato da noi leggendo il +flusso (SPS, PPS, intestazioni di slice, POC e insiemi di riferimento) e simulando il processo di uscita di C.5.2.2 e +C.5.2.3 (riordino, latenza, buffer pieno, `pic_output_flag`, RASL saltati dopo un CRA iniziale, un BLA o una fine di +sequenza, `no_output_of_prior_pics_flag`). Il conto coincide con i 15 YUV ufficiali e con il `readme` di +`BUMPING_A_ericsson_1`, che elenca le 17 immagini che non escono. Per `NoOutPrior_A_Qualcomm_1` (40), +`NoOutPrior_B_Qualcomm_1` (47) e `RAP_B_Bossen_2` (80), dove un IRAP scarta 3 immagini non ancora uscite, il numero è +stato prima calcolato; il decodificatore l'ha poi confermato, come `tutto` di ogni flusso senza YUV: i fotogrammi +decodificati hanno esattamente quell'MD5. + +## Che cosa copre ciascun flusso (Main, Main 10, Main Still Picture) + +Le caratteristiche vengono dai `readme` degli autori; profilo, dimensioni e fotogrammi dal flusso. «YUV» indica i flussi +con le righe per fotogramma. + +| Flusso | Profilo | Dimensioni | Fotogrammi | YUV | Che cosa prova | +|---|---|---|---:|:-:|---| +| `AMP_A_Samsung_7` | Main | 2560×1600 | 17 | | tutte le partizioni asimmetriche (2NxnU, 2NxnD, nLx2N, nRx2N); slice I, P e B; niente hash SEI | +| `AMP_B_Samsung_7` | Main | 2560×1600 | 17 | | AMP solo nelle PU più grandi del CU minimo | +| `AMVP_A_MTK_4` | Main | 416×240 | 30 | | predizione dei vettori (AMVP) senza scalatura dei candidati spaziali; slice I e P | +| `AMVP_B_MTK_4` | Main | 416×240 | 41 | | candidati AMVP con vicini di partizione, modo e riferimento diversi; più riferimenti, slice B | +| `AMVP_C_Samsung_7` | Main | 832×480 | 60 | | AMVP a basso ritardo; slice I e P | +| `BUMPING_A_ericsson_1` | Main | 416×240 | 49 | | ordine di uscita («bumping»), 4 livelli temporali, IDR e BLA con no_output_of_prior_pics_flag = 1: 17 immagini non escono (elencate nel readme) | +| `CAINIT_A_SHARP_4` | Main | 832×480 | 50 | | cabac_init_present_flag = 0: initType fisso; slice I e B | +| `CAINIT_B_SHARP_4` | Main | 832×480 | 50 | | cabac_init_flag nelle slice B | +| `CAINIT_C_SHARP_3` | Main | 832×480 | 50 | | cabac_init_flag nelle slice P | +| `CAINIT_D_SHARP_3` | Main | 832×480 | 50 | | cabac_init_flag nelle slice B unidirezionali | +| `CAINIT_E_SHARP_3` | Main | 832×480 | 50 | | come CAINIT_C, con 2×2 tile | +| `CAINIT_F_SHARP_3` | Main | 832×480 | 50 | | come CAINIT_D, con 2×2 tile | +| `CAINIT_G_SHARP_3` | Main | 832×480 | 50 | | come CAINIT_C, con segmenti di slice dipendenti di al più 3 CTB | +| `CAINIT_H_SHARP_3` | Main | 832×480 | 50 | | come CAINIT_D, con segmenti di slice dipendenti | +| `CIP_A_Panasonic_3` | Main | 416×240 | 2 | | predizione intra vincolata (constrained_intra_pred_flag), sostituzione dei campioni di riferimento; SAO e deblocking spenti | +| `cip_B_NEC_3` | Main | 416×240 | 5 | | predizione intra vincolata, un'immagine I e 4 P | +| `CIP_C_Panasonic_2` | Main | 416×240 | 2 | | come CIP_A, con 3 slice per immagine | +| `CONFWIN_A_Sony_1` | Main | 412×236 | 60 | | finestra di conformità (1 unità di ritaglio per lato: uscita 412×236), AUD, SEI | +| `DBLK_A_MAIN10_VIXS_4` | Main 10 | 176×144 | 8 | | Main 10: offset negativi del deblocking, PCM a 10 bit, predizione pesata, slice dipendenti | +| `DBLK_A_SONY_3` | Main | 832×480 | 30 | | beta_offset e tc_offset casuali (dal minimo al massimo), QP da 22 a 51, più slice, un PPS per immagine | +| `DBLK_B_SONY_3` | Main | 832×480 | 30 | | offset di QP della crominanza nel PPS e nelle slice | +| `DBLK_C_SONY_3` | Main | 832×480 | 30 | | deblocking acceso e spento a caso per slice | +| `DBLK_D_VIXS_2` | Main | 1280×720 | 8 | | filtri non attraverso le slice ma attraverso le tile (slice che coprono tile), 4×3 tile, PCM | +| `DBLK_E_VIXS_2` | Main | 1280×720 | 8 | | filtri attraverso le slice ma non attraverso le tile (3×3 tile) | +| `DBLK_F_VIXS_2` | Main | 1280×720 | 8 | | tile che coprono slice, filtri non attraverso le slice | +| `DBLK_G_VIXS_2` | Main | 1280×720 | 8 | | tile che coprono slice, filtri non attraverso le tile | +| `DELTAQP_C_SONY_3` | Main | 832×480 | 30 | | cu_qp_delta casuale, CBF nullo in alcune TU | +| `DSLICE_A_HHI_5` | Main | 1920×1080 | 50 | | segmenti di slice indipendenti e dipendenti | +| `DSLICE_B_HHI_5` | Main | 1920×1080 | 50 | | segmenti di slice dipendenti con WPP | +| `DSLICE_C_HHI_5` | Main | 1920×1080 | 50 | | segmenti di slice dipendenti con 3×2 tile | +| `ENTP_B_Qualcomm_1` | Main | 1920×1080 | 24 | | punti d'ingresso nell'intestazione con 2×3 tile e byte di emulazione nei sottoflussi | +| `ENTP_C_Qualcomm_1` | Main | 1920×1080 | 24 | | punti d'ingresso con WPP | +| `EXT_A_ericsson_4` | Main | 416×240 | 3 | | estensioni di SPS, PPS e intestazione di slice da ignorare (il flusso non è conforme, il decodificatore deve saltarle) | +| `FILLER_A_Sony_1` | Main | 416×240 | 60 | | unità NAL di riempimento (tipo 38) in fondo a ogni unità d'accesso | +| `HRD_A_Fujitsu_3` | Main | 416×240 | 96 | | SEI di temporizzazione HRD per unità di decodifica; hash SEI di tipo checksum | +| `INITQP_A_Sony_1` | Main | 416×240 | 60 | | init_qp_minus26 da −26 a 25, un PPS per immagine | +| `INITQP_B_Main10_Sony_1` | Main 10 | 416×240 | 90 | | Main 10: init_qp_minus26 da −38 a 25 | +| `ipcm_A_NEC_3` | Main | 416×240 | 1 | | PCM a 8 bit, CU PCM da 8 a 32 | +| `ipcm_B_NEC_3` | Main | 416×240 | 1 | | PCM a 6 bit | +| `ipcm_C_NEC_3` | Main | 416×240 | 1 | | PCM con pcm_loop_filter_disable_flag = 1 | +| `ipcm_D_NEC_3` | Main | 416×240 | 1 | | PCM e transquant bypass | +| `ipcm_E_NEC_2` | Main | 416×240 | 1 | | PCM con luma a 6 bit e croma a 8 bit, CU PCM 16 | +| `IPRED_A_docomo_2` | Main | 832×480 | 20 | | tutti i 35 modi intra su tutte le dimensioni di blocco; solo slice I, 20 immagini | +| `IPRED_B_Nokia_3` | Main Still Picture | 1920×1080 | 1 | sì | **Main Still Picture** (il profilo delle foto HEIC): una sola immagine I 1920×1080, tutti i modi intra | +| `IPRED_C_Mitsubishi_3` | Main | 832×480 | 4 | | tutti i modi intra su tutte le dimensioni; 4 immagini I, CTB 32 | +| `LS_A_Orange_2` | Main | 416×240 | 9 | | senza perdita (cu_transquant_bypass_flag) in ogni CU, con SAO e deblocking accesi | +| `LTRPSPS_A_Qualcomm_1` | Main | 416×240 | 500 | | riferimenti a lungo termine candidati nell'SPS e nell'intestazione (lt_idx_sps), modifica delle liste | +| `MAXBINS_A_TI_5` | Main | 416×240 | 2 | | CABAC vicino al massimo di bin per CTU 16×16, PCM; solo slice I | +| `MAXBINS_B_TI_5` | Main | 416×240 | 3 | | come MAXBINS_A, basso ritardo con slice B | +| `MAXBINS_C_TI_5` | Main | 416×240 | 3 | | come MAXBINS_A, accesso casuale | +| `MERGE_A_TI_3` | Main | 416×240 | 8 | | al più 1 candidato merge (five_minus_max_num_merge_cand = 4) | +| `MERGE_B_TI_3` | Main | 416×240 | 8 | | al più 2 candidati merge | +| `MERGE_C_TI_3` | Main | 416×240 | 8 | | al più 3 candidati merge | +| `MERGE_D_TI_3` | Main | 416×240 | 8 | | al più 4 candidati merge | +| `MERGE_E_TI_3` | Main | 416×240 | 8 | | 5 candidati merge | +| `MERGE_F_MTK_4` | Main | 416×240 | 41 | | merge senza candidato temporale (sps_temporal_mvp_enabled_flag = 0) | +| `MERGE_G_HHI_4` | Main | 832×480 | 2 | | ogni indice merge da 0 a 4 | +| `MVCLIP_A_qualcomm_3` | Main | 416×240 | 5 | | vettori candidati (AMVP e merge) ritagliati a 16 bit | +| `MVDL1ZERO_A_docomo_4` | Main | 832×480 | 500 | | mvd_l1_zero_flag acceso e spento a caso, più slice B per immagine, 500 immagini | +| `MVEDGE_A_qualcomm_3` | Main | 416×240 | 17 | | vettori che puntano fuori dall'immagine, nel bordo esteso | +| `NoOutPrior_A_Qualcomm_1` | Main | 832×480 | 40 | | CRA dopo una fine di sequenza: i suoi 7 RASL non si decodificano e le 3 immagini non ancora uscite si scartano | +| `NoOutPrior_B_Qualcomm_1` | Main | 832×480 | 47 | | IDR con no_output_of_prior_pics_flag = 1: 3 immagini non escono | +| `NUT_A_ericsson_5` | Main | 416×240 | 34 | | tutti i tipi di unità NAL VCL (TRAIL, TSA, STSA, RADL, RASL, BLA, IDR, CRA); i 2 RASL dopo un BLA non escono | +| `OPFLAG_A_Qualcomm_1` | Main | 416×240 | 500 | | pic_output_flag nell'intestazione di slice, 500 immagini | +| `OPFLAG_C_Qualcomm_1` | Main | 832×480 | 96 | | pic_output_flag = 0 per 4 immagini (POC 20, 31, 56, 72) | +| `PICSIZE_C_Bossen_1` | Main | 528×4216 | 10 | | 528×4216, l'altezza massima del livello 4.1, 2 colonne di tile; hash SEI checksum | +| `PICSIZE_D_Bossen_1` | Main | 4216×528 | 10 | | 4216×528, la larghezza massima del livello 4.1; hash SEI checksum | +| `PMERGE_A_TI_3` | Main | 416×240 | 8 | | livello di merge parallelo 2 (log2_parallel_merge_level_minus2 = 0) | +| `PMERGE_B_TI_3` | Main | 416×240 | 8 | | livello di merge parallelo 3 | +| `PMERGE_C_TI_3` | Main | 416×240 | 8 | | livello di merge parallelo 4 | +| `PMERGE_D_TI_3` | Main | 416×240 | 8 | | livello di merge parallelo 5 | +| `PMERGE_E_TI_3` | Main | 416×240 | 8 | | livello di merge parallelo 6 | +| `POC_A_Bossen_3` | Main | 416×240 | 5 | | regole di derivazione del POC | +| `PPS_A_qualcomm_7` | Main | 832×480 | 81 | | molti PPS con parametri casuali (intra vincolata, transform skip, tile, predizione pesata, filtri) | +| `PS_B_VIDYO_3` | Main | 416×240 | 25 | | estensione dell'SPS con bit in più da ignorare | +| `RAP_A_docomo_6` | Main | 416×240 | 86 | | il flusso comincia con un CRA: i suoi 7 RASL non si decodificano; i RASL dei CRA successivi sì | +| `RAP_B_Bossen_2` | Main | 416×240 | 80 | | VPS, SPS e PPS ripetuti e cambiati, CRA con immagini iniziali dopo una fine di sequenza, ritaglio a destra e in basso | +| `RPLM_A_qualcomm_4` | Main | 416×240 | 300 | | modifica delle liste di riferimento, liste di lunghezza variabile | +| `RPLM_B_qualcomm_4` | Main | 416×240 | 300 | | come RPLM_A, con più slice | +| `RPS_A_docomo_5` | Main | 416×240 | 44 | | RPS nell'intestazione con predizione inter-RPS | +| `RPS_B_qualcomm_5` | Main | 416×240 | 300 | | RPS casuali nell'intestazione, ordine di codifica casuale nel GOP | +| `RPS_C_ericsson_5` | Main | 416×240 | 40 | | i tre sottoinsiemi a breve termine, 64 RPS nell'SPS, DPB di 16 | +| `RPS_D_ericsson_6` | Main | 416×240 | 68 | | riferimenti a lungo e breve termine in tutti e cinque i sottoinsiemi, cicli di MSB | +| `RPS_E_qualcomm_5` | Main | 416×240 | 300 | | RPS casuali con riferimenti a lungo termine nell'intestazione | +| `RPS_F_docomo_2` | Main | 416×240 | 50 | | inter-RPS con voci non usate dall'immagine corrente | +| `RQT_A_HHI_4` | Main | 832×480 | 2 | | albero delle trasformate, profondità intra e inter 0 | +| `RQT_B_HHI_4` | Main | 832×480 | 2 | | profondità intra e inter 1 | +| `RQT_C_HHI_4` | Main | 832×480 | 2 | | profondità intra e inter 2 | +| `RQT_D_HHI_4` | Main | 832×480 | 2 | | profondità intra e inter 3 | +| `RQT_E_HHI_4` | Main | 832×480 | 2 | | profondità intra e inter 4 | +| `RQT_F_HHI_4` | Main | 832×480 | 2 | | profondità intra 0, inter 2 | +| `RQT_G_HHI_4` | Main | 832×480 | 2 | | profondità intra 2, inter 0 | +| `SAO_A_MediaTek_4` | Main | 416×240 | 60 | | SAO con merge a sinistra e in alto casuali | +| `SAO_B_MediaTek_5` | Main | 832×480 | 60 | | SAO di luma e di croma acceso a caso per slice, 3×1 tile | +| `SAO_C_Samsung_5` | Main | 1920×1080 | 5 | | offset SAO estremi | +| `SAO_D_Samsung_5` | Main | 1920×1080 | 5 | | offset SAO casuali | +| `SAO_E_Canon_4` | Main | 416×240 | 16 | | SAO solo a banda, offset ±7, parametri per ogni CTB, CTB 16 | +| `SAO_F_Canon_3` | Main | 416×240 | 16 | | come SAO_E, CTB 32 | +| `SAO_G_Canon_3` | Main | 416×240 | 16 | | come SAO_E, CTB 64 | +| `SAO_H_Parabola_1` | Main | 416×240 | 4 | | SAO a bordi diagonali (classi 2 e 3) agli angoli delle CTU con filtri spenti fra slice | +| `SAODBLK_A_MainConcept_4` | Main | 1016×760 | 500 | | slice non rettangolari, CTB 16, SAO e deblocking ai bordi e agli angoli delle slice, PCM, 500 immagini | +| `SDH_A_Orange_4` | Main | 1920×1080 | 2 | | occultamento del segno (sign data hiding) in ogni posizione di CG e dimensione di TU, anche con transquant bypass | +| `SLICES_A_Rovi_3` | Main | 640×480 | 9 | | slice di tipi diversi nella stessa immagine | +| `SLIST_A_Sony_5` | Main | 832×480 | 65 | | matrici di quantizzazione nell'SPS e in uno dei due PPS | +| `SLIST_B_Sony_9` | Main | 832×480 | 65 | | matrici spente, predefinite e trasmesse, 2 SPS e 2 PPS | +| `SLIST_C_Sony_4` | Main | 832×480 | 65 | | matrici predefinite e trasmesse nel PPS | +| `SLIST_D_Sony_9` | Main | 832×480 | 65 | | come SLIST_B con 4 slice per immagine (il flusso si chiama `str.bin`) | +| `SLPPLP_A_VIDYO_2` | Main | 416×240 | 33 | | sub_layer_profile_present_flag e sub_layer_level_present_flag, 3 livelli temporali | +| `STRUCT_A_Samsung_7` | Main | 832×480 | 60 | | CTU e CU minimi diversi (CTB 16) | +| `STRUCT_B_Samsung_7` | Main | 832×480 | 60 | | CTB 32, slice I e P | +| `TILES_A_Cisco_2` | Main | 1920×1080 | 100 | | 5×5 tile non uniformi, diverse in ogni immagine, filtri fra tile a caso | +| `TILES_B_Cisco_1` | Main | 1920×1080 | 100 | | come TILES_A, con più slice allineate alle tile e filtri fra slice a caso | +| `TMVP_A_MS_3` | Main | 416×240 | 17 | sì | slice_temporal_mvp_enabled_flag e predittore temporale dei vettori | +| `TSCL_A_VIDYO_5` | Main | 416×240 | 73 | | scalabilità temporale con 4 livelli, CRA | +| `TSCL_B_VIDYO_4` | Main | 416×240 | 73 | | scalabilità temporale con sole slice P | +| `TSKIP_A_MS_3` | Main | 1280×720 | 17 | sì | transform skip | +| `TSUNEQBD_A_MAIN10_Technicolor_2` | Main 10 | 1024×768 | 8 | | Main 10 con luma a 10 bit e croma a 9 bit, transform skip in intra e inter | +| `TUSIZE_A_Samsung_1` | Main | 2560×1600 | 5 | | trasformata minima 16×16 (CU minimo 32×32), 2560×1600 | +| `VPSID_A_VIDYO_2` | Main | 416×240 | 33 | | due VPS, vps_video_parameter_set_id = 4 | +| `VPSSPSPPS_A_MainConcept_1` | Main | da 176×144 a 1280×720 | 6 | | 6 immagini I di 6 risoluzioni, ognuna con VPS, SPS e PPS di identificativo diverso, tutti in testa al flusso | +| `WP_A_MAIN10_Toshiba_3` | Main 10 | 416×240 | 256 | | come WP_A, Main 10 | +| `WP_A_Toshiba_3` | Main | 416×240 | 256 | | predizione pesata nelle slice P con più indici di riferimento | +| `WP_B_Toshiba_3` | Main | 416×240 | 256 | | predizione pesata nelle slice P e B | +| `WP_MAIN10_B_Toshiba_3` | Main 10 | 416×240 | 256 | | come WP_B, Main 10 | +| `WPP_A_ericsson_MAIN10_2` | Main 10 | 416×240 | 48 | sì | come WPP_A, Main 10 | +| `WPP_A_ericsson_MAIN_2` | Main | 416×240 | 48 | sì | WPP con CTB 64: slice e segmenti dipendenti di 1 e 2 CTU, QP per TU, estensioni dell'intestazione | +| `WPP_B_ericsson_MAIN10_2` | Main 10 | 416×240 | 48 | sì | come WPP_B, Main 10 | +| `WPP_B_ericsson_MAIN_2` | Main | 416×240 | 48 | sì | come WPP_A, CTB 32 | +| `WPP_C_ericsson_MAIN10_2` | Main 10 | 416×240 | 48 | sì | come WPP_C, Main 10 | +| `WPP_C_ericsson_MAIN_2` | Main | 416×240 | 48 | sì | come WPP_A, CTB 16 | +| `WPP_D_ericsson_MAIN10_2` | Main 10 | 64×240 | 48 | sì | come WPP_D, Main 10 | +| `WPP_D_ericsson_MAIN_2` | Main | 64×240 | 48 | sì | WPP con l'immagine larga 1 CTB | +| `WPP_E_ericsson_MAIN10_2` | Main 10 | 128×240 | 48 | sì | come WPP_E, Main 10 | +| `WPP_E_ericsson_MAIN_2` | Main | 128×240 | 48 | sì | WPP con l'immagine larga 2 CTB | +| `WPP_F_ericsson_MAIN10_2` | Main 10 | 192×240 | 48 | sì | come WPP_F, Main 10 | +| `WPP_F_ericsson_MAIN_2` | Main | 192×240 | 48 | sì | WPP con l'immagine larga 3 CTB | + +## Dove sta ciascuno strumento + +| Strumento | Flussi | +|---|---| +| Main Still Picture (HEIC) | `IPRED_B_Nokia_3` | +| Main 10 | `DBLK_A_MAIN10_VIXS_4`, `INITQP_B_Main10_Sony_1`, `TSUNEQBD_A_MAIN10_Technicolor_2`, `WP_A_MAIN10_Toshiba_3`, `WP_MAIN10_B_Toshiba_3`, i sei `WPP_*_ericsson_MAIN10_2` | +| Solo intra, tutti i modi intra | `IPRED_A_docomo_2`, `IPRED_B_Nokia_3`, `IPRED_C_Mitsubishi_3`, `CIP_A_Panasonic_3`, `cip_B_NEC_3`, `CIP_C_Panasonic_2` | +| Transform skip | `TSKIP_A_MS_3`, `TSUNEQBD_A_MAIN10_Technicolor_2`, `PPS_A_qualcomm_7` | +| PCM | `ipcm_A_NEC_3`…`ipcm_E_NEC_2`, `MAXBINS_*`, `DBLK_A_MAIN10_VIXS_4`, `DBLK_D_VIXS_2`, `SAODBLK_A_MainConcept_4` | +| Senza perdita (transquant bypass) | `LS_A_Orange_2`, `SDH_A_Orange_4`, `ipcm_D_NEC_3` | +| Occultamento del segno (SDH) | `SDH_A_Orange_4` | +| SAO, ogni tipo | `SAO_A_MediaTek_4`…`SAO_H_Parabola_1` (banda in E, F, G; bordi diagonali in H), `SAODBLK_A_MainConcept_4` | +| Parametri del deblocking | `DBLK_A_SONY_3`, `DBLK_B_SONY_3`, `DBLK_C_SONY_3`, `DBLK_D_VIXS_2`…`DBLK_G_VIXS_2`, `DBLK_A_MAIN10_VIXS_4` | +| Partizioni asimmetriche (AMP) | `AMP_A_Samsung_7`, `AMP_B_Samsung_7` | +| Predittore temporale (TMVP) | `TMVP_A_MS_3`, `MERGE_F_MTK_4` (spento) | +| Merge e merge parallelo | `MERGE_A_TI_3`…`MERGE_G_HHI_4`, `PMERGE_A_TI_3`…`PMERGE_E_TI_3` | +| AMVP e vettori | `AMVP_A_MTK_4`, `AMVP_B_MTK_4`, `AMVP_C_Samsung_7`, `MVCLIP_A_qualcomm_3`, `MVEDGE_A_qualcomm_3`, `MVDL1ZERO_A_docomo_4` | +| Predizione pesata (WP) | `WP_A_Toshiba_3`, `WP_B_Toshiba_3`, `WP_A_MAIN10_Toshiba_3`, `WP_MAIN10_B_Toshiba_3`, `DBLK_A_MAIN10_VIXS_4` | +| Riferimenti a lungo termine | `LTRPSPS_A_Qualcomm_1`, `RPS_D_ericsson_6`, `RPS_E_qualcomm_5` | +| Insiemi di riferimento (RPS) e liste | `RPS_A_docomo_5`…`RPS_F_docomo_2`, `RPLM_A_qualcomm_4`, `RPLM_B_qualcomm_4`, `POC_A_Bossen_3` | +| Tile | `TILES_A_Cisco_2`, `TILES_B_Cisco_1`, `DBLK_D_VIXS_2`…`DBLK_G_VIXS_2`, `CAINIT_E/F_SHARP_3`, `DSLICE_C_HHI_5`, `ENTP_B_Qualcomm_1`, `SAO_B_MediaTek_5`, `PICSIZE_C_Bossen_1` | +| WPP | i dodici `WPP_*_ericsson_*_2`, `DSLICE_B_HHI_5`, `ENTP_C_Qualcomm_1` | +| Segmenti di slice dipendenti | `DSLICE_A_HHI_5`, `DSLICE_B_HHI_5`, `DSLICE_C_HHI_5`, `CAINIT_G/H_SHARP_3`, `WPP_*`, `DBLK_A_MAIN10_VIXS_4` | +| Punti d'ingresso | `ENTP_B_Qualcomm_1`, `ENTP_C_Qualcomm_1` | +| CRA, BLA, RASL, RADL, uscita | `NUT_A_ericsson_5`, `RAP_A_docomo_6`, `RAP_B_Bossen_2`, `BUMPING_A_ericsson_1`, `NoOutPrior_A_Qualcomm_1`, `NoOutPrior_B_Qualcomm_1`, `OPFLAG_A_Qualcomm_1`, `OPFLAG_C_Qualcomm_1`, `CONFWIN_A_Sony_1` | +| Matrici di quantizzazione | `SLIST_A_Sony_5`, `SLIST_B_Sony_9`, `SLIST_C_Sony_4`, `SLIST_D_Sony_9` | +| QP | `INITQP_A_Sony_1`, `INITQP_B_Main10_Sony_1`, `DELTAQP_C_SONY_3`, `DBLK_B_SONY_3`, `TUSIZE_A_Samsung_1` | +| CABAC | `CAINIT_A_SHARP_4`…`CAINIT_H_SHARP_3`, `MAXBINS_A_TI_5`…`MAXBINS_C_TI_5` | +| Albero delle trasformate e struttura | `RQT_A_HHI_4`…`RQT_G_HHI_4`, `STRUCT_A_Samsung_7`, `STRUCT_B_Samsung_7`, `TUSIZE_A_Samsung_1`, `SLICES_A_Rovi_3` | +| Insiemi di parametri | `VPSID_A_VIDYO_2`, `VPSSPSPPS_A_MainConcept_1`, `PPS_A_qualcomm_7`, `PS_B_VIDYO_3`, `EXT_A_ericsson_4`, `SLPPLP_A_VIDYO_2`, `TSCL_A_VIDYO_5`, `TSCL_B_VIDYO_4`, `HRD_A_Fujitsu_3`, `FILLER_A_Sony_1` | +| Dimensioni estreme | `PICSIZE_C_Bossen_1`, `PICSIZE_D_Bossen_1`, `AMP_A_Samsung_7` (2560×1600), `WPP_D_ericsson_MAIN_2` (1 CTB di larghezza) | + +## Estensioni di formato (RExt) + +Un piccolo gruppo di flussi `RExt` (4:0:0, 4:2:2, 4:4:4, 12 bit e i loro strumenti). Le foto HEIC e i video dei +telefoni sono Main, Main 10 o Main Still Picture, ma questi flussi erano nella serie e il decodificatore li decodifica +tutti esattamente: 4:0:0, 4:2:2 (due blocchi di croma per unità di trasformata, modi intra della tabella 8-3), 4:4:4, +fino a 12 bit, predizione fra componenti, RDPCM implicito, rotazione e contesto unico del transform skip, smoothing +intra spento, adattamento persistente di Rice, `chroma_qp_offset_list`. Restano rifiutati con un'eccezione la +precisione estesa (`extended_precision_processing_flag`, i profili a 16 bit) e l'allineamento del CABAC +(`cabac_bypass_alignment_enabled_flag`), che nessun flusso qui usa. Nessuno di questi zip conteneva il YUV. + +| Flusso | Profilo | Dimensioni | Fotogrammi | YUV | Che cosa prova | +|---|---|---|---:|:-:|---| +| `ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2` | RExt 4:2:2, 10 bit | 1920×1080 | 3 | | modi intra di croma in 4:2:2 (angoli adattati), 10 bit, 1920×1080 | +| `Bitdepth_A_RExt_Sony_1` | RExt 4:4:4, 12/8 bit | 1920×1080 | 16 | | 4:4:4 con luma a 12 bit e croma a 8 bit | +| `CCP_8bit_RExt_QCOM_1` | RExt 4:4:4, 8 bit | 1280×720 | 9 | | predizione fra componenti, 4:4:4 a 8 bit, 1280×720; niente hash SEI | +| `GENERAL_10b_422_RExt_Sony_1` | RExt 4:2:2, 10 bit | 400×384 | 2 | | Main 4:2:2 10 Intra, chroma_qp_offset_list | +| `GENERAL_12b_420_RExt_Sony_1` | RExt 4:2:0, 12 bit | 400×384 | 1 | | Main 12 Intra, 4:2:0 a 12 bit | +| `GENERAL_8b_400_RExt_Sony_1` | RExt 4:0:0, 8 bit | 400×384 | 1 | | Monochrome (4:0:0) a 8 bit con strumenti RExt | +| `GENERAL_8b_420_RExt_Sony_1` | RExt 4:2:0, 8 bit | 400×384 | 1 | | Main Intra (profilo RExt) 4:2:0 a 8 bit | +| `GENERAL_8b_444_RExt_Sony_2` | RExt 4:4:4, 8 bit | 400×384 | 14 | | Main 4:4:4 Intra: predizione fra componenti, rotazione e contesti del transform skip, RDPCM implicito, smoothing intra spento, adattamento persistente di Rice, chroma_qp_offset_list | +| `IPCM_A_RExt_NEC_2` | RExt 4:2:2, 10 bit | 416×240 | 1 | | PCM in 4:2:2 a 10 bit; niente hash SEI | +| `IPCM_B_RExt_NEC` | RExt 4:4:4, 12 bit | 416×240 | 1 | | PCM in 4:4:4 a 12 bit; niente hash SEI | + +## Che cosa è rimasto fuori, e perché + +Il limite era di circa 40 MB, preferendo i flussi piccoli: si è tenuto un flusso per ogni strumento e si sono lasciati +quelli grandi il cui strumento è già provato da altri. + +| Flusso | Peso | Perché è fuori | +|---|---:|---| +| `DELTAQP_A_BRCM_4` | 9,5 MB | `cu_qp_delta` è già in `DELTAQP_C_SONY_3` e nei `WPP_*` (QP per TU) | +| `DELTAQP_B_SONY_3` | 5,4 MB | gli offset di QP della crominanza sono già in `DBLK_B_SONY_3` | +| `SAODBLK_B_MainConcept_4` | 4,4 MB | come `SAODBLK_A_MainConcept_4`, più tile e transquant bypass, provati altrove | +| `LS_B_Orange_4` | 3,7 MB | il senza perdita è già in `LS_A_Orange_2`, `SDH_A_Orange_4` e `ipcm_D_NEC_3` | +| `ENTP_A_Qualcomm_1` | 2,6 MB | i punti d'ingresso con tile sono già in `ENTP_B_Qualcomm_1` | +| `OPFLAG_B_Qualcomm_1` | 2,1 MB | `pic_output_flag` è già in `OPFLAG_A_Qualcomm_1` e `OPFLAG_C_Qualcomm_1` | +| `AMP_D_Hisilicon_3`, `AMP_E_Hisilicon_3`, `AMP_F_Hisilicon_3` | 0,6–0,8 MB l'uno | AMP a 1080p, già in `AMP_A_Samsung_7` e `AMP_B_Samsung_7` | +| `PICSIZE_A_Bossen_1`, `PICSIZE_B_Bossen_1` | grandi | 1056×8440 e 8440×1056 al livello 5.1: la forma estrema è già in `PICSIZE_C/D` al livello 4.1 | +| il resto di `RExt` | | 16 bit ed EXTPREC, alto rendimento 4:4:4 (WPP di Apple), CCP a 10 e 12 bit, `Main_422_10_A/B`, `TSCTX`, `ExplicitRdpcm`, `PERSIST_RPARAM`, `QMATRIX`, `SAO_A_RExt`, `WAVETILES`, `Bitdepth_B` e gli altri `GENERAL`: le estensioni non servono ai file dei telefoni, basta il gruppo piccolo qui sopra | + +Le estensioni multistrato e 3D (MV-HEVC, SHVC, SCC) non sono nemmeno state guardate. + +## Che cosa non è verificato + +- Il numero di fotogrammi e `tutto` dei flussi senza YUV ufficiale, quale dei due MD5 di uno zip sia quello del YUV e + la disposizione a 16 bit di `TSUNEQBD_A_MAIN10_Technicolor_2` (10 e 9 bit) erano scelte nostre: il decodificatore le + ha confermate tutte: i suoi fotogrammi, in quel numero e in quella disposizione, hanno esattamente l'MD5 ufficiale + dello zip, che non può coincidere per caso. +- L'RDPCM esplicito (`explicit_rdpcm_flag`, solo nelle CU inter con transform skip o senza perdita) è acceso nell'SPS + di `Bitdepth_A_RExt_Sony_1` e `CCP_8bit_RExt_QCOM_1`, che coincidono, ma non si è contato quante CU lo usino davvero: + la prova vera sarebbe `ExplicitRdpcm_A/B`, rimasto fuori. +- `H265DecoderTests.TheSetExercisesEveryTool` controlla che ogni strumento che il decodificatore dichiara (tile anche non + uniformi e senza deblocking fra i tile, WPP, segmenti dipendenti, liste di scala nell'SPS e nel PPS, lungo termine, + PCM e gli strumenti RExt) sia acceso in almeno un flusso: acceso, non per forza usato in ogni sua variante. diff --git a/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/LS_A_Orange_2.bit b/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/LS_A_Orange_2.bit new file mode 100644 index 0000000..368b9e3 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/LS_A_Orange_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/LS_A_Orange_2.txt b/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/LS_A_Orange_2.txt new file mode 100644 index 0000000..9b90c20 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/LS_A_Orange_2.txt @@ -0,0 +1,21 @@ + +LS_A_Orange_1: + +conformance: HM-10.0 +category: Other Coding Tools +sub category: Lossless + +resolution: 416x240 +# of frames: 9 + +Specification: +- All the CUs are lossless. SAO and deblocking are enabled in the SPS and PPS. + +Purpose: +- Check that the decoder handles lossless coding. + +MD5: SEI message in the bitstream + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/riferimento.md5 new file mode 100644 index 0000000..adfee64 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/LS_A_Orange_2/riferimento.md5 @@ -0,0 +1,2 @@ +# LS_A_Orange_2.yuv 416x240 4:2:0 8 bit, 9 fotogrammi, 1347840 byte +tutto e14f82958f87a87be73a6f51e76ffdab diff --git a/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/LTRPSPS_A_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/LTRPSPS_A_Qualcomm_1.bit new file mode 100644 index 0000000..6020fc4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/LTRPSPS_A_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/LTRPSPS_A_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/LTRPSPS_A_Qualcomm_1.txt new file mode 100644 index 0000000..298eb47 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/LTRPSPS_A_Qualcomm_1.txt @@ -0,0 +1,13 @@ +Bitstream file name: LTRPSPS_A_Qualcomm_1.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: The bitstream is coded under the random access conditions described in the CTC, with the following modifications. Eight long-term reference picture candidates (four difference POC LSB values and 2 values of used_by_curr, giving a total of 8) are signaled in the SPS. The slice headers refer to long-term reference pictures that are either referred to from the SPS or may be explicitly signaled in the slice header. Reference picture list modification is applied on some pictures. + +Functional stage: Test parsing of long_term_ref_pics_present_flag, num_long_term_ref_pics_sps, lt_ref_pic_poc_lsb_sps, and used_by_curr_pic_lt_sps_flag in SPS. Test parsing of num_long_term_sps and lt_idx_sps in slice header syntax. + +Purpose: Check whether the decoder can decode slice headers when the long-term reference pictures from the list of candidates in the SPS are referred to. + +Picture size: 416x240 + +Frame rate: 50 fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..1c1fda5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/LTRPSPS_A_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# LTRPSPS_A_Qualcomm_1.yuv 416x240 4:2:0 8 bit, 500 fotogrammi, 74880000 byte +tutto e925d467c20180090c09c02d02c3aa25 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/MAXBINS_A_TI_5.bit b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/MAXBINS_A_TI_5.bit new file mode 100644 index 0000000..6cf8eb7 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/MAXBINS_A_TI_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/Readme.txt new file mode 100644 index 0000000..f757bfe --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/Readme.txt @@ -0,0 +1,21 @@ +MAXBINS_A_TI_5:(MAXBINS_A_TI_5.bit) + +Spec version: HM11.0 +Profile: Main +Level: 2 +(Category: Entropy Coding; Sub-category: Maximum number of bins) + +The purpose of the stream is to reach within 95% of the maximum number of bins per LCU based on the 5120 bits per 16x16 LCU constraint (IPCM is enabled). + +=============================== +Statistics for LCU with most bins: +=============================== +maxTotalBits 5102 +maxTotalBins 5836 + +The bitstream contains only I slices and one slice per picture. All intra configuration. + +=============================== +Revision note: +=============================== +In the 5th version, 112th's CTU bit size issue in the first picture was revised by editing its chroma SAO parameters. diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/riferimento.md5 new file mode 100644 index 0000000..06423d8 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_A_TI_5/riferimento.md5 @@ -0,0 +1,2 @@ +# MAXBINS_A_TI_5.yuv 416x240 4:2:0 8 bit, 2 fotogrammi, 299520 byte +tutto 1386fb149ddc11bd5a1d9111879acfa4 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/MAXBINS_B_TI_5.bit b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/MAXBINS_B_TI_5.bit new file mode 100644 index 0000000..42cfa71 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/MAXBINS_B_TI_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/Readme.txt new file mode 100644 index 0000000..60f654e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/Readme.txt @@ -0,0 +1,21 @@ +MAXBINS_B_TI_5:(MAXBINS_B_TI_5.bit) + +Spec version: HM11.0 +Profile: Main +Level: 2 +(Category: Entropy Coding; Sub-category: Maximum number of bins) + +The purpose of the stream is to reach within 95% of the maximum number of bins per LCU based on the 5120 bits per 16x16 LCU constraint (IPCM is enabled). + +=============================== +Statistics for LCU with most bins: +=============================== +maxTotalBits 5102 +maxTotalBins 5836 + +The bitstream contains I and B slices and one slice per picture. Low delay configuration. + +=============================== +Revision note: +=============================== +In the 5th version, 112th's CTU bit size issue in the first picture was revised by editing its chroma SAO parameters. diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/riferimento.md5 new file mode 100644 index 0000000..5656540 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_B_TI_5/riferimento.md5 @@ -0,0 +1,2 @@ +# MAXBINS_B_TI_5.yuv 416x240 4:2:0 8 bit, 3 fotogrammi, 449280 byte +tutto 21d6910760ea4963eab28b26709471fe diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/MAXBINS_C_TI_5.bit b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/MAXBINS_C_TI_5.bit new file mode 100644 index 0000000..0a436f4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/MAXBINS_C_TI_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/Readme.txt new file mode 100644 index 0000000..fb67260 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/Readme.txt @@ -0,0 +1,21 @@ +MAXBINS_C_TI_5:(MAXBINS_C_TI_5.bit) + +Spec version: HM11.0 +Profile: Main +Level: 2 +(Category: Entropy Coding; Sub-category: Maximum number of bins) + +The purpose of the stream is to reach within 95% of the maximum number of bins per LCU based on the 5120 bits per 16x16 LCU constraint (IPCM is enabled). + +=============================== +Statistics for LCU with most bins: +=============================== +maxTotalBits 5102 +maxTotalBins 5836 + +The bitstream contains I and B slices and one slice per picture. Random access configuration. + +=============================== +Revision note: +=============================== +In the 5th version, 112th's CTU bit size issue in the first picture was revised by editing its chroma SAO parameters. diff --git a/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/riferimento.md5 new file mode 100644 index 0000000..95bd166 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MAXBINS_C_TI_5/riferimento.md5 @@ -0,0 +1,2 @@ +# MAXBINS_C_TI_5.yuv 416x240 4:2:0 8 bit, 3 fotogrammi, 449280 byte +tutto 7a7e51fdd40c57d70af418f5082416fa diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/MERGE_A_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/MERGE_A_TI_3.bit new file mode 100644 index 0000000..cefaa70 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/MERGE_A_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/Readme_MERGE_A.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/Readme_MERGE_A.txt new file mode 100644 index 0000000..f283d20 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/Readme_MERGE_A.txt @@ -0,0 +1,9 @@ +MERGE_A_TI_2 (MERGE_A_TI_2.bit) + +Spec version: HM10.1 + +Check the maximum number of merging canidates permitted by the standard (i.e. 1, 2, 3, 4, 5) + +in slice header + +five_minus_max_num_merge_cand = 4 for MERGE_A_TI_2.bit diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/riferimento.md5 new file mode 100644 index 0000000..3b00245 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_A_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_A_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 3a15886a0158ef1aaf557869b2e9c522 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/MERGE_B_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/MERGE_B_TI_3.bit new file mode 100644 index 0000000..8246ef4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/MERGE_B_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/Readme_MERGE_B.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/Readme_MERGE_B.txt new file mode 100644 index 0000000..cd7d5d1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/Readme_MERGE_B.txt @@ -0,0 +1,9 @@ +MERGE_B_TI_2 (MERGE_B_TI_2.bit) + +Spec version: HM10.1 + +Check the maximum number of merging canidates permitted by the standard (i.e. 1, 2, 3, 4, 5) + +in slice header + +five_minus_max_num_merge_cand = 3 for MERGE_B_TI_2.bit diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/riferimento.md5 new file mode 100644 index 0000000..2b68b9c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_B_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_B_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 83b4dc9f229a8fba3777d9f4f87ce144 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/MERGE_C_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/MERGE_C_TI_3.bit new file mode 100644 index 0000000..f4b1dde Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/MERGE_C_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/Readme_MERGE_C.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/Readme_MERGE_C.txt new file mode 100644 index 0000000..35304c2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/Readme_MERGE_C.txt @@ -0,0 +1,9 @@ +MERGE_C_TI_2 (MERGE_C_TI_2.bit) + +Spec version: HM10.1 + +Check the maximum number of merging canidates permitted by the standard (i.e. 1, 2, 3, 4, 5) + +in slice header + +five_minus_max_num_merge_cand = 2 for MERGE_C_TI_2.bit diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/riferimento.md5 new file mode 100644 index 0000000..44fec9a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_C_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_C_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 216f0cc869e3989c8fb2cf261243160b diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/MERGE_D_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/MERGE_D_TI_3.bit new file mode 100644 index 0000000..54f47ee Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/MERGE_D_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/Readme_MERGE_D.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/Readme_MERGE_D.txt new file mode 100644 index 0000000..dd90851 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/Readme_MERGE_D.txt @@ -0,0 +1,9 @@ +MERGE_D_TI_2 (MERGE_D_TI_2.bit) + +Spec version: HM10.1 + +Check the maximum number of merging canidates permitted by the standard (i.e. 1, 2, 3, 4, 5) + +in slice header + +five_minus_max_num_merge_cand = 1 for MERGE_D_TI_2.bit diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/riferimento.md5 new file mode 100644 index 0000000..d7a57a7 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_D_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_D_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 104cccf2b8441862624777955d6ecdc4 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/MERGE_E_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/MERGE_E_TI_3.bit new file mode 100644 index 0000000..38224ef Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/MERGE_E_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/Readme_MERGE_E.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/Readme_MERGE_E.txt new file mode 100644 index 0000000..a492f77 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/Readme_MERGE_E.txt @@ -0,0 +1,9 @@ +MERGE_E_TI_2 (MERGE_E_TI_2.bit) + +Spec version: HM10.1 + +Check the maximum number of merging canidates permitted by the standard (i.e. 1, 2, 3, 4, 5) + +in slice header + +five_minus_max_num_merge_cand = 0 for MERGE_E_TI_2.bit diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/riferimento.md5 new file mode 100644 index 0000000..788a8ff --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_E_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_E_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 6e74dbd450123246c22bf01b389bbe11 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/MERGE_F_MTK_4.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/MERGE_F_MTK_4.bit new file mode 100644 index 0000000..02c23bc Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/MERGE_F_MTK_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/MERGE_F_MTK_4_Descriptions.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/MERGE_F_MTK_4_Descriptions.txt new file mode 100644 index 0000000..49204f1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/MERGE_F_MTK_4_Descriptions.txt @@ -0,0 +1,9 @@ +Software version: HM-10.0 + +Description : +All slices are coded as I, or B slices. Each picture contains only one slice. +sps_temporal_mvp_enable_flag is equal to 0 and five_minus_max_num_merge_cand is equal to 0 + +Purpose : +Check whether Merge operations perform correctly when temporal merging candidate is not included in merge candidate set. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/riferimento.md5 new file mode 100644 index 0000000..d9c481e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_F_MTK_4/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_F_MTK_4.yuv 416x240 4:2:0 8 bit, 41 fotogrammi, 6140160 byte +tutto a8f0982f026dfda1c02b4d4d3eb88132 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/MERGE_G_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/MERGE_G_HHI_4.bit new file mode 100644 index 0000000..6fbfe0b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/MERGE_G_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/MERGE_G_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/MERGE_G_HHI_4.txt new file mode 100644 index 0000000..b18218c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/MERGE_G_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test every merge index ranging from 0 to 4. +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/riferimento.md5 new file mode 100644 index 0000000..25d9ffd --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MERGE_G_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# MERGE_G_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto c82f4c88d9b2c73fabbeac8944da35a1 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/MVCLIP_A_qualcomm_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/MVCLIP_A_qualcomm_3.bit new file mode 100644 index 0000000..8734fb9 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/MVCLIP_A_qualcomm_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/MVCLIP_A_qualcomm_3.txt b/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/MVCLIP_A_qualcomm_3.txt new file mode 100644 index 0000000..02998db --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/MVCLIP_A_qualcomm_3.txt @@ -0,0 +1,11 @@ +MVCLIP_A_qualcomm_3: (MVCLIP_A_qualcomm_3.bit) + +Spec version: HM-10.1 + +(Category: Inter frame coding; Sub-category: Motion Vector Coding) + +Bitstream exercises clipping of MVP and Merge candidate motion vectors to 16-bit values. Clipped MVP and merge candidates are selected as MVP and Merge motion vectors. + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/riferimento.md5 new file mode 100644 index 0000000..cd3cbf9 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MVCLIP_A_qualcomm_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MVCLIP_A_qualcomm_3.yuv 416x240 4:2:0 8 bit, 5 fotogrammi, 748800 byte +tutto 78b398c201089b6b17bcbda2bbccf3ae diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/MVDL1ZERO_A_docomo_4.bit b/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/MVDL1ZERO_A_docomo_4.bit new file mode 100644 index 0000000..9588aac Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/MVDL1ZERO_A_docomo_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/MVDL1ZERO_A_docomo_4.txt b/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/MVDL1ZERO_A_docomo_4.txt new file mode 100644 index 0000000..2129e3e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/MVDL1ZERO_A_docomo_4.txt @@ -0,0 +1,16 @@ +MVDL1ZERO_A_docomo_4:(MVDL1ZERO_A_docomo_4.bit) + +Spec version: HM10.0 (revision 3410) +Picture size: 832x480 +Frame rate: 50 fps + +(Category: inter frame coding; Sub-category: mvd_l1_zero_flag) + +The purpose of the stream is to exercise the parsing of list 1 motion vecotor difference for bi-prediction according to mvd_l1_zero_flag in slice header (randamized on/off switching of mvd_l1_zero_flag for multiple B slices). +The bitstream contains multiple B slices per picture. Checksum SEI messages are included. + + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/riferimento.md5 new file mode 100644 index 0000000..da181e3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MVDL1ZERO_A_docomo_4/riferimento.md5 @@ -0,0 +1,2 @@ +# MVDL1ZERO_A_docomo_4.yuv 832x480 4:2:0 8 bit, 500 fotogrammi, 299520000 byte +tutto 593d1936f6fc2e1775ea2a691a601c34 diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/MVEDGE_A_qualcomm_3.bit b/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/MVEDGE_A_qualcomm_3.bit new file mode 100644 index 0000000..cc95fe0 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/MVEDGE_A_qualcomm_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/MVEDGE_A_qualcomm_3.txt b/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/MVEDGE_A_qualcomm_3.txt new file mode 100644 index 0000000..04f5a11 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/MVEDGE_A_qualcomm_3.txt @@ -0,0 +1,11 @@ +MVEDGE_A_qualcomm_3: (MVEDGE_A_qualcomm_3.bit) + +Spec version: HM-10.1 + +(Category: Inter frame coding; Sub-category: Motion Vector Coding) + +Bitstream exercises motion vectors pointing to the padded edge regions in a picture. + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/riferimento.md5 new file mode 100644 index 0000000..1250b0b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/MVEDGE_A_qualcomm_3/riferimento.md5 @@ -0,0 +1,2 @@ +# MVEDGE_A_qualcomm_3.yuv 416x240 4:2:0 8 bit, 17 fotogrammi, 2545920 byte +tutto 101c5bfe16ff1739909161794af29a2d diff --git a/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/NUT_A_ericsson_5.bit b/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/NUT_A_ericsson_5.bit new file mode 100644 index 0000000..ddcaecc Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/NUT_A_ericsson_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/NUT_A_ericsson_5.txt b/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/NUT_A_ericsson_5.txt new file mode 100644 index 0000000..e0512ed --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/NUT_A_ericsson_5.txt @@ -0,0 +1,6 @@ + +NUT_A_ericsson_5: + +This stream contains the video coding layer (VLC) NAL unit types TRAIL_N, TRAIL_R, TSA_N, TSA_R, STSA_N, STSA_R, RADL_R, RASL_R, RASL_N, RADL_N, BLA_W_LP, BLA_W_DLP, BLA_N_LP, IDR_W_DLP, IDR_N_LP, and CRA. + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/riferimento.md5 new file mode 100644 index 0000000..da1dfd8 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/NUT_A_ericsson_5/riferimento.md5 @@ -0,0 +1,2 @@ +# NUT_A_ericsson_5.yuv 416x240 4:2:0 8 bit, 34 fotogrammi, 5091840 byte +tutto 9dbe33badd0cc6dfcd1b53e546968fbd diff --git a/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/NoOutPrior_A_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/NoOutPrior_A_Qualcomm_1.bit new file mode 100644 index 0000000..dd9eea4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/NoOutPrior_A_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/NoOutPrior_A_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/NoOutPrior_A_Qualcomm_1.txt new file mode 100644 index 0000000..2b9b1fe --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/NoOutPrior_A_Qualcomm_1.txt @@ -0,0 +1,14 @@ +NoOutPrior_A_Qualcomm_1 + +Specification version: HM13.0 + +Category: Picture output + +Specification: +- 480p60 +- 50 frames +- Random access configuration +- Intra refresh type = CRA +- One slice per picture + +Purpose: Test no rasl output flag and no output pic prior flag when CRA follows and end of sequence. diff --git a/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..d30fbc6 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_A_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# NoOutPrior_A_Qualcomm_1.yuv 832x480 4:2:0 8 bit, 40 fotogrammi, 23961600 byte +tutto 1c5f20a08ab8dfa0f44d9a0ca23d174d diff --git a/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/NoOutPrior_B_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/NoOutPrior_B_Qualcomm_1.bit new file mode 100644 index 0000000..46ec8f8 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/NoOutPrior_B_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/NoOutPrior_B_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/NoOutPrior_B_Qualcomm_1.txt new file mode 100644 index 0000000..c6ba429 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/NoOutPrior_B_Qualcomm_1.txt @@ -0,0 +1,15 @@ +NoOutPrior_B_Qualcomm_1 + +Specification version: HM13.0 + +Category: Picture output + +Specification: +- 480p60 +- 50 frames +- Random access configuration +- Intra refresh type = IDR +- One slice per picture +- No output pic prior flag at IRAP is set to true. + +Purpose: Test no output pic prior flag at IDR. diff --git a/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..e4e0b0e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/NoOutPrior_B_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# NoOutPrior_B_Qualcomm_1.yuv 832x480 4:2:0 8 bit, 47 fotogrammi, 28154880 byte +tutto 048bca0ec216a3f88cf9fbb4bb5a61ac diff --git a/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/OPFLAG_A_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/OPFLAG_A_Qualcomm_1.bit new file mode 100644 index 0000000..65eb599 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/OPFLAG_A_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/OPFLAG_A_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/OPFLAG_A_Qualcomm_1.txt new file mode 100644 index 0000000..a346329 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/OPFLAG_A_Qualcomm_1.txt @@ -0,0 +1,13 @@ +Bitstream file name: OPFLAG_A_Qualcomm_1.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: The bitstream is coded under the random access conditions described in the CTC. The value of output_flag_present_flag is 1, indicating that the syntax element pic_output_flag is signaled in the slice header. + +Functional stage: Test parsing of output_flag_present_flag in PPS. Test parsing of pic_output_flag in slice header syntax. + +Purpose: Check whether the decoder can decode slice headers containing pic_output_flag. + +Picture size: 416x240 + +Frame rate: 50 fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..c2e4073 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_A_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# OPFLAG_A_Qualcomm_1.yuv 416x240 4:2:0 8 bit, 500 fotogrammi, 74880000 byte +tutto 35eeeca175938ee262f72b7485146f94 diff --git a/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/OPFLAG_C_Qualcomm_1.bit b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/OPFLAG_C_Qualcomm_1.bit new file mode 100644 index 0000000..097e987 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/OPFLAG_C_Qualcomm_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/OPFLAG_C_Qualcomm_1.txt b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/OPFLAG_C_Qualcomm_1.txt new file mode 100644 index 0000000..80d432a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/OPFLAG_C_Qualcomm_1.txt @@ -0,0 +1,16 @@ +OPFLAG_C_Qualcomm_1 + +Specification version: HM13.0 + +Category: Picture output + +Specification: +- 480p60 +- 100 frames +- Random access configuration +- One slice per picture +- Output flag present indicidation in PPS is set +- Picture with POC 20, 31, 56, and 72 are set to be not for output. +- MD5 checksum is included in the bitstream + +Purpose: Test picture output flag indication diff --git a/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/riferimento.md5 new file mode 100644 index 0000000..641c687 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/OPFLAG_C_Qualcomm_1/riferimento.md5 @@ -0,0 +1,2 @@ +# OPFLAG_C_Qualcomm_1.yuv 832x480 4:2:0 8 bit, 96 fotogrammi, 57507840 byte +tutto a82c4f6ee843150067bba60b9342fc50 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/PICSIZE_C_Bossen_1.bin b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/PICSIZE_C_Bossen_1.bin new file mode 100644 index 0000000..1b6ee80 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/PICSIZE_C_Bossen_1.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/PICSIZE_C_Bossen_1.txt b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/PICSIZE_C_Bossen_1.txt new file mode 100644 index 0000000..11c61c1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/PICSIZE_C_Bossen_1.txt @@ -0,0 +1,3 @@ +Test maximum height for level 4.1 +Picture size is 528x4216 +Picture is split into 2 tile colums diff --git a/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/riferimento.md5 new file mode 100644 index 0000000..58b8e5b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_C_Bossen_1/riferimento.md5 @@ -0,0 +1,2 @@ +# PICSIZE_C_Bossen_1.yuv 528x4216 4:2:0 8 bit, 10 fotogrammi, 33390720 byte +tutto 674f9f11eb956257d86782949ec00399 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/PICSIZE_D_Bossen_1.bin b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/PICSIZE_D_Bossen_1.bin new file mode 100644 index 0000000..b1567aa Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/PICSIZE_D_Bossen_1.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/PICSIZE_D_Bossen_1.txt b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/PICSIZE_D_Bossen_1.txt new file mode 100644 index 0000000..45dd610 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/PICSIZE_D_Bossen_1.txt @@ -0,0 +1,2 @@ +Test maximum height for level 4.1 +Picture size is 4216x528 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/riferimento.md5 new file mode 100644 index 0000000..fb3d2be --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PICSIZE_D_Bossen_1/riferimento.md5 @@ -0,0 +1,2 @@ +# PICSIZE_D_Bossen_1.yuv 4216x528 4:2:0 8 bit, 10 fotogrammi, 33390720 byte +tutto 5b76e0591618f5affe8b15b03d9c0bef diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/PMERGE_A_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/PMERGE_A_TI_3.bit new file mode 100644 index 0000000..38224ef Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/PMERGE_A_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/Readme_PMERGE_A.txt b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/Readme_PMERGE_A.txt new file mode 100644 index 0000000..5c3499d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/Readme_PMERGE_A.txt @@ -0,0 +1,10 @@ +PMERGE_A_TI_2 (PMERGE_A_TI_2.bit) + +Spec version: HM10.1 + +Check the parallel merge level permitted by the standard (i.e. 2, 3, 4, 5, 6 for CTB size 64x64) + + +in slice header + +log2_parallel_merge_level_minus2 = 0 for PMERGE_A_TI_2.bit \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/riferimento.md5 new file mode 100644 index 0000000..cbe4cd4 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_A_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# PMERGE_A_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 6e74dbd450123246c22bf01b389bbe11 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/PMERGE_B_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/PMERGE_B_TI_3.bit new file mode 100644 index 0000000..2d70db0 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/PMERGE_B_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/Readme_PMERGE_B.txt b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/Readme_PMERGE_B.txt new file mode 100644 index 0000000..a217e06 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/Readme_PMERGE_B.txt @@ -0,0 +1,10 @@ +PMERGE_B_TI_2 (PMERGE_B_TI_2.bit) + +Spec version: HM10.1 + +Check the parallel merge level permitted by the standard (i.e. 2, 3, 4, 5, 6 for CTB size 64x64) + + +in slice header + +log2_parallel_merge_level_minus2 = 1 for PMERGE_B_TI_2.bit \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/riferimento.md5 new file mode 100644 index 0000000..a7cdc12 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_B_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# PMERGE_B_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 7d0e57ebdbbc6633c972083a17d97550 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/PMERGE_C_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/PMERGE_C_TI_3.bit new file mode 100644 index 0000000..6a33494 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/PMERGE_C_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/Readme_PMERGE_C.txt b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/Readme_PMERGE_C.txt new file mode 100644 index 0000000..0966362 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/Readme_PMERGE_C.txt @@ -0,0 +1,10 @@ +PMERGE_C_TI_2 (PMERGE_C_TI_2.bit) + +Spec version: HM10.1 + +Check the parallel merge level permitted by the standard (i.e. 2, 3, 4, 5, 6 for CTB size 64x64) + + +in slice header + +log2_parallel_merge_level_minus2 = 2 for PMERGE_C_TI_2.bit \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/riferimento.md5 new file mode 100644 index 0000000..a15a199 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_C_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# PMERGE_C_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 7e23d874b198ec7a9f6086a20de0db76 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/PMERGE_D_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/PMERGE_D_TI_3.bit new file mode 100644 index 0000000..287dcf8 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/PMERGE_D_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/Readme_PMERGE_D.txt b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/Readme_PMERGE_D.txt new file mode 100644 index 0000000..b7a024b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/Readme_PMERGE_D.txt @@ -0,0 +1,10 @@ +PMERGE_D_TI_2 (PMERGE_D_TI_2.bit) + +Spec version: HM10.1 + +Check the parallel merge level permitted by the standard (i.e. 2, 3, 4, 5, 6 for CTB size 64x64) + + +in slice header + +log2_parallel_merge_level_minus2 = 3 for PMERGE_D_TI_2.bit \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/riferimento.md5 new file mode 100644 index 0000000..8d66dc8 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_D_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# PMERGE_D_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 9771b8c8a71e41547f14032e07be7d61 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/PMERGE_E_TI_3.bit b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/PMERGE_E_TI_3.bit new file mode 100644 index 0000000..aded743 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/PMERGE_E_TI_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/Readme_PMERGE_E.txt b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/Readme_PMERGE_E.txt new file mode 100644 index 0000000..1326f92 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/Readme_PMERGE_E.txt @@ -0,0 +1,10 @@ +PMERGE_E_TI_2 (PMERGE_E_TI_2.bit) + +Spec version: HM10.1 + +Check the parallel merge level permitted by the standard (i.e. 2, 3, 4, 5, 6 for CTB size 64x64) + + +in slice header + +log2_parallel_merge_level_minus2 = 4 for PMERGE_E_TI_2.bit \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/riferimento.md5 new file mode 100644 index 0000000..2f0cb46 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PMERGE_E_TI_3/riferimento.md5 @@ -0,0 +1,2 @@ +# PMERGE_E_TI_3.yuv 416x240 4:2:0 8 bit, 8 fotogrammi, 1198080 byte +tutto 26aed56afdb6cb7011fd5c3303379a9d diff --git a/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/POC_A_Bossen_3.bin b/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/POC_A_Bossen_3.bin new file mode 100644 index 0000000..5cadf4d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/POC_A_Bossen_3.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/POC_A_Bossen_3.txt b/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/POC_A_Bossen_3.txt new file mode 100644 index 0000000..bd53de2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/POC_A_Bossen_3.txt @@ -0,0 +1,2 @@ +Test some rules related to POC derivation + diff --git a/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/riferimento.md5 new file mode 100644 index 0000000..a0d3f17 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/POC_A_Bossen_3/riferimento.md5 @@ -0,0 +1,2 @@ +# POC_A_Bossen_3.yuv 416x240 4:2:0 8 bit, 5 fotogrammi, 748800 byte +tutto faf33bec64d3e58c426ed2772903a0bf diff --git a/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/PPS_A_qualcomm_7.bit b/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/PPS_A_qualcomm_7.bit new file mode 100644 index 0000000..d8f5d5d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/PPS_A_qualcomm_7.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/PPS_A_qualcomm_7.txt b/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/PPS_A_qualcomm_7.txt new file mode 100644 index 0000000..11aa375 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/PPS_A_qualcomm_7.txt @@ -0,0 +1,12 @@ +PPS_A_qualcomm_7: (PPS_A_qualcomm_7.bit) + +Spec version: HM-11.0 + +(Category PPS; Sub-category: Multiple PPS signalling) + +Bitstream exercises use of multiple PPS signalling with random PPS parameters (constrained intra, transform skip, tile configurations, WP, loop filter, etc.) that get randomly selected by coded pictures. + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/riferimento.md5 new file mode 100644 index 0000000..64d7796 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PPS_A_qualcomm_7/riferimento.md5 @@ -0,0 +1,2 @@ +# PPS_A_qualcomm_7.yuv 832x480 4:2:0 8 bit, 81 fotogrammi, 48522240 byte +tutto bccf29fab6744215fe007ea3a5d6da42 diff --git a/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/PS_B_VIDYO_3.bit b/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/PS_B_VIDYO_3.bit new file mode 100644 index 0000000..e215889 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/PS_B_VIDYO_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/PS_B_VIDYO_3.txt b/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/PS_B_VIDYO_3.txt new file mode 100644 index 0000000..f3c2532 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/PS_B_VIDYO_3.txt @@ -0,0 +1,16 @@ +Bitstream file name: PS_B_VIDYO_3.bit +Conformance point: HM-10.0 +Bitstream feature: +The bitstream is for testing bitstreams with stuffed extensions. +The bitstream has extension_flag set only for SPS. +Some random number of bits have been added after the extension_flag, which a conformant decoder should ignore. + +picture size: 416x240 (BasketballPass_416x240_50.yuv) +frame rate: 50 +number of encoded frames: 25 + +revision 2: + fixes the illegal nal_unit_type in some of the reference frames + +revision 3: + added proper profile and level \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/riferimento.md5 new file mode 100644 index 0000000..6185ac2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/PS_B_VIDYO_3/riferimento.md5 @@ -0,0 +1,2 @@ +# PS_B_VIDYO_3.yuv 416x240 4:2:0 8 bit, 25 fotogrammi, 3744000 byte +tutto eb85521ee103333eac61a8253637eac4 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/RAP_A_docomo_6.bit b/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/RAP_A_docomo_6.bit new file mode 100644 index 0000000..58d46b5 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/RAP_A_docomo_6.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/RAP_A_docomo_6.txt b/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/RAP_A_docomo_6.txt new file mode 100644 index 0000000..6c0c8ed --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/RAP_A_docomo_6.txt @@ -0,0 +1,14 @@ +RAP_A_docomo_6: (RAP_A_docomo_6.bit) +Frame rate: 30 fps +Picture size: 832x480 +Spec version: HM10.1 + +(Category: RAP; Sub-category: Bitstream starting with a CRA picture followed by RASL pictures that cannot be decoded) + +The purpose of the stream is to exercise the decoding of a conforming bitstream where the CRA is the first picture in the bitstream and is followed by 7 RASL pictures that are not decodable. There are two subsequent CRA pictures with RASL pictures, following the first CRA picture in this bitstream. These subsequent RASL pictures should be decodable since the associated CRA is not the first CRA picture in the bitstream. + +Note: In actual decoders, any RASL pictures associated with a CRA picture at the beginning of the bitstream or any RASL pictures associated with a BLA picture may be ignored (removed from the bitstream and discarded), as they are not specified for output and have no effect on the decoding process of any other pictures that are specified for output. + +The MD5 of the yuv file in output order decoded using the HM10.1-dev-3420 is included in RAP_A_docomo_6.md5. + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/riferimento.md5 new file mode 100644 index 0000000..71af765 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RAP_A_docomo_6/riferimento.md5 @@ -0,0 +1,2 @@ +# RAP_A_docomo_6.yuv 416x240 4:2:0 8 bit, 86 fotogrammi, 12879360 byte +tutto 8a536a80ed42b37b1ac5810bc046f82a diff --git a/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/RAP_B_Bossen_2.bit b/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/RAP_B_Bossen_2.bit new file mode 100644 index 0000000..4fbadd0 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/RAP_B_Bossen_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/RAP_B_Bossen_2.txt b/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/RAP_B_Bossen_2.txt new file mode 100644 index 0000000..c369778 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/RAP_B_Bossen_2.txt @@ -0,0 +1,8 @@ +Bitstream: RAP_B_Bossen_2.bit +Source resolution: 416x240 +Source frame rate: 50Hz + +Features: +- Test switching/repeating of VPS/SPS/PPS +- Test CRA picture with leading pictures following EOS nal unit +- Test conformance window cropping (right and bottom) diff --git a/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/riferimento.md5 new file mode 100644 index 0000000..3a135f0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RAP_B_Bossen_2/riferimento.md5 @@ -0,0 +1,2 @@ +# RAP_B_Bossen_2.yuv 416x240 4:2:0 8 bit, 80 fotogrammi, 11980800 byte +tutto f38befcc280f2fd0d23f48f807f843c2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/RPLM_A_qualcomm_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/RPLM_A_qualcomm_4.bit new file mode 100644 index 0000000..8aa0621 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/RPLM_A_qualcomm_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/RPLM_A_qualcomm_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/RPLM_A_qualcomm_4.txt new file mode 100644 index 0000000..c6d3b3b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/RPLM_A_qualcomm_4.txt @@ -0,0 +1,12 @@ +RPLM_A_qualcomm_4: (RPLM_A_qualcomm_4.bit) + +Spec version: HM-10.1 + +(Category RPLM; Sub-category: Slice header RPLM) + +Bitstream exercises random reference picture list modification with varying list sizes. + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/riferimento.md5 new file mode 100644 index 0000000..c0c30c8 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPLM_A_qualcomm_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RPLM_A_qualcomm_4.yuv 416x240 4:2:0 8 bit, 300 fotogrammi, 44928000 byte +tutto 011794872709c341880ee42ade036ed3 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/RPLM_B_qualcomm_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/RPLM_B_qualcomm_4.bit new file mode 100644 index 0000000..4683cc4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/RPLM_B_qualcomm_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/RPLM_B_qualcomm_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/RPLM_B_qualcomm_4.txt new file mode 100644 index 0000000..7c5c7fd --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/RPLM_B_qualcomm_4.txt @@ -0,0 +1,12 @@ +RPLM_B_qualcomm_4: (RPLM_B_qualcomm_4.bit) + +Spec version: HM-10.1 + +(Category RPLM; Sub-category: Slice header RPLM) + +Bitstream exercises random reference picture list modification with varying list sizes under multiple slice condition. + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/riferimento.md5 new file mode 100644 index 0000000..fb53976 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPLM_B_qualcomm_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RPLM_B_qualcomm_4.yuv 416x240 4:2:0 8 bit, 300 fotogrammi, 44928000 byte +tutto 653ac7c46fa7b9d7d966e3db317eb938 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/RPS_A_docomo_5.bit b/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/RPS_A_docomo_5.bit new file mode 100644 index 0000000..a7e67db Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/RPS_A_docomo_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/RPS_A_docomo_5.txt b/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/RPS_A_docomo_5.txt new file mode 100644 index 0000000..d054e55 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/RPS_A_docomo_5.txt @@ -0,0 +1,12 @@ +RPS_A_docomo_4: (RPS_A_docomo_4.bit) +Frame rate: 30 fps +Picture size: 832x480 +Spec version: HM10.1 + +(Category: RPS; Sub-category: Slice header RPS with short-term pictures and inter-RPS prediction) + +The purpose of the stream is to exercise the inter-RPS prediction method for sending the RPS for short-term pictures in the slice header. The last 3 frames of this 44 frames sequence contain Slice header RPS using the inter-RPS in addition to the RPS sent in the PPS. + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/riferimento.md5 new file mode 100644 index 0000000..3777983 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_A_docomo_5/riferimento.md5 @@ -0,0 +1,2 @@ +# RPS_A_docomo_5.yuv 416x240 4:2:0 8 bit, 44 fotogrammi, 6589440 byte +tutto 7f4ad6c6b3de54558b0db59629b87db9 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/RPS_B_qualcomm_5.bit b/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/RPS_B_qualcomm_5.bit new file mode 100644 index 0000000..31e941b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/RPS_B_qualcomm_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/RPS_B_qualcomm_5.txt b/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/RPS_B_qualcomm_5.txt new file mode 100644 index 0000000..dc12953 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/RPS_B_qualcomm_5.txt @@ -0,0 +1,12 @@ +RPS_B_qualcomm_5: (RPS_B_qualcomm_5.bit) + +Spec version: HM-10.1 + +(Category RPS; Sub-category: Slice header RPS with short-term reference pictures, without inter-RPS prediction) + +Bitstream exercises random RPS signaling in slice header along with random picture coding order within a GOP. + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/riferimento.md5 new file mode 100644 index 0000000..6cdf7dd --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_B_qualcomm_5/riferimento.md5 @@ -0,0 +1,2 @@ +# RPS_B_qualcomm_5.yuv 416x240 4:2:0 8 bit, 300 fotogrammi, 44928000 byte +tutto 6d1ed392b067050ebd3a24a37281da03 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/RPS_C_ericsson_5.bit b/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/RPS_C_ericsson_5.bit new file mode 100644 index 0000000..e44ac7b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/RPS_C_ericsson_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/RPS_C_ericsson_5.txt b/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/RPS_C_ericsson_5.txt new file mode 100644 index 0000000..e959db0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/RPS_C_ericsson_5.txt @@ -0,0 +1,5 @@ + +RPS_C_ericsson_5 + +This stream excercises the three RPS subsets for short-term reference pictures: RefPicSetStCurrBefore, RefPicSetStCurrAfter and RefPicSetStFoll. Reference pictures are moved between these three sets, there is a mix of RPS from the slice header and SPS. NumPocTotalCurr is 8 for one picture and DPB size is 16 for another. The bitstream contains 64 SPS RPSes. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/riferimento.md5 new file mode 100644 index 0000000..a3f84ae --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_C_ericsson_5/riferimento.md5 @@ -0,0 +1,2 @@ +# RPS_C_ericsson_5.yuv 416x240 4:2:0 8 bit, 40 fotogrammi, 5990400 byte +tutto 0306b9e3ec365115ccb7060c0a437b32 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/RPS_D_ericsson_6.bit b/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/RPS_D_ericsson_6.bit new file mode 100644 index 0000000..4890614 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/RPS_D_ericsson_6.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/RPS_D_ericsson_6.txt b/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/RPS_D_ericsson_6.txt new file mode 100644 index 0000000..75e524c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/RPS_D_ericsson_6.txt @@ -0,0 +1,3 @@ +RPS_D_ericsson_6 + +This stream exercises long-term and short-term reference pictures. Reference pictures are moved between all five RPS subsets and there is a mix of RPS from the slice header and SPS. MSB cycles on/off is tested. diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/riferimento.md5 new file mode 100644 index 0000000..ac792d4 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_D_ericsson_6/riferimento.md5 @@ -0,0 +1,2 @@ +# RPS_D_ericsson_6.yuv 416x240 4:2:0 8 bit, 68 fotogrammi, 10183680 byte +tutto d0fcd71e6266b1ae1f66b9cb1802ea03 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/RPS_E_qualcomm_5.bit b/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/RPS_E_qualcomm_5.bit new file mode 100644 index 0000000..86831da Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/RPS_E_qualcomm_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/RPS_E_qualcomm_5.txt b/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/RPS_E_qualcomm_5.txt new file mode 100644 index 0000000..989bc01 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/RPS_E_qualcomm_5.txt @@ -0,0 +1,12 @@ +RPS_E_qualcomm_5: (RPS_E_qualcomm_5.bit) + +Spec version: HM-10.1 + +(Category RPS; Sub-category: Slice header RPS with long-term reference pictures, without inter-RPS prediction) + +Bitstream exercises random RPS signaling with LTRPs in slice header along with random picture coding order within a GOP. + + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/riferimento.md5 new file mode 100644 index 0000000..807af7c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_E_qualcomm_5/riferimento.md5 @@ -0,0 +1,2 @@ +# RPS_E_qualcomm_5.yuv 416x240 4:2:0 8 bit, 300 fotogrammi, 44928000 byte +tutto c30d38bbd7ea483dc7ffe81325118e16 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/RPS_F_docomo_2.bit b/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/RPS_F_docomo_2.bit new file mode 100644 index 0000000..94e4ddf Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/RPS_F_docomo_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/RPS_F_docomo_2.txt b/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/RPS_F_docomo_2.txt new file mode 100644 index 0000000..eddf914 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/RPS_F_docomo_2.txt @@ -0,0 +1,10 @@ +RPS_F_docomo_2: (RPS_F_docomo_2.bit) +Frame rate: 30 fps +Picture size: 832x480 +Spec version: HM11.0 + +(Category: RPS; Sub-category: Slice header RPS with short-term pictures and inter-RPS prediction) + +The purpose of the stream is to exercise the inter-RPS prediction method for sending the RPS for short-term pictures in the slice header. The inter-RPS prediction signals some RPS entries that are not used by the current picture. (used_by_curr_pic_flag[ j ] equal to 0 and use_delta_flag[ j ] equal to 1). + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/riferimento.md5 new file mode 100644 index 0000000..3a6dbdf --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RPS_F_docomo_2/riferimento.md5 @@ -0,0 +1,2 @@ +# RPS_F_docomo_2.yuv 416x240 4:2:0 8 bit, 50 fotogrammi, 7488000 byte +tutto fd6e6d973d39622d197dbdf4543643f2 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/RQT_A_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/RQT_A_HHI_4.bit new file mode 100644 index 0000000..e16d5d6 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/RQT_A_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/RQT_A_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/RQT_A_HHI_4.txt new file mode 100644 index 0000000..b34c43e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/RQT_A_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra and inter depth 0: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/riferimento.md5 new file mode 100644 index 0000000..74d752d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_A_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_A_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto aa7f6ef07bf76ebddd52f7e528cd6ab8 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/RQT_B_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/RQT_B_HHI_4.bit new file mode 100644 index 0000000..7af1e95 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/RQT_B_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/RQT_B_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/RQT_B_HHI_4.txt new file mode 100644 index 0000000..75aa10e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/RQT_B_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra and inter depth 1: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/riferimento.md5 new file mode 100644 index 0000000..a4d0aeb --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_B_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_B_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto a63f4f4e966e77a5eb4e65dcdcc488a4 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/RQT_C_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/RQT_C_HHI_4.bit new file mode 100644 index 0000000..6fbfe0b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/RQT_C_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/RQT_C_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/RQT_C_HHI_4.txt new file mode 100644 index 0000000..56f717a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/RQT_C_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra and inter depth 2: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/riferimento.md5 new file mode 100644 index 0000000..d1b273e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_C_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_C_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto c82f4c88d9b2c73fabbeac8944da35a1 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/RQT_D_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/RQT_D_HHI_4.bit new file mode 100644 index 0000000..0e80211 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/RQT_D_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/RQT_D_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/RQT_D_HHI_4.txt new file mode 100644 index 0000000..3b543fc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/RQT_D_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra and inter depth 3: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/riferimento.md5 new file mode 100644 index 0000000..a58d0f6 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_D_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_D_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto 33b58b954fa82753526fda9e9e6bc8cb diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/RQT_E_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/RQT_E_HHI_4.bit new file mode 100644 index 0000000..e51e65a Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/RQT_E_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/RQT_E_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/RQT_E_HHI_4.txt new file mode 100644 index 0000000..c7f9ec8 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/RQT_E_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra and inter depth 4: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/riferimento.md5 new file mode 100644 index 0000000..d32ea57 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_E_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_E_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto 65f22431d0eb149e04c327f881ce6581 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/RQT_F_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/RQT_F_HHI_4.bit new file mode 100644 index 0000000..7e56393 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/RQT_F_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/RQT_F_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/RQT_F_HHI_4.txt new file mode 100644 index 0000000..e435579 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/RQT_F_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra depth 0 and inter depth 2: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/riferimento.md5 new file mode 100644 index 0000000..16242e4 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_F_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_F_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto 56ba354d919d06a33b44862dd18e9437 diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/RQT_G_HHI_4.bit b/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/RQT_G_HHI_4.bit new file mode 100644 index 0000000..65730c5 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/RQT_G_HHI_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/RQT_G_HHI_4.txt b/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/RQT_G_HHI_4.txt new file mode 100644 index 0000000..25335b5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/RQT_G_HHI_4.txt @@ -0,0 +1,8 @@ +conformance: HM-10.1 +resolution: 832x480 +# of frames: 2 +purpose: test RQT with intra depth 2 and inter depth 0: +MD5: SEI message in the bitstream +Profile: Main +Tier: Main +Level: 3.1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/riferimento.md5 new file mode 100644 index 0000000..ba40809 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/RQT_G_HHI_4/riferimento.md5 @@ -0,0 +1,2 @@ +# RQT_G_HHI_4.yuv 832x480 4:2:0 8 bit, 2 fotogrammi, 1198080 byte +tutto 2fb67256014a6840b69ca6dad2426304 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/SAODBLK_A_MainConcept_4.bin b/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/SAODBLK_A_MainConcept_4.bin new file mode 100644 index 0000000..17c11ef Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/SAODBLK_A_MainConcept_4.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/SAODBLK_A_MainConcept_4.txt b/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/SAODBLK_A_MainConcept_4.txt new file mode 100644 index 0000000..fb40431 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/SAODBLK_A_MainConcept_4.txt @@ -0,0 +1,12 @@ +file_name: SAODBLK_A_MainConcept_4.bin +resolution & level: 1016x760, main level 4.1 +frame-rate: 29.97 +length: 500 frames +features: +The unique features of these streams are 1) non-rectangular shape of slices and 2) the minimum size of CTU, which for chroma planes takes the value of 8x8 and exactly coincides with a block that is used for deblocking. These unique features together with SAO enabled impose a lot of challenges in multithreaded decoding for correct implementation of loop filtering on slice borders and especially slice convex and concave corners. +SAODBLK_A_Divx_1.bin has only slices +SliceMode : 1 +SliceArgument : 128 +SliceSegmentMode : 1 +SliceSegmentArgument : 128 +LFCrossSliceBoundaryFlag : 1 \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/riferimento.md5 new file mode 100644 index 0000000..cce1ad6 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAODBLK_A_MainConcept_4/riferimento.md5 @@ -0,0 +1,2 @@ +# SAODBLK_A_MainConcept_4.yuv 1016x760 4:2:0 8 bit, 500 fotogrammi, 579120000 byte +tutto b9c98937bcb6be445348fdc89c208f1e diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/SAO_A_MediaTek_4.bit b/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/SAO_A_MediaTek_4.bit new file mode 100644 index 0000000..7010d30 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/SAO_A_MediaTek_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/SAO_A_MediaTek_4.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/SAO_A_MediaTek_4.txt new file mode 100644 index 0000000..acbff13 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/SAO_A_MediaTek_4.txt @@ -0,0 +1,14 @@ +SAO_A_MediaTek_1 +Spec version: HM-10.0 +with fix for #1071 (https://hevc.hhi.fraunhofer.de/trac/hevc/changeset/3408) +fix PROFILE_LEVEL_INDICATOR + +(Category: SAO) + + +The purpose of the stream is to exercise random SAO merge left/up flag values +The bitstream contains I, B slices and one slice per picture. Checksum SEI messages are included in bitstream. + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/riferimento.md5 new file mode 100644 index 0000000..6cc005d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_A_MediaTek_4/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_A_MediaTek_4.yuv 416x240 4:2:0 8 bit, 60 fotogrammi, 8985600 byte +tutto 272e694a2262a2b34f6248f787a4431d diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/SAO_B_MediaTek_5.bit b/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/SAO_B_MediaTek_5.bit new file mode 100644 index 0000000..c4ff6e9 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/SAO_B_MediaTek_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/SAO_B_MediaTek_5.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/SAO_B_MediaTek_5.txt new file mode 100644 index 0000000..2a7334d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/SAO_B_MediaTek_5.txt @@ -0,0 +1,9 @@ +SAO_B_MediaTek_1 +Spec version: HM-10.0 +with fix for #1071 (https://hevc.hhi.fraunhofer.de/trac/hevc/changeset/3408) +fix PROFILE_LEVEL_INDICATOR + +(Category: SAO; sub categories: Tile- and component-level control) + +The purpose of the stream is to exercise tiles / randomly enabling SAO Y and/or SAO UV per slice +The bitstream contains I, B slices and one slice per picture. Checksum SEI messages are included in bitstream. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/riferimento.md5 new file mode 100644 index 0000000..1572bb7 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_B_MediaTek_5/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_B_MediaTek_5.yuv 832x480 4:2:0 8 bit, 60 fotogrammi, 35942400 byte +tutto 90cc57237e3ce47eb3b4c901e200112d diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/SAO_C_Samsung_5.bin b/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/SAO_C_Samsung_5.bin new file mode 100644 index 0000000..96c629e Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/SAO_C_Samsung_5.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/SAO_C_Samsung_5.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/SAO_C_Samsung_5.txt new file mode 100644 index 0000000..0f42154 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/SAO_C_Samsung_5.txt @@ -0,0 +1,8 @@ +SAO_C_Samsung +Spec version: HM14.0 + +(Category: SAO) + +The purpose of the stream is to exercise extreme SAO offsets values +The bitstream contains I, P slices and one slice per picture. Checksum SEI messages are included in bitstream. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/riferimento.md5 new file mode 100644 index 0000000..88bd659 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_C_Samsung_5/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_C_Samsung_5.yuv 1920x1080 4:2:0 8 bit, 5 fotogrammi, 15552000 byte +tutto 962290491f2f1a1e70ab7aa63d2264bc diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/SAO_D_Samsung_5.bin b/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/SAO_D_Samsung_5.bin new file mode 100644 index 0000000..84fd60c Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/SAO_D_Samsung_5.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/SAO_D_Samsung_5.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/SAO_D_Samsung_5.txt new file mode 100644 index 0000000..2f530a5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/SAO_D_Samsung_5.txt @@ -0,0 +1,8 @@ +SAO_D_Samsung +Spec version: HM14.0 + +(Category: SAO) + +The purpose of the stream is to exercise random SAO offsets values +The bitstream contains I, P slices and one slice per picture. Checksum SEI messages are included in bitstream. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/riferimento.md5 new file mode 100644 index 0000000..2072aa1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_D_Samsung_5/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_D_Samsung_5.yuv 1920x1080 4:2:0 8 bit, 5 fotogrammi, 15552000 byte +tutto 6db9575a7737816b1d7a3a3bf3ba126c diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/SAO_E_Canon_4.bit b/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/SAO_E_Canon_4.bit new file mode 100644 index 0000000..8fe043b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/SAO_E_Canon_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/SAO_E_Canon_4.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/SAO_E_Canon_4.txt new file mode 100644 index 0000000..45f7a9f --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/SAO_E_Canon_4.txt @@ -0,0 +1,5 @@ +Specification: All slices are coded as I or B slices. Each picture contains only one slice. A set of SAO parameters is associated to each CTB for all frames. This means that no SAO merge flag (up or left) is used. Only the Band Offset (BO) SAO type is used and the 4 BO offsets are forced to be -7 or 7 in a random way. The Coded Tree Block size is set to 16x16. + +Functionnal stage: Tests loading of maximum SAO information at CTB level and frame. + +Purpose: Check that decoder can properly decode slices of coded frames with full SAO information. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/riferimento.md5 new file mode 100644 index 0000000..d578d85 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_E_Canon_4/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_E_Canon_4.yuv 416x240 4:2:0 8 bit, 16 fotogrammi, 2396160 byte +tutto 0b04a1378274a6ffbb8f6121e027290c diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/SAO_F_Canon_3.bit b/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/SAO_F_Canon_3.bit new file mode 100644 index 0000000..1b72833 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/SAO_F_Canon_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/SAO_F_Canon_3.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/SAO_F_Canon_3.txt new file mode 100644 index 0000000..c74e2cc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/SAO_F_Canon_3.txt @@ -0,0 +1,5 @@ +Specification: All slices are coded as I or B slices. Each picture contains only one slice. A set of SAO parameters is associated to each CTB for all frames. This means that no SAO merge flag (up or left) is used. Only the Band Offset (BO) SAO type is used and the 4 BO offsets are forced to be -7 or 7 in a random way. The Coded Tree Block size is set to 32x32. + +Functionnal stage: Tests loading of maximum SAO information at CTB level and frame. + +Purpose: Check that decoder can properly decode slices of coded frames with full SAO information. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/riferimento.md5 new file mode 100644 index 0000000..823ef91 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_F_Canon_3/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_F_Canon_3.yuv 416x240 4:2:0 8 bit, 16 fotogrammi, 2396160 byte +tutto 5c295ecba132d1e68a12dd8209e86a02 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/SAO_G_Canon_3.bit b/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/SAO_G_Canon_3.bit new file mode 100644 index 0000000..d84ab97 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/SAO_G_Canon_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/SAO_G_Canon_3.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/SAO_G_Canon_3.txt new file mode 100644 index 0000000..a0671c3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/SAO_G_Canon_3.txt @@ -0,0 +1,5 @@ +Specification: All slices are coded as I or B slices. Each picture contains only one slice. A set of SAO parameters is associated to each CTB for all frames. This means that no SAO merge flag (up or left) is used. Only the Band Offset (BO) SAO type is used and the 4 BO offsets are forced to be -7 or 7 in a random way. The Coded Tree Block size is set to 64x64. + +Functionnal stage: Tests loading of maximum SAO information at CTB level and frame. + +Purpose: Check that decoder can properly decode slices of coded frames with full SAO information. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/riferimento.md5 new file mode 100644 index 0000000..a11bdb1 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_G_Canon_3/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_G_Canon_3.yuv 416x240 4:2:0 8 bit, 16 fotogrammi, 2396160 byte +tutto 1f743a3e28617b8bae3e348096edcf76 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/SAO_H_Parabola_1.bit b/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/SAO_H_Parabola_1.bit new file mode 100644 index 0000000..c196003 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/SAO_H_Parabola_1.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/SAO_H_Parabola_1.txt b/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/SAO_H_Parabola_1.txt new file mode 100644 index 0000000..6e081af --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/SAO_H_Parabola_1.txt @@ -0,0 +1,7 @@ +Test bitstreams #SAO_H + +Specification: All slices are coded as I slices. Each picture contains multiple slices. SAO edge modes 2 and 3 are used (diagonal). slice_loop_filter_across_slices_enabled_flag is set to 0. + +Functional stage: Tests SAO decoding process with different diagonal neighbour availabilty. + +Purpose: Check that, when slice_loop_filter_across_slices_enabled_flag is set to zero, the decoder can properly apply the SAO filter in CTU corners whether diagonally neighbouring CTUs are available or not. diff --git a/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/riferimento.md5 new file mode 100644 index 0000000..610c94c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SAO_H_Parabola_1/riferimento.md5 @@ -0,0 +1,2 @@ +# SAO_H_Parabola_1.yuv 416x240 4:2:0 8 bit, 4 fotogrammi, 599040 byte +tutto 7e23c16898b14831b25d7857b69a9a9a diff --git a/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/SDH_A_Orange_4.bit b/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/SDH_A_Orange_4.bit new file mode 100644 index 0000000..5f38456 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/SDH_A_Orange_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/SDH_A_Orange_4.txt b/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/SDH_A_Orange_4.txt new file mode 100644 index 0000000..75f1f97 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/SDH_A_Orange_4.txt @@ -0,0 +1,50 @@ + +SDH_A_Orange_4: + +conformance: HM-10.0 +category: Entropy coding +sub category: Sign Data Hiding + +resolution: 1920x1080 +# of frames: 2 + +Specification: +A. sign_data_hiding_flag is on: + At least 100 CGs have lastSigScanPos-firstSigScanPos = 3. + At least 2000 CGs have lastSigScanPos-firstSigScanPos < 3. + At least 1000 CGs have lastSigScanPos-firstSigScanPos > 3 and infer the sign bit to be positive. + At least 1000 CGS have lastSigScanPos-firstSigScanPos > 3 and infer the sign bit to be negative. +o Testing position of CG with SDH: + Sign inference happens for all possible combinations of (TU size, CG position in TU) at least once in the frame. +o Testing significance positions: + All possible combinations for (lastSigScanPos, firstSigScanPos ) in a CG appear at least once in the frame. +o Testing the correctness of the inference of the sign (odd/even) and testing if the calculation of the sum creates + overflows (e.g. implementations with 8, 16 or 32 bits adder): + * 4x4 TU + 1. lastSigScanPos-firstSigScanPos = 3, 4 combinations of (first sign bit, sum parity): (negative, even), (positive, odd). + 2. lastSigScanPos-firstSigScanPos < 3, 4 combinations of (first sign bit, sum parity) : (negative, even), (positive, odd). + 3. lastSigScanPos-firstSigScanPos > 3, first sign bit even, sum of signed values, not including initial sign-inferred coeff, + include at least + (0, ±2, ±4, ±6, ±8, ±10, ±12, ±14, ±16, ±32, ±64, ±128, ±256, ±512, ±1024, ±2048, ±4096, ±8192, ±16384) + 4. lastSigScanPos-firstSigScanPos > 3, first sign bit odd, sum of signed values, not including initial sign-inferred coeff, + include at least + (±1, ±3, ±5, ±7, ±9, ±11, ±13, ±15, ±17, ±33, ±129, ±257, ±513, ±1025, ±2049, ±4097, ±8193, ±16385) + 5. One CG with all coefficients to maximum absolute value and sign inference. + 6. One CG with all coefficients to minimum absolute value and sign inference. + * 8x8 TU + 1. Repeat the test cases for 4x4 TU for all 4 CGs. + * 16x16 TU + 1. Repeat the test cases for 4x4 TU for all 16 CGs. + * 32x32 TU + 1. Repeat the test cases for 4x4 TU for all 64 CGs. + +B. sign_data_hiding_flag is on: + At least 500 CGs have lastSigScanPos-firstSigScanPos > 3 and the CU they belong to has cu_transquant_bypass_flag=1. + At least 500 CGs have lastSigScanPos-firstSigScanPos > 3 and the CU they belong to has cu_transquant_bypass_flag=0. + + + +Purpose: +Test SDH sign inference, and test SDH in conjunction with cu_transquant_bypass_flag. + +MD5: SEI message in the bitstream diff --git a/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/riferimento.md5 new file mode 100644 index 0000000..8ca842e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SDH_A_Orange_4/riferimento.md5 @@ -0,0 +1,2 @@ +# SDH_A_Orange_4.yuv 1920x1080 4:2:0 8 bit, 2 fotogrammi, 6220800 byte +tutto 0a1a6a76a86dbdc7ca479e4235f5b822 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/SLICES_A_Rovi_3.bin b/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/SLICES_A_Rovi_3.bin new file mode 100644 index 0000000..0508b2d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/SLICES_A_Rovi_3.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/SLICES_A_Rovi_3.txt b/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/SLICES_A_Rovi_3.txt new file mode 100644 index 0000000..aa4e787 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/SLICES_A_Rovi_3.txt @@ -0,0 +1,2 @@ +Stream to test decoding of pictures comprising slices of different types. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/riferimento.md5 new file mode 100644 index 0000000..7c5d23b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLICES_A_Rovi_3/riferimento.md5 @@ -0,0 +1,2 @@ +# SLICES_A_Rovi_3.yuv 640x480 4:2:0 8 bit, 9 fotogrammi, 4147200 byte +tutto c2d63a4d145a5713afecd822032ec271 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/Readme.txt new file mode 100644 index 0000000..0104c86 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/Readme.txt @@ -0,0 +1,13 @@ +SLIST_A_Sony_4: +Spec version: HM10.1 + +Check the switching of scaling list in SPS and PPS + +scaling_list_enable_flag is 1. +1 SPS and 2 PPS are included. +SPS: Scaling list data is included +PPS: Scaling list data is included in one PPS and is not included in another PPS +PPS is switched in each picture +If scaling list data is not included in PPS, scaling list in SPS is applied. + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/SLIST_A_Sony_5.bin b/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/SLIST_A_Sony_5.bin new file mode 100644 index 0000000..272d411 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/SLIST_A_Sony_5.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/riferimento.md5 new file mode 100644 index 0000000..90438b3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_A_Sony_5/riferimento.md5 @@ -0,0 +1,2 @@ +# SLIST_A_Sony_5.yuv 832x480 4:2:0 8 bit, 65 fotogrammi, 38937600 byte +tutto b00bc5362e6fad1a0e704aad8e69b863 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/Readme.txt new file mode 100644 index 0000000..6327034 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/Readme.txt @@ -0,0 +1,12 @@ +SLIST_B_Sony_8: +Spec version: HM10.1 + +Check various combination of scaling list off, default scaling list and scaling list data in PS + +scaling_list_enable_flag is 0 or 1. +2 SPS and 2 PPS are included. +SPS: Scaling list data is included in one SPS and is not included in another SPS +PPS: Scaling list data is included in one PPS and is not included in another PPS + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/SLIST_B_Sony_9.bin b/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/SLIST_B_Sony_9.bin new file mode 100644 index 0000000..9176b69 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/SLIST_B_Sony_9.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/riferimento.md5 new file mode 100644 index 0000000..26a5045 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_B_Sony_9/riferimento.md5 @@ -0,0 +1,2 @@ +# SLIST_B_Sony_9.yuv 832x480 4:2:0 8 bit, 65 fotogrammi, 38937600 byte +tutto 312b4ebb3e885587d5e12b78aa95977a diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/Readme.txt new file mode 100644 index 0000000..9c38d35 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/Readme.txt @@ -0,0 +1,13 @@ +SLIST_C_Sony_3: +Spec version: HM10.1 + +Check the switching of default scaling list and scaling list in PS + +scaling_list_enable_flag is 1. +1 SPS and 2 PPS are included. +SPS: Scaling list data is not included +PPS: Scaling list data is included in one PPS and is not included in another PPS +PPS is switched in each picture +If scaling list data is not included in both SPS and PPS, the default scaling list is applied. + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/SLIST_C_Sony_4.bin b/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/SLIST_C_Sony_4.bin new file mode 100644 index 0000000..59f7074 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/SLIST_C_Sony_4.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/riferimento.md5 new file mode 100644 index 0000000..ac37fe4 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_C_Sony_4/riferimento.md5 @@ -0,0 +1,2 @@ +# SLIST_C_Sony_4.yuv 832x480 4:2:0 8 bit, 65 fotogrammi, 38937600 byte +tutto 61024c25cbd60e9bf86dbe3bc5b9b48b diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/Readme.txt b/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/Readme.txt new file mode 100644 index 0000000..e501761 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/Readme.txt @@ -0,0 +1,11 @@ +SLIST_D_Sony_9: +Spec version: HM10.1 + +Check various combination of scaling list off, default scaling list and scaling list data in PS + +scaling_list_enable_flag is 0 or 1. +2 SPS and 2 PPS are included. +SPS: Scaling list data is included in one SPS and is not included in another SPS +PPS: Scaling list data is included in one PPS and is not included in another PPS +Each picture includes 4 slices +PPS is switched in each picture diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/riferimento.md5 new file mode 100644 index 0000000..803f9ed --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/riferimento.md5 @@ -0,0 +1,2 @@ +# str.yuv 832x480 4:2:0 8 bit, 65 fotogrammi, 38937600 byte +tutto 8d38ce43b17627ff1f86e526bfb7ffc4 diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/str.bin b/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/str.bin new file mode 100644 index 0000000..8aee579 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SLIST_D_Sony_9/str.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/SLPPLP_A_VIDYO_2.bit b/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/SLPPLP_A_VIDYO_2.bit new file mode 100644 index 0000000..d53c06b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/SLPPLP_A_VIDYO_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/SLPPLP_A_VIDYO_2.txt b/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/SLPPLP_A_VIDYO_2.txt new file mode 100644 index 0000000..68d5759 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/SLPPLP_A_VIDYO_2.txt @@ -0,0 +1,12 @@ +Bitstream file name: SLPPLP_A_VIDYO_2.bit +Conformance point: HM-12.1 +Bitstream feature: +The bitstream is testing sub_layer_profile_present_flag and sub_layer_level_present_flag. The bitstream contains 3 temporal layers (two sublayers) + +picture size: 416x240 (BasketballPass_416x240_50.yuv) +frame rate: 50 +number of encoded frames: 33 + +revision 2: + fixes the issue where the profile_compatibility_flag is not set for the sub layers. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/riferimento.md5 new file mode 100644 index 0000000..69ec86c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/SLPPLP_A_VIDYO_2/riferimento.md5 @@ -0,0 +1,2 @@ +# SLPPLP_A_VIDYO_2.yuv 416x240 4:2:0 8 bit, 33 fotogrammi, 4942080 byte +tutto 99e13916ede2bc9b77718787579104a9 diff --git a/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/STRUCT_A_Samsung_7.bin b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/STRUCT_A_Samsung_7.bin new file mode 100644 index 0000000..b278560 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/STRUCT_A_Samsung_7.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/STRUCT_A_Samsung_7.txt b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/STRUCT_A_Samsung_7.txt new file mode 100644 index 0000000..c67cf3f --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/STRUCT_A_Samsung_7.txt @@ -0,0 +1,9 @@ +Category: Block structure and partitioning; Sub-category: - + +The purpose of the stream is to exercise various CTU and Minimum CU size. + +The bitstream contains I, P, and B slices and one slice per picture. + +Checksum SEI messages are not included. + +Spec. version : HM15.0. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/riferimento.md5 new file mode 100644 index 0000000..efb2691 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_A_Samsung_7/riferimento.md5 @@ -0,0 +1,2 @@ +# STRUCT_A_Samsung_7.yuv 832x480 4:2:0 8 bit, 60 fotogrammi, 35942400 byte +tutto 02f02cc9a67222004ae18ee6bebd475a diff --git a/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/STRUCT_B_Samsung_7.bin b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/STRUCT_B_Samsung_7.bin new file mode 100644 index 0000000..7c4ab18 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/STRUCT_B_Samsung_7.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/STRUCT_B_Samsung_7.txt b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/STRUCT_B_Samsung_7.txt new file mode 100644 index 0000000..eb33158 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/STRUCT_B_Samsung_7.txt @@ -0,0 +1,9 @@ +Category: Block structure and partitioning; Sub-category: - + +The purpose of the stream is to exercise various CTU and Minimum CU size. + +The bitstream contains I, and P slices and one slice per picture. + +Checksum SEI messages are not included. + +Spec. version : HM15.0. diff --git a/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/riferimento.md5 new file mode 100644 index 0000000..645aefc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/STRUCT_B_Samsung_7/riferimento.md5 @@ -0,0 +1,2 @@ +# STRUCT_B_Samsung_7.yuv 832x480 4:2:0 8 bit, 60 fotogrammi, 35942400 byte +tutto 1f472e014aff120681e8482c8a04ef93 diff --git a/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/TILES_A_Cisco_2.bin b/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/TILES_A_Cisco_2.bin new file mode 100644 index 0000000..771a612 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/TILES_A_Cisco_2.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/TILES_A_Cisco_2.txt b/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/TILES_A_Cisco_2.txt new file mode 100644 index 0000000..033f8ed --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/TILES_A_Cisco_2.txt @@ -0,0 +1,25 @@ +TILES_A_Cisco_2 + +Specification version: HM10.0 + +Category: Tiles + +Specification: +- Minimum level = 4.1 +- 1080p60 +- 100 frames +- All slices are I or P slices. Each picture contains only one slice. +- num_tiles_columns_minus1 = 4 (maximum value for level 4.1) +- num_tiles_rows_minus1 = 4 (maximum value for level 4.1) +- uniform_spacing_flag = 0 +- column_width_minus1[i] = random value for each frame +- row_height_minus1[i] = random value for each frame +- loop_filter_across_tiles_enabled_flag = random value for each frame + +Functional stage: Test dependency breaks at tile boundaries + +Purpose: Test random non-uniform tile spacing with maximum number of tiles and disabling/enabling of deblocking filter across tile boundaries. + + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/riferimento.md5 new file mode 100644 index 0000000..fdcd576 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TILES_A_Cisco_2/riferimento.md5 @@ -0,0 +1,2 @@ +# TILES_A_Cisco_2.yuv 1920x1080 4:2:0 8 bit, 100 fotogrammi, 311040000 byte +tutto 946f0771fa87d49f684f96871c9c3c88 diff --git a/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/TILES_B_Cisco_1.bin b/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/TILES_B_Cisco_1.bin new file mode 100644 index 0000000..5b31319 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/TILES_B_Cisco_1.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/TILES_B_Cisco_1.txt b/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/TILES_B_Cisco_1.txt new file mode 100644 index 0000000..567c44b --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/TILES_B_Cisco_1.txt @@ -0,0 +1,28 @@ +TILES_B_Cisco_1 + +Specification version: HM10.0 + +Category: Tiles + +Specification: +- Minimum level = 4.1 +- 1080p60 +- 100 frames +- All slices are I or P slices. +- Each picture contains a random number of slices. +- All slice boundaries aligned with tile boundaries. +- num_tiles_columns_minus1 = 4 (maximum value for level 4.1) +- num_tiles_rows_minus1 = 4 (maximum value for level 4.1) +- uniform_spacing_flag = 0 +- column_width_minus1[i] = random value for each frame +- row_height_minus1[i] = random value for each frame +- loop_filter_across_tiles_enabled_flag = random value for each frame +- pps_loop_filter_across_slices_enabled_flag = random value for each frame +- slice_loop_filter_across_slices_enabled_flag = random value for each slice + +Functional stage: Test dependency breaks at tile boundaries and enabling/disabling the deblocking filter at tile/slice boundaries. + +Purpose: Test random non-uniform tile spacing with maximum number of tiles and randomly disabling/enabling the deblocking filter across tile/slice boundaries. + + + diff --git a/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/riferimento.md5 new file mode 100644 index 0000000..c8afabc --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TILES_B_Cisco_1/riferimento.md5 @@ -0,0 +1,2 @@ +# TILES_B_Cisco_1.yuv 1920x1080 4:2:0 8 bit, 100 fotogrammi, 311040000 byte +tutto 3382291f2b19ee2d760647d4cc756e95 diff --git a/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/TMVP_A_MS_3.bit b/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/TMVP_A_MS_3.bit new file mode 100644 index 0000000..15eb4cc Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/TMVP_A_MS_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/TMVP_A_MS_3.txt b/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/TMVP_A_MS_3.txt new file mode 100644 index 0000000..3a11957 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/TMVP_A_MS_3.txt @@ -0,0 +1,5 @@ +Bitstream file name: TMVP_A_MS_3.bit +Conformance point: HM11.0 +Explanation of bitstream features: Check if slice_temporal_mvp_enable_flag is parsed and temporal motion vector predictor is generated correctly. +Picture size: 416x240 +Frame rate: 30Hz diff --git a/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/riferimento.md5 new file mode 100644 index 0000000..b443bf6 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TMVP_A_MS_3/riferimento.md5 @@ -0,0 +1,19 @@ +# TMVP_A_MS_3.yuv 416x240 4:2:0 8 bit, 17 fotogrammi, 2545920 byte +tutto 168f8096e56b8a8c1aa03fa5fffdfd23 +0 f1f6de35d3093a49d704685a1531e911 +1 034d7d6e1a981c43fe8d7488881d0986 +2 0908437601fec6d0351cdba1aabbc38a +3 e64c90730b8efe36d2b1e3695fb04eb8 +4 99955c4d59314094df24ee181b04f85b +5 29d711a4ed3aa36f37cecf26a9b1ec56 +6 97c09841d06dc86c1e5119fa53f2cf74 +7 db4c0c32dcadf65fa0bad8d75c161c0e +8 00e655898c0a558ae6c16c7651bf174e +9 8bcb69fbcbe7c597687a7247684b3f13 +10 ef68c67a790659967042682235d0bb6d +11 0e9fc152a1aeda05cf361b38b3f0c27b +12 28f9f0f497bc8b791d0cb30371bee441 +13 e21f042b7599b61d0cb2578ee38ebce7 +14 d932460310f88fb2690088901c5dcfb7 +15 87076d7d20866a2a16e31629155d351d +16 dfa2bdc135bb9c514583d1c5f7b753bf diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/TSCL_A_VIDYO_5.bit b/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/TSCL_A_VIDYO_5.bit new file mode 100644 index 0000000..c8eb3f4 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/TSCL_A_VIDYO_5.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/TSCL_A_VIDYO_5.txt b/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/TSCL_A_VIDYO_5.txt new file mode 100644 index 0000000..eacf072 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/TSCL_A_VIDYO_5.txt @@ -0,0 +1,34 @@ +Bitstream file name: TSCL_A_VIDYO_5.bit +Conformance point: HM-10.0 +Bitstream feature: +The bitstream is for testing temporal scalability. +The bitstream has 4 temporal layers, and was encoded with the following options as the prediction structure. + +IntraPeriod : 32 # Period of I-Frame ( -1 = only first) +DecodingRefreshType : 1 # Random Accesss 0:none, 1:CDR, 2:IDR +GOPSize : 8 # GOP Size (number of B slice = GOPSize-1) +# Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs +Frame1: B 8 1 0.442 0 0 0 2 2 -8 -16 0 +Frame2: B 4 2 0.3536 0 0 1 2 3 -4 -12 4 0 +Frame3: B 2 3 0.3536 0 0 2 2 4 -2 -10 2 6 0 +Frame4: B 1 4 0.68 0 0 3 2 5 -1 -9 1 3 7 0 +Frame5: B 3 4 0.68 0 0 3 2 5 -1 -3 -11 1 5 0 +Frame6: B 6 3 0.3536 0 0 2 2 4 -2 -4 -6 2 0 +Frame7: B 5 4 0.68 0 0 3 2 5 -1 -3 -5 1 3 0 +Frame8: B 7 4 0.68 0 0 3 2 5 -1 -3 -5 -7 1 0 + +picture size: 416x240 (BasketballPass_416x240_50.yuv) +frame rate: 50 +number of encoded frames: 73 + +revision 2: + fixes the illegal nal_unit_type in some of the reference frames + +revision 3: + fixes the illegal nal_unit_type in leading pictures for CRA pictures + +revision 4: + added proper profile and level + +revision 5: + fixes the issue with RPS in CRA pictures \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/riferimento.md5 new file mode 100644 index 0000000..1e29dfb --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSCL_A_VIDYO_5/riferimento.md5 @@ -0,0 +1,2 @@ +# TSCL_A_VIDYO_5.yuv 416x240 4:2:0 8 bit, 73 fotogrammi, 10932480 byte +tutto 27cbe23eabe1b174d745c286cc2ed8ff diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/TSCL_B_VIDYO_4.bit b/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/TSCL_B_VIDYO_4.bit new file mode 100644 index 0000000..143b184 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/TSCL_B_VIDYO_4.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/TSCL_B_VIDYO_4.txt b/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/TSCL_B_VIDYO_4.txt new file mode 100644 index 0000000..cf29b44 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/TSCL_B_VIDYO_4.txt @@ -0,0 +1,27 @@ +Bitstream file name: TSCL_A_VIDYO_4.bit +Conformance point: HM-10.0 +Bitstream feature: +The bitstream is for testing temporal scalability. +The bitstream has 4 temporal layers, and was encoded with the following options as the prediction structure. + +IntraPeriod : -1 # Period of I-Frame ( -1 = only first) +DecodingRefreshType : 0 # Random Accesss 0:none, 1:CDR, 2:IDR +GOPSize : 4 # GOP Size (number of B slice = GOPSize-1) +# Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs +Frame1: P 1 3 0.4624 0 0 2 4 4 -1 -5 -9 -13 0 +Frame2: P 2 2 0.4624 0 0 1 4 4 -2 -6 -10 -14 0 +Frame3: P 3 3 0.4624 0 0 2 4 4 -1 -3 -7 -11 0 +Frame4: P 4 1 0.578 0 0 0 3 3 -4 -8 -12 0 + +picture size: 416x240 (BasketballPass_416x240_50.yuv) +frame rate: 50 +number of encoded frames: 73 + +revision 2: + fixes the illegal nal_unit_type in some of the reference frames + +revision 3: + fixes the illegal nal_unit_type in leading pictures for CRA pictures + +revision 4: + added proper profile and level \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/riferimento.md5 new file mode 100644 index 0000000..de20be0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSCL_B_VIDYO_4/riferimento.md5 @@ -0,0 +1,2 @@ +# TSCL_B_VIDYO_4.yuv 416x240 4:2:0 8 bit, 73 fotogrammi, 10932480 byte +tutto 95e7910b85c08a01e2e9ce72c92d7d62 diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/TSKIP_A_MS_3.bit b/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/TSKIP_A_MS_3.bit new file mode 100644 index 0000000..6c016fb Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/TSKIP_A_MS_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/TSKIP_A_MS_3.txt b/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/TSKIP_A_MS_3.txt new file mode 100644 index 0000000..b9cfec3 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/TSKIP_A_MS_3.txt @@ -0,0 +1,5 @@ +Bitstream file name: TSKIP_A_MS_3.bit +Conformance point: HM11.0 +Explanation of bitstream features: Check if transform_skip_enabled_flag is parsed and transform skipping functions correctly. +Picture size: 1280x720 +Frame rate: 30Hz diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/riferimento.md5 new file mode 100644 index 0000000..24bcb76 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSKIP_A_MS_3/riferimento.md5 @@ -0,0 +1,19 @@ +# TSKIP_A_MS_3.yuv 1280x720 4:2:0 8 bit, 17 fotogrammi, 23500800 byte +tutto 4280cb848219176f4fcad51f3290210d +0 41718f3f1605194cdea2a2adcddcef38 +1 81eeec52ae19aaa0545a66bca480ab07 +2 5052618951d1ea16b0d5a8b51faf99f7 +3 5508081392ab858a87ccd40e6631131f +4 520fa2c0a8f1ee82ba52461dc9c28305 +5 f30bd3d5d59895ce62e02a7cd05d6fb6 +6 c503cfe60a384dbdfd28bb316d1e5935 +7 bba08427ff68492ea1e84eb326958193 +8 227f9a7db627e3e7f199c735402e1753 +9 274a3f236f1571c32c7bdea758078985 +10 68dc528dc74ecc0718191151f8163d21 +11 7cb40c95517a2dec5ebe6218d5480cd5 +12 830cbec1799a9d63d340b78e0af6f23c +13 665b3fc980f78c2373477c3e3346726a +14 c7e4660fb173a19882475c9234fb9e6e +15 ce3ab0120ab0b56655972e52961b0dad +16 074479b891b7054e525759a5a2d48f4c diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/TSUNEQBD_A_MAIN10_Technicolor_2.bit b/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/TSUNEQBD_A_MAIN10_Technicolor_2.bit new file mode 100644 index 0000000..019c586 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/TSUNEQBD_A_MAIN10_Technicolor_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/TSUNEQBD_A_MAIN10_Technicolor_2.txt b/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/TSUNEQBD_A_MAIN10_Technicolor_2.txt new file mode 100644 index 0000000..2a0a82c --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/TSUNEQBD_A_MAIN10_Technicolor_2.txt @@ -0,0 +1,19 @@ +conformance: HM-11.0 Main 10 profile, Level 5.1 +resolution: 1024x768 +chroma sampling: 4:2:0 +framerate: 30Hz +luma bitdepth: 10 +chroma bitdepth: 9 +# of frames: 8 + +purpose: Check Transform Skip intra and inter with unequal bitdepth (luma: 10-bit, chroma: 9-bit) +syntax elements: + -In PPS, transform_skip_enabled_flag set to 1 + -In Transform Unit (residual_coding()), transform_skip_flag set to 1 for Y, Cb, Cr for both intra and inter prediction modes. + +files in zip: +-TSUNEQBD_A_MAIN10_Technicolor_2.bit: bitstream file +-TSUNEQBD_A_MAIN10_Technicolor_2.md5: MD5 of bitstream file +-TSUNEQBD_A_MAIN10_Technicolor_2.trc: Trace of decoded bitstream +-TSUNEQBD_A_MAIN10_Technicolor_2.txt: This description file +-TSUNEQBD_A_MAIN10_Technicolor_2_yuv.md5: MD5 file of the complete decoded yuv file \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/riferimento.md5 new file mode 100644 index 0000000..38f9c49 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TSUNEQBD_A_MAIN10_Technicolor_2/riferimento.md5 @@ -0,0 +1,2 @@ +# TSUNEQBD_A_MAIN10_Technicolor_2.yuv 1024x768 4:2:0 10/9 bit, 8 fotogrammi, 18874368 byte +tutto 1bed23df7253170eeb8efc3fd1b740a3 diff --git a/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/TUSIZE_A_Samsung_1.bin b/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/TUSIZE_A_Samsung_1.bin new file mode 100644 index 0000000..fefb406 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/TUSIZE_A_Samsung_1.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/TUSIZE_A_Samsung_1.txt b/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/TUSIZE_A_Samsung_1.txt new file mode 100644 index 0000000..5cc6f8e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/TUSIZE_A_Samsung_1.txt @@ -0,0 +1,19 @@ +- Bitstream file name +- - log2_min_transform_block_size_minus2_2_Samsung_1.bin +- Explanation of bitstream features +- - Test exercises CTU size 64 with depth 2 and log2_min_transform_block_size_minus2 = 2. +- - So minimum CU size is 32x32 and miminun transform size for Luma is 16x16 (Chroma 8x8). +- - Bit streams consist of I and P slices. +- Minimum level of this bitstream (or picture size) +- - 5 +- Frame rate +- - 30 + +Specification: +All slices are coded as I, or P slices. Each picture contains only one slice. log2_min_transform_block_size_minus2 is set equal to 2. +For current bit stream Maximum CU size is 64x64, miminun CU size is 32x32, miminun transform size for Luma is 16x16 (for Chroma 8x8). +Functional stage: +Test the reconstruction process of slices with limited minimum transfrom size. +Purpose: +Check if decoder properly decodes slices with RQT with minimum transfrom size different from 4x4 (default). + diff --git a/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/riferimento.md5 new file mode 100644 index 0000000..b187ff4 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/TUSIZE_A_Samsung_1/riferimento.md5 @@ -0,0 +1,2 @@ +# TUSIZE_A_Samsung_1.yuv 2560x1600 4:2:0 8 bit, 5 fotogrammi, 30720000 byte +tutto 5e6c198c852e92cdcca0e137fc2610c4 diff --git a/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/VPSID_A_VIDYO_2.bit b/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/VPSID_A_VIDYO_2.bit new file mode 100644 index 0000000..e470306 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/VPSID_A_VIDYO_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/VPSID_A_VIDYO_2.txt b/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/VPSID_A_VIDYO_2.txt new file mode 100644 index 0000000..eaebd27 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/VPSID_A_VIDYO_2.txt @@ -0,0 +1,11 @@ +Bitstream file name: VPSID_A_VIDYO_2.bit +Conformance point: HM-12.1 +Bitstream feature: +The bitstream is testing vps_video_parameter_set_id. This bitstream contains two vps's. The correct one has the value "4". The bitstream has 3 temporal layers and the correct VPS has the temporal_nesting_flag turned off. + +picture size: 416x240 (BasketballPass_416x240_50.yuv) +frame rate: 50 +number of encoded frames: 33 + +revision 2: + fixes an issue where a zero_byte is missing for the second VPS nal unit. \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/riferimento.md5 new file mode 100644 index 0000000..5f7f013 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/VPSID_A_VIDYO_2/riferimento.md5 @@ -0,0 +1,2 @@ +# VPSID_A_VIDYO_2.yuv 416x240 4:2:0 8 bit, 33 fotogrammi, 4942080 byte +tutto 99e13916ede2bc9b77718787579104a9 diff --git a/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/VPSSPSPPS_A_MainConcept_1.bin b/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/VPSSPSPPS_A_MainConcept_1.bin new file mode 100644 index 0000000..9798628 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/VPSSPSPPS_A_MainConcept_1.bin differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/VPSSPSPPS_A_MainConcept_1.txt b/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/VPSSPSPPS_A_MainConcept_1.txt new file mode 100644 index 0000000..ef1e1af --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/VPSSPSPPS_A_MainConcept_1.txt @@ -0,0 +1,19 @@ +file_name: VPSSPSPPS_A_MainConcept_1.bin +resolution & level: main 6.2, Chroma format 4:2:0 +Frame: 0 POC: 0, SLICE_TYPE: I 176x144 +Frame: 1 POC: 0, SLICE_TYPE: I 320x240 +Frame: 2 POC: 0, SLICE_TYPE: I 352x288 +Frame: 3 POC: 0, SLICE_TYPE: I 640x480 +Frame: 4 POC: 0, SLICE_TYPE: I 704x576 +Frame: 5 POC: 0, SLICE_TYPE: I 1280x720 +frame-rate: 29.97 +length: 6 frames +features: +The stream excercises conformance with SPS, VPS, and PPS. The stream contains only 6 I frames, each of them with a different resolution. Each frame has parameters sets with a unique ID: +frame 0, VPS_ID = 1, SPS_ID = 3, PPS_ID = 2 +frame 1, VPS_ID = 3, SPS_ID = 4, PPS_ID = 1 +frame 2, VPS_ID = 2, SPS_ID = 5, PPS_ID = 6 +frame 3, VPS_ID = 4, SPS_ID = 1, PPS_ID = 3 +frame 4, VPS_ID = 5, SPS_ID = 2, PPS_ID = 4 +frame 5, VPS_ID = 6, SPS_ID = 6, PPS_ID = 5 +All headers are at the beginning of the file (prior to any frames), some of the headers are duplicated. The order of the headers is arbitrary: VPS_NUT, PPS_NUT, PPS_NUT, VPS_NUT, VPS_NUT, VPS_NUT, VPS_NUT, VPS_NUT, SPS_NUT, VPS_NUT, ... diff --git a/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/riferimento.md5 new file mode 100644 index 0000000..f99782e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/VPSSPSPPS_A_MainConcept_1/riferimento.md5 @@ -0,0 +1,2 @@ +# VPSSPSPPS_A_MainConcept_1.yuv variabile(176x144,320x240,352x288,640x480,704x576,1280x720) 4:2:0 8 bit, 6 fotogrammi, 2756736 byte +tutto 1ddf74263cb4953cfdfcf99c563d88ea diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/WPP_A_ericsson_MAIN10_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/WPP_A_ericsson_MAIN10_2.bit new file mode 100644 index 0000000..5c61d0b Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/WPP_A_ericsson_MAIN10_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/WPP_A_ericsson_MAIN10_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/WPP_A_ericsson_MAIN10_2.txt new file mode 100644 index 0000000..4f91846 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/WPP_A_ericsson_MAIN10_2.txt @@ -0,0 +1,33 @@ +WPP_A_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 416x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The sequence contains six GOPs, which are all 8 pictures long. The first three GOPs have pictures with the following characteristics: +1. One slice in the frame, constant QP +2. One slice in the frame, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +3. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, constant QP +4. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +5. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, constant QP +6. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +7. Random combination of independent/dependent slice segments, constant QP +8. Random combination of independent/dependent slice segments, QP of each TU is set to a value such that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +The final three GOPs feature a mixture of single slice pictures, and pictures coded using multiple slices and multiple slice segments. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation with and without different types of slice. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/riferimento.md5 new file mode 100644 index 0000000..a110a33 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN10_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_A_ericsson_MAIN10_2.yuv 416x240 4:2:0 10 bit, 48 fotogrammi, 14376960 byte +tutto e68b9d75ff9cf1d9486e964051351f69 +0 b249a02131585ca69b8e4a390dd43fa0 +1 945638ce80022e44c95f4261b5d19c05 +2 6babc24a2bbc797d3787ca1fceea744e +3 b857e461dfe6e3a6af5e5b77efca7e9d +4 4dd1d877dbe15dca87da00b6941702c5 +5 e53d9b92c09ba5e5cbcad5731e53be5b +6 6a33c7ee3409fdf8bc6cf8bfbc42accf +7 dcc1b4a16dce237c509fe574f90efdb5 +8 a6593049e229584a70f7cef29f1dcb30 +9 3072beba856ca9dd0418da8a0ebde1cc +10 8f4634b7fafb40db1f7252f23f2d3862 +11 c9113de8646a3379e4b0771d77880d5e +12 0bec4c76353a6db699de488f306a58c5 +13 4a21da0867e328436830bb94eaedf8b1 +14 7072d3f83c77c7de29f0e187e39b9326 +15 44293420851196556283054c143b06e9 +16 103997d86a23de54b9a9f3198b81df1c +17 c77667e2ca009c91fdebb5791f586322 +18 d1eeda6346262ff6c983567517d3db82 +19 03985c8256edf8187f3acfb1b9c1dccd +20 d0b9eb81778a0441b531c82578b4e4d6 +21 cd4c9f257798708ee1868e647c3383fb +22 f35111e0c8acdc6197a5184e2eaa80e7 +23 edacf71e573086b3c77c1b55768694eb +24 f73abf3b6bde50bf534e6a339baedf04 +25 2048f8e6ce8c9f3f73f2e0e3897adc71 +26 f516507ee7d11e2be24e8214a79381b4 +27 94c324f1888209d579386798d156c139 +28 69b7d46a89628eb4bb8bdeed70a1169e +29 b6c23d7e79d917b2a79a8f80c5a7ec60 +30 2d4ddb9dae91ccff767798d510116dc5 +31 f6aaacc0ddfa085e2bc2678355fd6de0 +32 00dc889fc9172cbcf4309655b3163e45 +33 395524414543de2c608a983fa57f8caf +34 0aee9141aa27fddcaf820299cd2ca4b6 +35 f51692dae010c4e850ad4a30cb789fb2 +36 ccd32f422a24927cd691ed1a2c2b0ff6 +37 bde2d880f113f7a18e952f96ee471864 +38 5ddaedcba989ec46e06021a5240094a4 +39 16d03aca9bcc9644f03db35118ada156 +40 43c5a7a5fcae01c9162d438050bba4ca +41 b24cdd81fbea352141205aef1da9a08b +42 fbf546ec9181c94472166a3d5c477218 +43 9075e20ca324bb40268a294f5ed1d2ba +44 6dfffd499ecbf016da5481b8a49bca22 +45 441dd5de2ac9d7fac7730bd5ea0c5202 +46 990c1a2e38cbf400cf473d8a02f16a7e +47 9c684a6d1dc771228d1e7ec99c345a8b diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/WPP_A_ericsson_MAIN_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/WPP_A_ericsson_MAIN_2.bit new file mode 100644 index 0000000..f6bc24f Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/WPP_A_ericsson_MAIN_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/WPP_A_ericsson_MAIN_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/WPP_A_ericsson_MAIN_2.txt new file mode 100644 index 0000000..4f91846 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/WPP_A_ericsson_MAIN_2.txt @@ -0,0 +1,33 @@ +WPP_A_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 416x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The sequence contains six GOPs, which are all 8 pictures long. The first three GOPs have pictures with the following characteristics: +1. One slice in the frame, constant QP +2. One slice in the frame, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +3. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, constant QP +4. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +5. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, constant QP +6. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +7. Random combination of independent/dependent slice segments, constant QP +8. Random combination of independent/dependent slice segments, QP of each TU is set to a value such that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +The final three GOPs feature a mixture of single slice pictures, and pictures coded using multiple slices and multiple slice segments. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation with and without different types of slice. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/riferimento.md5 new file mode 100644 index 0000000..6c524a0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_A_ericsson_MAIN_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_A_ericsson_MAIN_2.yuv 416x240 4:2:0 8 bit, 48 fotogrammi, 7188480 byte +tutto cd7e815eb47e8138fec2185d4de84304 +0 c6462f3f36ac456baeffc67a5ae29b68 +1 95e63dcdebbad398f7f3fa32c57a80b8 +2 398e5174c4547fb59f70cf819e195763 +3 c98b9cef4bdc1651b23f0c2391723983 +4 9e11618cd5bc4ce22becbfdbfd4d69f6 +5 06336e18fef8de59a120bf2f5c70ff51 +6 22c08e5f0cfdb6e4bc5743684a5b2ac5 +7 1dd85c1913b501d147a440e31c456d36 +8 bb70cd8730f9b9d70fab62fc3598727f +9 c4ed9030ae0fdbf7c27dd807a681b95c +10 1783f198d12219d2e0cabda64540b42e +11 ab8f4f9d8960f606be692b0614b6d392 +12 cc25a3a6fbb5df694736fda397933ee3 +13 37097818d451c7862a07e8fe7f98b4dd +14 9cbdbafd4ad662e338666c9bf26289d7 +15 deb17ccf19b47795c386fc668f3be361 +16 ba5087362e13ce8c357a63cdbeddc71a +17 1d7468ff7928de7db15e6b880117c62d +18 5e8095124884e4818f0fb619ecb14174 +19 c102fe6856f7e539d870805c856283ae +20 b0bfe721160489f9a7222a3839404e91 +21 eff37a5dcb54c2aa8e0a1b62bd0d9672 +22 659900eb377f57d8a5991563b5913a9f +23 9dd5b3f2a56208b3b49bca9e5472f90f +24 c286d8550c9d5d22a578106a6d37f094 +25 50ff052ca87d7da03a9d80ab6522df57 +26 21f1469a58b09e5f9e874c48a8cceec1 +27 00c30d2b3c49ffada36caf140d1392aa +28 935ff6007a8349959dc58b0f842cd265 +29 28eba0497b0dcd5a26ecf9ff3acb36cb +30 ea1198ca4dee6b131e7d89b2c0aa9da9 +31 06c5edaa00ca6088c2ea293614bdefac +32 aa3e44d035da453ce5b8a971c2b0e929 +33 f42b3b28594079f535fb07a4e1cb3071 +34 c7eddee597d1c083751bbbba02282311 +35 dd08b41a4a1ac0e91e2b933e1986b779 +36 ada4077115ac5509f1dcf94a51020306 +37 f8cb281db443cd2536ddaec564d52eaf +38 86e0c894ac41b7504cebcb5c3d408ef8 +39 61e48e5e08e476b1286098ef7cc49910 +40 003eebe8aaa2c7728da40a7ac69c84d3 +41 c9da394a36c1c8de9342cd9e692d048f +42 bad21ceef38e1279008ca8cd87204866 +43 5b875b9e58ea310eebedfbf8a6cc4be4 +44 10f546ec270f3b7d4f4907d7f7095087 +45 6ef22fe7cb30cf55f664554faf0fbbf8 +46 f47f559fbc725b95dbc6a16a92c6d0fd +47 b0dcbe722f6e4d61816c60af6d4ea8da diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/WPP_B_ericsson_MAIN10_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/WPP_B_ericsson_MAIN10_2.bit new file mode 100644 index 0000000..843d1ea Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/WPP_B_ericsson_MAIN10_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/WPP_B_ericsson_MAIN10_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/WPP_B_ericsson_MAIN10_2.txt new file mode 100644 index 0000000..63f1dc5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/WPP_B_ericsson_MAIN10_2.txt @@ -0,0 +1,33 @@ +WPP_B_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 416x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 32x32 is used to encode the sequence. The sequence contains six GOPs, which are all 8 pictures long. The first three GOPs have pictures with the following characteristics: +1. One slice in the frame, constant QP +2. One slice in the frame, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +3. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, constant QP +4. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +5. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, constant QP +6. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +7. Random combination of independent/dependent slice segments, constant QP +8. Random combination of independent/dependent slice segments, QP of each TU is set to a value such that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +The final three GOPs feature a mixture of single slice pictures, and pictures coded using multiple slices and multiple slice segments. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation with and without different types of slice. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/riferimento.md5 new file mode 100644 index 0000000..1e36e99 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN10_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_B_ericsson_MAIN10_2.yuv 416x240 4:2:0 10 bit, 48 fotogrammi, 14376960 byte +tutto d8290fc1eec3a196aa796c92e71a779b +0 bc75f48829134712cfd91071f783af79 +1 5c4df74586174836aee2402771b68df8 +2 619002bf8e0f27098be3bcb94de28656 +3 3b93628cc7efe737dcbda66d3d384440 +4 72ccd70db4ba470aa6811098b3df340d +5 46430250476d8bc3f2b92590443a2bd7 +6 1849a1962fb74beb890b23918f860c9e +7 8117652f670a867acdf015eb937d50ce +8 1b6983aaf402bb6bcb588c88b87fa205 +9 4eb208ab91eb05aaffd0c8664369bc82 +10 5de15185de76caf493fe3ac1b79b9f22 +11 21c04673f0f10175b932323d27d76cef +12 025d490d50fdef124a835651ebd41150 +13 541172e16cb11aab4869e15c4fe4205c +14 120f64c9473c0ef3af2627614c74819b +15 de869167cc57ef5261510c8d31f79b4a +16 c574911284a01dc0a17c0a88a5c16ef5 +17 0e5ca269943daa64fc0eb67198857703 +18 aa483089fc90ade9c6824bfe089e0061 +19 fb73f23abb6585401dd0f6053d2738b3 +20 c24b8ba638925855ede952ddfa801c1f +21 8d5a87f7da49c8e6acd48c47ecbf1328 +22 51a778ec501552b2d0b61f459955c625 +23 37a3080379f59ed5ac1ecfcd63617b3a +24 cb320467bcf834d0c7352c9442b2f7d3 +25 0276794bfe55243ecd9dfe537300e716 +26 a2da6493a3997be7a8a03d34ed7947b6 +27 8d8e3c58ad0ad11d44add635bbe2d083 +28 d47b75daeb09d286153520bca156d72b +29 00a88cb88bfe0551dfbb524a698bc2bc +30 8254e61c7f2abbd036c4238c6023f27a +31 672c4295820b5157e4fd6f6940b1f009 +32 345bafc8d16cbdd4ba1dee51128f8c31 +33 4239c0382604756f1e30ac6f3142283f +34 6e262ab70ae006c2508bc97bcaa78943 +35 d384ed3b2a875b01a7354b4b5745c8b3 +36 ec29bdc3ce306aab72829fea822fb68b +37 afcfedd4fac40036d2089abf5ee88a77 +38 22f98a8817c578e8ae39b0a5bcdfbfee +39 796386550d166ed46aeac369aa5c541f +40 82de052aa56d163f24430c948fa276f1 +41 6ef58a62260207511e35ff87d0ea3be1 +42 e8a490af5d4663d6ba2daa6b4c248fcb +43 b227ea5fdb71d2aaa221ce6df146a000 +44 1377678ddc8f01de848d9a533de3418b +45 0d4f08301bb2090e6e5368ed8e5ceb59 +46 92b27e267b8d3300e31b3de35d1a474f +47 c9f1f4114227724926b263cb71fed3d7 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/WPP_B_ericsson_MAIN_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/WPP_B_ericsson_MAIN_2.bit new file mode 100644 index 0000000..11084fb Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/WPP_B_ericsson_MAIN_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/WPP_B_ericsson_MAIN_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/WPP_B_ericsson_MAIN_2.txt new file mode 100644 index 0000000..63f1dc5 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/WPP_B_ericsson_MAIN_2.txt @@ -0,0 +1,33 @@ +WPP_B_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 416x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 32x32 is used to encode the sequence. The sequence contains six GOPs, which are all 8 pictures long. The first three GOPs have pictures with the following characteristics: +1. One slice in the frame, constant QP +2. One slice in the frame, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +3. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, constant QP +4. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +5. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, constant QP +6. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +7. Random combination of independent/dependent slice segments, constant QP +8. Random combination of independent/dependent slice segments, QP of each TU is set to a value such that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +The final three GOPs feature a mixture of single slice pictures, and pictures coded using multiple slices and multiple slice segments. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation with and without different types of slice. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/riferimento.md5 new file mode 100644 index 0000000..f90d8be --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_B_ericsson_MAIN_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_B_ericsson_MAIN_2.yuv 416x240 4:2:0 8 bit, 48 fotogrammi, 7188480 byte +tutto e37c7e561a1226640a7bf98e81df78b1 +0 6b81f61949a002d94f99e69ffecffdf5 +1 c97e18c2fe3e6fbc09646107bb680bb2 +2 2b5035ebbcf8b6118a37aec27d7cb1d9 +3 59327fb043eafdbd710b07ed0b810e51 +4 3a6b03c4610b812fcbd50daef67aecf6 +5 6d971c6688ef58edefe2fe94c2641ce4 +6 3a4bc3cb85452b4714a2dd3130e57f38 +7 edeed91e563f24232da709ae405dfcde +8 391881d5ae87dc06c622b9491e0df5be +9 c7154d9ffc13252bd9b705a2e97ebc00 +10 fa3a089fe042fcba78f54cbc9725be22 +11 517828b90b9ba32a6cc2c6ba8acba5f3 +12 9336bd685a33e158a7194f175db7f680 +13 f75ac3f071104d888ad618ceb2fceb47 +14 7346272162d1ac95e9f1aa6d12a766b7 +15 fce45723969aeb635ce30a4dbc1bcd1a +16 8aac11e9eef6ec6f277715291b5f3ca5 +17 716ca0231e32daaee80100f9735e963a +18 8451e22962d950f58355ba5d04be90f4 +19 59b9c9f012211fdb588fe8963f349091 +20 92109be4f2eb59aef7e884326d0806d5 +21 563ada687afe11b9308a7935e02fbc55 +22 39ded724d9f3f987ce5985cf837495ee +23 90c390407b25d5928a1ccb71ecacde75 +24 d7099a37d664bf6fd4f4bb3c22364431 +25 c1d2d41dfb884704da292dced67996f8 +26 cb2743baa3fade056720a0bbc93758df +27 4824d5ad8892470535e45109f09d02c8 +28 df32cdb0a84356245eadbc4edf4fd377 +29 a8045845553ee2650cfd3ad85be6461c +30 9ca43df7f3702c05fc06e8c5cc691113 +31 46231e90c2d48f16868a2959a1f32d89 +32 afe41ac9ad0c11be30442ceccd11790f +33 0b8fe57a858e6ae7762bf41d74cc9876 +34 1835bcf668d10e1ece2c82a8036ee3f3 +35 d0838ccdecdbd96b91cb02bffd4b9fe8 +36 cc8f77515e5234fc8b6fa4641a18abbb +37 d502e8bce1854953a56808bbb835aa14 +38 5e20ea3af33985445312aa709b413b7a +39 fe24cefff0d643ca4e3405c0414959b2 +40 27869f87da2bacce72c4e055e0756a64 +41 2cff327ebbf1be703a0813fab027c25c +42 18ca866a2c4be8baba19af273443c1ce +43 70971bb0637b85aa833c27e312cc6292 +44 ae69403c4232956d4b75afb59518d4da +45 62f8f5c843bfdd5ec876cc0846afbc46 +46 815084f4a54bfbadf2e61f04675d7184 +47 c686c50198ddd54f713d704c1ffff29f diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/WPP_C_ericsson_MAIN10_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/WPP_C_ericsson_MAIN10_2.bit new file mode 100644 index 0000000..4158e8f Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/WPP_C_ericsson_MAIN10_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/WPP_C_ericsson_MAIN10_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/WPP_C_ericsson_MAIN10_2.txt new file mode 100644 index 0000000..6b10e5d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/WPP_C_ericsson_MAIN10_2.txt @@ -0,0 +1,33 @@ +WPP_C_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 416x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 16x16 is used to encode the sequence. The sequence contains six GOPs, which are all 8 pictures long. The first three GOPs have pictures with the following characteristics: +1. One slice in the frame, constant QP +2. One slice in the frame, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +3. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, constant QP +4. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +5. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, constant QP +6. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +7. Random combination of independent/dependent slice segments, constant QP +8. Random combination of independent/dependent slice segments, QP of each TU is set to a value such that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +The final three GOPs feature a mixture of single slice pictures, and pictures coded using multiple slices and multiple slice segments. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation with and without different types of slice. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/riferimento.md5 new file mode 100644 index 0000000..cb026b2 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN10_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_C_ericsson_MAIN10_2.yuv 416x240 4:2:0 10 bit, 48 fotogrammi, 14376960 byte +tutto aadac4d468d5950551d606c1016abc9c +0 70517c248383da65e08f6a60a44d0bb1 +1 a6526be7743ea9c9780753f4085dc414 +2 bac9d5b1cb9dcc70ef2331357b451af1 +3 03326c424d3db7898fa173643deb4809 +4 c52886d6311436f4658802b4c2568b96 +5 fb9d1ed90780c875027ccd280fbea0c4 +6 f463557eec4ec8d99f3c40c1e2617a6a +7 2667fe866e1d0f6843acc021ab77eeaa +8 1f125d077eeffcec4286ee40c9dc2c75 +9 91d51b281ee48edad8f688c470fd543f +10 e74b61b9defb16ce2645fdf6eeb323dd +11 017bdffe5105c407a275c0d032b907d7 +12 9d5cf44cf22745b161ec769ce5397bd1 +13 e938fbd52fa18c41b2af424a0d665ed9 +14 001bd4af2124ce373e340ae1c44ab2e8 +15 585bf9cf9f52c9b1ee5384f1f9eacf87 +16 486b2dcfff914d9ad0771ac716bbd04f +17 dc40eb377f068d2eafec537413cc05a9 +18 6055f1f973f52e943c1a7c95c20ea088 +19 acbd9b8113eaf780537f52f798145d05 +20 72ae8eb1fee6b7b20dc7732b760e41b9 +21 0165f07834ab9b4c05a30de7a20f1bb2 +22 91c85e9f1d14922ad07d8c63e018589d +23 d3bff91720ce890b64485670f9f3315d +24 ec8960208142bd96444f3418d98c289c +25 3d3d1de1b15196600bb82c0e53f26895 +26 388e4ede418bb6f72c1f1b8ed375159c +27 e979cb598c34b630a66a58a192ce8a87 +28 148b996a841b47fb5a94ff8c641ffae7 +29 114a02ec4bcee57d4867bcb4dbaaa2e7 +30 ef316d2b22aef3973746755bea7969c2 +31 fddfc477a5a1d6028eb66613d7563141 +32 d652d9fc80fb7f4cf61f301e826441a1 +33 2b53442b4a00c1e714ff3bb00266d49c +34 6d90fbd782d530812a3e6b515f9499b1 +35 16cb53d13c419ac0aebe0080529d6a7e +36 c2c31258768cce339358b0d83b24753c +37 7d6e74b6171ecf589f802fbd0150ceb0 +38 2f8f6ac6b0012d2a2f1d31c9a6514a31 +39 c4ca959cadafcec9330a30a6c8cfd1c0 +40 cfa4e39deb7fd24b519e3c1f4f7c3318 +41 6e350e70995ce0cc0b3cdf33d1e2aca2 +42 274ccde67a956809eccde65292d97798 +43 18e3fdd50b647ec14366a5b8de490697 +44 b598cd6d2cf42d6d7c12bd88c308a66d +45 bc4ced7779aaba726810f96450faf1fe +46 58e4d7b29a8b2b50646eb10ab50993be +47 ea00379eed64925188fdf1b6bfca4ef3 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/WPP_C_ericsson_MAIN_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/WPP_C_ericsson_MAIN_2.bit new file mode 100644 index 0000000..657bb65 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/WPP_C_ericsson_MAIN_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/WPP_C_ericsson_MAIN_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/WPP_C_ericsson_MAIN_2.txt new file mode 100644 index 0000000..6b10e5d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/WPP_C_ericsson_MAIN_2.txt @@ -0,0 +1,33 @@ +WPP_C_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 416x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 16x16 is used to encode the sequence. The sequence contains six GOPs, which are all 8 pictures long. The first three GOPs have pictures with the following characteristics: +1. One slice in the frame, constant QP +2. One slice in the frame, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +3. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, constant QP +4. Maximum number of independent slice segments in the frame, at least one slice segment is 1 CTU long, at least one slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +5. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, constant QP +6. Maximum number of dependent slice segments in the frame, at least one dependent slice segment is 1 CTU long, at least one dependent slice segment is 2 CTUs long, QP of each TU is set to a value such that abs(QP - QPSlice)>2. +7. Random combination of independent/dependent slice segments, constant QP +8. Random combination of independent/dependent slice segments, QP of each TU is set to a value such that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +The final three GOPs feature a mixture of single slice pictures, and pictures coded using multiple slices and multiple slice segments. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation with and without different types of slice. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/riferimento.md5 new file mode 100644 index 0000000..97f1008 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_C_ericsson_MAIN_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_C_ericsson_MAIN_2.yuv 416x240 4:2:0 8 bit, 48 fotogrammi, 7188480 byte +tutto e067aa3a6a12cd5743849ded793c8d3f +0 3fc1ebec8e6b1f3c383a39b9df1cbad9 +1 98491603ded4169e894c98c388a50e4e +2 273e2ac970656b23f85b6dfb7822d29c +3 e1caf18e25699d119c75315e4bbed3ca +4 e346f4d25cf64e3302c996eed97539cc +5 a0a748b47276145706675bf805c45e9a +6 66a8d9ef3f1aeeb88e02925616bd71c6 +7 cf17c94ee6cc42d001c3fe50a9a547e9 +8 f9587d85eca05f23af04f3aaa5523668 +9 d40f0ab4661416f00d56169d05d6371c +10 e35de07753884b9a8547e14783ee981a +11 022326312d82130d7edf9856ebaf556d +12 b00b46c10981803a57f38f55696c3c0f +13 d2ebcc935ecd9daf9d96df75366dbccf +14 bf1b69e5d3fd076368a5ce086aa1998e +15 2b0233e18b21db1210c43ced8a2427fa +16 67018a163f1b96ae9f87cb3ab6fa0936 +17 0d49e3e9bb74560640b1b3f2ad6a5cf0 +18 876f49d7432a88ef6553dd71173244a9 +19 47fc002903c96bcfad0c7dba92a458d6 +20 ec8aef26cd5418e382f675cfa225c6cd +21 23dd2b004673d0e2c33595028a5b0ed1 +22 3c15aa67f21a3ec9620fd1efa8396b16 +23 f51eec2ea301d12ff43783e8e31923bb +24 cd09256ed9bbd3a486a66421bc46e06d +25 329d037d9fb5ece74cedf618317139ab +26 9404cd3fd1f3bb8b330d3e3464ba8864 +27 e53aae57642f2ff47de5578a00222ab3 +28 306da865c79a5d22d7b7601e3e4437b4 +29 ea92f64c0c78bfe576fa39e19f20343a +30 eee6f3cec228a227a897b2859d58d506 +31 01d04936849d0836fe4e8fb0ccefff3e +32 bb290c1f730d241938c5eef1ec9db5a8 +33 aadd69304ca0b58fd56df521188fcdf9 +34 ba0935940c0d364104e5885ddd4f56b3 +35 efee9b80031aff07353d92c55cdef46b +36 1ebce32b924215ad800d3f99afa8014e +37 83168ef4d381808919b4255df19e9cc2 +38 43aab65297c088e25921263cf2a1f9f8 +39 8e4e1686e18560f681582a13f8b2e8d2 +40 261fca455c9d912a033057c2a90aa9fd +41 cd58b2915a0cc8355356e761e3808ee7 +42 31bfe5f45ab85ae140d167802b1c0edb +43 0de1ab66b1d06d3243ee93a15af00c58 +44 1e4b6e2d79f08cf32a223acb69162f05 +45 e538a037720151ea9af8be5e8e87b74c +46 080d1240250a16d44f12d55411ad2788 +47 5566eb44bbd8851b07f091ccbc31265b diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/WPP_D_ericsson_MAIN10_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/WPP_D_ericsson_MAIN10_2.bit new file mode 100644 index 0000000..b30bfd6 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/WPP_D_ericsson_MAIN10_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/WPP_D_ericsson_MAIN10_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/WPP_D_ericsson_MAIN10_2.txt new file mode 100644 index 0000000..2fa2c0e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/WPP_D_ericsson_MAIN10_2.txt @@ -0,0 +1,23 @@ +WPP_D_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 64x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The picture is 1 CTU wide. The sequence contains six GOPs, which are all 8 pictures long. The GOPs are encoded with varying numbers of slices and slice segments. Even frames have fixed QP, while the QP in odd frames is set so that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised when a picture is 1 CTU wide. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation when a picture is 1 CTU wide. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/riferimento.md5 new file mode 100644 index 0000000..e17a28a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN10_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_D_ericsson_MAIN10_2.yuv 64x240 4:2:0 10 bit, 48 fotogrammi, 2211840 byte +tutto dde9aa65b78a8ca5602d834f234655d4 +0 99c32639a0e3c52ca5067bdb9a398074 +1 d03533c0ea7726f8ef46cae7c2ead974 +2 a4eee208bfe39fb30bc6f91c237d421f +3 bcda88b9fd9b2f81b7ae30f54dc60fd0 +4 299c1e468cb5f45da00ffb36832acdc6 +5 53540dcefb2080ab7a590ac9db0de874 +6 888c5afd5e2ae319b648ac15df5e86ef +7 bd032dab758199577a7c4ad9fa2b697f +8 71d6482774310a5ef88bc5b4d2cfbcd3 +9 3ff701937dc1abec6e9fe1e5803a7f5f +10 eaa582aff4c8b21d28d2d73f1b8c963f +11 c7e862fdaaa45819fd3d7afa110554db +12 7a2dafd487c8d17b55b3cfde509321eb +13 1648e15d841a245ae93a617ccf75b0bb +14 47279f9dfe2873815c8617cf333d0a28 +15 82fc38aaacf1464d4451a18415f1d277 +16 5edf1629344673c998182c6585dd80fd +17 acfd3ebdae3176451555dd69d5107a0e +18 f359026589447cd987552fbcdd08b879 +19 55078b87c01764a9cf7849ac0316c5f1 +20 3d8c35c1771ae575f8a31d0ea07c4262 +21 cdde43a97003c5d895d20e7e31935eb5 +22 2d77cc5398d3a56a7af6a5d7e5d46ed3 +23 93bc8ae221c059d0d5b6cc7a9db1d70d +24 e7e34e5c2bfe2f6a57b1ff111eb1c769 +25 9000bf87b7e59e8054c5c7a77a8d2cdb +26 33b1d9ee99a1eba9e61322405f21dac9 +27 8b63c834c5dbc9dac63d1f84a613b28c +28 5fc191e3b0edd1142aec714d8fb4ce54 +29 74c4581868a9186c87606ca98b6e27fc +30 7c2e61c19ce5039674cdb99f3cfdf915 +31 28021f05e8269f0c37ca1a92951bb119 +32 cbc8adc875560092dfe71b472ab924c9 +33 d719f8361a2bdaf903068b10eabb5bd1 +34 4bb390f6c354e399aa42dd2389c9a5fc +35 0bbb8fb70c16aeddf710ad531110e6c3 +36 66cae6c78de74253658b1817b908305c +37 b88f9d9c0f1438fca0f53ca455297684 +38 b72a570d21151aabc79c405f39fb22ec +39 497162cc738af64f6015c464e261f2a7 +40 b6a93913a15599815567fbf9fda9d9aa +41 3861c368bcf7db1c2834627a5e9fc9a4 +42 d2948bf26951708269ef8de90a834abf +43 096f9ed661fb7069d5e8b5d49aeeaf1a +44 17500ae65c2e1c452eb8ff29f24eb18f +45 cd39ff3a3e4706ffc36cdd4c346bdc9d +46 10b644ad93b76519097c0aa5f1c3d681 +47 988df14489183fb6c7d11a18d19a6096 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/WPP_D_ericsson_MAIN_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/WPP_D_ericsson_MAIN_2.bit new file mode 100644 index 0000000..03e3262 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/WPP_D_ericsson_MAIN_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/WPP_D_ericsson_MAIN_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/WPP_D_ericsson_MAIN_2.txt new file mode 100644 index 0000000..2fa2c0e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/WPP_D_ericsson_MAIN_2.txt @@ -0,0 +1,23 @@ +WPP_D_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 64x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The picture is 1 CTU wide. The sequence contains six GOPs, which are all 8 pictures long. The GOPs are encoded with varying numbers of slices and slice segments. Even frames have fixed QP, while the QP in odd frames is set so that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised when a picture is 1 CTU wide. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation when a picture is 1 CTU wide. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/riferimento.md5 new file mode 100644 index 0000000..d1d08cf --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_D_ericsson_MAIN_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_D_ericsson_MAIN_2.yuv 64x240 4:2:0 8 bit, 48 fotogrammi, 1105920 byte +tutto f710612103f386c415be3e6300693451 +0 df80cf7d64bc9a429c0f348490118493 +1 110102406bf1f095b5c45117c594ef1e +2 e43ee3e163603e7b257cc42b69ff5166 +3 5d777c6719f8cc00b7734a960d5c8de7 +4 8f7401ad105beda2749d1640361ed6ac +5 b0119687c3983f16b14d864047cf5a84 +6 d0e183c1d9da80ce5c49546f76b25db6 +7 70a0c15b87e9e8f923622a5b2add8699 +8 5b6f69613ce69ded2c29ab27a6ccd1f8 +9 2c30fdd9fa340e9b2ab408a5efe8d81a +10 33e32303d79e92763ba67b8aefb30261 +11 86249cbc094b19d61f1228b6d40b4f10 +12 1641717b3b88a630934a6df4ffcbf92e +13 9f1fcdff62912830a5b1c3ad5c91b1bf +14 efe2b1755b69b9e0cae8f8205a34b1b1 +15 48d8f32b950a6155d20da1db48234f51 +16 56e6655ccd993d85b4a17249d68d0893 +17 01b0531b0c2ae4f5cec93620bb4ee5fa +18 1355ea2a3c41d97f56544e41e45960ce +19 4f70cf2c9646c33343084333aed571df +20 efdce4b357bcb7e695ff8b807d084bd0 +21 dddad1862096e7472efdaaa84a83db9d +22 6fbc0b9e32f8cd4e0ab6adcd5260533c +23 c1d666578794327d657eed394ca3bc7f +24 30709d5309b5cb8c24efa957dce00fe8 +25 98656a69bc41e2a027f85fa27c7aa306 +26 87d1739bc1a2f4bf69e15e4e90b47a08 +27 501abccc379c2151c41c4c98e5a34b28 +28 f81693da18496d961f61254f25c7fb94 +29 a70f9677d6ac33766551f0f0dd8575e1 +30 05b68e05acd879815d2f1131def2dc01 +31 43f6d77ff8171bd111c54a91e28a659a +32 aeea679d6c5583654666a2c166606d44 +33 1bfe26438411b3535a1dda2a381d37b7 +34 e442dc93a32823ca1a02704bcd460ddb +35 047bab85951963aa896ff2c241c5662f +36 94398730c82f5d61ad3b60298b3f9169 +37 4d7c7167c63907e47637cf47eca2fe87 +38 8d4e693424d8247440f80fe5e63586fa +39 e5db678429905b28321e4da26002367a +40 418e407ad685b3640da848916fb3768a +41 01409e0c173a80d32f2efeb41def3925 +42 ae1f1c9e7353eb8bd7460d1f46c7d41f +43 cfd038f4d312e610b76a0ebbeb0d576a +44 58a18c1991c06f3591cc4f7dbb966f9f +45 009515456fb653ae629ac845379f3b16 +46 0dc22f93e0d59e35c65dd51c82afc9e1 +47 7b893503833d2bb59da0d00bb1dbf2ad diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/WPP_E_ericsson_MAIN10_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/WPP_E_ericsson_MAIN10_2.bit new file mode 100644 index 0000000..76e9279 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/WPP_E_ericsson_MAIN10_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/WPP_E_ericsson_MAIN10_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/WPP_E_ericsson_MAIN10_2.txt new file mode 100644 index 0000000..21cf427 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/WPP_E_ericsson_MAIN10_2.txt @@ -0,0 +1,23 @@ +WPP_E_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 128x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The picture is 2 CTUs wide. The sequence contains six GOPs, which are all 8 pictures long. The GOPs are encoded with varying numbers of slices and slice segments. Even frames have fixed QP, while the QP in odd frames is set so that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised when a picture is 2 CTUs wide. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation when a picture is 2 CTUs wide. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/riferimento.md5 new file mode 100644 index 0000000..c5c46df --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN10_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_E_ericsson_MAIN10_2.yuv 128x240 4:2:0 10 bit, 48 fotogrammi, 4423680 byte +tutto f12e746306c59544d6162de0b62c4649 +0 8ca75813e859e2fe49ac295b4d451190 +1 5e76eba4989c76809326a92d73cc4ad1 +2 db87a8e48ca2a342ebc3d010f2831085 +3 a1331fa958f2150d2d968357db8c8f44 +4 be9f16bb4b23308b419e9dde8fe13768 +5 afdafac9807fe1026aa90b413d750de5 +6 5c0c692acaf34ba231a1297df9ae5dbc +7 a8d1a097cea748b9a86de9fca37bb256 +8 98c4c14e05e54bef7d036a342c389f0e +9 f85d3247dadedaa7a2f8ec40831146ab +10 f0734813d0e13ea6182b3425813dcca6 +11 c7193c9ed8fc00763bac14cc8d276ecf +12 8996b3130667da94aa0636c7eb0a4a34 +13 b510a3fa962b871a5a6ceab7b9b4515c +14 cbc65a377804298a7c4f6e148d281f09 +15 203e381194ae27ba4177019a496125bd +16 a7911f8b9a891007423d4083079c5b46 +17 4f571db1abaa8f3360cfdbfcf694f96b +18 0847a55965a970fe69ef6c1779512d0e +19 81285f7045286db474a35d42437fe49a +20 c68fb3d0404f7c86bf9efbaf55473d90 +21 34f9b9305f20eb0b99505d7cd75b0bcc +22 f9d5e87e60ed248406bf522a5ba65d9f +23 051ac5e61c09a698464272ac7b778875 +24 107c6b9cde5254779e49dd669373ff7b +25 4924e11f2c1807bc2c18674a623c391c +26 d90551bba9a8736fb3b15328536dac14 +27 20bd6ecb152387f1e60e79d0f1a23a95 +28 a284218c9add8eba7fca4ac83879092a +29 60fd85cbacf8890829d872c0961d6800 +30 07490f73c4659ba5dab70b6f908e6850 +31 49fd2a4406fc958118e2f8a4f002f33a +32 8aacedbcfaf06089908bf15bbb8ccf11 +33 2039eee9b9911ad76174c057f9cd9520 +34 b7aadf1f128ee5174c275c622f873987 +35 58ddda386ef7c85103e293ede85a7cbe +36 b69f36998070be646f3b85a05aa13dda +37 a8b5b41db8007e3b63c5ef63748a5f56 +38 fe9cd3b451763583cb8e8ff11e168370 +39 209751607b1e6fb115e2913184b547ba +40 ff73de1d0c5f5cadba9992b4c232bb8a +41 eb603f10e03f1d8dd9b1d28efce4e3d1 +42 1c6721f3ac1c36a9899681637913e6cc +43 eca5f4e408830765509d06401e86e3f6 +44 45eff37e725801b135375d72b0f231b0 +45 f9dc2e9847eaabe8c37bd9782777f038 +46 be60ca354a053dbe52f7c114383662a5 +47 5fc479f9e7a3cf9af157c51b299530a3 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/WPP_E_ericsson_MAIN_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/WPP_E_ericsson_MAIN_2.bit new file mode 100644 index 0000000..917635a Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/WPP_E_ericsson_MAIN_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/WPP_E_ericsson_MAIN_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/WPP_E_ericsson_MAIN_2.txt new file mode 100644 index 0000000..21cf427 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/WPP_E_ericsson_MAIN_2.txt @@ -0,0 +1,23 @@ +WPP_E_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 128x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The picture is 2 CTUs wide. The sequence contains six GOPs, which are all 8 pictures long. The GOPs are encoded with varying numbers of slices and slice segments. Even frames have fixed QP, while the QP in odd frames is set so that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised when a picture is 2 CTUs wide. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation when a picture is 2 CTUs wide. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/riferimento.md5 new file mode 100644 index 0000000..bfcb3eb --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_E_ericsson_MAIN_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_E_ericsson_MAIN_2.yuv 128x240 4:2:0 8 bit, 48 fotogrammi, 2211840 byte +tutto 485798dbf95ad61232075df2f294aa3f +0 3a7bae7c63b6f44768eef74b630bce60 +1 a4284eafe7d39e7fcc244aea4ce2e57a +2 595a8e4cd975e57e95c34c675c96d6ab +3 8ddffc64d3b6dee90eaece330411773f +4 d447d318e0786d041916546f90a47e38 +5 14b9dbcc122f6f5f7e6ccd31b17f5538 +6 0f61417d529fed9212592885a6ee4b18 +7 2d6614a249e3e4168c1608350e49232d +8 cb9b86a55de234c085b5a71f32c980c4 +9 b19ef1af86dd99335890512e3684f6c9 +10 fe572e9a788d126569b122d8f6afa558 +11 b63de565d398eb049d2538e82a9febc0 +12 ac8d549181f5bd944040ed355ed3b2d8 +13 e92dfb5e65808265fba404cdc510ebbb +14 33e4dc3f9f837697ee620ce237bdd517 +15 5d97c3463eec3c0b55fc72e52adb4ae2 +16 7597efc71ece72f6eee4be3393d62701 +17 f9651c9bb146ee544a5d4c5da5f5894b +18 7bdc4bf85d3cfdc3033f7d58056fcd96 +19 d728b346c18460f73e38823b55be859a +20 4ab017fbf0de0646ced7c7204ae9e3af +21 e5867d79b3aad1016a23c4138a4a18c4 +22 ed710b0dfd6b00a86d8d20c22579285e +23 3cd0e8c6fcadac2d7679451b55fe9188 +24 2313aaf910e8c70c914a843414d83f16 +25 b5821598c208c626a9c0af96bc4712ab +26 d86206b3326ded562eda48787a322fc4 +27 1a5ad2774dbcb23e0433e901ef20af3d +28 502e6047b3d459ab41f43365509e496f +29 bc7a4fbcdf4fb107980fea50fc97ed5f +30 07cc218102e92f56aacd21b802540dca +31 945e79414171553aacf04957f95af8d1 +32 ad79e07fd27a282f82b31bcccb5e7540 +33 da6bf23d673bdb49b7e773d344078232 +34 290d61a68115b1f4f11d238bf1cbef1f +35 282223a13fbaa2848b01a4f9a654b258 +36 9b29ddf2e7048cddd42d471b9ee12572 +37 782574b9fb13c80d2cb68c17db96ff51 +38 b211a65cec3cc7f215148b57c92a79c1 +39 6b872aba65eb16567743b0af23eacbe3 +40 f5de9710eb252028c08205110297fa2d +41 c50743e691efe56f7c90a2793b743140 +42 bcb487dc8612db490aaaa507fcfb23e3 +43 0c77e2c170383d539c562b141e78e81d +44 a5bcbe383cec9d8041f4f128722adf57 +45 98b2eb95474664445f27de8751471d3e +46 7589a379ea3722a7400d5ccab1b3c88b +47 966a512e2506c5050efa4fd39f1edfb0 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/WPP_F_ericsson_MAIN10_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/WPP_F_ericsson_MAIN10_2.bit new file mode 100644 index 0000000..fc113d8 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/WPP_F_ericsson_MAIN10_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/WPP_F_ericsson_MAIN10_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/WPP_F_ericsson_MAIN10_2.txt new file mode 100644 index 0000000..86056d0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/WPP_F_ericsson_MAIN10_2.txt @@ -0,0 +1,23 @@ +WPP_F_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 192x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The picture is 3 CTUs wide. The sequence contains six GOPs, which are all 8 pictures long. The GOPs are encoded with varying numbers of slices and slice segments. Even frames have fixed QP, while the QP in odd frames is set so that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised when a picture is 3 CTUs wide. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation when a picture is 3 CTUs wide. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/riferimento.md5 new file mode 100644 index 0000000..7a08e4e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN10_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_F_ericsson_MAIN10_2.yuv 192x240 4:2:0 10 bit, 48 fotogrammi, 6635520 byte +tutto 210055a33d7d912fda6a3c40764b0482 +0 fb3cb4fc02580c6b9587af9e287cef12 +1 1bdbba9f480e851e38a218d44bd4312b +2 bcef0415096a8f5417e0ac9a405a59ed +3 caf03c237215fb0f76ea06e33f1d2b91 +4 60ba7802410264424300cba715c895bc +5 b280512230743d3420089a64065944ea +6 c8f047d30cc8f3e12c2a9b45e186ace2 +7 7e0ce3f431a60282a0f4b7c2d1bcea90 +8 06a085e6748d6f5d8f96532ee12b9602 +9 ea62a34e951af99ec163df190f570df8 +10 94ed430cbc1dedd02a9d33f6d3a86e99 +11 39ad5027971e75231522be27e75c56c2 +12 c7b79048f776f748689614cb66d93e50 +13 a3befb76f9746fc472d8858d5dbb837b +14 bae162b95ebfaf07f6bae0f1714301cc +15 85ff3955808079bc9f32c1ee11b1c74d +16 1deffcd94967ba75d2308fb387256bfa +17 d2025301aa9c16019a71cb640d153373 +18 66313fe26073f9d36e948c7dad87c619 +19 63b7804753d8f99430dd1cb15ab23507 +20 66d1ab69202de69268cd5b2df1bbb144 +21 40a338e4e63618ed262a97f839a4967e +22 4d7c072cfe0dcbf9198a07f295947646 +23 18fdf8314b0265216cba6a2be1fcdecd +24 d0d99f82170bb25cd66f6fb0950be71d +25 6bc32710d9fcafb23883853b48792471 +26 ee5ec38afa1861b94e5bb1186a87ae24 +27 b23aab58e03db377c8d0ddfcbb37e296 +28 e6e5caa847570ac4f0ad1314d0b85325 +29 409039f8aa3c227d0823fd94a47189cd +30 14a9339169d9c29c329281f23007d34b +31 27ed732e0ec2d58251302ff152caa77b +32 1731dff94b7d13b9c30826c3965fed78 +33 8d528f08d3a657046d2fa577f522c094 +34 238938e524284c388b07768d5ae0b067 +35 b0903e4078709783849419e1a3645659 +36 6eaa63cf968ffbfed3bd8191a346cec7 +37 dfeb186ce9dfa55dbb668560adf4a00f +38 9bb85757caca162e92a51c567e1d5a3a +39 332983dab0e652545e8f80fb4f35e9e5 +40 849ddb511bf96cffa0b2c93aa67b2994 +41 b93e8977b7480c16d3062cc23c96e49d +42 b8e9fe4fa359eaaaea2ce1d2c89e9238 +43 04cffed6830eb731f6b79cb65d3df755 +44 f21603b2bbecbf8449cc841031eb7b81 +45 88cd685bf23f521bb0f5c3db460c32db +46 e9c9a4b7bd4d2cc25a2c4dd25c5fd9ea +47 59201f5461aafde39b901720636901c5 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/WPP_F_ericsson_MAIN_2.bit b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/WPP_F_ericsson_MAIN_2.bit new file mode 100644 index 0000000..66ba05d Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/WPP_F_ericsson_MAIN_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/WPP_F_ericsson_MAIN_2.txt b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/WPP_F_ericsson_MAIN_2.txt new file mode 100644 index 0000000..86056d0 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/WPP_F_ericsson_MAIN_2.txt @@ -0,0 +1,23 @@ +WPP_F_ericsson_MAIN_2 + +Conformance point: HM-10.1 + +Picture size: 192x240 + +Frame rate: 25 frames/second + +Specification: +entropy_coding_sync_enabled_flag is set to 1. A CTU size of 64x64 is used to encode the sequence. The picture is 3 CTUs wide. The sequence contains six GOPs, which are all 8 pictures long. The GOPs are encoded with varying numbers of slices and slice segments. Even frames have fixed QP, while the QP in odd frames is set so that abs(QP - QPSlice)>2. + +The first GOP is coded using all Intra CUs, the second GOP is coded with skip disabled. + +Random amounts of slice extension bytes are encoded in each slice header. + + +Functional stage: +Tests that entropy coding is correctly synchronised when a picture is 3 CTUs wide. Tests that the QP predictor is reset to QPslice at the beginning of every CTU row. May be used to test handling of entry points by a parallel decoder. + + +Purpose: +The bitstream checks that a decoder can correctly perform entropy coding synchronisation when a picture is 3 CTUs wide. It checks that a decoder can correctly derive QP predictors when entropy_coding_sync_enabled_flag is set to 1. It can also be used to check that a decoder can correctly handle entry points when slice header extensions are used. + diff --git a/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/riferimento.md5 new file mode 100644 index 0000000..58e8921 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WPP_F_ericsson_MAIN_2/riferimento.md5 @@ -0,0 +1,50 @@ +# WPP_F_ericsson_MAIN_2.yuv 192x240 4:2:0 8 bit, 48 fotogrammi, 3317760 byte +tutto 2aaf16274fe8e799d72fa08a4963850d +0 24767ea62517f2ddfb7ed850c9d9cf10 +1 1453f61102617970b108989e554ba661 +2 0d8823e0e818404356dae064f983681b +3 88a0e15343791599b913e75f9006bc13 +4 50de9b6fca265ed831fbb4aafa7e6f0a +5 2032088cb1c06db6aa1da823dc1a0bbe +6 46db1da6f6309c1ebc7aa65916ee1336 +7 a25187596e3c6651efe7f99b5b075a91 +8 77fb6004e72a26e2334a2edb89294f43 +9 e5d760b7becd091988bceb5de2629213 +10 25cefcf19ff4b517bf8b8d678e33dc26 +11 dfcc51b15a74f83654f70be7ca4f2b25 +12 c3b788dbf78db56b54c1ce27a50687f4 +13 d464ffcb43f606b0e3a4c0d6ca1d0be4 +14 b2b3f5291600e008a9b41e73871d1520 +15 679570dd2acc6fa56700072004bf0925 +16 4e447a15a3e8e34a30ecebc396baea70 +17 b8edf2fe67b835de018c10ff4522ef18 +18 f0634e0395bea3a83a46d365fbd1b7b9 +19 c409609182b1bd7c2c7b160f1018866e +20 dbb60478a7970044fabc08becff8ca74 +21 b45c8d01f70749d8b71c0985dcb0ffb1 +22 ce06c2591510d7d0859b0d3ddeea08e3 +23 edaad037ba14b88c6111f8d65348871d +24 265c46c5915a80d3c707c9634d048968 +25 16c86e7ac464e2029ad0b17dc4d0570d +26 7e89d84b9b88884f4127bd0900046b09 +27 b45f48e0fa11f4e44c6a20937d984da7 +28 c9377a417d529a03097ee539331d9515 +29 8b826aa410e9aeae54f8462c294639cc +30 e93385e4308c731c017d909e87595683 +31 ed785a341f4a1eaa1e8170ad9e15b01b +32 ed5b577a51ffc3f9c78f6af74024b2a6 +33 2bfed754025c3ee03b22d426b1712e35 +34 c5c1f9b5feb32638fdacb4a6e86a1a30 +35 4635ca20d54f951813b967a44d547f02 +36 a51f936659fe585ad956c27c97acf24c +37 8c945e6331bcac6b50de15a8e2e2d206 +38 812efc8549b28f5be36680687b8f96fc +39 08b6cf2637821fd2662d75a5b815ff72 +40 ef3828ed7f5b2ca572668b8f0105abe9 +41 628b8e0a934aafefaeb3fcec17cfbbff +42 41e51de55e670912dd151b9ed900cd32 +43 87c573dbea0bf77e7966b917eb0cd662 +44 bd38f3ea8337283d82555dc350d138c1 +45 71aa84ccb4041563a5125f8eee192ebe +46 af253b59d9c729ee429cf0af3b722b33 +47 dd7f4ab916384f45bbec63fd048f932e diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/WP_A_MAIN10_Toshiba_3.bit b/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/WP_A_MAIN10_Toshiba_3.bit new file mode 100644 index 0000000..6da8b5f Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/WP_A_MAIN10_Toshiba_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/WP_A_MAIN10_Toshiba_3.txt b/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/WP_A_MAIN10_Toshiba_3.txt new file mode 100644 index 0000000..bf4dd2a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/WP_A_MAIN10_Toshiba_3.txt @@ -0,0 +1,4 @@ +conformance: HM-10.0 +resolution: 416x240 +purpose: weighted sample prediction for P slices with plural reference indices +MD5: SEI message in the bitstream \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/riferimento.md5 new file mode 100644 index 0000000..f2efb7d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_A_MAIN10_Toshiba_3/riferimento.md5 @@ -0,0 +1,2 @@ +# WP_A_MAIN10_Toshiba_3.yuv 416x240 4:2:0 10 bit, 256 fotogrammi, 76677120 byte +tutto c48e853010a234786dc87790d053b03a diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/WP_A_Toshiba_3.bit b/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/WP_A_Toshiba_3.bit new file mode 100644 index 0000000..5d89790 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/WP_A_Toshiba_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/WP_A_Toshiba_3.txt b/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/WP_A_Toshiba_3.txt new file mode 100644 index 0000000..bf4dd2a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/WP_A_Toshiba_3.txt @@ -0,0 +1,4 @@ +conformance: HM-10.0 +resolution: 416x240 +purpose: weighted sample prediction for P slices with plural reference indices +MD5: SEI message in the bitstream \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/riferimento.md5 new file mode 100644 index 0000000..3b53920 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_A_Toshiba_3/riferimento.md5 @@ -0,0 +1,2 @@ +# WP_A_Toshiba_3.yuv 416x240 4:2:0 8 bit, 256 fotogrammi, 38338560 byte +tutto 127b99d0c11c930b6f248750b5848a0b diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/WP_B_Toshiba_3.bit b/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/WP_B_Toshiba_3.bit new file mode 100644 index 0000000..9a50dac Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/WP_B_Toshiba_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/WP_B_Toshiba_3.txt b/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/WP_B_Toshiba_3.txt new file mode 100644 index 0000000..08df2fd --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/WP_B_Toshiba_3.txt @@ -0,0 +1,4 @@ +conformance: HM-10.0 +resolution: 416x240 +purpose: weighted sample prediction for P and B slices with plural reference indices. +MD5: SEI message in the bitstream \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/riferimento.md5 new file mode 100644 index 0000000..fcd63ff --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_B_Toshiba_3/riferimento.md5 @@ -0,0 +1,2 @@ +# WP_B_Toshiba_3.yuv 416x240 4:2:0 8 bit, 256 fotogrammi, 38338560 byte +tutto 82d39f8cd09e532b8fa9d35894c96258 diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/WP_MAIN10_B_Toshiba_3.bit b/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/WP_MAIN10_B_Toshiba_3.bit new file mode 100644 index 0000000..9dd7a50 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/WP_MAIN10_B_Toshiba_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/WP_MAIN10_B_Toshiba_3.txt b/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/WP_MAIN10_B_Toshiba_3.txt new file mode 100644 index 0000000..08df2fd --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/WP_MAIN10_B_Toshiba_3.txt @@ -0,0 +1,4 @@ +conformance: HM-10.0 +resolution: 416x240 +purpose: weighted sample prediction for P and B slices with plural reference indices. +MD5: SEI message in the bitstream \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/riferimento.md5 new file mode 100644 index 0000000..d11e211 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/WP_MAIN10_B_Toshiba_3/riferimento.md5 @@ -0,0 +1,2 @@ +# WP_MAIN10_B_Toshiba_3.yuv 416x240 4:2:0 10 bit, 256 fotogrammi, 76677120 byte +tutto ed891c60a17f5cbc64e1848f0ea9cf45 diff --git a/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/cip_B_NEC_3.bit b/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/cip_B_NEC_3.bit new file mode 100644 index 0000000..3a35791 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/cip_B_NEC_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/cip_B_NEC_3.txt b/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/cip_B_NEC_3.txt new file mode 100644 index 0000000..b53f798 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/cip_B_NEC_3.txt @@ -0,0 +1,13 @@ +Bitstream file name: cip_B_NEC_3.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: The bitstream contains an I-picture and 4 P-pictures. Each picture contains only one slice. constrained_intra_pred_flag is equal to 1. + +Functional stage: Test the reference sample substitution process for intra sample prediction. + +Purpose: Check that decoder can correctly decode slices of coded pictures containing intra PUs with unavailable samples for intra prediction. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/riferimento.md5 new file mode 100644 index 0000000..f2c9a7f --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/cip_B_NEC_3/riferimento.md5 @@ -0,0 +1,2 @@ +# cip_B_NEC_3.yuv 416x240 4:2:0 8 bit, 5 fotogrammi, 748800 byte +tutto 1315714c7b3f3237b469259f66d9b7aa diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/ipcm_A_NEC_3.bit b/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/ipcm_A_NEC_3.bit new file mode 100644 index 0000000..07562d9 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/ipcm_A_NEC_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/ipcm_A_NEC_3.txt b/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/ipcm_A_NEC_3.txt new file mode 100644 index 0000000..61f8ad4 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/ipcm_A_NEC_3.txt @@ -0,0 +1,13 @@ +Bitstream file name: ipcm_A_NEC_3.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. pcm_enabled_flag is equal to 1. Both pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 7. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 0, 2 and 0, respectively. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. + +Purpose: Check that decoder can correctly decode the slice of coded frames containing pcm_flags. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/riferimento.md5 new file mode 100644 index 0000000..4859e65 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_A_NEC_3/riferimento.md5 @@ -0,0 +1,2 @@ +# ipcm_A_NEC_3.yuv 416x240 4:2:0 8 bit, 1 fotogrammi, 149760 byte +tutto 8049988c383486e076ea2494edda3831 diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/ipcm_B_NEC_3.bit b/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/ipcm_B_NEC_3.bit new file mode 100644 index 0000000..7a54052 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/ipcm_B_NEC_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/ipcm_B_NEC_3.txt b/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/ipcm_B_NEC_3.txt new file mode 100644 index 0000000..6b3d11f --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/ipcm_B_NEC_3.txt @@ -0,0 +1,13 @@ +Bitstream file name: ipcm_B_NEC_3.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. pcm_enabled_flag is equal to 1. Both pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 5. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 0, 1 and 0, respectively. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. Test parsing of pcm_sample_luma and pcm_sample_chroma data in PCM sample syntax. + +Purpose: Check that decoder can correctly decode the slice of the coded frame containing pcm_flags, and pcm_sample_luma and pcm_sample_chroma data. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/riferimento.md5 new file mode 100644 index 0000000..d17e8ad --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_B_NEC_3/riferimento.md5 @@ -0,0 +1,2 @@ +# ipcm_B_NEC_3.yuv 416x240 4:2:0 8 bit, 1 fotogrammi, 149760 byte +tutto 23a3b7024fd9bc64b946b9961ab0f51e diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/ipcm_C_NEC_3.bit b/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/ipcm_C_NEC_3.bit new file mode 100644 index 0000000..f036eaa Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/ipcm_C_NEC_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/ipcm_C_NEC_3.txt b/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/ipcm_C_NEC_3.txt new file mode 100644 index 0000000..e3d7e01 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/ipcm_C_NEC_3.txt @@ -0,0 +1,13 @@ +Bitstream file name: ipcm_C_NEC_3.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. Both pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 7. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 0, 1 and 1, respectively. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. Test parsing of pcm_sample_luma and pcm_sample_chroma data in PCM sample syntax. Test skipping of loop filtering on samples associated with pcm_flag equal to 1. + +Purpose: Check that decoder can correctly decode the slice of the coded frame containing pcm_flags, and pcm_sample_luma and pcm_sample_chroma data. Check that decoder can skip loop filtering on samples associated with pcm_flag equal to 1. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/riferimento.md5 new file mode 100644 index 0000000..7ae690d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_C_NEC_3/riferimento.md5 @@ -0,0 +1,2 @@ +# ipcm_C_NEC_3.yuv 416x240 4:2:0 8 bit, 1 fotogrammi, 149760 byte +tutto c3e74c399b73a5ab2dbd20523f583464 diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/ipcm_D_NEC_3.bit b/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/ipcm_D_NEC_3.bit new file mode 100644 index 0000000..a8dc761 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/ipcm_D_NEC_3.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/ipcm_D_NEC_3.txt b/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/ipcm_D_NEC_3.txt new file mode 100644 index 0000000..a65da4d --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/ipcm_D_NEC_3.txt @@ -0,0 +1,13 @@ +Bitstream file name: ipcm_D_NEC_3.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. Both pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 7. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 0, 1 and 0, respectively. transquant_bypass_enable_flag is equal to 1. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. Test parsing of pcm_sample_luma and pcm_sample_chroma data in PCM sample syntax. Test skipping of loop filtering on samples associated with both cu_transquant_bypass_flag and pcm_flag equal to 1. + +Purpose: Check that decoder can correctly decode the slice of the coded frame containing pcm_flags, and pcm_sample_luma and pcm_sample_chroma data. Check that decoder can skip loop filtering on samples associated with both cu_transquant_bypass_flag and pcm_flag equal to 1. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/riferimento.md5 new file mode 100644 index 0000000..e257543 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_D_NEC_3/riferimento.md5 @@ -0,0 +1,2 @@ +# ipcm_D_NEC_3.yuv 416x240 4:2:0 8 bit, 1 fotogrammi, 149760 byte +tutto aa64a16240064bc2a90fadf979a62a7b diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/ipcm_E_NEC_2.bit b/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/ipcm_E_NEC_2.bit new file mode 100644 index 0000000..6663d94 Binary files /dev/null and b/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/ipcm_E_NEC_2.bit differ diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/ipcm_E_NEC_2.txt b/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/ipcm_E_NEC_2.txt new file mode 100644 index 0000000..bd5607a --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/ipcm_E_NEC_2.txt @@ -0,0 +1,13 @@ +Bitstream file name: ipcm_E_NEC_2.bit + +Conformance point: HM-12.0 + +Explanation of bitstream features: Contain single coded picture. The coded picture contains only one intra slice. pcm_enabled_flag is equal to 1. pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 are equal to 5 and 7, respectively. log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_coding_block_size, and pcm_loop_filter_disable_flag are equal to 1, 0 and 0, respectively. + +Functional stage: Test parsing of pcm_flags in coding unit syntax. Test parsing of pcm_sample_luma and pcm_sample_chroma data in PCM sample syntax with different bit depth precisions. + +Purpose: Check that decoder can correctly decode the slice of the coded frame containing pcm_flags, and pcm_sample_luma and pcm_sample_chroma data with different pcm_sample_bit_depth_luma_minus1 and pcm_sample_bit_depth_chroma_minus1 values. + +Picture size: 416x240 (Minimum level of this bitstream is 2.0.) + +Frame rate: 30fps diff --git a/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/riferimento.md5 b/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/riferimento.md5 new file mode 100644 index 0000000..5980451 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/Conformita/ipcm_E_NEC_2/riferimento.md5 @@ -0,0 +1,2 @@ +# ipcm_E_NEC_2.yuv 416x240 4:2:0 8 bit, 1 fotogrammi, 149760 byte +tutto e1cd7a16d3f6a342855044ccba3e41f5 diff --git a/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs b/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs new file mode 100644 index 0000000..12e0f99 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265ConformanceStream.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text.RegularExpressions; + +namespace Febe.Tests.Codecs.H265; + +/// +/// One stream of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there): the bitstream as +/// published, the readme of its authors and riferimento.md5, written once from the official reconstruction. +/// +/// +/// riferimento.md5 has a header line «# name WxH chroma bits bit, N fotogrammi, B byte» (WxH is «variabile(…)» when +/// the stream changes size), the line «tutto md5» with the MD5 of the whole official YUV file, and one «i md5» line per +/// output frame only for the streams whose zip shipped the YUV file itself. Frames are laid out as in that file: planes +/// Y, Cb, Cr cropped to the conformance window, one byte per sample up to 8 bits, otherwise two bytes little endian for +/// every plane. +/// +internal sealed partial class H265ConformanceStream +{ + private H265ConformanceStream(string name, string folder) + { + Name = name; + Folder = folder; + } + + public static string Root => Path.Combine(AppContext.BaseDirectory, "Media", "H265", "Conformita"); + + public string Name { get; } + + public string Folder { get; } + + /// The Annex B bitstream as published (.bit or .bin). + public string BitstreamPath { get; private set; } = ""; + + /// The readme of the stream's authors, as published. + public string ReadmePath { get; private set; } = ""; + + /// Format range extensions (4:0:0, 4:2:2, 4:4:4, more than 10 bits, RExt tools). + public bool IsRangeExtension => Name.Contains("_RExt_", StringComparison.Ordinal); + + /// Output size, or null when the stream changes size (then only lists them). + public (int Width, int Height)? Size { get; private set; } + + public IReadOnlyList<(int Width, int Height)> Sizes { get; private set; } = []; + + /// "4:0:0", "4:2:0", "4:2:2" or "4:4:4". + public string Chroma { get; private set; } = ""; + + public int LumaBitDepth { get; private set; } + + public int ChromaBitDepth { get; private set; } + + public int FrameCount { get; private set; } + + public long ByteCount { get; private set; } + + /// MD5 of the whole official reconstruction. + public string TotalMd5 { get; private set; } = ""; + + /// MD5 of each output frame, in output order; empty when the zip did not ship the YUV file. + public IReadOnlyList FrameMd5 { get; private set; } = []; + + public static IEnumerable Names() => + Directory.EnumerateDirectories(Root).Select(Path.GetFileName).OfType().Order(StringComparer.Ordinal); + + public static H265ConformanceStream Load(string name) + { + var folder = Path.Combine(Root, name); + var stream = new H265ConformanceStream(name, folder); + var files = Directory.GetFiles(folder); + stream.BitstreamPath = files.Single(f => Path.GetExtension(f) is ".bit" or ".bin"); + stream.ReadmePath = files.Single(f => Path.GetExtension(f) == ".txt"); + stream.ReadReference(Path.Combine(folder, "riferimento.md5")); + return stream; + } + + /// Bytes of one frame of the given size, as laid out in the official YUV file. + public long FrameBytes(int width, int height) + { + long chroma = Chroma switch + { + "4:0:0" => 0, + "4:2:0" => 2L * ((width + 1) / 2) * ((height + 1) / 2), + "4:2:2" => 2L * ((width + 1) / 2) * height, + _ => 2L * width * height, + }; + return ((long)width * height + chroma) * (Math.Max(LumaBitDepth, ChromaBitDepth) > 8 ? 2 : 1); + } + + /// + /// Compares decoded frames, in output order and in the layout of the YUV file, with the reference: frame by frame + /// when the reference has them, then the MD5 of all of them together. Returns null when they match. + /// + public string? Compare(IReadOnlyList frames) + { + for (var i = 0; i < Math.Min(frames.Count, FrameMd5.Count); i++) + { + if (Convert.ToHexStringLower(MD5.HashData(frames[i])) != FrameMd5[i]) + { + return $"{Name}: il fotogramma {i} è diverso dal riferimento."; + } + } + + if (frames.Count != FrameCount) + { + return $"{Name}: {frames.Count} fotogrammi invece di {FrameCount}."; + } + + using var all = IncrementalHash.CreateHash(HashAlgorithmName.MD5); + foreach (var frame in frames) + { + all.AppendData(frame); + } + + return Convert.ToHexStringLower(all.GetHashAndReset()) == TotalMd5 ? null : $"{Name}: l'MD5 di tutti i fotogrammi è diverso dal riferimento."; + } + + private void ReadReference(string path) + { + var lines = File.ReadAllLines(path); + var header = HeaderPattern().Match(lines[0]); + if (!header.Success) + { + throw new InvalidDataException($"{Name}: intestazione di riferimento.md5 non riconosciuta: {lines[0]}"); + } + + var sizes = SizePattern().Matches(header.Groups["size"].Value) + .Select(m => (int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture), int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture))) + .ToList(); + Sizes = sizes; + Size = header.Groups["size"].Value.StartsWith("variabile(", StringComparison.Ordinal) ? null : sizes.Single(); + Chroma = header.Groups["chroma"].Value; + LumaBitDepth = int.Parse(header.Groups["luma"].Value, CultureInfo.InvariantCulture); + ChromaBitDepth = header.Groups["cbits"].Success ? int.Parse(header.Groups["cbits"].Value, CultureInfo.InvariantCulture) : LumaBitDepth; + FrameCount = int.Parse(header.Groups["frames"].Value, CultureInfo.InvariantCulture); + ByteCount = long.Parse(header.Groups["bytes"].Value, CultureInfo.InvariantCulture); + + var frames = new List(); + foreach (var line in lines.Skip(1)) + { + var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length != 2 || !Md5Pattern().IsMatch(parts[1])) + { + throw new InvalidDataException($"{Name}: riga di riferimento.md5 non riconosciuta: {line}"); + } + + if (parts[0] == "tutto") + { + TotalMd5 = parts[1]; + } + else if (int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var index) && index == frames.Count) + { + frames.Add(parts[1]); + } + else + { + throw new InvalidDataException($"{Name}: riferimento.md5 fuori ordine: {line}"); + } + } + + FrameMd5 = frames; + } + + [GeneratedRegex(@"^# \S+\.yuv (?\d+x\d+|variabile\((\d+x\d+,)*\d+x\d+\)) (?4:[024]:[024]) (?\d+)(/(?\d+))? bit, (?\d+) fotogrammi, (?\d+) byte$")] + private static partial Regex HeaderPattern(); + + [GeneratedRegex(@"(\d+)x(\d+)")] + private static partial Regex SizePattern(); + + [GeneratedRegex("^[0-9a-f]{32}$")] + private static partial Regex Md5Pattern(); +} diff --git a/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs b/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs new file mode 100644 index 0000000..89d3bab --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265ConformanceTests.cs @@ -0,0 +1,151 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.H265; + +namespace Febe.Tests.Codecs.H265; + +/// +/// The streams of the ITU-T H.265.1 conformance set in Media/H265/Conformita (see LEGGIMI.md there). Every stream, Main, +/// Main 10, Main Still Picture and the format range extensions (4:0:0, 4:2:2, 4:4:4, 12 bits, RExt tools), must give +/// exactly the frames of its official YUV (the MD5 of each frame where the YUV came with the stream, of the whole YUV for +/// all). +/// +[TestClass] +public sealed class H265ConformanceTests +{ + public static IEnumerable Streams => H265ConformanceStream.Names().Select(n => new object[] { n }); + + [TestMethod] + [DynamicData(nameof(Streams))] + public void FramesMatchTheReference(string name) + { + var stream = H265ConformanceStream.Load(name); + var frames = new List(); + var decoder = new H265Decoder(); + decoder.FrameOutput += frame => frames.Add(frame.ToYuvFile()); + decoder.DecodeAnnexB(File.ReadAllBytes(stream.BitstreamPath)); + decoder.Flush(); + Assert.IsNull(stream.Compare(frames)); + } + + [TestMethod] + public void TheSetIsTheOneTheReadmeDescribes() + { + var names = H265ConformanceStream.Names().ToList(); + Assert.HasCount(146, names); + Assert.AreEqual(10, names.Count(n => H265ConformanceStream.Load(n).IsRangeExtension)); + var readme = File.ReadAllText(Path.Combine(H265ConformanceStream.Root, "LEGGIMI.md")); + var missing = names.Where(n => !readme.Contains($"`{n}`", StringComparison.Ordinal)).ToList(); + Assert.IsEmpty(missing, $"LEGGIMI.md non descrive: {string.Join(", ", missing)}"); + Assert.AreEqual(15, names.Count(n => H265ConformanceStream.Load(n).FrameMd5.Count > 0), "flussi con il YUV ufficiale"); + } + + [TestMethod] + [DynamicData(nameof(Streams))] + public void TheReferenceIsComplete(string name) + { + var stream = H265ConformanceStream.Load(name); + Assert.IsGreaterThan(0, stream.FrameCount); + Assert.AreEqual(32, stream.TotalMd5.Length, $"{name}: manca la riga «tutto»"); + Assert.IsTrue(stream.FrameMd5.Count == 0 || stream.FrameMd5.Count == stream.FrameCount, $"{name}: righe per fotogramma"); + Assert.IsTrue(stream.LumaBitDepth is >= 8 and <= 12 && stream.ChromaBitDepth is >= 8 and <= 12, $"{name}: profondità"); + if (stream.Size is var (width, height)) + { + Assert.AreEqual(stream.FrameCount * stream.FrameBytes(width, height), stream.ByteCount, $"{name}: byte del YUV"); + } + else + { + // A stream that changes size: at least the bytes are a sum of frames of the sizes it lists. + Assert.IsGreaterThan(1, stream.Sizes.Count); + Assert.IsTrue(stream.Sizes.Any(s => stream.ByteCount >= stream.FrameBytes(s.Width, s.Height)), $"{name}: byte del YUV"); + } + + if (!stream.IsRangeExtension) + { + Assert.AreEqual("4:2:0", stream.Chroma, $"{name}: i profili Main, Main 10 e Main Still Picture sono 4:2:0"); + Assert.IsLessThanOrEqualTo(10, Math.Max(stream.LumaBitDepth, stream.ChromaBitDepth), name); + } + + var data = File.ReadAllBytes(stream.BitstreamPath); + CollectionAssert.AreEqual(new byte[] { 0, 0, 1 }, data.AsSpan(data[2] == 1 ? 0 : 1, 3).ToArray(), $"{name}: non comincia con un codice d'inizio (Annex B)"); + } + + [TestMethod] + [DynamicData(nameof(Streams))] + public void EveryDecodedPictureHasOneHashOrNoneHas(string name) + { + // Counted independently from the bitstream: either no picture carries a decoded picture hash, or every coded + // picture carries exactly one, with one value per colour component. NUT_A is the exception: its two RASL + // pictures after a BLA, which a decoder skips, have none. + var stream = H265ConformanceStream.Load(name); + var data = File.ReadAllBytes(stream.BitstreamPath); + var hashes = H265PictureHashes.Read(data); + if (hashes.Count == 0) + { + return; + } + + var pictures = CountPictures(data); + var expected = name == "NUT_A_ericsson_5" ? pictures - 2 : pictures; + Assert.HasCount(expected, hashes, $"{name}: {pictures} immagini"); + Assert.AreEqual(hashes.Count, hashes.Select(h => h.Picture).Distinct().Count(), name); + var planes = stream.Chroma == "4:0:0" ? 1 : 3; + Assert.IsTrue(hashes.All(h => h.Planes.Length == planes), $"{name}: componenti per hash"); + var type = name is "HRD_A_Fujitsu_3" or "PICSIZE_C_Bossen_1" or "PICSIZE_D_Bossen_1" ? H265HashType.Checksum : H265HashType.Md5; + Assert.IsTrue(hashes.All(h => h.Type == type), $"{name}: tipo di hash"); + } + + [TestMethod] + public void PictureHashesFollowTheDefinition() + { + // 3×2 samples in a stride of 4; the fourth column must be left out. + ushort[] samples = [1, 2, 3, 999, 4, 5, 6, 999]; + CollectionAssert.AreEqual(MD5.HashData(new byte[] { 1, 2, 3, 4, 5, 6 }), H265PictureHashes.Compute(H265HashType.Md5, samples, 3, 2, 4, 8)); + ushort[] wide = [0x3FF, 0x100]; + CollectionAssert.AreEqual(MD5.HashData(new byte[] { 0xFF, 0x03, 0x00, 0x01 }), H265PictureHashes.Compute(H265HashType.Md5, wide, 2, 1, 2, 10)); + + // Checksum (D.3.19): every sample xored with (x & 0xFF) ^ (y & 0xFF) ^ (x >> 8) ^ (y >> 8), high byte too above 8 bits. + var expected = (1 ^ 0) + (2 ^ 1) + (3 ^ 2) + (4 ^ 1) + (5 ^ 0) + (6 ^ 3); + CollectionAssert.AreEqual(new byte[] { 0, 0, 0, (byte)expected }, H265PictureHashes.Compute(H265HashType.Checksum, samples, 3, 2, 4, 8)); + var expectedWide = (0xFF ^ 0) + (0x03 ^ 0) + (0x00 ^ 1) + (0x01 ^ 1); + CollectionAssert.AreEqual(new byte[] { 0, 0, (byte)(expectedWide >> 8), (byte)expectedWide }, H265PictureHashes.Compute(H265HashType.Checksum, wide, 2, 1, 2, 10)); + + // CRC (D.3.19): bit by bit from 0xFFFF with the polynomial 0x1021 over the bytes and two zero bytes, which is + // CRC-16/AUG-CCITT: 0x1D0F over no bytes, 0xE5CC over "123456789" (the check value of that CRC). + CollectionAssert.AreEqual(new byte[] { 0x1D, 0x0F }, H265PictureHashes.Compute(H265HashType.Crc, ReadOnlySpan.Empty, 0, 0, 0, 8)); + ushort[] digits = [.. "123456789".Select(c => (ushort)c)]; + CollectionAssert.AreEqual(new byte[] { 0xE5, 0xCC }, H265PictureHashes.Compute(H265HashType.Crc, digits, 9, 1, 9, 8)); + } + + [TestMethod] + public void AStreamOfOnePictureHasItsHash() + { + // IPRED_B (Main Still Picture, one 1920×1080 picture): one MD5 per component, decoding index 0. + var data = File.ReadAllBytes(H265ConformanceStream.Load("IPRED_B_Nokia_3").BitstreamPath); + var hash = H265PictureHashes.Read(data).Single(); + Assert.AreEqual(0, hash.Picture); + Assert.AreEqual(H265HashType.Md5, hash.Type); + Assert.IsTrue(hash.Planes.All(p => p.Length == 16)); + } + + /// Coded pictures of layer 0: VCL NAL units whose slice segment header starts with first_slice_segment_in_pic_flag = 1. + private static int CountPictures(byte[] data) + { + var count = 0; + for (var i = 0; i + 5 < data.Length; i++) + { + if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) + { + var type = (data[i + 3] >> 1) & 63; + var layer = ((data[i + 3] & 1) << 5) | (data[i + 4] >> 3); + if (type < 32 && layer == 0 && (data[i + 5] & 0x80) != 0) + { + count++; + } + + i += 2; + } + } + + return count; + } +} diff --git a/tests/Febe.Tests/Media/H265/H265DecoderTests.cs b/tests/Febe.Tests/Media/H265/H265DecoderTests.cs new file mode 100644 index 0000000..276866e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265DecoderTests.cs @@ -0,0 +1,277 @@ +using Febe.Core.Codecs.H264; +using Febe.Core.Codecs.H265; +using Pps = Febe.Core.Codecs.H265.Pps; +using Sps = Febe.Core.Codecs.H265.Sps; + +namespace Febe.Tests.Codecs.H265; + +/// +/// The HEVC decoder beyond the whole frames of : every decoded picture of every stream +/// of the set, in decoding order and before cropping, against the hash its encoder wrote in the bitstream (so a wrong +/// picture is found where it first goes wrong, also when it is never output); length-prefixed samples; damaged streams. +/// +[TestClass] +public sealed class H265DecoderTests +{ + public static IEnumerable AllStreams => H265ConformanceStream.Names().Select(n => new object[] { n }); + + [TestMethod] + [DynamicData(nameof(AllStreams))] + public void EveryPictureMatchesItsHash(string name) + { + var stream = H265ConformanceStream.Load(name); + var data = File.ReadAllBytes(stream.BitstreamPath); + var hashes = H265PictureHashes.Read(data).ToDictionary(h => h.Picture); + + var decoder = new H265Decoder(); + int decoded = 0, hashed = 0; + var wrong = new List(); + decoder.PictureDecoded += picture => + { + decoded++; + if (!hashes.TryGetValue((int)picture.DecodeIndex, out var hash)) + { + return; + } + + hashed++; + for (var c = 0; c < hash.Planes.Length; c++) + { + var width = c == 0 ? picture.Width : picture.ChromaWidth; + var height = c == 0 ? picture.Height : picture.ChromaHeight; + var actual = H265PictureHashes.Compute(hash.Type, picture.Planes[c], width, height, width, picture.BitDepth(c)); + if (!actual.AsSpan().SequenceEqual(hash.Planes[c])) + { + wrong.Add($"immagine {picture.DecodeIndex} (POC {picture.Poc}), componente {c}"); + break; + } + } + }; + + var frames = 0; + decoder.FrameOutput += _ => frames++; + decoder.DecodeAnnexB(data); + Assert.IsEmpty(wrong, $"{name}: {string.Join("; ", wrong)}"); + if (hashes.Count > 0) + { + // Every decoded picture has its hash; the hashes left are those of RASL pictures that are skipped. + Assert.AreEqual(decoded, hashed, $"{name}: immagini decodificate senza hash"); + Assert.IsLessThanOrEqualTo(decoder.PicturesDecoded - decoded, hashes.Count - hashed, $"{name}: hash senza immagine"); + } + + Assert.AreEqual(stream.FrameCount, frames, $"{name}: fotogrammi in uscita"); + } + + [TestMethod] + public void TheHashesCoverInterPictures() + { + // The check above is worth something for inter prediction only if the hashes cover P and B pictures: count + // them in the streams that carry hashes, decoding a few streams whose names say they are about inter tools. + string[] names = ["MERGE_A_TI_3", "TMVP_A_MS_3", "WP_A_Toshiba_3", "WP_B_Toshiba_3", "PMERGE_A_TI_3", "MVCLIP_A_qualcomm_3", "MVEDGE_A_qualcomm_3", "SAO_A_MediaTek_4", "RAP_B_Bossen_2"]; + var none = new List(); + foreach (var name in names) + { + var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath); + var hashes = H265PictureHashes.Read(data).Select(h => h.Picture).ToHashSet(); + var inter = 0; + var decoder = new H265Decoder(); + decoder.PictureDecoded += picture => inter += !picture.IntraOnly && hashes.Contains((int)picture.DecodeIndex) ? 1 : 0; + decoder.DecodeAnnexB(data); + if (inter == 0) + { + none.Add(name); + } + } + + Assert.IsEmpty(none, $"nessuna immagine inter con hash: {string.Join(", ", none)}"); + } + + [TestMethod] + public void TheSetExercisesEveryTool() + { + // The hash checks are worth something for a tool only if some stream of the set turns it on: read the parameter + // sets of every stream and look for each tool the decoder claims to handle. + var seen = new HashSet(); + byte[]? buffer = null; + foreach (var name in H265ConformanceStream.Names()) + { + var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath); + var position = 0; + while (NalUnits.NextAnnexB(data, ref position, out var unit)) + { + var nal = data.AsSpan(unit); + if (nal.Length < 3 || (nal[0] & 1) != 0 || (nal[1] >> 3) != 0) + { + continue; + } + + var type = (nal[0] >> 1) & 63; + if (type == 33) + { + var s = Sps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader()); + Mark(seen, "liste di scala", s.ScalingListEnabled); + Mark(seen, "lungo termine", s.LongTermRefsPresent); + Mark(seen, "PCM", s.PcmEnabled); + Mark(seen, "4:0:0", s.ChromaArrayType == 0); + Mark(seen, "4:2:2", s.ChromaArrayType == 2); + Mark(seen, "4:4:4", s.ChromaArrayType == 3); + Mark(seen, "12 bit", s.BitDepthY == 12); + Mark(seen, "rotazione", s.TransformSkipRotationEnabled); + Mark(seen, "contesto del transform skip", s.TransformSkipContextEnabled); + Mark(seen, "RDPCM implicito", s.ImplicitRdpcmEnabled); + Mark(seen, "smoothing intra spento", s.IntraSmoothingDisabled); + Mark(seen, "Rice persistente", s.PersistentRiceAdaptationEnabled); + Mark(seen, "RDPCM esplicito", s.ExplicitRdpcmEnabled); + } + else if (type == 34) + { + var p = Pps.Parse(H265NalUnit.Unescape(nal, ref buffer).Reader()); + Mark(seen, "tile", p.TilesEnabled); + Mark(seen, "tile non uniformi", p.TilesEnabled && !p.UniformSpacing); + Mark(seen, "deblocking non attraverso i tile", p.TilesEnabled && !p.LoopFilterAcrossTilesEnabled); + Mark(seen, "WPP", p.EntropyCodingSyncEnabled); + Mark(seen, "segmenti dipendenti", p.DependentSliceSegmentsEnabled); + Mark(seen, "liste di scala nel PPS", p.ScalingList is not null); + Mark(seen, "predizione fra componenti", p.CrossComponentPredictionEnabled); + Mark(seen, "chroma_qp_offset_list", p.ChromaQpOffsetListEnabled); + } + } + } + + string[] tools = + [ + "liste di scala", "liste di scala nel PPS", "lungo termine", "PCM", "tile", "tile non uniformi", + "deblocking non attraverso i tile", "WPP", "segmenti dipendenti", "4:0:0", "4:2:2", "4:4:4", "12 bit", + "rotazione", "contesto del transform skip", "RDPCM implicito", "smoothing intra spento", "Rice persistente", + "predizione fra componenti", "chroma_qp_offset_list", "RDPCM esplicito", + ]; + var missing = tools.Where(t => !seen.Contains(t)).ToList(); + Assert.IsEmpty(missing, $"strumenti che nessun flusso usa: {string.Join(", ", missing)}"); + } + + private static void Mark(HashSet seen, string tool, bool used) + { + if (used) + { + seen.Add(tool); + } + } + + [TestMethod] + [DataRow("IPRED_A_docomo_2")] + [DataRow("IPRED_C_Mitsubishi_3")] + [DataRow("ipcm_E_NEC_2")] + public void LengthPrefixedSamplesGiveTheSameFrames(string name) + { + // The stream as an MP4 would hold it: VPS, SPS and PPS in an hvcC record, each access unit a sample of NAL + // units with a 4-byte length. + var stream = H265ConformanceStream.Load(name); + var data = File.ReadAllBytes(stream.BitstreamPath); + var parameterSets = new List(); + var samples = new List>(); + var position = 0; + while (NalUnits.NextAnnexB(data, ref position, out var range)) + { + var nal = data[range]; + var type = (nal[0] >> 1) & 63; + if (type is >= 32 and <= 34 && samples.Count == 0) + { + parameterSets.Add(nal); + } + else + { + if (samples.Count == 0 || (type < 32 && (nal[2] & 0x80) != 0 && samples[^1].Any(n => ((n[0] >> 1) & 63) < 32))) + { + samples.Add([]); + } + + samples[^1].Add(nal); + } + } + + var hvcC = new List(new byte[21]) { 0xFC | 3, 1, 0x20, (byte)(parameterSets.Count >> 8), (byte)parameterSets.Count }; + hvcC[0] = 1; + foreach (var set in parameterSets) + { + hvcC.AddRange([(byte)(set.Length >> 8), (byte)set.Length, .. set]); + } + + var frames = new List(); + var decoder = new H265Decoder(); + decoder.FrameOutput += frame => frames.Add(frame.ToYuvFile()); + Assert.AreEqual(4, decoder.ConfigureHvcC([.. hvcC])); + foreach (var sample in samples) + { + var bytes = new List(); + foreach (var nal in sample) + { + bytes.AddRange([(byte)(nal.Length >> 24), (byte)(nal.Length >> 16), (byte)(nal.Length >> 8), (byte)nal.Length, .. nal]); + } + + decoder.DecodeSample([.. bytes], 4); + } + + decoder.Flush(); + Assert.IsNull(stream.Compare(frames)); + } + + [TestMethod] + [DataRow("IPRED_A_docomo_2", 2701)] + [DataRow("IPRED_C_Mitsubishi_3", 2702)] + [DataRow("ipcm_A_NEC_3", 2703)] + [DataRow("ipcm_E_NEC_2", 2704)] + [DataRow("SAO_H_Parabola_1", 2705)] + [DataRow("MAXBINS_A_TI_5", 2706)] + [DataRow("CAINIT_E_SHARP_3", 2707)] + [DataRow("WPP_C_ericsson_MAIN_2", 2708)] + [DataRow("TILES_B_Cisco_1", 2709)] + [DataRow("DSLICE_A_HHI_5", 2710)] + [DataRow("MVEDGE_A_qualcomm_3", 2711)] + [DataRow("WP_B_Toshiba_3", 2712)] + [DataRow("TMVP_A_MS_3", 2713)] + [DataRow("PMERGE_B_TI_3", 2714)] + public void DamagedStreamsGiveFramesOrAnH265Exception(string name, int seed) + { + var data = File.ReadAllBytes(H265ConformanceStream.Load(name).BitstreamPath); + if (data.Length > 400_000) + { + data = data[..400_000]; + } + + var random = new Random(seed); + for (var trial = 0; trial < 12; trial++) + { + var copy = (byte[])data.Clone(); + var changes = 1 + random.Next(20); + for (var k = 0; k < changes; k++) + { + var p = random.Next(copy.Length); + copy[p] = random.Next(3) switch + { + 0 => (byte)random.Next(256), + 1 => (byte)(copy[p] ^ (1 << random.Next(8))), + _ => 0xFF, + }; + } + + if (random.Next(4) == 0) + { + copy = copy[..random.Next(copy.Length)]; + } + + try + { + var decoder = new H265Decoder(); + decoder.FrameOutput += _ => { }; + decoder.DecodeAnnexB(copy); + } + catch (H265Exception) + { + } + catch (Exception ex) + { + Assert.Fail($"{name}, variante {trial} del seme {seed}: {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}"); + } + } + } +} diff --git a/tests/Febe.Tests/Media/H265/H265PictureHashes.cs b/tests/Febe.Tests/Media/H265/H265PictureHashes.cs new file mode 100644 index 0000000..769622e --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265PictureHashes.cs @@ -0,0 +1,244 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; + +namespace Febe.Tests.Codecs.H265; + +/// hash_type of the decoded picture hash SEI message (ITU-T H.265, D.2.20 and D.3.19). +internal enum H265HashType +{ + Md5 = 0, + Crc = 1, + Checksum = 2, +} + +/// +/// The decoded picture hash of one coded picture: one value per colour component (one for 4:0:0, otherwise three), +/// computed by the encoder over the whole decoded sample arrays (pic_width_in_luma_samples × pic_height_in_luma_samples, +/// before the conformance window crops them). +/// +/// Index of the coded picture in decoding order, counting every picture of the bitstream (also +/// the RASL pictures a decoder skips). +internal sealed record H265PictureHash(int Picture, H265HashType Type, byte[][] Planes); + +/// +/// Reads the decoded picture hash SEI messages of an Annex B bitstream, independently of any decoder, so that a decoded +/// picture can be checked against what its encoder computed (most conformance streams carry an MD5 per picture, also +/// when their zip has no reconstructed YUV file). Written from the text of ITU-T H.265 (7.3.1, 7.3.5, D.2.20, D.3.19). +/// +internal static class H265PictureHashes +{ + private const int SuffixSei = 40; + + public static List Read(ReadOnlySpan annexB) + { + var hashes = new List(); + var picture = -1; + foreach (var (start, length) in NalUnits(annexB)) + { + var nal = annexB.Slice(start, length); + if (nal.Length < 3 || (nal[0] & 0x80) != 0) + { + continue; + } + + var type = (nal[0] >> 1) & 63; + var layer = ((nal[0] & 1) << 5) | (nal[1] >> 3); + if (layer != 0) + { + continue; + } + + if (type < 32) + { + // first_slice_segment_in_pic_flag is the first bit of every slice segment header; the byte after the + // two-byte NAL header can never be an emulation prevention byte. + if ((nal[2] & 0x80) != 0) + { + picture++; + } + } + else if (type == SuffixSei && picture >= 0) + { + ReadSei(Unescape(nal[2..]), picture, hashes); + } + } + + return hashes; + } + + /// + /// The hash of one decoded sample array as D.3.19 defines it: samples in raster order, one byte each up to 8 bits, + /// otherwise two bytes with the low one first. + /// + public static byte[] Compute(H265HashType type, ReadOnlySpan samples, int width, int height, int stride, int bitDepth) + { + var bytesPerSample = bitDepth > 8 ? 2 : 1; + if (type == H265HashType.Checksum) + { + uint sum = 0; + for (var y = 0; y < height; y++) + { + var row = samples.Slice(y * stride, width); + for (var x = 0; x < width; x++) + { + var mask = (uint)((x & 0xFF) ^ (y & 0xFF) ^ (x >> 8) ^ (y >> 8)); + sum += (row[x] & 0xFFu) ^ mask; + if (bytesPerSample == 2) + { + sum += (uint)(row[x] >> 8) ^ mask; + } + } + } + + var result = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(result, sum); + return result; + } + + // MD5 and CRC both read pictureData, the samples as bytes; the CRC needs two zero bytes after them. + var data = new byte[width * height * bytesPerSample + 2]; + var at = 0; + for (var y = 0; y < height; y++) + { + var row = samples.Slice(y * stride, width); + for (var x = 0; x < width; x++) + { + data[at++] = (byte)row[x]; + if (bytesPerSample == 2) + { + data[at++] = (byte)(row[x] >> 8); + } + } + } + + if (type == H265HashType.Md5) + { + return MD5.HashData(data.AsSpan(0, at)); + } + + uint crc = 0xFFFF; + for (var bit = 0; bit < (at + 2) * 8; bit++) + { + var msb = (crc >> 15) & 1; + var value = (uint)(data[bit >> 3] >> (7 - (bit & 7))) & 1; + crc = (((crc << 1) + value) & 0xFFFF) ^ (msb * 0x1021); + } + + return [(byte)(crc >> 8), (byte)crc]; + } + + private static void ReadSei(byte[] rbsp, int picture, List hashes) + { + var at = 0; + // sei_message() repeats while more_rbsp_data(): stop at the byte that holds only the stop bit. + while (at < rbsp.Length && !(at == rbsp.Length - 1 && rbsp[at] == 0x80)) + { + var payloadType = ReadFfCoded(rbsp, ref at); + var payloadSize = ReadFfCoded(rbsp, ref at); + if (payloadType < 0 || payloadSize < 0 || at + payloadSize > rbsp.Length) + { + throw new InvalidDataException("Messaggio SEI troncato."); + } + + if (payloadType == 132 && payloadSize >= 1) + { + var type = (H265HashType)rbsp[at]; + var size = type switch { H265HashType.Md5 => 16, H265HashType.Crc => 2, H265HashType.Checksum => 4, _ => 0 }; + if (size == 0 || (payloadSize - 1) % size != 0 || (payloadSize - 1) / size is not (1 or 3)) + { + throw new InvalidDataException($"Hash dell'immagine non valido: tipo {(int)type}, {payloadSize} byte."); + } + + var planes = new byte[(payloadSize - 1) / size][]; + for (var c = 0; c < planes.Length; c++) + { + planes[c] = rbsp.AsSpan(at + 1 + c * size, size).ToArray(); + } + + if (hashes.Count > 0 && hashes[^1].Picture == picture) + { + throw new InvalidDataException($"Due hash per l'immagine {picture}."); + } + + hashes.Add(new H265PictureHash(picture, type, planes)); + } + + at += payloadSize; + } + } + + private static int ReadFfCoded(byte[] rbsp, ref int at) + { + var value = 0; + while (at < rbsp.Length && rbsp[at] == 0xFF) + { + value += 255; + at++; + } + + return at < rbsp.Length ? value + rbsp[at++] : -1; + } + + /// Removes the emulation prevention bytes (0x03 after two zero bytes). + private static byte[] Unescape(ReadOnlySpan payload) + { + var result = new byte[payload.Length]; + var length = 0; + var zeros = 0; + foreach (var b in payload) + { + if (zeros >= 2 && b == 3) + { + zeros = 0; + continue; + } + + result[length++] = b; + zeros = b == 0 ? zeros + 1 : 0; + } + + return result[..length]; + } + + /// Start and length of each NAL unit after a 0x000001 start code, trailing zero bytes excluded. + private static List<(int Start, int Length)> NalUnits(ReadOnlySpan data) + { + var units = new List<(int, int)>(); + var start = -1; + var i = 0; + while (i + 2 < data.Length) + { + var next = data[i..].IndexOf((ReadOnlySpan)[0, 0, 1]); + if (next < 0) + { + break; + } + + next += i; + if (start >= 0) + { + units.Add((start, TrimZeros(data, start, next))); + } + + start = next + 3; + i = start; + } + + if (start >= 0 && start < data.Length) + { + units.Add((start, TrimZeros(data, start, data.Length))); + } + + return units; + } + + private static int TrimZeros(ReadOnlySpan data, int start, int end) + { + while (end > start && data[end - 1] == 0) + { + end--; + } + + return end - start; + } +} 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/H265/H265TablesTests.cs b/tests/Febe.Tests/Media/H265/H265TablesTests.cs new file mode 100644 index 0000000..6566843 --- /dev/null +++ b/tests/Febe.Tests/Media/H265/H265TablesTests.cs @@ -0,0 +1,190 @@ +using Febe.Core.Codecs.H265; + +namespace Febe.Tests.Codecs.H265; + +/// The tables of the HEVC decoder against values read in ITU-T H.265, independently of how the code builds them. +[TestClass] +public sealed class H265TablesTests +{ + [TestMethod] + public void TheDctMatrixHasTheRowsOfTheStandard() + { + // §8.6.4.2: row 0 is 64 everywhere; the odd rows of the 32-, 16-, 8- and 4-point matrices start as listed. + short[] row1 = [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4]; + short[] row2 = [90, 87, 80, 70, 57, 43, 25, 9]; + short[] row4 = [89, 75, 50, 18]; + short[] row8 = [83, 36]; + for (var n = 0; n < 32; n++) + { + Assert.AreEqual(64, H265Tables.DctMatrix[n]); + } + + CollectionAssert.AreEqual(row1, H265Tables.DctMatrix.AsSpan(32, 16).ToArray()); + CollectionAssert.AreEqual(row2, H265Tables.DctMatrix.AsSpan(2 * 32, 8).ToArray()); + CollectionAssert.AreEqual(row4, H265Tables.DctMatrix.AsSpan(4 * 32, 4).ToArray()); + CollectionAssert.AreEqual(row8, H265Tables.DctMatrix.AsSpan(8 * 32, 2).ToArray()); + + // The 4-point matrix: rows 0, 8, 16 and 24, first four columns. + short[] four = [64, 64, 64, 64, 83, 36, -36, -83, 64, -64, -64, 64, 36, -83, 83, -36]; + for (var k = 0; k < 4; k++) + { + CollectionAssert.AreEqual(four.AsSpan(k * 4, 4).ToArray(), H265Tables.DctMatrix.AsSpan(k * 8 * 32, 4).ToArray(), $"riga {k}"); + } + + // Even rows are symmetric, odd rows antisymmetric. + for (var k = 0; k < 32; k++) + { + for (var n = 0; n < 16; n++) + { + var sign = (k & 1) == 0 ? 1 : -1; + Assert.AreEqual(H265Tables.DctMatrix[(k * 32) + n], sign * H265Tables.DctMatrix[(k * 32) + 31 - n], $"k {k}, n {n}"); + } + } + } + + [TestMethod] + public void TheDstAndTheSmallTablesAreThoseOfTheStandard() + { + CollectionAssert.AreEqual(new short[] { 29, 55, 74, 84, 74, 74, 0, -74, 84, -29, -74, 55, 55, -84, 74, -29 }, H265Tables.DstMatrix); + CollectionAssert.AreEqual(new[] { 40, 45, 51, 57, 64, 72 }, H265Tables.LevelScale); + CollectionAssert.AreEqual(new byte[] { 29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37 }, H265Tables.ChromaQp30To43); + + // Table 8-12: β′ is 0 up to Q 15, 6 at 16, 64 at 51; tC′ is 0 up to 17, 1 at 18, 24 at 53. + Assert.HasCount(52, H265Tables.Beta); + Assert.HasCount(54, H265Tables.Tc); + Assert.AreEqual(0, H265Tables.Beta[15]); + Assert.AreEqual(6, H265Tables.Beta[16]); + Assert.AreEqual(18, H265Tables.Beta[28]); + Assert.AreEqual(20, H265Tables.Beta[29]); + Assert.AreEqual(64, H265Tables.Beta[51]); + Assert.AreEqual(0, H265Tables.Tc[17]); + Assert.AreEqual(1, H265Tables.Tc[18]); + Assert.AreEqual(4, H265Tables.Tc[37]); + Assert.AreEqual(24, H265Tables.Tc[53]); + + // Tables 8-4 and 8-5. + Assert.AreEqual(32, H265Tables.IntraPredAngle[2]); + Assert.AreEqual(0, H265Tables.IntraPredAngle[10]); + Assert.AreEqual(-32, H265Tables.IntraPredAngle[18]); + Assert.AreEqual(0, H265Tables.IntraPredAngle[26]); + Assert.AreEqual(32, H265Tables.IntraPredAngle[34]); + Assert.AreEqual(-4096, H265Tables.InvAngle[11 - 11]); + Assert.AreEqual(-256, H265Tables.InvAngle[18 - 11]); + Assert.AreEqual(-4096, H265Tables.InvAngle[25 - 11]); + for (var mode = 11; mode <= 25; mode++) + { + // invAngle = Round(256 × 32 ÷ intraPredAngle). + Assert.AreEqual((int)Math.Round(8192.0 / H265Tables.IntraPredAngle[mode]), H265Tables.InvAngle[mode - 11], $"modo {mode}"); + } + + // Table 7-6. + Assert.AreEqual(16, H265Tables.DefaultScalingIntra[0]); + Assert.AreEqual(17, H265Tables.DefaultScalingIntra[10]); + Assert.AreEqual(115, H265Tables.DefaultScalingIntra[63]); + Assert.AreEqual(17, H265Tables.DefaultScalingInter[10]); + Assert.AreEqual(91, H265Tables.DefaultScalingInter[63]); + } + + [TestMethod] + public void TheScansArePermutationsInTheOrderOfTheStandard() + { + for (var log2 = 0; log2 < 6; log2++) + { + var size = 1 << log2; + for (var scanIdx = 0; scanIdx < 3; scanIdx++) + { + var scan = H265Tables.ScanOrder[log2][scanIdx]; + if (scan is null) + { + continue; + } + + var positions = scan.Select(p => (p >> 8) * size + (p & 0xFF)).ToList(); + Assert.HasCount(size * size, positions, $"log2 {log2}, scanIdx {scanIdx}"); + Assert.AreEqual(size * size, positions.Distinct().Count(), $"log2 {log2}, scanIdx {scanIdx}"); + } + } + + // §6.5.3: the up-right diagonal starts (0,0), (0,1), (1,0), (0,2), (1,1), (2,0) as (x, y). + var diagonal = H265Tables.ScanOrder[2][0]; + (int X, int Y)[] start = [(0, 0), (0, 1), (1, 0), (0, 2), (1, 1), (2, 0)]; + for (var i = 0; i < start.Length; i++) + { + Assert.AreEqual(start[i], (diagonal[i] & 0xFF, diagonal[i] >> 8), $"posizione {i}"); + } + + // Horizontal goes along the rows, vertical along the columns. + Assert.AreEqual((1, 0), (H265Tables.ScanOrder[2][1][1] & 0xFF, H265Tables.ScanOrder[2][1][1] >> 8)); + Assert.AreEqual((0, 1), (H265Tables.ScanOrder[2][2][1] & 0xFF, H265Tables.ScanOrder[2][2][1] >> 8)); + + for (var scanIdx = 0; scanIdx < 3; scanIdx++) + { + var scan = H265Tables.ScanOrder[2][scanIdx]; + for (var i = 0; i < 16; i++) + { + Assert.AreEqual(i, H265Tables.ScanPosition4x4[scanIdx][((scan[i] >> 8) * 4) + (scan[i] & 0xFF)]); + } + } + } + + [TestMethod] + public void TheCabacInitialValuesAreThoseOfTheStandard() + { + Assert.HasCount(173, CabacTables.InitValues[0]); + Assert.HasCount(3, CabacTables.InitValues); + Assert.IsTrue(CabacTables.InitValues.All(t => t.Length == CabacTables.ContextCount)); + + // Spot values of tables 9-5 to 9-37, by initType. + (int Context, byte I, byte P, byte B)[] spots = + [ + (CabacTables.SaoTypeIdx, 200, 185, 160), + (CabacTables.SplitCuFlag + 2, 157, 126, 126), + (CabacTables.CuSkipFlag + 1, 154, 185, 185), + (CabacTables.PredModeFlag, 154, 149, 134), + (CabacTables.PartMode, 184, 154, 154), + (CabacTables.PartMode + 1, 154, 139, 139), + (CabacTables.PrevIntraLumaPredFlag, 184, 154, 183), + (CabacTables.IntraChromaPredMode, 63, 152, 152), + (CabacTables.MergeFlag, 154, 110, 154), + (CabacTables.MergeIdx, 154, 122, 137), + (CabacTables.InterPredIdc + 3, 154, 31, 31), + (CabacTables.SplitTransformFlag, 153, 124, 224), + (CabacTables.CbfLuma + 1, 141, 111, 111), + (CabacTables.CbfChroma + 1, 138, 107, 92), + (CabacTables.AbsMvdGreater0Flag, 154, 140, 169), + (CabacTables.LastSigCoeffXPrefix + 5, 153, 79, 94), + (CabacTables.LastSigCoeffYPrefix + 17, 63, 108, 93), + (CabacTables.CodedSubBlockFlag + 2, 134, 61, 61), + (CabacTables.SigCoeffFlag, 111, 155, 170), + (CabacTables.SigCoeffFlag + 41, 111, 140, 140), + (CabacTables.CoeffAbsLevelGreater1Flag + 21, 227, 167, 152), + (CabacTables.CoeffAbsLevelGreater2Flag + 3, 167, 122, 107), + ]; + foreach (var (context, i, p, b) in spots) + { + Assert.AreEqual(i, CabacTables.InitValues[0][context], $"contesto {context}, I"); + Assert.AreEqual(p, CabacTables.InitValues[1][context], $"contesto {context}, P"); + Assert.AreEqual(b, CabacTables.InitValues[2][context], $"contesto {context}, B"); + } + } + + [TestMethod] + public void ContextsAreInitialisedWithTheFormulaOfTheStandard() + { + // §9.3.2.2, m = slopeIdx × 5 − 45 and n = (offsetIdx << 3) − 16. 154: m = 0, n = 64, so preCtxState 64 at any + // QP: valMps 1, pStateIdx 0. + var engine = new CabacEngine(); + engine.InitContexts(0, 26); + Assert.AreEqual((0 << 1) | 1, engine.Contexts[CabacTables.CuTransquantBypassFlag]); + + // 63 (intra_chroma_pred_mode, I): m = −30, n = 104; at QP 26 ((−30 × 26) >> 4) + 104 = 55: valMps 0, pStateIdx 8. + Assert.AreEqual(8 << 1, engine.Contexts[CabacTables.IntraChromaPredMode]); + + // 139 (split_cu_flag, ctxInc 0, I): m = −5, n = 72; at QP 26 ((−5 × 26) >> 4) + 72 = 63: valMps 0, pStateIdx 0. + Assert.AreEqual(0, engine.Contexts[CabacTables.SplitCuFlag]); + + // At QP 51 the same context: ((−5 × 51) >> 4) + 72 = 56: pStateIdx 7. Clip3(0, 51, SliceQpY) for QP above 51. + engine.InitContexts(0, 51); + Assert.AreEqual(7 << 1, engine.Contexts[CabacTables.SplitCuFlag]); + } +} diff --git a/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs b/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs new file mode 100644 index 0000000..fbf5b73 --- /dev/null +++ b/tests/Febe.Tests/Media/Heif/HeifDecoderTests.cs @@ -0,0 +1,549 @@ +using Febe.Core.Codecs.H265; +using Febe.Core.Codecs.Images; +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; + +/// +/// 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. +/// +[TestClass] +public sealed class HeifDecoderTests +{ + /// 416×240 streams, 8 bit, whose first picture is intra: tiles of a grid. + 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 + { + -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.R, corner.G, corner.B)); + + 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 TheImageFacadeReadsAHeicAsAnyOtherPhoto() + { + // irot 1: a quarter turn anticlockwise. The facade gives the pixels as stored and the turn as the orientation. + 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)); + builder.Item(1, "hvc1", picture.Data, -hvcC, ispe, -builder.Property(HeifBuilder.Irot(1))); + var file = builder.Build(); + var info = ImageDecoder.Identify(file); + Assert.AreEqual(ImageFormat.Heif, info.Format); + Assert.AreEqual((picture.Frame.Width, picture.Frame.Height, 8), (info.Width, info.Height, info.Metadata.Orientation)); + using var image = ImageDecoder.Decode(file, out var decoded); + CollectionAssert.AreEqual(Rgba(picture.Frame), image.ToArray()); + Assert.AreEqual(8, decoded.Metadata.Orientation); + Assert.ThrowsExactly(() => ImageDecoder.Decode(file, ImageLimits.Default with { MaxPixels = 1000 })); + + // Past the bytes ImageDecoding reads first, the size still comes from the boxes alone. + byte[] large = [.. file, 0, 4, 0x93, 0xE0, .. "free"u8, .. new byte[300_000 - 8]]; + Assert.IsGreaterThan(ImageDecoding.HeaderBytes, large.Length); + using var stream = new MemoryStream(large); + Assert.AreEqual((picture.Frame.Height, picture.Frame.Width), ImageDecoding.ReadSize(stream)); + } + + [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(() => 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(() => 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(() => 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(() => 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(() => 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"); + } + + [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(); + 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(); + } + + /// The frame in RGBA, as the video frames are converted (the same coefficients, opaque). + 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; + } +} diff --git a/tests/Febe.Tests/Media/Heif/HeifFiles.cs b/tests/Febe.Tests/Media/Heif/HeifFiles.cs new file mode 100644 index 0000000..2c213df --- /dev/null +++ b/tests/Febe.Tests/Media/Heif/HeifFiles.cs @@ -0,0 +1,256 @@ +using System.Text; +using Febe.Core.Codecs.H264; +using Febe.Core.Codecs.H265; +using Febe.Tests.Codecs.H265; + +namespace Febe.Tests.Codecs.Heif; + +/// +/// 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 +/// hvcC record, its NAL units with 4-byte lengths; and the picture itself, decoded straight from the Annex B +/// stream (not through hvcC), to compare with. +/// +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(); + var picture = new List(); + 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(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(); + 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!); + } +} + +/// +/// A builder of HEIF files (ISO/IEC 23008-12) for the tests: ftyp, a meta box with hdlr, +/// pitm, iinf, iloc (version 1, offsets in the file or in idat), iref and +/// iprp, then one mdat with the data of the items. +/// +internal sealed class HeifBuilder +{ + private readonly List items = []; + private readonly List properties = []; + private readonly List<(string Type, uint From, uint[] To)> references = []; + + public uint Primary { get; set; } = 1; + + /// Major brand of the ftyp box. + public string Brand { get; set; } = "heic"; + + /// The item data goes into idat instead of mdat. + public bool InIdat { get; set; } + + /// The ipma entries use 16-bit property indices (flags bit 0). + public bool WideIndices { get; set; } + + /// Adds an item; are indices from , negative for essential. + public HeifBuilder Item(uint id, string type, byte[] data, params int[] properties) + { + items.Add(new Entry(id, type, data, properties)); + 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) + { + 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]); + + /// The data of a grid item (version 0): rows, columns, output size in 16 or 32 bits. + 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]; + + /// The data of an Exif item: the offset of the TIFF header after «Exif\0\0», then both. + 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.Where(i => i.SharesWith is null).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 { 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)start)); + iloc.AddRange(U32((uint)length)); + } + + var ipma = new List(); + 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 { 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.Where(i => i.SharesWith is null).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]; + + /// A full box: holds the version in its top byte and the flags below. + 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) + { + 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); + } +}