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

Merged
Alby96 merged 12 commits from funzione/decoder-hevc into main 2026-11-26 14:40:07 +01:00
491 changed files with 14935 additions and 214 deletions

No files matched your search

+12
View File
@@ -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 | 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 | 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 | 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 | | 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 |
+2 -1
View File
@@ -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 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 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 ## Porte
@@ -266,6 +266,7 @@ public static class IsoBmffReader
internal int Channels; internal int Channels;
internal int SampleRate; internal int SampleRate;
internal byte[]? Avcc; internal byte[]? Avcc;
internal byte[]? Hvcc;
internal byte[]? Asc; internal byte[]? Asc;
internal long EditOffset; internal long EditOffset;
internal List<MediaSample> Samples = []; internal List<MediaSample> Samples = [];
@@ -505,6 +506,10 @@ public static class IsoBmffReader
{ {
track.Avcc = data[s..(s + c)]; track.Avcc = data[s..(s + c)];
} }
else if (t == "hvcC")
{
track.Hvcc = data[s..(s + c)];
}
} }
} }
else if (track.Handler == "soun" && size >= 8 + 28) else if (track.Handler == "soun" && size >= 8 + 28)
@@ -925,6 +930,7 @@ public static class IsoBmffReader
Timescale = video.Timescale > 0 ? video.Timescale : 1, Timescale = video.Timescale > 0 ? video.Timescale : 1,
Duration = DurationOf(video), Duration = DurationOf(video),
AvcConfiguration = video.Avcc, AvcConfiguration = video.Avcc,
HevcConfiguration = video.Hvcc,
Samples = video.Samples, Samples = video.Samples,
}; };
} }
@@ -595,6 +595,7 @@ public static class MatroskaReader
Height = v.Height, Height = v.Height,
Rotation = roll is 90 or 180 or 270 ? roll : 0, Rotation = roll is 90 or 180 or 270 ? roll : 0,
AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null, AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null,
HevcConfiguration = v.CodecId == "V_MPEGH/ISO/HEVC" ? v.CodecPrivate : null,
Timescale = timescale, Timescale = timescale,
Duration = trackUnits, Duration = trackUnits,
Samples = samples, Samples = samples,
@@ -22,7 +22,7 @@ public enum ContainerFormat
MpegPs, MpegPs,
} }
/// <summary>Video codecs recognised in a container; only <see cref="H264"/> can be decoded.</summary> /// <summary>Video codecs recognised in a container; <see cref="H264"/> and <see cref="Hevc"/> can be decoded.</summary>
public enum VideoCodec public enum VideoCodec
{ {
Unknown, Unknown,
@@ -115,6 +115,13 @@ public sealed class VideoTrack : MediaTrack
/// <summary>The AVCDecoderConfigurationRecord (<c>avcC</c>) of an H.264 track stored with length prefixes.</summary> /// <summary>The AVCDecoderConfigurationRecord (<c>avcC</c>) of an H.264 track stored with length prefixes.</summary>
public byte[]? AvcConfiguration { get; init; } public byte[]? AvcConfiguration { get; init; }
/// <summary>
/// The HEVCDecoderConfigurationRecord (<c>hvcC</c>, ISO/IEC 14496-15 §8.3.3) of an HEVC track stored with length
/// prefixes: the <c>hvcC</c> box of an <c>hvc1</c> or <c>hev1</c> sample entry, the CodecPrivate of a Matroska
/// <c>V_MPEGH/ISO/HEVC</c> track.
/// </summary>
public byte[]? HevcConfiguration { get; init; }
/// <summary>True when the samples are an Annex B byte stream (start codes), as in AVI.</summary> /// <summary>True when the samples are an Annex B byte stream (start codes), as in AVI.</summary>
public bool AnnexB { get; init; } public bool AnnexB { get; init; }
+12 -5
View File
@@ -6,7 +6,10 @@ namespace Febe.Core.Codecs.Containers;
/// <summary>A sample to write: its size, its times in track units, whether it is a sync sample.</summary> /// <summary>A sample to write: its size, its times in track units, whether it is a sync sample.</summary>
public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key); public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key);
/// <summary>A track to write: H.264 video (with its <c>avcC</c>) or AAC audio (with its AudioSpecificConfig).</summary> /// <summary>
/// A track to write: H.264 video (with its <c>avcC</c>), HEVC video (with its <c>hvcC</c>, as an <c>hvc1</c> sample entry) or
/// AAC audio (with its AudioSpecificConfig).
/// </summary>
public sealed class Mp4OutputTrack public sealed class Mp4OutputTrack
{ {
public required bool IsVideo { get; init; } public required bool IsVideo { get; init; }
@@ -27,6 +30,9 @@ public sealed class Mp4OutputTrack
public byte[]? AvcConfiguration { get; init; } public byte[]? AvcConfiguration { get; init; }
/// <summary>The <c>hvcC</c> of an HEVC video track (then <see cref="AvcConfiguration"/> stays null).</summary>
public byte[]? HevcConfiguration { get; init; }
public byte[]? AacConfiguration { get; init; } public byte[]? AacConfiguration { get; init; }
public int SampleRate { get; init; } public int SampleRate { get; init; }
@@ -59,7 +65,7 @@ public static class Mp4Writer
foreach (var track in tracks) 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)); throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
} }
@@ -533,7 +539,8 @@ public static class Mp4Writer
private static Box Avc1(Mp4OutputTrack track) 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.Zero(6);
entry.U16(1); entry.U16(1);
entry.Zero(16); entry.Zero(16);
@@ -546,8 +553,8 @@ public static class Mp4Writer
entry.Zero(32); entry.Zero(32);
entry.U16(0x0018); entry.U16(0x0018);
entry.U16(0xFFFF); entry.U16(0xFFFF);
var avcC = new Box("avcC"); var avcC = new Box(hevc ? "hvcC" : "avcC");
avcC.Bytes(track.AvcConfiguration); avcC.Bytes(hevc ? track.HevcConfiguration : track.AvcConfiguration);
entry.Child(avcC); entry.Child(avcC);
return entry; return entry;
} }
@@ -2,6 +2,7 @@ using System.Buffers;
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Globalization; using System.Globalization;
using Febe.Core.Codecs.H264; using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
namespace Febe.Core.Codecs.Containers; namespace Febe.Core.Codecs.Containers;
@@ -524,6 +525,13 @@ public static class MpegPsReader
return; 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) if (final)
{ {
Codec = type switch Codec = type switch
@@ -620,7 +628,7 @@ public static class MpegPsReader
: Codec.ToString(), : Codec.ToString(),
Width = Width, Width = Width,
Height = Height, Height = Height,
AnnexB = Codec == VideoCodec.H264, AnnexB = Codec is VideoCodec.H264 or VideoCodec.Hevc,
Timescale = ClockRate, Timescale = ClockRate,
Duration = ticks ?? 0, Duration = ticks ?? 0,
}; };
+174
View File
@@ -0,0 +1,174 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.H265;
/// <summary>A malformed or unsupported HEVC stream.</summary>
public sealed class H265Exception(string message) : Exception(message);
/// <summary>
/// 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 <see cref="NalUnits.Padding"/>), so reads never
/// need a bounds check; reading past the payload gives zeros and is detected through <see cref="BitsLeft"/>.
/// </summary>
internal sealed class BitReader
{
private readonly byte[] data;
private readonly int length;
private int position;
/// <param name="data">The payload, followed by at least sixteen bytes of zero padding.</param>
/// <param name="length">Bytes of payload.</param>
/// <param name="startByte">First byte to read (after the two-byte NAL unit header).</param>
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;
/// <summary>more_rbsp_data() (§7.2): true while bits remain before the rbsp_stop_one_bit.</summary>
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));
}
/// <summary>u(n), 0 to 32 bits.</summary>
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;
}
/// <summary>ue(v): Exp-Golomb code (§9.2).</summary>
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));
}
/// <summary>A ue(v) value that must not exceed <paramref name="max"/>.</summary>
internal int ReadUe(int max)
{
var value = ReadUe();
if (value > (uint)max)
{
throw new H265Exception("Valore fuori dall'intervallo ammesso.");
}
return (int)value;
}
/// <summary>se(v): signed Exp-Golomb code (§9.2.2).</summary>
internal int ReadSe()
{
var code = ReadUe();
var magnitude = (int)((code + 1) >> 1);
return (code & 1) != 0 ? magnitude : -magnitude;
}
/// <summary>A se(v) value inside [<paramref name="min"/>, <paramref name="max"/>].</summary>
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;
}
/// <summary>Moves to the next byte boundary (byte_alignment() and the alignment bits before PCM samples).</summary>
internal void AlignToByte() => position = (position + 7) & ~7;
}
/// <summary>One HEVC NAL unit, with its RBSP (the two-byte header included at its start).</summary>
internal readonly record struct H265NalUnit(int Type, int LayerId, int TemporalId, byte[] Rbsp, int Length)
{
/// <summary>A reader positioned after the two-byte NAL unit header (§7.3.1.2).</summary>
internal BitReader Reader() => new(Rbsp, Length, 2);
/// <summary>Removes the emulation prevention bytes of one NAL unit into <paramref name="buffer"/>, grown when needed.</summary>
internal static H265NalUnit Unescape(ReadOnlySpan<byte> 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);
}
}
+201
View File
@@ -0,0 +1,201 @@
using System.Buffers.Binary;
using System.Numerics;
using Lps = Febe.Core.Codecs.H264.CabacTables;
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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 &lt;&lt; 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.
/// </summary>
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;
/// <summary>Initialises every context variable for an initType and the slice QP (§9.3.2.2).</summary>
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);
}
}
/// <summary>
/// Initialises the arithmetic decoder (§9.3.2.5) at a bit position of <paramref name="source"/>; reading stops at
/// <paramref name="endByte"/> (the end of the slice segment data), past which the decoder sees zeros.
/// </summary>
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.");
}
}
/// <summary>The bit position right after the last bit the decoder has read (after a terminating bin equal to 1).</summary>
internal int BitPosition => (next * 8) - bits;
/// <summary>DecodeDecision (§9.3.4.3.2).</summary>
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;
/// <summary>DecodeBypass (§9.3.4.3.4).</summary>
internal int Bypass()
{
offset = (offset << 1) | Take(1);
if (offset >= range)
{
offset -= range;
return 1;
}
return 0;
}
/// <summary><paramref name="count"/> bypass bins (at most 16), the first one in the most significant bit.</summary>
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;
}
/// <summary>
/// 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 <see cref="BitPosition"/> is where the bitstream goes on.
/// </summary>
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;
}
}
}
+141
View File
@@ -0,0 +1,141 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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 (<see cref="H264.CabacTables"/>).
/// </summary>
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;
/// <summary>Number of context variables kept by the decoder.</summary>
internal const int ContextCount = CuChromaQpOffsetIdx + 1;
/// <summary>
/// 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).
/// </summary>
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]),
];
/// <summary>initValue of every context by initType: InitValues[initType][ctx].</summary>
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<byte>(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;
}
}
@@ -0,0 +1,543 @@
namespace Febe.Core.Codecs.H265;
/// <summary>The in-loop filters (§8.7): deblocking (§8.7.2) then sample adaptive offset (§8.7.3), on the whole picture.</summary>
public sealed partial class H265Decoder
{
private ushort[] saoSource = [];
/// <summary>The left and top edges of a coding block, unless filterEdgeFlag of §8.7.2.3 is 0 for them.</summary>
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);
}
}
/// <summary>Whether deblocking may cross into the block at (xN, yN) from the current one: slice and tile boundaries.</summary>
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;
}
/// <summary>The edges between the prediction blocks of an inter coding unit (§8.7.2.3).</summary>
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;
}
}
}
/// <summary>
/// bS of §8.7.2.4 between the 4×4 blocks <paramref name="p"/> and <paramref name="q"/> of the grid, in the CTBs
/// <paramref name="ctbP"/> and <paramref name="ctbQ"/>.
/// </summary>
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;
/// <summary>Filters every vertical (or horizontal) edge of the picture: luma on the 8×8 grid, chroma on the 8×8 grid of chroma samples.</summary>
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);
}
}
}
}
/// <summary>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.</summary>
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);
}
}
}
}
}
/// <summary>dSam of §8.7.2.5.6 for one line.</summary>
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);
}
/// <summary>Sample adaptive offset (§8.7.3) of every CTB, from a copy of the deblocked picture.</summary>
private void ApplySao(Picture picture)
{
var log2Ctb = sps.Log2CtbSize;
var heightInCtbs = sps.HeightInCtbs;
Span<bool> 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);
}
}
}
}
/// <summary>Whether the samples of the CTB at (nx, ny) can be used by the edge offset of the CTB <paramref name="rs"/>.</summary>
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<short> offsets, int bitDepth, int max, int sx, int sy)
{
Span<int> 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<short> offsets, int max, int sx, int sy, ReadOnlySpan<bool> 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<int> 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);
}
}
}
}
}
@@ -0,0 +1,966 @@
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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.
/// </summary>
public sealed partial class H265Decoder
{
/// <summary>fL of table 8-11 (luma, quarter samples 1 to 3), taps at −3 to +4.</summary>
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,
];
/// <summary>fC of table 8-12 (chroma, eighth samples 1 to 7), taps at −1 to +2.</summary>
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,
];
/// <summary>l0CandIdx and l1CandIdx of table 8-7 (combined bi-predictive merging candidates).</summary>
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];
/// <summary>predSamplesL0 and predSamplesL1 of the block being predicted, at 14-bit precision.</summary>
private readonly short[] predL0 = new short[64 * 64];
private readonly short[] predL1 = new short[64 * 64];
/// <summary>The reference samples a block needs, padded at the picture edges (8-228, 8-229).</summary>
private readonly ushort[] refBlock = new ushort[(64 + 7) * (64 + 7)];
/// <summary>The horizontal pass of a block filtered in both directions.</summary>
private readonly short[] filterTemp = new short[(64 + 7) * 64];
/// <summary>RefPicList0 and RefPicList1 of a P or B slice (§8.3.4), its collocated picture and NoBackwardPredFlag.</summary>
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<int> 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];
}
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>The motion of a merged prediction unit (§8.5.3.2.2 to §8.5.3.2.5).</summary>
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<MvField> 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;
/// <summary>8×4 and 4×8 prediction units are never bi-predicted (8-118): list 1 is dropped.</summary>
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;
}
/// <summary>mvpLX of AMVP (§8.5.3.2.6, §8.5.3.2.7) for list <paramref name="x"/> and a reference index.</summary>
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<int> 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);
}
/// <summary>The first conditions of §8.5.3.2.7: the neighbour refers to the same picture, in list X or in list Y.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>The scaling of a motion vector by POC distances (8-179 to 8-181, 8-205 to 8-207).</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>The collocated motion vectors (§8.5.3.2.9).</summary>
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;
}
/// <summary>The decoding process for inter sample prediction (§8.5.3.3) of one prediction block, written into the picture.</summary>
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);
}
}
}
/// <summary>The default weighted sample prediction (§8.5.3.3.4.2): a rounded shift, or the rounded mean of both lists.</summary>
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);
}
}
}
}
/// <summary>The explicit weighted sample prediction (§8.5.3.3.4.3) with the weights and offsets of the slice header.</summary>
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);
}
}
}
}
/// <summary>
/// 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.
/// </summary>
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<ushort>(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));
}
}
/// <summary>
/// One row of a filter over samples, <paramref name="step"/> apart (1 horizontally, the stride vertically): 8 outputs
/// at a time in vectors where the processor has them, the rest one by one.
/// </summary>
private static void FilterRow(ushort[] source, int start, int step, ReadOnlySpan<sbyte> f, int w, int shift, Span<short> 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<short> c0 = Vector128.Create((short)f[0]), c1 = Vector128.Create((short)f[1]);
Vector128<short> c2 = Vector128.Create((short)f[2]), c3 = Vector128.Create((short)f[3]);
if (taps == 8)
{
Vector128<short> c4 = Vector128.Create((short)f[4]), c5 = Vector128.Create((short)f[5]);
Vector128<short> 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<int> lo = Vector128<int>.Zero, hi = Vector128<int>.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);
}
}
}
/// <summary>The vertical pass over the 14-bit rows of the horizontal one (8-236, 8-246), shifted by 6.</summary>
private static void FilterColumn(short[] source, int start, int stride, ReadOnlySpan<sbyte> f, int w, Span<short> 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<int> c0 = Vector128.Create((int)f[0]), c1 = Vector128.Create((int)f[1]);
Vector128<int> c2 = Vector128.Create((int)f[2]), c3 = Vector128.Create((int)f[3]);
if (taps == 8)
{
Vector128<int> c4 = Vector128.Create((int)f[4]), c5 = Vector128.Create((int)f[5]);
Vector128<int> 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);
}
}
}
}
@@ -0,0 +1,271 @@
namespace Febe.Core.Codecs.H265;
/// <summary>Intra sample prediction (§8.4.4.2): reference samples, their substitution and filtering, planar, DC and angular.</summary>
public sealed partial class H265Decoder
{
/// <summary>
/// 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.
/// </summary>
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];
/// <summary>Predicts a block of component <paramref name="cIdx"/> at (<paramref name="x0"/>, <paramref name="y0"/>) in its own samples.</summary>
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<int> 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];
/// <summary>Whether a neighbouring sample can be used for intra prediction (§8.4.4.2.2), in luma locations.</summary>
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;
}
}
@@ -0,0 +1,597 @@
namespace Febe.Core.Codecs.H265;
/// <summary>residual_coding() (§7.3.8.11) and the scaling, transformation and reconstruction of §8.6.</summary>
public sealed partial class H265Decoder
{
/// <summary>ctxIdxMap of sig_coeff_flag in 4×4 blocks (9-55), by raster position.</summary>
private static readonly byte[] s_sigCtxMap4x4 = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
/// <summary>No residual DPCM; horizontal; vertical (§8.6.8, the direction of explicit_rdpcm_dir_flag + 1).</summary>
private const int RdpcmNone = 0;
private const int RdpcmHorizontal = 1;
private const int RdpcmVertical = 2;
/// <summary>TransCoeffLevel of the block being decoded, raster order (y &lt;&lt; log2) + x; zero outside it.</summary>
private readonly int[] coefficients = new int[32 * 32];
/// <summary>Raster positions of the nonzero entries of <see cref="coefficients"/>.</summary>
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];
/// <summary>The luma residual of the transform unit, for the cross-component prediction of its chroma (§8.6.6).</summary>
private readonly int[] lumaResidual = new int[32 * 32];
/// <summary>Decodes the residual of one transform block and adds it to the prediction in the picture.</summary>
/// <param name="cIdx">Colour component.</param>
/// <param name="x0">Left of the block, in samples of the component.</param>
/// <param name="y0">Top of the block, in samples of the component.</param>
/// <param name="log2">Log2 of the block size.</param>
/// <param name="predModeIntra">The intra prediction mode of the block, −1 for inter.</param>
/// <param name="resScale">ResScaleVal of the cross-component prediction of a chroma block, 0 for none.</param>
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);
}
/// <summary>A chroma block without coefficients whose residual is only the cross-component prediction (§8.6.6).</summary>
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);
}
/// <summary>The residual modification process for transform blocks using cross-component prediction (8-xx of §8.6.6).</summary>
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;
}
}
/// <summary>The directional residual modification (§8.6.8): each residual sample accumulates the previous ones.</summary>
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];
}
}
}
}
/// <summary>The picture construction (§8.6.7): prediction plus residual, clipped to the bit depth.</summary>
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);
}
}
}
/// <summary>The scaling process for transform coefficients (§8.6.3), on the nonzero coefficients.</summary>
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);
}
}
/// <summary>
/// residual_coding(): fills <see cref="coefficients"/> and <see cref="nonzero"/>; 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).
/// </summary>
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<int> sigPositions = stackalloc int[16];
Span<int> 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);
}
}
File diff suppressed because it is too large. Load diff
+778
View File
@@ -0,0 +1,778 @@
using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.H265;
/// <summary>What an access unit offers to start decoding from (see <see cref="H265Decoder.AccessPoint"/>).</summary>
public enum H265AccessPoint
{
/// <summary>A picture that is not IRAP, or no picture: decoding cannot start here.</summary>
None,
/// <summary>A CRA picture: decoding starts here, but its RASL pictures (shown before it) are skipped.</summary>
Cra,
/// <summary>An IDR or BLA picture: nothing decoded after it refers to anything before.</summary>
Idr,
}
/// <summary>
/// An HEVC (ITU-T H.265 | ISO/IEC 23008-2) decoder written from the Recommendation, for the Main, Main 10 and Main Still
/// Picture profiles and the format range extensions up to 12 bits: 4:0:0, 4:2:0, 4:2:2 and 4:4:4, tiles, wavefronts,
/// 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 <see cref="H265Exception"/>): 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.
/// </summary>
public sealed partial class H265Decoder
{
private readonly Sps?[] spss = new Sps?[16];
private readonly Pps?[] ppss = new Pps?[64];
private readonly List<Picture> dpb = [];
private readonly Stack<Picture> pool = new();
private byte[]? rbsp;
/// <summary>No picture decoded yet: the next IRAP picture is "picture 0" of C.5.2.2.</summary>
private bool firstPicture = true;
/// <summary>At the start of the bitstream or after an end of sequence: the next CRA picture has NoRaslOutputFlag 1.</summary>
private bool afterEndOfSequence = true;
private bool seenIrap;
/// <summary>NoRaslOutputFlag of the IRAP picture the current pictures are associated with.</summary>
private bool irapNoRaslOutput;
/// <summary>PicOrderCntVal of prevTid0Pic (§8.3.1).</summary>
private int prevTid0Poc;
private long codedPictures;
/// <summary>The slices of the current picture are skipped (a RASL picture that cannot be decoded, no IRAP yet).</summary>
private bool skipping;
/// <summary>
/// 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 <see cref="missing"/> in place of every "no reference picture" (§8.3.3).
/// </summary>
private readonly List<(Picture Picture, int Poc)> refStCurrBefore = [];
private readonly List<(Picture Picture, int Poc)> refStCurrAfter = [];
private readonly List<(Picture Picture, int Poc)> refLtCurr = [];
/// <summary>
/// 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.
/// </summary>
private Picture? missing;
/// <summary>
/// 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.
/// </summary>
private readonly List<Sps> pendingSps = [];
private readonly List<Pps> pendingPps = [];
/// <summary>
/// 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.
/// </summary>
private const int DpbMargin = 1;
/// <summary>Raised for each frame in output order (the bumping process of C.5.2.4), cropped.</summary>
public event Action<H265Frame>? FrameOutput;
/// <summary>
/// Raised for each picture once decoded and filtered, in decoding order and cropped, when <see cref="Wanted"/> accepts
/// its decoding index: a caller that maps pictures to the samples of a container takes them here, without waiting for
/// the output order. Pictures with pic_output_flag 0 are raised too.
/// </summary>
public event Action<H265Frame>? FrameDecoded;
/// <summary>Which pictures <see cref="FrameDecoded"/> hands out, by decoding index; null hands out all of them.</summary>
public Func<long, bool>? Wanted { get; set; }
/// <summary>Raised for each picture once decoded and filtered, in decoding order (for the decoded picture hash).</summary>
internal event Action<Picture>? PictureDecoded;
/// <summary>Coded pictures met so far, also those skipped.</summary>
public long PicturesDecoded => codedPictures;
/// <summary>
/// The size every picture must have once cropped (a HEIF image of known <c>ispe</c>), 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 <see cref="H265Exception"/> before anything of its size is allocated.
/// </summary>
public (int Width, int Height)? ExpectedFrameSize { get; set; }
/// <summary>Decodes a whole Annex B byte stream, then outputs every picture left.</summary>
public void DecodeAnnexB(ReadOnlySpan<byte> stream)
{
var position = 0;
while (NalUnits.NextAnnexB(stream, ref position, out var unit))
{
Decode(stream[unit]);
}
Flush();
}
/// <summary>
/// Reads the parameter sets of an <c>hvcC</c> box (HEVCDecoderConfigurationRecord, ISO/IEC 14496-15 §8.3.3); returns
/// the size of the NAL length fields of the samples.
/// </summary>
public int ConfigureHvcC(ReadOnlySpan<byte> 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;
}
/// <summary>Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture.</summary>
public void DecodeSample(ReadOnlySpan<byte> sample, int lengthSize)
{
var position = 0;
while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
Decode(sample[unit]);
}
FinishPicture();
}
/// <summary>Decodes one access unit in Annex B form (an AVI chunk, a PES packet) and finishes its picture.</summary>
public void DecodeAccessUnitAnnexB(ReadOnlySpan<byte> accessUnit)
{
var position = 0;
while (NalUnits.NextAnnexB(accessUnit, ref position, out var unit))
{
Decode(accessUnit[unit]);
}
FinishPicture();
}
/// <summary>
/// Whether decoding can start at this access unit (§8.1.3): exactly at an IDR or BLA picture; at a CRA picture too,
/// but then its RASL pictures, which follow it in decoding order and refer to pictures before it, are not decoded.
/// <paramref name="lengthSize"/> is the size of the NAL length fields, 0 for Annex B.
/// </summary>
public static H265AccessPoint AccessPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
{
var position = 0;
while (true)
{
Range unit;
var more = lengthSize == 0
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
if (!more)
{
return H265AccessPoint.None;
}
var nal = accessUnit[unit];
if (nal.Length < 3 || (nal[0] & 0x80) != 0 || (((nal[0] & 1) << 5) | (nal[1] >> 3)) != 0)
{
continue; // too short, forbidden bit set, or a layer above 0
}
var type = (nal[0] >> 1) & 63;
if (type > 31)
{
continue; // parameter sets, SEI, delimiters: the picture comes after them
}
return type switch
{
>= 16 and <= 20 => H265AccessPoint.Idr,
21 => H265AccessPoint.Cra,
_ => H265AccessPoint.None,
};
}
}
/// <summary>Finishes the picture being decoded and outputs every picture still waiting, in output order.</summary>
public void Flush()
{
FinishPicture();
while (Bump())
{
}
}
private void Decode(ReadOnlySpan<byte> 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);
}
/// <summary>The decoding process for the reference picture set (§8.3.2), and the marking of the DPB it implies.</summary>
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<bool> 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;
}
}
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>Takes a new PPS, as <see cref="InstallSps"/> does.</summary>
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;
}
}
/// <summary>Installs the parameter sets that waited for the end of the picture.</summary>
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<bool> 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;
}
/// <summary>The conditions of C.5.2.2 and C.5.2.3 on the pictures waiting for output.</summary>
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);
}
}
}
/// <summary>The bumping process (C.5.2.4): outputs the waiting picture with the smallest POC; false when none waits.</summary>
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);
}
/// <summary>
/// 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 <see cref="H265Exception"/> and is dropped.
/// </summary>
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;
}
}
}
}
@@ -0,0 +1,77 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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 <c>H264StreamInfo</c> is for H.264.
/// </summary>
public static class H265StreamInfo
{
/// <summary>nal_unit_type of a sequence parameter set (table 7-1).</summary>
private const int SpsType = 33;
/// <summary>The picture size of an SPS NAL unit (two-byte header included); false when it is not an SPS or is damaged.</summary>
public static bool TryPictureSize(ReadOnlySpan<byte> 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;
}
}
/// <summary>
/// The picture size of the first whole SPS of an Annex B byte stream; an SPS that the end of
/// <paramref name="stream"/> cuts counts only when <paramref name="complete"/> says nothing follows.
/// </summary>
public static bool TryPictureSizeFromAnnexB(ReadOnlySpan<byte> stream, bool complete, out int width, out int height)
{
width = height = 0;
ReadOnlySpan<byte> 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;
}
}
+190
View File
@@ -0,0 +1,190 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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).
/// </summary>
internal static class H265Tables
{
/// <summary>intraPredAngle by intra prediction mode (table 8-4); modes 0 (planar) and 1 (DC) have none.</summary>
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,
];
/// <summary>invAngle of the modes 11 to 25 (table 8-5), indexed by mode − 11.</summary>
internal static readonly short[] InvAngle = [-4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096];
/// <summary>QpC as a function of qPi for ChromaArrayType 1 (table 8-10), for qPi from 30 to 43.</summary>
internal static readonly byte[] ChromaQp30To43 = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
/// <summary>
/// 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).
/// </summary>
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,
];
/// <summary>QpC of chroma from qPi (8-258 to 8-261, table 8-10): the table for 4:2:0, Min(qPi, 51) otherwise.</summary>
internal static int ChromaQp(int qPi, int chromaArrayType) =>
chromaArrayType != 1 ? Math.Min(qPi, 51) : qPi < 30 ? qPi : qPi > 43 ? qPi - 6 : ChromaQp30To43[qPi - 30];
/// <summary>β′ for Q from 0 to 51 (table 8-12).</summary>
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,
];
/// <summary>tC′ for Q from 0 to 53 (table 8-12).</summary>
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,
];
/// <summary>levelScale[qP % 6] of the scaling process (§8.6.3).</summary>
internal static readonly int[] LevelScale = [40, 45, 51, 57, 64, 72];
/// <summary>Default values of ScalingList[1..3][0..2] (intra), in up-right diagonal order (table 7-6).</summary>
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,
];
/// <summary>Default values of ScalingList[1..3][3..5] (inter), in up-right diagonal order (table 7-6).</summary>
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,
];
/// <summary>
/// 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 &lt;&lt; 8).
/// </summary>
internal static readonly ushort[][][] ScanOrder = BuildScans();
/// <summary>For the 4×4 scans: position in scan order of each raster position (y * 4 + x), by scanIdx.</summary>
internal static readonly byte[][] ScanPosition4x4 = BuildInverse4x4();
/// <summary>
/// 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.
/// </summary>
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,
];
/// <summary>
/// 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.
/// </summary>
internal static readonly short[] DctMatrix = BuildDct();
/// <summary>The 4×4 DST matrix of §8.6.4.2 (trType 1), transMatrix[k][n] = DstMatrix[k * 4 + n].</summary>
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;
}
}
File diff suppressed because it is too large. Load diff
+189
View File
@@ -0,0 +1,189 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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).
/// </summary>
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)];
}
/// <summary>The SPS of the picture: a picture of the pool is reused for another SPS of the same size.</summary>
internal Sps Sps { get; set; }
internal int Width { get; }
internal int Height { get; }
internal int ChromaWidth { get; }
internal int ChromaHeight { get; }
/// <summary>Y, Cb and Cr; the chroma arrays are empty for 4:0:0.</summary>
internal ushort[][] Planes { get; }
internal int Poc;
internal bool ShortTerm;
internal bool LongTerm;
/// <summary>Marked "needed for output" (C.5.2).</summary>
internal bool NeededForOutput;
internal bool OutputFlag;
internal int LatencyCount;
/// <summary>Position of the coded picture in decoding order, counting the pictures that are skipped too.</summary>
internal long DecodeIndex;
/// <summary>A picture generated for a missing reference (§8.3.3): never output, its samples are not meaningful.</summary>
internal bool Generated;
/// <summary>Every slice of the picture is an I slice: it does not depend on other pictures.</summary>
internal bool IntraOnly;
/// <summary>The motion of every 4×4 luma block (§8.5.3), kept for the pictures that take this one as collocated (TMVP).</summary>
internal MvField[] Motion { get; }
/// <summary>Index in <see cref="Slices"/> of the slice of each CTB (raster order), −1 where none was decoded.</summary>
internal int[] CtbSlice = [];
/// <summary>The independent slice segment headers of the picture, with their reference picture lists.</summary>
internal List<SliceHeader> 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);
/// <summary>The picture cropped to the conformance window.</summary>
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<ushort>(width * height);
for (var y = 0; y < height; y++)
{
plane.AsSpan(((y0 + y) * stride) + x0, width).CopyTo(result.AsSpan(y * width, width));
}
return result;
}
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>A decoded HEVC frame, cropped to the conformance window, with one 16-bit value per sample.</summary>
/// <param name="Width">Luma width after cropping.</param>
/// <param name="Height">Luma height after cropping.</param>
/// <param name="ChromaFormat">ChromaArrayType: 0 (only luma), 1 (4:2:0), 2 (4:2:2), 3 (4:4:4).</param>
/// <param name="BitDepthLuma">Bits per luma sample.</param>
/// <param name="BitDepthChroma">Bits per chroma sample.</param>
/// <param name="Y">Luma, <paramref name="Width"/> × <paramref name="Height"/>.</param>
/// <param name="Cb">Blue-difference chroma (empty for 4:0:0).</param>
/// <param name="Cr">Red-difference chroma, same size as <paramref name="Cb"/>.</param>
/// <param name="Poc">Picture order count.</param>
/// <param name="DecodeIndex">Position of the coded picture in decoding order.</param>
/// <param name="MatrixCoefficients">matrix_coeffs of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified).</param>
/// <param name="FullRange">video_full_range_flag of the VUI.</param>
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)
{
/// <summary>
/// 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.
/// </summary>
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<ushort[]>)[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;
}
}
+498
View File
@@ -0,0 +1,498 @@
namespace Febe.Core.Codecs.H265;
/// <summary>slice_type (§7.4.7.1).</summary>
internal enum SliceType
{
B = 0,
P = 1,
I = 2,
}
/// <summary>
/// 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.
/// </summary>
internal sealed class SliceHeader
{
internal bool FirstSliceSegmentInPic;
internal bool NoOutputOfPriorPics;
internal int PpsId;
internal bool Dependent;
internal int SegmentAddress;
/// <summary>SliceAddrRs: the address of the first CTB of the slice (of its independent slice segment).</summary>
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;
/// <summary>LumaWeightLX and luma_offset_lX by [list][refIdx] (§7.4.7.3).</summary>
internal readonly int[][] LumaWeight = [new int[16], new int[16]];
internal readonly int[][] LumaOffset = [new int[16], new int[16]];
/// <summary>ChromaWeightLX and ChromaOffsetLX by [list][refIdx * 2 + (cIdx − 1)].</summary>
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 = [];
/// <summary>RefPicList0 and RefPicList1 (§8.3.4) of the slice, by [list][refIdx].</summary>
internal readonly Picture[][] RefPicList = [new Picture[16], new Picture[16]];
/// <summary>PicOrderCntVal of each entry of <see cref="RefPicList"/>, kept for the pictures that use this one as collocated.</summary>
internal readonly int[][] RefPoc = [new int[16], new int[16]];
/// <summary>Whether each entry of <see cref="RefPicList"/> is a long-term reference picture (LongTermRefPic of §8.5.3.2.8).</summary>
internal readonly bool[][] RefIsLongTerm = [new bool[16], new bool[16]];
/// <summary>ColPic (§8.5.3.2.8), when slice_temporal_mvp_enabled_flag is 1.</summary>
internal Picture? ColPic;
/// <summary>NoBackwardPredFlag (§8.5.3.2.9): no reference picture follows the current one in output order.</summary>
internal bool NoBackwardPred;
/// <summary>NumPicTotalCurr (7-55).</summary>
internal int NumPicTotalCurr;
/// <summary>The byte where slice_segment_data() starts in the RBSP.</summary>
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,
};
/// <summary>
/// Reads a slice segment header. <paramref name="previous"/> is the header of the last independent slice segment of
/// the current picture (for a dependent one); <paramref name="sps"/> and <paramref name="pps"/> are those it refers to.
/// </summary>
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();
}
}
/// <summary>pred_weight_table() (§7.3.6.3), as the weights and offsets of §7.4.7.3.</summary>
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<bool> lumaFlags = stackalloc bool[16];
Span<bool> 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;
}
}
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
namespace Febe.Core.Codecs.H265;
/// <summary>
/// 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.
/// </summary>
internal static class Transform
{
/// <param name="coefficients">Scaled coefficients d, raster (y &lt;&lt; log2) + x.</param>
/// <param name="output">Residual samples, raster.</param>
/// <param name="temp">Intermediate values, at least the block size.</param>
/// <param name="log2">Log2 of the block size.</param>
/// <param name="dst">trType 1: the 4×4 DST of intra luma blocks.</param>
/// <param name="maxX">Largest column with a nonzero coefficient.</param>
/// <param name="maxY">Largest row with a nonzero coefficient.</param>
/// <param name="bitDepth">Bit depth of the component.</param>
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<short> 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;
}
}
}
}
+698
View File
@@ -0,0 +1,698 @@
using System.Buffers.Binary;
using System.Text;
using Febe.Core.Codecs.H265;
namespace Febe.Core.Codecs.Heif;
/// <summary>
/// Decoder of HEIF still images with HEVC pictures (HEIC, ISO/IEC 23008-12), written from the standard on the HEVC
/// decoder of <see cref="H265Decoder"/>: the primary item, coded (<c>hvc1</c>) or a grid of coded tiles (<c>grid</c>, as
/// phones write their photos), its colour (<c>colr</c> nclx, otherwise the VUI of the pictures), its alpha plane (an
/// auxiliary image), the clean aperture (<c>clap</c>), rotation and mirroring (<c>irot</c>, <c>imir</c>, returned as an
/// orientation), and the EXIF block (<c>Exif</c> item). Not handled (a <see cref="HeifException"/>): images of other
/// codecs (AVIF, JPEG), derived images other than grids (overlays, identity), image sequences (<c>moov</c> only),
/// protected items, and essential properties Febe does not know.
/// </summary>
public static class HeifDecoder
{
private const string AlphaHevc = "urn:mpeg:hevc:2015:auxid:1";
private const string AlphaCicp = "urn:mpeg:mpegB:cicp:systems:auxiliary:alpha";
/// <summary>Properties Febe knows: an essential property outside these makes an item undecodable (§6.5.2).</summary>
private static readonly HashSet<uint> Known =
[
HeifFile.HvcC, HeifFile.Ispe, HeifFile.Colr, HeifFile.Irot, HeifFile.Imir, HeifFile.Clap, HeifFile.AuxC, HeifFile.Pixi,
0x70617370, // 'pasp'
0x636C6C69, // 'clli'
0x6D646376, // 'mdcv'
0x72726566, // 'rref'
];
/// <summary>True when the first bytes are those of a HEIF file of still images (an <c>ftyp</c> with a HEIF brand).</summary>
public static bool Looks(ReadOnlySpan<byte> start) => HeifFile.Looks(start);
/// <summary>Size, orientation and alpha of the primary image, without decoding it.</summary>
public static HeifInfo ReadInfo(Stream stream, HeifLimits? limits = null)
{
ArgumentNullException.ThrowIfNull(stream);
limits ??= HeifLimits.Default;
return Guard(() =>
{
var file = HeifFile.Read(stream, limits);
var primary = Primary(file);
var (width, height, tiles) = CodedSize(stream, file, primary, limits);
var crop = CleanAperture(file, primary, width, height);
return new HeifInfo(crop.Width, crop.Height, OrientationOf(file, primary), AlphaOf(file, primary) is not null, tiles);
});
}
/// <summary>Decodes the primary image of a seekable stream.</summary>
public static HeifImage Decode(Stream stream, HeifLimits? limits = null)
{
ArgumentNullException.ThrowIfNull(stream);
limits ??= HeifLimits.Default;
return Guard(() => DecodePrimary(stream, limits));
}
/// <summary>Decodes the primary image of a whole file in memory.</summary>
public static HeifImage Decode(byte[] data, HeifLimits? limits = null)
{
ArgumentNullException.ThrowIfNull(data);
using var stream = new MemoryStream(data, writable: false);
return Decode(stream, limits);
}
/// <summary>
/// The EXIF block (a TIFF structure) of the primary image of a HEIF file whose first bytes are
/// <paramref name="head"/>; null when there is none, the file is not HEIF, or the block lies past those bytes.
/// </summary>
public static byte[]? FindExif(ReadOnlySpan<byte> head)
{
if (!HeifFile.Looks(head))
{
return null;
}
using var stream = new MemoryStream(head.ToArray(), writable: false);
try
{
var file = HeifFile.Read(stream, HeifLimits.Default);
return ExifOf(stream, file, file.Item(file.PrimaryId), HeifLimits.Default);
}
catch (Exception ex) when (ex is HeifException or EndOfStreamException or ArgumentException or IndexOutOfRangeException
or OverflowException or InvalidOperationException)
{
return null;
}
}
/// <summary>Runs <paramref name="work"/>, turning every sign of a damaged file into a <see cref="HeifException"/>.</summary>
private static T Guard<T>(Func<T> work)
{
try
{
return work();
}
catch (H265Exception ex)
{
throw new HeifException("Immagine HEVC del file HEIF non decodificabile: " + ex.Message);
}
catch (AggregateException ex)
{
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.");
}
}
/// <summary>
/// What the tiles decoded in parallel raised, as one <see cref="HeifException"/>: the first of theirs, else the first
/// HEVC error, else a damaged file, whatever the exceptions were.
/// </summary>
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.");
}
}
}
/// <summary>The grid description of §6.6.2.3.1: rows, columns, output size.</summary>
private static (int Rows, int Columns, int Width, int Height) GridOf(Stream stream, HeifFile file, HeifItem grid, HeifLimits limits)
{
var data = file.ReadItem(stream, grid, limits);
if (data.Length < 8 || data[0] != 0)
{
throw new HeifException("Descrizione della griglia HEIF non valida.");
}
var wide = (data[1] & 1) != 0;
var rows = data[2] + 1;
var columns = data[3] + 1;
int width, height;
if (wide)
{
if (data.Length < 12)
{
throw new HeifException("Descrizione della griglia HEIF troncata.");
}
width = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(4)), int.MaxValue);
height = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(8)), int.MaxValue);
}
else
{
width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(4));
height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(6));
}
if (rows * columns > limits.MaxTiles || grid.DerivedFrom.Count != rows * columns)
{
throw new HeifException("Riquadri della griglia HEIF mancanti o in eccesso.");
}
return (rows, columns, width, height);
}
/// <summary>The size of an image before the clean aperture: of the grid output, or of the coded picture.</summary>
private static (int Width, int Height, int Tiles) CodedSize(Stream stream, HeifFile file, HeifItem item, HeifLimits limits)
{
int width, height, tiles = 1;
if (item.Type == HeifFile.Grid)
{
(var rows, var columns, width, height) = GridOf(stream, file, item, limits);
tiles = rows * columns;
}
else
{
(width, height) = Ispe(file, item) ?? throw new HeifException("Manca la dimensione (ispe) dell'immagine HEIF.");
}
if (width <= 0 || height <= 0 || (long)width * height > Math.Min(limits.MaxPixels, Array.MaxLength / 4))
{
throw new HeifException("Dimensioni dell'immagine HEIF non valide o eccessive.");
}
return (width, height, tiles);
}
private static (int Width, int Height)? Ispe(HeifFile file, HeifItem item)
{
if (file.Property(item, HeifFile.Ispe) is not { } p)
{
return null;
}
var body = file.Body(p);
return ((int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(body[4..]), int.MaxValue),
(int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(body[8..]), int.MaxValue));
}
private static HeifImage DecodePrimary(Stream stream, HeifLimits limits)
{
var file = HeifFile.Read(stream, limits);
var primary = Primary(file);
var (width, height, _) = CodedSize(stream, file, primary, limits);
var pixels = new byte[(long)width * height * 4];
var bitDepth = 8;
var nclx = Nclx(file, primary);
DecodeImage(stream, file, primary, limits, (frame, x0, y0) =>
{
var w = Math.Min(frame.Width, width - x0);
var h = Math.Min(frame.Height, height - y0);
if (w <= 0 || h <= 0)
{
return;
}
bitDepth = frame.BitDepthLuma;
var planes = Planes(frame);
var (matrix, full) = nclx ?? (frame.MatrixCoefficients, frame.FullRange);
var k = YuvToRgb.For(matrix, full, frame.BitDepthLuma, frame.BitDepthChroma, frame.Height);
YuvToRgb.Convert(planes, k, 1, pixels.AsSpan(((y0 * width) + x0) * 4), width * 4, 4, w, h);
});
var hasAlpha = false;
if (AlphaOf(file, primary) is { } alpha)
{
try
{
CheckDecodable(file, alpha);
var (aw, ah, _) = CodedSize(stream, file, alpha, limits);
if (aw == width && ah == height)
{
DecodeImage(stream, file, alpha, limits, (frame, x0, y0) => WriteAlpha(frame, pixels, width, height, x0, y0));
hasAlpha = true;
}
}
catch (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),
};
}
/// <summary>
/// Decodes a coded image or the tiles of a grid, handing each picture to <paramref name="place"/> with the position
/// of its top-left sample in the image, inside it. Tiles are decoded on several threads; <paramref name="place"/>
/// writes disjoint areas. Every picture must have the size of its <c>ispe</c>, checked by the HEVC decoder before it
/// allocates anything: a small <c>ispe</c> cannot hide a picture of the largest size.
/// </summary>
private static void DecodeImage(Stream stream, HeifFile file, HeifItem item, HeifLimits limits, Action<H265Frame, int, int> 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<uint>();
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<uint, byte[]>();
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);
}
}
/// <summary>One coded picture of a known size: its <c>hvcC</c>, then its sample of length-prefixed NAL units.</summary>
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<ushort> Planes(H265Frame frame)
{
var (sx, sy) = frame.ChromaFormat switch
{
1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma);
}
/// <summary>The luma of an alpha picture into the alpha bytes: full range as is, limited range stretched.</summary>
private static void WriteAlpha(H265Frame frame, byte[] pixels, int width, int height, int x0, int y0)
{
var w = Math.Min(frame.Width, width - x0);
var h = Math.Min(frame.Height, height - y0);
var shift = Math.Max(0, frame.BitDepthLuma - 8);
var offset = 16 << shift;
var scale = (int)Math.Round(255.0 / 219.0 / (1 << shift) * 65536);
for (var y = 0; y < h; y++)
{
var source = frame.Y.AsSpan(y * frame.Width, w);
var target = pixels.AsSpan(((((y0 + y) * width) + x0) * 4) + 3);
for (var x = 0; x < source.Length; x++)
{
var v = frame.FullRange ? source[x] >> shift : (((source[x] - offset) * scale) + 32768) >> 16;
target[x * 4] = (byte)(v < 0 ? 0 : v > 255 ? 255 : v);
}
}
}
/// <summary>The alpha plane of an image: an item that is its auxiliary image (<c>auxl</c>) of the alpha type.</summary>
private static HeifItem? AlphaOf(HeifFile file, HeifItem image)
{
foreach (var item in file.Items)
{
if (!item.AuxiliaryOf.Contains(image.Id) || file.Property(item, HeifFile.AuxC) is not { } auxC)
{
continue;
}
var body = file.Body(auxC)[4..];
var end = body.IndexOf((byte)0);
var type = Encoding.ASCII.GetString(end >= 0 ? body[..end] : body);
if (type is AlphaHevc or AlphaCicp)
{
return item;
}
}
return null;
}
/// <summary>matrix_coefficients and full_range_flag of an nclx <c>colr</c> property, of the image or its first tile.</summary>
private static (int Matrix, bool Full)? Nclx(HeifFile file, HeifItem image)
{
foreach (var candidate in ColourCarriers(file, image))
{
foreach (var (index, _) in candidate.Properties)
{
var p = index < file.Properties.Count ? file.Properties[index] : default;
if (p.Type != HeifFile.Colr || p.Length < 11)
{
continue;
}
var body = file.Body(p);
if (body[..4].SequenceEqual("nclx"u8))
{
return (BinaryPrimitives.ReadUInt16BigEndian(body[8..]), (body[10] & 0x80) != 0);
}
}
}
return null;
}
private static byte[]? IccOf(HeifFile file, HeifItem image)
{
foreach (var candidate in ColourCarriers(file, image))
{
foreach (var (index, _) in candidate.Properties)
{
var p = index < file.Properties.Count ? file.Properties[index] : default;
if (p.Type == HeifFile.Colr && p.Length > 4)
{
var body = file.Body(p);
if (body[..4].SequenceEqual("prof"u8) || body[..4].SequenceEqual("rICC"u8))
{
return body[4..].ToArray();
}
}
}
}
return null;
}
private static IEnumerable<HeifItem> ColourCarriers(HeifFile file, HeifItem image)
{
yield return image;
if (image.DerivedFrom.Count > 0 && file.Item(image.DerivedFrom[0]) is { } tile)
{
yield return tile;
}
}
/// <summary>
/// The clean aperture of ISO/IEC 14496-12 §12.1.4: a rectangle centred on the picture centre moved by the offsets;
/// the whole image when there is none or it does not fit.
/// </summary>
private static (int Left, int Top, int Width, int Height) CleanAperture(HeifFile file, HeifItem image, int width, int height)
{
if (file.Property(image, HeifFile.Clap) is not { Length: >= 32 } p)
{
return (0, 0, width, height);
}
var body = file.Body(p);
var cw = Ratio(BinaryPrimitives.ReadUInt32BigEndian(body), BinaryPrimitives.ReadUInt32BigEndian(body[4..]));
var ch = Ratio(BinaryPrimitives.ReadUInt32BigEndian(body[8..]), BinaryPrimitives.ReadUInt32BigEndian(body[12..]));
var ho = Ratio(BinaryPrimitives.ReadInt32BigEndian(body[16..]), BinaryPrimitives.ReadUInt32BigEndian(body[20..]));
var vo = Ratio(BinaryPrimitives.ReadInt32BigEndian(body[24..]), BinaryPrimitives.ReadUInt32BigEndian(body[28..]));
if (double.IsNaN(cw) || double.IsNaN(ch) || double.IsNaN(ho) || double.IsNaN(vo))
{
return (0, 0, width, height);
}
var left = (int)Math.Round(ho + ((width - 1) / 2.0) - ((cw - 1) / 2.0));
var top = (int)Math.Round(vo + ((height - 1) / 2.0) - ((ch - 1) / 2.0));
var w = (int)Math.Round(cw);
var h = (int)Math.Round(ch);
if (w <= 0 || h <= 0 || left < 0 || top < 0 || left + w > width || top + h > height)
{
return (0, 0, width, height);
}
return (left, top, w, h);
}
private static double Ratio(double numerator, uint denominator) => denominator == 0 ? double.NaN : numerator / denominator;
/// <summary>
/// The rotations (<c>irot</c>: quarter turns anticlockwise) and mirrors (<c>imir</c>: axis 0 vertical, left and
/// right swap; axis 1 horizontal, top and bottom swap) of the image, composed in the order of its properties, as one
/// EXIF orientation. The transform is kept as a clockwise rotation of r quarter turns after an optional left-right
/// mirror.
/// </summary>
internal static int OrientationOf(HeifFile file, HeifItem image)
{
var r = 0;
var mirrored = false;
foreach (var (index, _) in image.Properties)
{
if (index >= file.Properties.Count)
{
continue;
}
var p = file.Properties[index];
if (p.Length < 1)
{
continue;
}
var value = file.Meta[p.Start];
if (p.Type == HeifFile.Irot)
{
r = (r + 4 - (value & 3)) & 3;
}
else if (p.Type == HeifFile.Imir)
{
// A left-right mirror after R(r)·M^m is R(−r)·M^(m+1); a top-bottom one is R(2)·(left-right).
r = (value & 1) == 0 ? (4 - r) & 3 : (6 - r) & 3;
mirrored = !mirrored;
}
}
return mirrored ? r switch { 0 => 2, 1 => 7, 2 => 4, _ => 5 } : r switch { 0 => 1, 1 => 6, 2 => 3, _ => 8 };
}
/// <summary>The EXIF item describing the image (or the only EXIF item of the file), without its offset prefix.</summary>
private static byte[]? ExifOf(Stream stream, HeifFile file, HeifItem? image, HeifLimits limits)
{
HeifItem? exif = null;
var count = 0;
foreach (var item in file.Items)
{
if (item.Type != HeifFile.Exif)
{
continue;
}
count++;
if (image is not null && item.Describes.Contains(image.Id))
{
exif = item;
break;
}
exif ??= item;
}
if (exif is null || (count > 1 && (image is null || !exif.Describes.Contains(image.Id))))
{
return null;
}
try
{
// exif_tiff_header_offset, then (usually «Exif\0\0» and) the TIFF header (ISO/IEC 23008-12 Annex A.2.1).
var data = file.ReadItem(stream, exif, limits);
if (data.Length < 12)
{
return null;
}
var offset = BinaryPrimitives.ReadUInt32BigEndian(data);
var start = 4 + (long)offset;
if (start + 8 > data.Length)
{
return null;
}
var tiff = data.AsSpan((int)start);
return tiff[..4].SequenceEqual("II*\0"u8) || tiff[..4].SequenceEqual("MM\0*"u8) ? tiff.ToArray() : null;
}
catch (Exception ex) when (ex is HeifException or EndOfStreamException or IOException)
{
return null; // an EXIF block that cannot be read: the image stands without it
}
}
/// <summary>The Orientation tag (0x0112) of the first IFD of a TIFF structure; 1 without it or when damaged.</summary>
internal static int ExifOrientationOf(ReadOnlySpan<byte> tiff)
{
if (tiff.Length < 8)
{
return 1;
}
var little = tiff[0] == (byte)'I';
var ifd = U32(tiff[4..], little);
if (ifd > (uint)(tiff.Length - 2))
{
return 1;
}
var entries = U16(tiff[(int)ifd..], little);
for (var i = 0; i < entries; i++)
{
var entry = (long)ifd + 2 + (12L * i);
if (entry + 12 > tiff.Length)
{
break;
}
var e = tiff.Slice((int)entry, 12);
if (U16(e, little) != 0x0112)
{
continue;
}
var value = U16(e[2..], little) switch
{
3 => U16(e[8..], little),
4 => U32(e[8..], little),
_ => 0u,
};
return value is >= 1 and <= 8 ? (int)value : 1;
}
return 1;
}
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
private static uint U32(ReadOnlySpan<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt32LittleEndian(b) : BinaryPrimitives.ReadUInt32BigEndian(b);
}
+571
View File
@@ -0,0 +1,571 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Containers;
namespace Febe.Core.Codecs.Heif;
/// <summary>An item of a HEIF file (ISO/IEC 23008-12 §6.2, the <c>iinf</c>, <c>iloc</c> and <c>ipma</c> entries of one ID).</summary>
internal sealed class HeifItem(uint id)
{
internal uint Id { get; } = id;
/// <summary>item_type of the <c>infe</c> box: <c>hvc1</c>, <c>grid</c>, <c>Exif</c>, <c>mime</c>, ...; 0 when unknown.</summary>
internal uint Type { get; set; }
/// <summary>construction_method of <c>iloc</c>: 0 from the file, 1 from the <c>idat</c> box.</summary>
internal int ConstructionMethod { get; set; }
/// <summary>The extents of the item's data: offset (base_offset added) and length (0: to the end of the file).</summary>
internal List<(long Offset, long Length)> Extents { get; } = [];
/// <summary>Whether <c>iloc</c> lists the item at all.</summary>
internal bool Located { get; set; }
/// <summary>The associated properties, in the order of <c>ipma</c>: index in <see cref="HeifFile.Properties"/>, essential.</summary>
internal List<(int Index, bool Essential)> Properties { get; } = [];
/// <summary>The items this one is derived from (<c>dimg</c>), in order: the tiles of a grid.</summary>
internal List<uint> DerivedFrom { get; } = [];
/// <summary>The items this one is an auxiliary image of (<c>auxl</c>).</summary>
internal List<uint> AuxiliaryOf { get; } = [];
/// <summary>The items this one describes (<c>cdsc</c>): an <c>Exif</c> item and its image.</summary>
internal List<uint> Describes { get; } = [];
}
/// <summary>A property of the <c>ipco</c> box: its type and where its body lies in <see cref="HeifFile.Meta"/>.</summary>
internal readonly record struct HeifProperty(uint Type, int Start, int Length);
/// <summary>
/// The structure of a HEIF file, read from the boxes of its file-level <c>meta</c> box (ISO/IEC 23008-12 §6 and
/// ISO/IEC 14496-12 §8.11): primary item, items with their locations, properties and references. Only the
/// <c>meta</c> box is kept in memory; item data is read from the stream when asked for.
/// </summary>
internal sealed class HeifFile
{
internal const uint Hvc1 = 0x68766331; // 'hvc1'
internal const uint Grid = 0x67726964; // 'grid'
internal const uint Exif = 0x45786966; // 'Exif'
internal const uint HvcC = 0x68766343; // 'hvcC'
internal const uint Ispe = 0x69737065; // 'ispe'
internal const uint Colr = 0x636F6C72; // 'colr'
internal const uint Irot = 0x69726F74; // 'irot'
internal const uint Imir = 0x696D6972; // 'imir'
internal const uint Clap = 0x636C6170; // 'clap'
internal const uint AuxC = 0x61757843; // 'auxC'
internal const uint Pixi = 0x70697869; // 'pixi'
private const int MaxItems = 100_000;
private readonly Dictionary<uint, HeifItem> items = [];
private HeifFile(byte[] meta, long fileLength)
{
Meta = meta;
FileLength = fileLength;
}
/// <summary>The body of the <c>meta</c> box.</summary>
internal byte[] Meta { get; }
internal long FileLength { get; }
internal uint PrimaryId { get; private set; }
internal List<HeifProperty> Properties { get; } = [];
/// <summary>The body of the <c>idat</c> box (start and length in <see cref="Meta"/>); length −1 without one.</summary>
internal (int Start, int Length) Idat { get; private set; } = (0, -1);
internal IEnumerable<HeifItem> Items => items.Values;
internal HeifItem? Item(uint id) => items.GetValueOrDefault(id);
/// <summary>True when the file starts with an <c>ftyp</c> box naming a HEIF brand of still images with HEVC.</summary>
internal static bool Looks(ReadOnlySpan<byte> start)
{
if (start.Length < 16 || !start.Slice(4, 4).SequenceEqual("ftyp"u8))
{
return false;
}
var size = (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(start), (uint)start.Length);
if (IsHeifBrand(start.Slice(8, 4)))
{
return true;
}
for (var b = 16; b + 4 <= size; b += 4)
{
if (IsHeifBrand(start.Slice(b, 4)))
{
return true;
}
}
return false;
}
private static bool IsHeifBrand(ReadOnlySpan<byte> brand) =>
brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) || brand.SequenceEqual("heim"u8) || brand.SequenceEqual("heis"u8)
|| brand.SequenceEqual("mif1"u8) || brand.SequenceEqual("mif2"u8) || brand.SequenceEqual("MiHE"u8);
/// <summary>Reads the top-level boxes of a seekable stream up to its file-level <c>meta</c> box and parses it.</summary>
internal static HeifFile Read(Stream stream, HeifLimits limits)
{
var length = stream.Length;
long position = 0;
Span<byte> header = stackalloc byte[16];
for (var i = 0; i < 10_000 && position + 8 <= length; i++)
{
stream.Position = position;
stream.ReadExactly(header[..8]);
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
var headerSize = 8;
if (size == 1)
{
if (position + 16 > length)
{
break;
}
stream.ReadExactly(header.Slice(8, 8));
var wide = BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
size = wide > long.MaxValue ? -1 : (long)wide;
headerSize = 16;
}
else if (size == 0)
{
size = length - position;
}
if (size < headerSize || size > length - position)
{
throw new HeifException("Box HEIF danneggiato.");
}
if (header.Slice(4, 4).SequenceEqual("meta"u8))
{
var bodyLength = size - headerSize;
if (bodyLength > limits.MaxMetaBytes || bodyLength < 4)
{
throw new HeifException("Box meta HEIF troppo grande o vuoto.");
}
var meta = new byte[bodyLength];
stream.ReadExactly(meta);
var file = new HeifFile(meta, length);
try
{
file.Parse();
}
catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or ArgumentException or OverflowException)
{
throw new HeifException("Box meta HEIF danneggiato.");
}
return file;
}
position += size;
}
throw new HeifException("Manca il box meta HEIF.");
}
private HeifItem ItemOf(uint id)
{
if (!items.TryGetValue(id, out var item))
{
if (items.Count >= MaxItems)
{
throw new HeifException("Troppi 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<byte> body)
{
var version = body[0];
if (version > 2)
{
throw new HeifException("Versione di iloc non gestita.");
}
var offsetSize = body[4] >> 4;
var lengthSize = body[4] & 15;
var baseOffsetSize = body[5] >> 4;
var indexSize = version is 1 or 2 ? body[5] & 15 : 0;
var p = 6;
long count;
if (version < 2)
{
count = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
}
else
{
count = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
if (count > MaxItems)
{
throw new HeifException("Troppi 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<byte> body, ref int p, int size)
{
long value;
switch (size)
{
case 0:
return 0;
case 4:
value = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
break;
case 8:
var wide = BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
if (wide > long.MaxValue)
{
throw new HeifException("Posizione HEIF fuori misura.");
}
value = (long)wide;
break;
default:
throw new HeifException("Ampiezza di campo di iloc non valida.");
}
p += size;
return value;
}
private void ParseIref(int start, int count)
{
var wide = Meta[start] != 0;
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start + 4, count - 4))
{
var body = Meta.AsSpan(s, c);
var p = 0;
var from = Id(body, ref p, wide);
var references = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
var item = ItemOf(from);
var list = type switch
{
"dimg" => item.DerivedFrom,
"auxl" => item.AuxiliaryOf,
"cdsc" => item.Describes,
_ => null,
};
for (var r = 0; r < references; r++)
{
var to = Id(body, ref p, wide);
list?.Add(to);
}
}
}
private static uint Id(ReadOnlySpan<byte> body, ref int p, bool wide)
{
if (wide)
{
var id = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
return id;
}
var narrow = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
return narrow;
}
private void ParseIprp(int start, int count)
{
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start, count))
{
if (type == "ipco")
{
foreach (var (t, ps, pc) in IsoBmffReader.Children(Meta, s, c))
{
Properties.Add(new HeifProperty(BinaryPrimitives.ReadUInt32BigEndian(System.Text.Encoding.Latin1.GetBytes(t)), ps, pc));
}
}
}
foreach (var (type, s, c) in IsoBmffReader.Children(Meta, start, count))
{
if (type != "ipma")
{
continue;
}
var body = Meta.AsSpan(s, c);
var version = body[0];
var large = (body[3] & 1) != 0;
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
var p = 8;
for (var e = 0u; e < entries; e++)
{
var id = Id(body, ref p, version >= 1);
var associations = body[p++];
var item = ItemOf(id);
for (var a = 0; a < associations; a++)
{
int index;
bool essential;
if (large)
{
var v = BinaryPrimitives.ReadUInt16BigEndian(body[p..]);
p += 2;
essential = (v & 0x8000) != 0;
index = v & 0x7FFF;
}
else
{
var v = body[p++];
essential = (v & 0x80) != 0;
index = v & 0x7F;
}
if (index > 0)
{
item.Properties.Add((index - 1, essential)); // index 0: no property
}
}
}
}
}
/// <summary>The first property of <paramref name="type"/> associated with <paramref name="item"/>, or null.</summary>
internal HeifProperty? Property(HeifItem item, uint type)
{
foreach (var (index, _) in item.Properties)
{
if (index < Properties.Count && Properties[index].Type == type)
{
return Properties[index];
}
}
return null;
}
internal ReadOnlySpan<byte> Body(HeifProperty property) => Meta.AsSpan(property.Start, property.Length);
/// <summary>The bytes of an item, its extents one after the other.</summary>
internal byte[] ReadItem(Stream stream, HeifItem item, HeifLimits limits)
{
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;
}
/// <summary>How many bytes <see cref="ReadItem"/> would read for an item, checked as it checks them, without reading.</summary>
internal long ItemLength(HeifItem item, HeifLimits limits)
{
Locate(item, limits, out var total);
return total;
}
/// <summary>The extents of an item, each checked against the file (or <c>idat</c>), and their total.</summary>
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;
}
}
+100
View File
@@ -0,0 +1,100 @@
namespace Febe.Core.Codecs.Heif;
/// <summary>A HEIF file that cannot be decoded: damaged, truncated, or of a kind Febe does not handle.</summary>
public sealed class HeifException(string message) : Exception(message);
/// <summary>
/// The still image of a HEIF file (HEIC: ISO/IEC 23008-12 with HEVC pictures), decoded: <see cref="Width"/> ×
/// <see cref="Height"/> pixels, top row first, four bytes each R, G, B, A (8 bits, alpha not premultiplied, 255 without
/// an alpha plane). The clean aperture (<c>clap</c>) is already applied; the rotation and mirroring are not: they are in
/// <see cref="Orientation"/>, as an EXIF orientation, for the caller to apply.
/// </summary>
/// <remarks>
/// The same layout as <c>RgbaImage</c> of the image codecs (branch funzione/codec-immagini, not merged here): when that
/// branch is merged, <see cref="Pixels"/> becomes the buffer of an <c>RgbaImage</c> and <see cref="Orientation"/> its
/// <c>ImageMetadata.Orientation</c>, so that <c>ImageOrientation.Apply</c> turns it upright.
/// </remarks>
public sealed class HeifImage
{
internal HeifImage(int width, int height, byte[] pixels)
{
Width = width;
Height = height;
Pixels = pixels;
}
/// <summary>Width in pixels as stored (orientation not applied).</summary>
public int Width { get; }
/// <summary>Height in pixels as stored.</summary>
public int Height { get; }
/// <summary>The pixels, R, G, B, A, row after row.</summary>
public byte[] Pixels { get; }
/// <summary>
/// How the pixels must be turned to be shown, as an EXIF orientation 1-8 (1: as they are; 6: 90° clockwise; 3: 180°;
/// 8: 90° anticlockwise; 2, 4, 5, 7 with a mirror), from the <c>irot</c> and <c>imir</c> properties of the image in
/// the order the file lists them. The EXIF block's own orientation is not part of it (HEIF says the transformative
/// properties rule, and phones write both): it is in <see cref="ExifOrientation"/>.
/// </summary>
public int Orientation { get; init; } = 1;
/// <summary>Whether an alpha plane (an auxiliary image) filled the alpha of <see cref="Pixels"/>.</summary>
public bool HasAlpha { get; init; }
/// <summary>Bits per luma sample of the coded pictures (8, 10, 12); the pixels have 8 whatever this is.</summary>
public int BitDepth { get; init; } = 8;
/// <summary>The EXIF block of the image (its <c>Exif</c> item) as a TIFF structure, or null.</summary>
public byte[]? Exif { get; init; }
/// <summary>The Orientation tag of <see cref="Exif"/>, 1-8; 1 without it. Informative only: see <see cref="Orientation"/>.</summary>
public int ExifOrientation { get; init; } = 1;
/// <summary>The ICC profile of a <c>colr</c> property of type <c>prof</c> or <c>rICC</c>, or null.</summary>
public byte[]? IccProfile { get; init; }
/// <summary>The image as shown: <see cref="Width"/> and <see cref="Height"/> swapped when the orientation turns it a quarter.</summary>
public (int Width, int Height) DisplaySize => Orientation >= 5 ? (Height, Width) : (Width, Height);
}
/// <summary>What a HEIF file says about its primary image, read without decoding any picture.</summary>
/// <param name="Width">Width as stored, after the clean aperture.</param>
/// <param name="Height">Height as stored, after the clean aperture.</param>
/// <param name="Orientation">As <see cref="HeifImage.Orientation"/>.</param>
/// <param name="HasAlpha">Whether an alpha plane goes with the image.</param>
/// <param name="Tiles">Coded pictures of the image: 1, or the tiles of a grid.</param>
public sealed record HeifInfo(int Width, int Height, int Orientation, bool HasAlpha, int Tiles)
{
/// <summary>The size as shown (orientation applied).</summary>
public (int Width, int Height) DisplaySize => Orientation >= 5 ? (Height, Width) : (Width, Height);
}
/// <summary>Bounds that keep a damaged or hostile file from taking the memory or the processors.</summary>
public sealed record HeifLimits
{
/// <summary>The default limits.</summary>
public static HeifLimits Default { get; } = new();
/// <summary>Pixels of the image at most (100 megapixels: 400 MB of RGBA).</summary>
public long MaxPixels { get; init; } = 100_000_000;
/// <summary>Bytes of the <c>meta</c> box at most.</summary>
public int MaxMetaBytes { get; init; } = 32 * 1024 * 1024;
/// <summary>Bytes of one item at most.</summary>
public int MaxItemBytes { get; init; } = 128 * 1024 * 1024;
/// <summary>
/// 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.
/// </summary>
public long MaxTotalBytes { get; init; } = 512L * 1024 * 1024;
/// <summary>Tiles of a grid at most (256 × 256).</summary>
public int MaxTiles { get; init; } = 65_536;
/// <summary>Tiles decoded at the same time at most.</summary>
public int MaxParallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
}
@@ -0,0 +1,74 @@
using System.Runtime.InteropServices;
using Febe.Core.Codecs.Heif;
namespace Febe.Core.Codecs.Images;
/// <summary>
/// HEIC/HEIF photos through the image facade (<see cref="ImageDecoder"/>): the decoder written in house
/// (<see cref="HeifDecoder"/>, on the HEVC decoder) gives straight RGBA8, which becomes an <see cref="RgbaImage"/>
/// without a copy; the <c>irot</c>/<c>imir</c> properties become <see cref="ImageMetadata.Orientation"/>, so that
/// <see cref="ImageOrientation.Apply"/> turns the picture upright as it does for the EXIF orientation of a JPEG.
/// </summary>
internal static class HeifImageDecoder
{
/// <summary>Size, alpha and orientation of the primary image, without decoding it.</summary>
public static ImageInfo Identify(ReadOnlyMemory<byte> 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 });
}
/// <summary>Decodes the primary image; the pixels are the decoder's own array, never pooled.</summary>
public static RgbaImage Decode(ReadOnlyMemory<byte> 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);
/// <summary>A read-only stream over the bytes, without copying them when they are an array.</summary>
private static MemoryStream Open(ReadOnlyMemory<byte> 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);
}
+10 -2
View File
@@ -6,8 +6,12 @@ namespace Febe.Core.Codecs.Images;
/// </summary> /// </summary>
public static class ImageDecoder public static class ImageDecoder
{ {
/// <summary>Whether Febe has a decoder for <paramref name="format"/>.</summary> /// <summary>
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 <paramref name="format"/>. For <see cref="ImageFormat.Heif"/> only the HEVC
/// pictures (HEIC) decode: a HEIF of other pictures (AV1, JPEG) raises <see cref="ImageDecodeException"/>.
/// </summary>
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;
/// <summary>Size, frames and metadata of an image, without decoding the pixels.</summary> /// <summary>Size, frames and metadata of an image, without decoding the pixels.</summary>
/// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception> /// <exception cref="ImageFormatNotSupportedException">The format is not known or has no decoder yet.</exception>
@@ -20,6 +24,7 @@ public static class ImageDecoder
ImageFormat.Gif => GifDecoder.Identify(data, limits), ImageFormat.Gif => GifDecoder.Identify(data, limits),
ImageFormat.Bmp => BmpDecoder.Identify(data, limits), ImageFormat.Bmp => BmpDecoder.Identify(data, limits),
ImageFormat.WebP => WebPDecoder.Identify(data, limits), ImageFormat.WebP => WebPDecoder.Identify(data, limits),
ImageFormat.Heif => HeifImageDecoder.Identify(data, limits),
var other => throw NotSupported(other), var other => throw NotSupported(other),
}; };
@@ -35,6 +40,7 @@ public static class ImageDecoder
ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled), ImageFormat.Gif => GifDecoder.Decode(data, limits, pooled),
ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled), ImageFormat.Bmp => BmpDecoder.Decode(data, limits, pooled),
ImageFormat.WebP => WebPDecoder.Decode(data, limits, pooled), ImageFormat.WebP => WebPDecoder.Decode(data, limits, pooled),
ImageFormat.Heif => HeifImageDecoder.Decode(data, out _, limits),
var other => throw NotSupported(other), var other => throw NotSupported(other),
}; };
@@ -56,6 +62,8 @@ public static class ImageDecoder
return BmpDecoder.Decode(data, out info, limits, pooled); return BmpDecoder.Decode(data, out info, limits, pooled);
case ImageFormat.WebP: case ImageFormat.WebP:
return WebPDecoder.Decode(data, out info, limits, pooled); return WebPDecoder.Decode(data, out info, limits, pooled);
case ImageFormat.Heif:
return HeifImageDecoder.Decode(data, out info, limits);
case var other: case var other:
throw NotSupported(other); throw NotSupported(other);
} }
+229
View File
@@ -0,0 +1,229 @@
using System.Numerics;
namespace Febe.Core.Codecs;
/// <summary>
/// The sample planes of a decoded picture, whatever its codec: luma <see cref="Width"/> × <see cref="Height"/>, chroma
/// subsampled by <c>1 &lt;&lt; ChromaShiftX</c> and <c>1 &lt;&lt; ChromaShiftY</c> (4:2:0: 1 and 1; 4:2:2: 1 and 0; 4:4:4:
/// 0 and 0), no chroma at all for a monochrome picture. Samples are 8-bit bytes (H.264) or 16-bit values of any bit
/// depth up to 16 (HEVC).
/// </summary>
internal readonly struct YuvPlanes<T>(
T[] y, T[] cb, T[] cr, int width, int height, int chromaShiftX, int chromaShiftY, bool monochrome, int bitDepthY, int bitDepthC)
where T : unmanaged, IBinaryInteger<T>
{
internal T[] Y { get; } = y;
internal T[] Cb { get; } = cb;
internal T[] Cr { get; } = cr;
internal int Width { get; } = width;
internal int Height { get; } = height;
internal int ChromaShiftX { get; } = chromaShiftX;
internal int ChromaShiftY { get; } = chromaShiftY;
internal bool Monochrome { get; } = monochrome;
internal int BitDepthY { get; } = bitDepthY;
internal int BitDepthC { get; } = bitDepthC;
/// <summary>Width of a chroma row (rounded up, as for odd H.264 widths).</summary>
internal int ChromaWidth => (Width + (1 << ChromaShiftX) - 1) >> ChromaShiftX;
}
/// <summary>
/// Conversion of Y′CbCr samples to 8-bit RGB (ITU-T H.273 for the meaning of matrix_coeffs and video_full_range_flag):
/// BT.709 (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.
/// <para>
/// 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.
/// </para>
/// </summary>
internal static class YuvToRgb
{
private const int Shift = 16;
private const double One = 1 << Shift;
private const int Half = 1 << (Shift - 1);
/// <summary>The integer coefficients for one matrix, range and bit depth.</summary>
internal readonly struct Coefficients
{
internal bool Identity { get; init; }
/// <summary>YCgCo (matrix 8): G = Y + Cg, R = Y − Cg + Co, B = Y − Cg − Co, Cg and Co scaled by <see cref="ChromaScale"/>.</summary>
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; }
/// <summary>Right shift that brings an identity-matrix sample to 8 bits, luma and chroma.</summary>
internal int IdentityShiftY { get; init; }
internal int IdentityShiftC { get; init; }
}
/// <summary>
/// The coefficients for <paramref name="matrix"/> (matrix_coeffs; unspecified, unknown or approximated as the class
/// says: BT.709 from 720 lines up, BT.601 below), <paramref name="fullRange"/> and the bit depths of the samples.
/// </summary>
internal static Coefficients For(int matrix, bool fullRange, int bitDepthY, int bitDepthC, int height)
{
if (matrix == 0)
{
return new Coefficients { Identity = true, IdentityShiftY = Math.Max(0, bitDepthY - 8), IdentityShiftC = Math.Max(0, bitDepthC - 8) };
}
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),
};
}
/// <summary>
/// Converts the picture reduced by <paramref name="factor"/> (each output pixel the mean of factor × factor converted
/// pixels) into <paramref name="target"/>: <paramref name="width"/> × <paramref name="height"/> pixels of
/// <paramref name="pixelSize"/> bytes (3: R, G, B; 4: R, G, B and an alpha of 255), rows <paramref name="stride"/>
/// bytes apart. The output must fit in the picture: width × factor ≤ its width, height × factor ≤ its height.
/// </summary>
internal static void Convert<T>(in YuvPlanes<T> p, in Coefficients k, int factor, Span<byte> target, int stride, int pixelSize, int width, int height)
where T : unmanaged, IBinaryInteger<T>
{
var area = factor * factor;
var cw = p.ChromaWidth;
var sx = p.ChromaShiftX;
var sy = p.ChromaShiftY;
ReadOnlySpan<T> yPlane = p.Y, cbPlane = p.Cb, crPlane = p.Cr;
var mono = p.Monochrome;
for (var oy = 0; oy < height; oy++)
{
var row = target.Slice(oy * stride, width * pixelSize);
for (var ox = 0; ox < width; ox++)
{
int r = 0, g = 0, b = 0;
for (var dy = 0; dy < factor; dy++)
{
var y = (oy * factor) + dy;
var lumaRow = y * p.Width;
var chromaRow = (y >> sy) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var luma = int.CreateTruncating(yPlane[lumaRow + x]);
int u, v;
if (mono)
{
u = v = k.ChromaMiddle;
}
else
{
var c = chromaRow + (x >> sx);
u = int.CreateTruncating(cbPlane[c]);
v = int.CreateTruncating(crPlane[c]);
}
if (k.Identity)
{
g += Clip(luma >> k.IdentityShiftY);
b += Clip(mono ? luma >> k.IdentityShiftY : u >> k.IdentityShiftC);
r += Clip(mono ? luma >> k.IdentityShiftY : v >> k.IdentityShiftC);
continue;
}
var l = (luma - k.LumaOffset) * k.LumaScale;
u -= k.ChromaMiddle;
v -= k.ChromaMiddle;
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;
}
+2 -2
View File
@@ -81,7 +81,7 @@ internal static class ContentAnalysis
return new ContentFacts(type, length, sha, width, height, null, hash, date, null); return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
} }
/// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. HEIC).</summary> /// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. AVIF).</summary>
private static (int? Width, int? Height, ulong? Hash) Decode(byte[] bytes) private static (int? Width, int? Height, ulong? Hash) Decode(byte[] bytes)
{ {
try try
@@ -121,7 +121,7 @@ internal static class ContentAnalysis
} }
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException) 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
} }
} }
+9 -3
View File
@@ -1,5 +1,6 @@
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Globalization; using System.Globalization;
using Febe.Core.Codecs.Heif;
using Febe.Core.Domain; using Febe.Core.Domain;
namespace Febe.Core.Import; 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. /// camera wrote the zone. The modification date of IFD0 (0x0132) is not used: editors rewrite it.
/// <para> /// <para>
/// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (<c>eXIf</c> chunk), WebP (<c>EXIF</c> chunk). /// Containers: JPEG (APP1 «Exif»), TIFF and raw formats built on it, PNG (<c>eXIf</c> chunk), WebP (<c>EXIF</c> chunk).
/// HEIC keeps its EXIF in an item of the <c>meta</c> box and is not read. Every offset is checked: a damaged block gives /// HEIC and HEIF keep their EXIF in an item of the <c>meta</c> box (<see cref="HeifDecoder.FindExif"/>): read when the
/// no date, never an exception. /// item lies within the first bytes read. Every offset is checked: a damaged block gives no date, never an exception.
/// </para> /// </para>
/// </summary> /// </summary>
public static class ExifDateReader public static class ExifDateReader
@@ -46,7 +47,7 @@ public static class ExifDateReader
} }
} }
/// <summary>The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG or WebP; empty when there is none.</summary> /// <summary>The TIFF structure holding the EXIF data of a JPEG, TIFF, PNG, WebP or HEIC; empty when there is none.</summary>
internal static ReadOnlySpan<byte> FindTiff(ReadOnlySpan<byte> data) internal static ReadOnlySpan<byte> FindTiff(ReadOnlySpan<byte> data)
{ {
if (data.Length < 8) if (data.Length < 8)
@@ -74,6 +75,11 @@ public static class ExifDateReader
return FindInWebp(data); 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 []; return [];
} }
+7 -5
View File
@@ -21,7 +21,7 @@ var import = new ImportService(new ImportEnvironment
Clock = clock, Clock = clock,
Thumbnails = new ThumbnailStore(data.Thumbnails), Thumbnails = new ThumbnailStore(data.Thumbnails),
HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta 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) VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska, AVI, WMV, FLV e MPEG (null: la stessa, predefinita)
SetFileTimeToPublication = settings.SetFileTimeToPublication, SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, 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 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 `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 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 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 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. pacchetti PES, non si elencano, nemmeno se H.264 o HEVC.
- HEIC/HEIF: si riconoscono, ma i codec di Febe (PNG, JPEG, GIF, BMP, WebP) non li decodificano: niente dimensioni, - HEIC/HEIF: dimensioni, impronta e miniatura vengono dal decodificatore scritto in casa (`Febe.Core.Codecs.Heif`, sul
impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica. 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 - 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. 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. - La data `mvhd` si legge come UTC, come vuole il formato; alcune fotocamere vi scrivono l'ora locale.
+1 -1
View File
@@ -14,7 +14,7 @@ public static class DamagedImage
{ {
/// <summary> /// <summary>
/// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or /// 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. /// picture too large to decode.
/// </summary> /// </summary>
public static bool IsDamaged(ReadOnlyMemory<byte> data) => ImageDecoding.IsDamaged(data); public static bool IsDamaged(ReadOnlyMemory<byte> data) => ImageDecoding.IsDamaged(data);
+27 -8
View File
@@ -1,11 +1,12 @@
using Febe.Core.Codecs.Heif;
using Febe.Core.Codecs.Images; using Febe.Core.Codecs.Images;
namespace Febe.Core.Library; namespace Febe.Core.Library;
/// <summary> /// <summary>
/// Decodes images with the in-house codecs (<see cref="ImageDecoder"/>: JPEG, PNG, GIF, BMP, WebP), applying the /// Decodes images with the in-house codecs (<see cref="ImageDecoder"/>: JPEG, PNG, GIF, BMP, WebP and HEIC through
/// EXIF orientation (photos from phones) and, for JPEG, decoding directly at a reduced size when a smaller picture is /// <see cref="HeifDecoder"/>), applying the EXIF orientation (photos from phones; for HEIC its <c>irot</c>/<c>imir</c>)
/// enough, which saves memory and time. /// and, for JPEG, decoding directly at a reduced size when a smaller picture is enough, which saves memory and time.
/// </summary> /// </summary>
internal static class ImageDecoding internal static class ImageDecoding
{ {
@@ -23,7 +24,7 @@ internal static class ImageDecoding
/// <summary> /// <summary>
/// Decodes an image upright, as straight RGBA. When <paramref name="minLongSide"/> is given the codec may decode /// Decodes an image upright, as straight RGBA. When <paramref name="minLongSide"/> 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 /// 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).
/// </summary> /// </summary>
public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null) public static RgbaImage? DecodeUpright(Stream stream, int? minLongSide = null)
{ {
@@ -78,12 +79,15 @@ internal static class ImageDecoding
/// <summary> /// <summary>
/// True when <paramref name="data"/> is in a format Febe decodes but cannot be decoded because it is damaged or /// True when <paramref name="data"/> 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 /// 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 /// 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. /// 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.
/// </summary> /// </summary>
internal static bool IsDamaged(ReadOnlyMemory<byte> data) internal static bool IsDamaged(ReadOnlyMemory<byte> 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; return false;
} }
@@ -114,7 +118,7 @@ internal static class ImageDecoding
/// <summary> /// <summary>
/// Bytes read first by <see cref="ReadSize(Stream)"/> for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is /// Bytes read first by <see cref="ReadSize(Stream)"/> 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 /// 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 (<see cref="HeifDecoder.ReadInfo"/>), never its pictures.
/// </summary> /// </summary>
internal const int HeaderBytes = 256 * 1024; internal const int HeaderBytes = 256 * 1024;
@@ -138,8 +142,23 @@ internal static class ImageDecoding
return ReadSize(ReadAll(stream)); return ReadSize(ReadAll(stream));
} }
var start = stream.Position;
var data = new byte[HeaderBytes]; var data = new byte[HeaderBytes];
stream.ReadExactly(data); 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)) 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 // PNG keeps metadata (eXIf) anywhere before IEND and checks every chunk, WebP refuses a RIFF that runs
+244 -164
View File
@@ -1,6 +1,9 @@
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Numerics;
using Febe.Core.Codecs;
using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264; using Febe.Core.Codecs.H264;
using Febe.Core.Codecs.H265;
namespace Febe.Core.Library; namespace Febe.Core.Library;
@@ -51,9 +54,9 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff
/// <summary> /// <summary>
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover): /// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
/// the container readers of <see cref="ContainerReader"/> and the H.264 decoder written in house /// the container readers of <see cref="ContainerReader"/> and the H.264 and HEVC decoders written in house
/// (<see cref="H264Decoder"/>). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the /// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
/// neutral tile. /// interface shows the neutral tile.
/// </summary> /// </summary>
public sealed class VideoFrameDecoder public sealed class VideoFrameDecoder
{ {
@@ -179,8 +182,10 @@ public sealed class VideoFrameDecoder
target = start; target = start;
} }
var frames = decoding.Decode([target], ct); // The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
if (!frames.TryGetValue(target, out var frame) && target != 0) // 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 = new Decoding(stream, video, maxRun).Decode([0], ct);
frames.TryGetValue(0, out frame); 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 private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or H265Exception or IOException
or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException or InvalidOperationException or EndOfStreamException or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException
or OverflowException or InvalidDataException; or InvalidOperationException or OverflowException or InvalidDataException;
/// <summary>The H.264 video track of a container with its samples; null for other codecs or without video.</summary> /// <summary>The H.264 or HEVC video track of a container with its samples; null for other codecs or without video.</summary>
private static VideoTrack? Open(Stream stream) private static VideoTrack? Open(Stream stream)
{ {
// The creation time does not matter here: any date is accepted (the readers add a day to «now»). // 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); var container = ContainerReader.Read(stream, AnyDate, samples: true);
return container?.Video is { Codec: VideoCodec.H264, Samples.Count: > 0 } video return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
&& (video.AnnexB || video.AvcConfiguration is not null) {
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
_ => false,
}
? video ? video
: null; : null;
} }
@@ -342,15 +351,98 @@ public sealed class VideoFrameDecoder
return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys]; return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys];
} }
/// <summary>Where decoding can start, whatever the codec.</summary>
private enum StartPoint
{
/// <summary>Decoding cannot start here.</summary>
None,
/// <summary>Close: an H.264 picture of I slices that is not IDR, an HEVC CRA picture (its RASL pictures are lost).</summary>
Intra,
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
Idr,
}
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
private static int LengthSize(VideoTrack video)
{
if (video.AnnexB)
{
return 0;
}
return video.Codec == VideoCodec.Hevc
? video.HevcConfiguration is { Length: > 21 } hvcC ? (hvcC[21] & 3) + 1 : 4
: video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4;
}
/// <summary>A decoded frame of either codec.</summary>
private sealed class Frame(H264Frame? avc, H265Frame? hevc)
{
internal H264Frame? Avc { get; } = avc;
internal H265Frame? Hevc { get; } = hevc;
}
/// <summary>The decoder of the track's codec, configured from its configuration record.</summary>
private sealed class Runner
{
private readonly H264Decoder? avc;
private readonly H265Decoder? hevc;
private readonly int lengthSize;
internal Runner(VideoTrack video, Func<bool> wanted, Action<Frame> found)
{
if (video.Codec == VideoCodec.Hevc)
{
hevc = new H265Decoder { Wanted = _ => wanted() };
hevc.FrameDecoded += frame => found(new Frame(null, frame));
lengthSize = video.AnnexB ? 0 : hevc.ConfigureHvcC(video.HevcConfiguration);
}
else
{
// 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<byte> sample)
{
if (hevc is not null)
{
if (lengthSize == 0)
{
hevc.DecodeAccessUnitAnnexB(sample);
}
else
{
hevc.DecodeSample(sample, lengthSize);
}
}
else if (lengthSize == 0)
{
avc!.DecodeAccessUnitAnnexB(sample);
}
else
{
avc!.DecodeSample(sample, lengthSize);
}
}
}
/// <summary> /// <summary>
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
/// </summary> /// </summary>
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun) private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
{ {
private readonly Dictionary<int, H264Frame> found = []; private readonly Dictionary<int, Frame> found = [];
private readonly HashSet<int> wanted = []; private readonly HashSet<int> wanted = [];
private readonly int[] keys = KeyIndices(video); private readonly int[] keys = KeyIndices(video);
private readonly Dictionary<int, H264AccessPoint> accessPoints = []; private readonly Dictionary<int, StartPoint> accessPoints = [];
private readonly int lengthSize = LengthSize(video);
private byte[] buffer = new byte[64 * 1024]; private byte[] buffer = new byte[64 * 1024];
/// <summary>The sample being decoded: the picture it finishes is that sample's frame.</summary> /// <summary>The sample being decoded: the picture it finishes is that sample's frame.</summary>
@@ -360,9 +452,9 @@ public sealed class VideoFrameDecoder
/// The sample where decoding for <paramref name="index"/> starts. A container without an index (an AVI cut short, /// The sample where decoding for <paramref name="index"/> starts. A container without an index (an AVI cut short,
/// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give /// 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 /// 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 /// exact start (an IDR picture, or an HEVC BLA picture) is taken when it is within the run limit (the frame comes
/// picture of I slices (close, though pictures after it may refer to earlier ones); otherwise the IDR picture /// out exact); otherwise the nearest close one (an H.264 picture of I slices, an HEVC CRA picture: close, though
/// further back, or the first sample. /// pictures after it may refer to earlier ones); otherwise the exact start further back, or the first sample.
/// </summary> /// </summary>
internal int RunStart(int index) internal int RunStart(int index)
{ {
@@ -378,91 +470,91 @@ public sealed class VideoFrameDecoder
accessPoints[candidate] = point; accessPoints[candidate] = point;
} }
if (point == H264AccessPoint.Idr) if (point == StartPoint.Idr)
{ {
return index - candidate <= maxRun || intra < 0 ? candidate : intra; return index - candidate <= maxRun || intra < 0 ? candidate : intra;
} }
if (point == H264AccessPoint.IntraPicture && intra < 0) if (point == StartPoint.Intra && intra < 0)
{ {
intra = candidate; intra = candidate;
} }
if (index - candidate > maxRun && intra >= 0) 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; return index <= maxRun || intra < 0 ? 0 : intra;
} }
private H264AccessPoint AccessPointOf(int index) private StartPoint AccessPointOf(int index)
{ {
try try
{ {
var sample = ContainerReader.ReadSample(stream, video.Samples[index], ref buffer); 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; if (video.Codec == VideoCodec.Hevc)
return H264Decoder.AccessPoint(sample, lengthSize); {
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) catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException)
{ {
return H264AccessPoint.None; return StartPoint.None;
} }
} }
internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct) internal Dictionary<int, Frame> Decode(int[] targets, CancellationToken ct)
{ {
foreach (var t in targets) foreach (var t in targets)
{ {
wanted.Add(t); wanted.Add(t);
} }
H264Decoder? decoder = null; Runner? runner = null;
var next = 0; var next = 0;
var lengthSize = 4;
foreach (var target in targets) foreach (var target in targets)
{ {
var key = RunStart(target); 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 runner = null;
// 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);
next = key; next = key;
} }
try try
{ {
if (next == key && !video.AnnexB) // 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
lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration); // the frames after it.
} runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
for (; next <= target; next++) for (; next <= target; next++)
{ {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
current = next; current = next;
var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer); runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer));
if (video.AnnexB)
{
decoder.DecodeAccessUnitAnnexB(sample);
}
else
{
decoder.DecodeSample(sample, lengthSize);
}
} }
} }
catch (Exception ex) when (ex is H264Exception or ContainerException or EndOfStreamException or IndexOutOfRangeException catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or ArgumentException or InvalidOperationException) 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 // 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. // 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
} }
} }
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
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));
/// <summary> /// <summary>
/// A coarse grid of mean luma and chroma values, to compare frames without their compression noise; values on the /// The grid on an 8-bit scale: luma means in the first half, mean distances of the chroma from its middle in the
/// 8-bit scale whatever the bit depth, the chroma at any sampling (its own grid over its own plane). /// second (zero for a monochrome picture).
/// </summary> /// </summary>
private static double[] Grid(H264Frame frame) private static double[] Grid<T>(in YuvPlanes<T> frame)
where T : unmanaged, IBinaryInteger<T>
{ {
var grid = new double[GridSize * GridSize * 2]; var grid = new double[GridSize * GridSize * 2];
var counts = new int[GridSize * GridSize]; var counts = new int[GridSize * GridSize];
var wide = frame.BytesPerSample == 2; var lumaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthY - 8));
ReadOnlySpan<ushort> y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Y) : default; ReadOnlySpan<T> luma = frame.Y;
var lumaShift = frame.BitDepthLuma - 8;
for (var y = 0; y < frame.Height; y++) for (var y = 0; y < frame.Height; y++)
{ {
var gy = y * GridSize / frame.Height; var gy = y * GridSize / frame.Height;
var start = y * frame.Width; var row = luma.Slice(y * frame.Width, frame.Width);
for (var x = 0; x < frame.Width; x++) for (var x = 0; x < row.Length; x++)
{ {
var cell = (gy * GridSize) + (x * GridSize / frame.Width); 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]++; counts[cell]++;
} }
} }
var cw = frame.ChromaWidth;
var ch = frame.ChromaHeight;
ReadOnlySpan<ushort> cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cb) : default;
ReadOnlySpan<ushort> cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cr) : default;
var chromaShift = frame.BitDepthChroma - 8;
var middle = 1 << (frame.BitDepthChroma - 1);
var chromaCounts = new int[GridSize * GridSize]; var chromaCounts = new int[GridSize * GridSize];
for (var y = 0; y < ch; y++) if (!frame.Monochrome)
{ {
var gy = y * GridSize / ch; var cw = frame.ChromaWidth;
for (var x = 0; x < cw; x++) var ch = (frame.Height + (1 << frame.ChromaShiftY) - 1) >> frame.ChromaShiftY;
var middle = 1 << (frame.BitDepthC - 1);
var chromaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthC - 8)) / 2;
ReadOnlySpan<T> cb = frame.Cb, cr = frame.Cr;
for (var y = 0; y < ch; y++)
{ {
var cell = (gy * GridSize) + (x * GridSize / cw); var gy = y * GridSize / ch;
var i = (y * cw) + x; for (var x = 0; x < cw; x++)
int u, v;
if (wide)
{ {
u = Math.Abs(cb16[i] - middle) >> chromaShift; var cell = (gy * GridSize) + (x * GridSize / cw);
v = Math.Abs(cr16[i] - middle) >> chromaShift; 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
} }
/// <summary> /// <summary>
/// The frame in RGB: BT.709, BT.601 or BT.2020 coefficients as the stream says (unspecified: BT.709 from 720 lines /// The planes of an H.264 frame of 8-bit samples, at any chroma sampling. A monochrome frame comes with grey 4:2:0
/// 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 planes (<see cref="H264Frame"/>), which the conversion does not read.
/// 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 <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary> /// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) private static YuvPlanes<byte> Planes(H264Frame frame)
{ {
var (kr, kb) = frame.MatrixCoefficients switch 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);
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);
/// <summary>
/// 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.
/// </summary>
private static YuvPlanes<ushort> 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);
}
/// <summary>Chroma subsampling of chroma_format_idc (0, monochrome, as 4:2:0: the planes H.264 gives it are that size).</summary>
private static (int X, int Y) ChromaShifts(int chromaFormat) => chromaFormat switch
{
0 or 1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
private static YuvPlanes<ushort> Planes(H265Frame frame)
{
var (sx, sy) = frame.ChromaFormat switch
{
1 => (1, 1),
2 => (1, 0),
_ => (0, 0),
};
return new(frame.Y, frame.Cb, frame.Cr, frame.Width, frame.Height, sx, sy, frame.ChromaFormat == 0, frame.BitDepthLuma, frame.BitDepthChroma);
}
private static VideoImage ToImage(Frame frame, int rotation, int maxLongSide) =>
frame.Hevc is { } h ? ToImage(h, rotation, maxLongSide) : ToImage(frame.Avc!, rotation, maxLongSide);
/// <summary>
/// The frame in RGB: BT.709 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited
/// or full range, reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) =>
frame.BytesPerSample == 2
? ToImage(WidePlanes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide)
: ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
/// <summary>
/// An HEVC frame in RGB, as <see cref="ToImage(H264Frame, int, int)"/>: any chroma format (4:0:0 in grey) and bit
/// depth, brought to 8 bits.
/// </summary>
internal static VideoImage ToImage(H265Frame frame, int rotation, int maxLongSide) =>
ToImage(Planes(frame), frame.MatrixCoefficients, frame.FullRange, rotation, maxLongSide);
private static VideoImage ToImage<T>(in YuvPlanes<T> planes, int matrix, bool fullRange, int rotation, int maxLongSide)
where T : unmanaged, IBinaryInteger<T>
{
var factor = 1; var factor = 1;
if (maxLongSide > 0) 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); factor = Math.Max(1, (longSide + maxLongSide - 1) / maxLongSide);
} }
var width = Math.Max(1, frame.Width / factor); var width = Math.Max(1, planes.Width / factor);
var height = Math.Max(1, frame.Height / 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 rgb = new byte[width * height * 3];
var cw = frame.ChromaWidth; var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
var shiftX = frame.ChromaFormat == 3 ? 0 : 1; YuvToRgb.Convert(planes, k, factor, rgb, width * 3, 3, width, height);
var shiftY = frame.ChromaFormat is 2 or 3 ? 0 : 1;
var wide = frame.BytesPerSample == 2;
ReadOnlySpan<ushort> y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Y) : default;
ReadOnlySpan<ushort> cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cb) : default;
ReadOnlySpan<ushort> cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(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);
}
}
return Rotate(new VideoImage(width, height, rgb), rotation); 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) private static VideoImage Rotate(VideoImage image, int rotation)
{ {
rotation = ((rotation % 360) + 360) % 360; rotation = ((rotation % 360) + 360) % 360;
+1
View File
@@ -20,6 +20,7 @@
<ItemGroup> <ItemGroup>
<None Include="campioni\**\*" CopyToOutputDirectory="PreserveNewest" /> <None Include="campioni\**\*" CopyToOutputDirectory="PreserveNewest" />
<None Include="Media\H264\Conformita\**\*" CopyToOutputDirectory="PreserveNewest" /> <None Include="Media\H264\Conformita\**\*" CopyToOutputDirectory="PreserveNewest" />
<None Include="Media\H265\Conformita\**\*" CopyToOutputDirectory="PreserveNewest" />
<!-- Immagini di riferimento dei codec di casa (Imaging/Riferimenti/LEGGIMI.md). --> <!-- Immagini di riferimento dei codec di casa (Imaging/Riferimenti/LEGGIMI.md). -->
<None Include="Imaging\Riferimenti\**\*" CopyToOutputDirectory="PreserveNewest" /> <None Include="Imaging\Riferimenti\**\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup> </ItemGroup>
+2 -1
View File
@@ -126,6 +126,7 @@ public sealed class ImagingBaseTests
Assert.Contains("TIFF", error.Message); Assert.Contains("TIFF", error.Message);
Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => ImageDecoder.Identify(Encoding.ASCII.GetBytes("testo qualsiasi"))); Assert.ThrowsExactly<ImageFormatNotSupportedException>(() => 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.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));
} }
} }
@@ -29,7 +29,7 @@ public sealed class DamagedImageTests
Assert.IsFalse(DamagedImage.IsDamaged(ReadOnlyMemory<byte>.Empty)); Assert.IsFalse(DamagedImage.IsDamaged(ReadOnlyMemory<byte>.Empty));
Assert.IsFalse(DamagedImage.IsDamaged(new byte[100]), "un formato sconosciuto"); 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]]; 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] [TestMethod]
@@ -0,0 +1,150 @@
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H265;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// HEVC videos through the containers and the frame decoder: the test videos are built from streams of the ITU-T H.265.1
/// set, so the frame expected is the one the decoder gives straight from the stream (itself bit exact on those streams).
/// </summary>
[TestClass]
public sealed class HevcVideoTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero);
/// <summary>416×240, 8 bit, 60 frames shown in another order than they are decoded.</summary>
private const string Moving = "INITQP_A_Sony_1";
[TestMethod]
[DataRow("mp4")]
[DataRow("mkv")]
[DataRow("avi")]
[DataRow("frammentato.mp4")]
[DataRow("senza-indice.avi")]
[DataRow("senza-indice-con-parametri.avi")]
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.IsTrue(es.Rank.Where((r, i) => r != i).Any(), "il flusso deve riordinare i fotogrammi");
using var temp = new TempFolder("fotogramma-hevc");
var data = kind switch
{
"mkv" => TestVideos.Matroska(es),
"avi" => TestVideos.Avi(es),
"senza-indice.avi" => TestVideos.Avi(es, index: false),
"senza-indice-con-parametri.avi" => TestVideos.Avi(es.WithParameterSetsEverywhere(), index: false),
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
_ => TestVideos.Mp4(es),
};
var path = TestVideos.Write(temp, "video." + kind, data);
var container = ContainerReader.ReadFile(path, Now);
Assert.AreEqual(VideoCodec.Hevc, container!.Video!.Codec);
Assert.AreEqual(kind.EndsWith("avi", StringComparison.Ordinal), container.Video.AnnexB);
if (!container.Video.AnnexB)
{
CollectionAssert.AreEqual(es.AvcC, container.Video.HevcConfiguration, "hvcC del contenitore");
}
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
Assert.IsNotNull(image);
// AVI has no presentation times: there frames are shown in decoding order.
var position = Math.Min(30, es.Count - 1);
var rank = kind.EndsWith("avi", StringComparison.Ordinal) ? es.Rank[position] : position;
var reference = VideoFrameDecoder.ToImage(Shown(Moving)[rank], 0, 0);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
}
[TestMethod]
[DataRow("INITQP_B_Main10_Sony_1")]
[DataRow("WPP_B_ericsson_MAIN10_2")]
public async Task Main10VideosGiveTheirFrame(string name)
{
var es = ElementaryStream.LoadHevc(name);
using var temp = new TempFolder("fotogramma-hevc-10");
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 270));
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero);
Assert.IsNotNull(image);
var reference = VideoFrameDecoder.ToImage(Shown(name)[0], 270, 0);
Assert.AreEqual(10, Shown(name)[0].BitDepthLuma);
Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height));
Assert.AreEqual((es.Height, es.Width), (image.Width, image.Height), "ruotato di un quarto");
CollectionAssert.AreEqual(reference.Rgb, image.Rgb);
var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path);
Assert.IsNotNull(bmp);
Assert.AreEqual((byte)'B', bmp[0]);
}
[TestMethod]
public async Task AnHevcVideoOfAStillPictureIsRecognisedAndOneThatMovesIsNot()
{
var es = ElementaryStream.LoadHevc(Moving);
using var temp = new TempFolder("fermo-hevc");
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsStill);
Assert.AreEqual(0, result.Difference);
var moving = TestVideos.Write(temp, "movimento.mkv", TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4")));
var other = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(moving);
Assert.IsNotNull(other);
Assert.IsFalse(other.IsStill, $"differenza {other.Difference}");
}
[TestMethod]
public void AccessPointsAreTheIrapPictures()
{
var es = ElementaryStream.LoadHevc(Moving);
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.LengthPrefixed(0), 4));
Assert.AreEqual(H265AccessPoint.Idr, H265Decoder.AccessPoint(es.WithStartCodes(0), 0));
var inter = Enumerable.Range(0, es.Count).First(i => !es.Key[i]);
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint(es.LengthPrefixed(inter), 4));
// A CRA picture (NAL unit type 21): decoding starts there, its RASL pictures are lost.
byte[] cra = [0, 0, 0, 3, 21 << 1, 1, 0x80];
Assert.AreEqual(H265AccessPoint.Cra, H265Decoder.AccessPoint(cra, 4));
Assert.AreEqual(H265AccessPoint.None, H265Decoder.AccessPoint([0, 0, 0, 2, 34 << 1, 1], 4), "solo parametri");
}
[TestMethod]
public void TenBitFramesAndOtherChromaFormatsBecomeTheRightColours()
{
static H265Frame Flat(ushort y, ushort c, int format, int bits, int matrix, bool full)
{
var chroma = format == 0 ? 0 : format == 3 ? 4 : format == 2 ? 2 : 1;
return new(2, 2, format, bits, bits, [y, y, y, y], [.. Enumerable.Repeat(c, chroma)], [.. Enumerable.Repeat(c, chroma)], 0, 0, matrix, full);
}
// Limited range at 10 bits: 64 is black, 940 white.
CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 1, 10, 1, false), 0, 0).Rgb[..3]);
// The same grey at 8, 10 and 12 bits, in every chroma format (4:0:0 has no chroma at all).
var grey = VideoFrameDecoder.ToImage(Flat(128, 128, 1, 8, 6, true), 0, 0).Rgb;
foreach (var format in new[] { 0, 1, 2, 3 })
{
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(512, 512, format, 10, 6, true), 0, 0).Rgb, $"formato {format}");
CollectionAssert.AreEqual(grey, VideoFrameDecoder.ToImage(Flat(2048, 2048, format, 12, 6, true), 0, 0).Rgb, $"formato {format}, 12 bit");
}
// Pure red of BT.601 at 10 bits (limited range): Y 324, Cb 360, Cr 960.
var red = VideoFrameDecoder.ToImage(new H265Frame(2, 2, 1, 10, 10, [324, 324, 324, 324], [360], [960], 0, 0, 6, false), 0, 0).Rgb;
Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}");
}
/// <summary>The frames of a conformance stream in output order, decoded straight from its Annex B form.</summary>
private static List<H265Frame> Shown(string name)
{
var frames = new List<H265Frame>();
var decoder = new H265Decoder();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(name).BitstreamPath));
return frames;
}
}
@@ -275,6 +275,24 @@ public sealed class LegacyContainerTests
Assert.IsNull(container.Audio); 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] [TestMethod]
public void TheEndOfALongProgramStreamGivesItsDuration() public void TheEndOfALongProgramStreamGivesItsDuration()
{ {
@@ -25,7 +25,7 @@ internal sealed record AsfOptions
/// <summary>What a test MPEG program stream holds.</summary> /// <summary>What a test MPEG program stream holds.</summary>
internal sealed record PsOptions internal sealed record PsOptions
{ {
/// <summary>«mpeg2», «mpeg1» or «h264» (then <see cref="Stream"/> gives the pictures).</summary> /// <summary>«mpeg2», «mpeg1», «h264» or «hevc» (for these two <see cref="Stream"/> gives the pictures).</summary>
public string Video { get; init; } = "mpeg2"; public string Video { get; init; } = "mpeg2";
public int Width { get; init; } = 720; public int Width { get; init; } = 720;
public int Height { get; init; } = 576; 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 /// 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. /// 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 /// 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 <see cref="PsOptions.Stream"/>. /// and filler slice bytes; H.264 and HEVC pictures are the access units of <see cref="PsOptions.Stream"/>.
/// </summary> /// </summary>
public static byte[] MpegPs(PsOptions o) public static byte[] MpegPs(PsOptions o)
{ {
var random = new Random(o.Seed); var random = new Random(o.Seed);
var frameTicks = o.Video == "h264" ? 3000 : 3600; // 30 or 25 pictures a second var coded = o.Video is "h264" or "hevc";
var frames = o.Video == "h264" ? o.Stream!.Count : o.Frames; var frameTicks = coded ? 3000 : 3600; // 30 or 25 pictures a second
var frames = coded ? o.Stream!.Count : o.Frames;
using var output = new MemoryStream(); using var output = new MemoryStream();
var audioTime = o.FirstPts; var audioTime = o.FirstPts;
for (var i = 0; i < frames; i++) 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]); output.Write([0, 0, 1, 0xBB, 0, 12, 0x80, 0x00, 0x01, 0x04, 0xE1, 0xFF, 0xE0, 0xE0, 0xE8, 0xC0, 0xC0, 0x20]);
if (o.StreamMap) 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[] map = [videoType, 0xE0, 0, 0, 0x04, 0xC0, 0, 0];
byte[] body = [0x80, 0x01, 0, 0, .. U16((ushort)map.Length), .. map, 0, 0, 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]); 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) for (var offset = 0; offset < picture.Length; offset += 2000)
{ {
var chunk = picture.AsSpan(offset, Math.Min(2000, picture.Length - offset)).ToArray(); var chunk = picture.AsSpan(offset, Math.Min(2000, picture.Length - offset)).ToArray();
@@ -25,6 +25,8 @@ public sealed class MalformedInputTests
[DataRow("flv")] [DataRow("flv")]
[DataRow("mpg")] [DataRow("mpg")]
[DataRow("h264.mpg")] [DataRow("h264.mpg")]
[DataRow("hevc.mp4")]
[DataRow("hevc.mkv")]
public void TruncatedFilesNeverBreakTheReaders(string kind) public void TruncatedFilesNeverBreakTheReaders(string kind)
{ {
var file = Build(kind); var file = Build(kind);
@@ -62,6 +64,9 @@ public sealed class MalformedInputTests
[DataRow("wmv", 5815)] [DataRow("wmv", 5815)]
[DataRow("flv", 5816)] [DataRow("flv", 5816)]
[DataRow("mpg", 5817)] [DataRow("mpg", 5817)]
[DataRow("hevc.mp4", 5815)]
[DataRow("hevc.mkv", 5816)]
[DataRow("hevc.avi", 5817)]
public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed) public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed)
{ {
var file = Build(kind); var file = Build(kind);
@@ -313,7 +318,10 @@ public sealed class MalformedInputTests
private static byte[] Build(string kind) 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 return kind switch
{ {
"frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true), "frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true),
+69 -12
View File
@@ -13,7 +13,7 @@ namespace Febe.Tests.Codecs.Containers;
/// </summary> /// </summary>
internal sealed class ElementaryStream internal sealed class ElementaryStream
{ {
private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height) private ElementaryStream(string name, List<List<byte[]>> units, int[] rank, bool[] key, byte[] avcC, int width, int height, bool hevc = false)
{ {
Name = name; Name = name;
Units = units; Units = units;
@@ -22,10 +22,14 @@ internal sealed class ElementaryStream
AvcC = avcC; AvcC = avcC;
Width = width; Width = width;
Height = height; Height = height;
Hevc = hevc;
} }
public string Name { get; } public string Name { get; }
/// <summary>An HEVC stream (of the H.265.1 set): then <see cref="AvcC"/> holds its <c>hvcC</c> record.</summary>
public bool Hevc { get; }
/// <summary>The NAL units (without start codes) of each access unit, in decoding order.</summary> /// <summary>The NAL units (without start codes) of each access unit, in decoding order.</summary>
public List<List<byte[]>> Units { get; } public List<List<byte[]>> Units { get; }
@@ -119,22 +123,74 @@ internal sealed class ElementaryStream
return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height); return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height);
} }
/// <summary>
/// An HEVC stream of the H.265.1 set cut into access units (§7.4.2.4.4: parameter sets, delimiters and prefix SEI
/// open the next one), with an <c>hvcC</c> record of its VPS, SPS and PPS. Every access unit must give one output
/// frame: streams with skipped RASL pictures or pic_output_flag 0 do not fit.
/// </summary>
public static ElementaryStream LoadHevc(string name)
{
var annexB = File.ReadAllBytes(H265.H265ConformanceStream.Load(name).BitstreamPath);
var units = new List<List<byte[]>>();
List<byte[]>? current = null;
var hasSlice = false;
foreach (var nal in SplitAnnexB(annexB))
{
var type = (nal[0] >> 1) & 63;
var startsPicture = type < 32 && nal.Length > 2 && (nal[2] & 0x80) != 0; // first_slice_segment_in_pic_flag
var beforePicture = type is (>= 32 and <= 35) or 39 or (>= 41 and <= 44) or (>= 48 and <= 55);
if (current is null || (hasSlice && (startsPicture || beforePicture)))
{
current = [];
units.Add(current);
hasSlice = false;
}
current.Add(nal);
hasSlice |= type < 32;
}
var key = units.Select(u => u.Any(n => ((n[0] >> 1) & 63) is >= 16 and <= 23)).ToArray();
var decoder = new Febe.Core.Codecs.H265.H265Decoder();
var frames = new List<Febe.Core.Codecs.H265.H265Frame>();
decoder.FrameOutput += frames.Add;
decoder.DecodeAnnexB(annexB);
Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi");
var rank = new int[frames.Count];
for (var i = 0; i < frames.Count; i++)
{
rank[frames[i].DecodeIndex] = i; // FrameOutput comes in output order
}
var sets = units.SelectMany(u => u).Where(n => ((n[0] >> 1) & 63) is >= 32 and <= 34).DistinctBy(Convert.ToBase64String).ToList();
var hvcC = new List<byte>(new byte[21]) { 0xFC | 3, (byte)sets.Count };
hvcC[0] = 1;
foreach (var set in sets)
{
hvcC.AddRange([(byte)(0x80 | ((set[0] >> 1) & 63)), 0, 1, (byte)(set.Length >> 8), (byte)set.Length, .. set]);
}
return new ElementaryStream(name, units, rank, key, [.. hvcC], frames[0].Width, frames[0].Height, hevc: true);
}
private static bool IsParameterSet(byte[] nal, bool hevc) => hevc ? ((nal[0] >> 1) & 63) is >= 32 and <= 34 : (nal[0] & 0x1F) is 7 or 8;
/// <summary>The same stream with only its first access unit, repeated: a video of a still picture.</summary> /// <summary>The same stream with only its first access unit, repeated: a video of a still picture.</summary>
public ElementaryStream FirstPictureRepeated(int times) public ElementaryStream FirstPictureRepeated(int times)
{ {
var units = Enumerable.Repeat(Units[0], times).ToList(); var units = Enumerable.Repeat(Units[0], times).ToList();
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height); return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height, Hevc);
} }
/// <summary> /// <summary>
/// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a /// The same stream with its parameter sets repeated in every access unit, as some cameras and recorders write them: a
/// decoder started at any of its P or B frames finds its parameter sets. /// decoder started at any of its P or B frames finds its parameter sets.
/// </summary> /// </summary>
public ElementaryStream WithParameterSetsEverywhere() public ElementaryStream WithParameterSetsEverywhere()
{ {
var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList(); var sets = Units[0].Where(n => IsParameterSet(n, Hevc)).ToList();
var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).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); return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height, Hevc);
} }
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary> /// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
@@ -227,7 +283,8 @@ internal static class TestVideos
Width = es.Width, Width = es.Width,
Height = es.Height, Height = es.Height,
Rotation = rotation, Rotation = rotation,
AvcConfiguration = es.AvcC, AvcConfiguration = es.Hevc ? null : es.AvcC,
HevcConfiguration = es.Hevc ? es.AvcC : null,
}, },
}; };
if (audio) 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 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]), var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]),
Element(0x86, "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video); Element(0x86, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
var blocks = new List<byte[]> { Element(0xE7, [0]) }; var blocks = new List<byte[]> { Element(0xE7, [0]) };
for (var i = 0; i < es.Count; i++) for (var i = 0; i < es.Count; i++)
{ {
@@ -392,7 +449,7 @@ internal static class TestVideos
} }
var strh = new List<byte>(); var strh = new List<byte>();
strh.AddRange("vidsH264"u8.ToArray()); strh.AddRange(es.Hevc ? "vidsHEVC"u8.ToArray() : "vidsH264"u8.ToArray());
foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 }) foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 })
{ {
strh.AddRange(Le32(v)); strh.AddRange(Le32(v));
@@ -406,7 +463,7 @@ internal static class TestVideos
} }
strf.AddRange([1, 0, 24, 0]); 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]); strf.AddRange(new byte[20]);
var hdrl = new List<byte[]> { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) }; var hdrl = new List<byte[]> { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) };
if (idit is not null) if (idit is not null)
@@ -445,9 +502,9 @@ internal static class TestVideos
return path; 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), [.. 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) private static byte[] Box(string type, params byte[][] children)
{ {
@@ -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.
@@ -0,0 +1,2 @@
# ADJUST_IPRED_ANGLE_A_RExt_Mitsubishi_2.yuv 1920x1080 4:2:2 10 bit, 3 fotogrammi, 24883200 byte
tutto b045776950c2e06d35348bd03268c07f
@@ -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.
@@ -0,0 +1,2 @@
# AMP_A_Samsung_7.yuv 2560x1600 4:2:0 8 bit, 17 fotogrammi, 104448000 byte
tutto 93a5875d58072db5539c04e1e943ed9d
@@ -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.
@@ -0,0 +1,2 @@
# AMP_B_Samsung_7.yuv 2560x1600 4:2:0 8 bit, 17 fotogrammi, 104448000 byte
tutto 4e051fad4145d5127e16ac2999500069
@@ -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).
@@ -0,0 +1,2 @@
# AMVP_A_MTK_4.yuv 416x240 4:2:0 8 bit, 30 fotogrammi, 4492800 byte
tutto 5dd1b1099391ad659225fbf94965a6c7
@@ -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.
@@ -0,0 +1,2 @@
# AMVP_B_MTK_4.yuv 416x240 4:2:0 8 bit, 41 fotogrammi, 6140160 byte
tutto 7fecb4fe8ee4d4838f4a9873b062b819
@@ -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.
@@ -0,0 +1,2 @@
# AMVP_C_Samsung_7.yuv 832x480 4:2:0 8 bit, 60 fotogrammi, 35942400 byte
tutto 75155ad034919a2846bbdcba13b5f733
@@ -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.
@@ -0,0 +1,2 @@
# BUMPING_A_ericsson_1.yuv 416x240 4:2:0 8 bit, 49 fotogrammi, 7338240 byte
tutto 64f213eb1cf45614f0eeb50fd1b725bf
@@ -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
@@ -0,0 +1,2 @@
# Bitdepth_A_RExt_Sony_1.yuv 1920x1080 4:4:4 12/8 bit, 16 fotogrammi, 199065600 byte
tutto 2b65fa2f384085926deb4f9d20fcd798
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_A_SHARP_4.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto 550c5a918fecda6a284aa5f44c0e2f33
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_B_SHARP_4.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto 0c633f8ee5a4c5779cff48ca86273685
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_C_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto 9c6c5363724a8bad54e2869b655fbf3b
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_D_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto 0231e327044e45971fc30a43a1bd8275
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_E_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto 55af76d5527af999d12ccc37b1f6b7ae
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_F_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto 88d8cd2d303b662f0a92a25256957b69
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_G_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto a7036eac7798f6e8691f0975786d6811
@@ -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
@@ -0,0 +1,2 @@
# CAINIT_H_SHARP_3.yuv 832x480 4:2:0 8 bit, 50 fotogrammi, 29952000 byte
tutto cfdd3ce0f4cf1eafd012dcb266311d06
@@ -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
@@ -0,0 +1,2 @@
# CCP_8bit_RExt_QCOM.yuv 1280x720 4:4:4 8 bit, 9 fotogrammi, 24883200 byte
tutto 54231c6f121ca65d8b94a747b9504b8b
@@ -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
@@ -0,0 +1,2 @@
# CIP_A_Panasonic_3.yuv 416x240 4:2:0 8 bit, 2 fotogrammi, 299520 byte
tutto 4cbf601ba98d63f642defab5eaa12c8d
@@ -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
@@ -0,0 +1,2 @@
# CIP_C_Panasonic_2.yuv 416x240 4:2:0 8 bit, 2 fotogrammi, 299520 byte
tutto ed985932fef2aa8a74ded970070bdab2
Loaded 100 of 491 files, more files were not shown because too many files have changed in this diff. Show more