diff --git a/.gitea/scripts/ambiente-prove.sh b/.gitea/scripts/ambiente-prove.sh index ece19fc..d7c0f47 100755 --- a/.gitea/scripts/ambiente-prove.sh +++ b/.gitea/scripts/ambiente-prove.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché # nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le -# sue lingue, Xvfb, ffmpeg e ffprobe, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi +# sue lingue, Xvfb, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi # caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody # (65534) vengono con Debian (prove dell'avvio del contenitore). # @@ -16,7 +16,6 @@ $sudo apt-get update -qq $sudo apt-get install -y -qq --no-install-recommends \ chromium chromium-l10n \ xvfb \ - ffmpeg \ nsis zip \ locales tzdata libicu76 ca-certificates \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ @@ -27,8 +26,6 @@ $sudo locale-gen > /dev/null echo "== Strumenti delle prove" chromium --version command -v Xvfb -ffmpeg -version | head -n 1 || true -ffprobe -version | head -n 1 || true echo "makensis $(makensis -VERSION)" echo "node $(node --version)" locale -a | grep -i '^it_IT\.utf8$' diff --git a/.gitea/scripts/riepilogo-prove.sh b/.gitea/scripts/riepilogo-prove.sh index a5ab3bd..f7be7e3 100755 --- a/.gitea/scripts/riepilogo-prove.sh +++ b/.gitea/scripts/riepilogo-prove.sh @@ -6,7 +6,10 @@ # .gitea/scripts/riepilogo-prove.sh [saltate ammesse] # # Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono -# Chromium, Xvfb, ffmpeg, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. +# Chromium, Xvfb, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. Fa eccezione +# solo la categoria «da fare»: le inconclusive di FeaturesStillToDo (flussi di conformità H.264 delle parti che il +# decodificatore non gestisce ancora) il cui motivo comincia con «da fare: » si elencano e non contano fra le saltate. +# Qualunque altra inconclusiva, anche con «da fare: » nel messaggio, è una saltata. set -euo pipefail cartella="${1:?Indica la cartella con i file .trx.}" @@ -25,11 +28,17 @@ trap 'rm -f "$riepilogo"' EXIT fallite_totali=0 saltate_totali=0 +dafare_totali=0 +# «Da fare»: una inconclusiva di FeaturesStillToDo il cui motivo comincia con «da fare: » subito dopo la cornice di MSTest +# («Assert.Inconclusive. », «Assert.Inconclusive failed. », «Assert.Inconclusive non riuscito. »): segna una parte non +# ancora scritta, non un ambiente rotto, e si conta a parte. Il nome della prova e l'inizio del motivo sono entrambi +# vincolati: nessun'altra prova può saltarsi in silenzio scrivendo «da fare: » nel messaggio. +da_fare='$1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" && $2 ~ /^FeaturesStillToDo( |\(|$)/ && $3 ~ /^Assert\.Inconclusive[^.]*\. *da fare: /' { echo "### Prove" echo - echo "| Risultati | Totale | Superate | Fallite | Saltate |" - echo "|---|---:|---:|---:|---:|" + echo "| Risultati | Totale | Superate | Fallite | Saltate | Da fare |" + echo "|---|---:|---:|---:|---:|---:|" } > "$riepilogo" for trx in "${file[@]}"; do @@ -57,18 +66,20 @@ for trx in "${file[@]}"; do printf "%s\t%s\t%s\n", attributo(testata, "outcome"), testo_xml(attributo(testata, "testName")), testo_xml(messaggio) }')" - totale=0; superate=0; fallite=0; saltate=0 + totale=0; superate=0; fallite=0; saltate=0; dafare=0 if [[ -n "$righe" ]]; then totale=$(printf '%s\n' "$righe" | wc -l) superate=$(printf '%s\n' "$righe" | awk -F'\t' '$1 == "Passed"' | wc -l) fallite=$(printf '%s\n' "$righe" | awk -F'\t' '$1 == "Failed" || $1 == "Error" || $1 == "Timeout" || $1 == "Aborted"' | wc -l) + dafare=$(printf '%s\n' "$righe" | awk -F'\t' "$da_fare" | wc -l) fi - saltate=$((totale - superate - fallite)) + saltate=$((totale - superate - fallite - dafare)) fallite_totali=$((fallite_totali + fallite)) saltate_totali=$((saltate_totali + saltate)) + dafare_totali=$((dafare_totali + dafare)) - echo "== $nome: totale $totale · superate $superate · fallite $fallite · saltate $saltate" - echo "| \`$nome\` | $totale | $superate | $fallite | $saltate |" >> "$riepilogo" + echo "== $nome: totale $totale · superate $superate · fallite $fallite · saltate $saltate · da fare $dafare" + echo "| \`$nome\` | $totale | $superate | $fallite | $saltate | $dafare |" >> "$riepilogo" if (( fallite > 0 )); then echo " Fallite:" @@ -80,23 +91,29 @@ for trx in "${file[@]}"; do if (( saltate > 0 )); then echo " Saltate, per motivo:" # Il motivo senza la cornice di MSTest («Il metodo … ha generato un'eccezione. Assert.Inconclusive.»). - printf '%s\n' "$righe" | awk -F'\t' '$1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" { + printf '%s\n' "$righe" | awk -F'\t' "!($da_fare)"' && $1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" { m = $3; sub(/^.*Assert\.Inconclusive\. */, "", m); if (m == "") m = "(nessun motivo)"; print m }' \ | sort | uniq -c | sort -rn | awk 'NR <= 30 { sub(/^ */, " "); print }' fi + + if (( dafare > 0 )); then + echo " Da fare (parti non ancora scritte, non contano come saltate):" + printf '%s\n' "$righe" | awk -F'\t' "$da_fare"' { + if (++n > 60) next; m = $3; sub(/^.*da fare: /, "da fare: ", m); print " - " m }' | sort + fi done esito=0 { echo - echo "Fallite: $fallite_totali · saltate: $saltate_totali (ammesse: $ammesse)." + echo "Fallite: $fallite_totali · saltate: $saltate_totali (ammesse: $ammesse) · da fare: $dafare_totali." } >> "$riepilogo" if (( fallite_totali > 0 )); then echo "Prove fallite: $fallite_totali (i file .trx sono fra gli artefatti dell'esecuzione)." >&2 esito=1 fi if (( saltate_totali > ammesse )); then - echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 + echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 esito=1 fi diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index 11bbd59..aa9821a 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -4,7 +4,8 @@ # soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); # prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests # (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con -# Chromium, Xvfb, ffmpeg, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi. +# Chromium, Xvfb, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi, tranne +# le «da fare» di H264ConformanceTests.FeaturesStillToDo (riepilogo-prove.sh le conta a parte). # Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di # questa esecuzione, scritto nel registro per rifare un errore; # installatore Febe-Setup--ci..exe e lo zip portabile, artefatti per 14 giorni; @@ -108,7 +109,7 @@ jobs: echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)." echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\"" - - name: Chromium, Xvfb, ffmpeg, NSIS e lingua italiana + - name: Chromium, Xvfb, NSIS e lingua italiana run: bash .gitea/scripts/ambiente-prove.sh - uses: actions/setup-dotnet@v4 diff --git a/docker/Dockerfile b/docker/Dockerfile index c416a2a..02ec824 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -14,7 +14,7 @@ # test tutte le prove: un'immagine con prove rosse non esiste. Qui non ci sono Chromium né Xvfb, quindi le prove # con il browser vero risultano «inconcludenti» (saltate) e girano solo dove ci sono (CI, sviluppo); # publish Febe.Server autosufficiente per linux-x64: nell'immagine non serve il runtime .NET; -# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ffmpeg, ICU, caratteri +# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ICU, caratteri # (anche emoji), certificati, fusi orari, lingua italiana; tini come processo 1; setpriv per PUID/PGID. # # Vedi docs/docker.md per volumi, variabili, porte, sandbox, salute e aggiornamento. @@ -74,7 +74,7 @@ LABEL org.opencontainers.image.title="Febe" \ org.opencontainers.image.source="https://gitea.encke-hake.ts.net/Alby96/Febe" \ org.opencontainers.image.url="https://gitea.encke-hake.ts.net/Alby96/Febe" -# Chromium della distribuzione con le sue lingue, il display virtuale, ffmpeg (miniature dei video importati), ICU e +# Chromium della distribuzione con le sue lingue, il display virtuale, ICU e # le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua # italiana generata, tini come processo 1 (raccoglie i processi di Chromium), setpriv (util-linux) per PUID/PGID. # Prima gli aggiornamenti di sicurezza della distribuzione già pubblicati, anche quelli arrivati dopo l'immagine di @@ -85,7 +85,6 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends \ chromium chromium-l10n \ xvfb \ - ffmpeg \ libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ ca-certificates tzdata locales \ diff --git a/docs/decisioni.md b/docs/decisioni.md index ede35f5..f757f23 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -483,4 +483,21 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Correzione della riga sulle immagini di riferimento: l'insieme è di 116 file per 2.003.752 byte (circa 2,0 MB), non «circa 2,2 MB» | Somma di `git ls-tree -l` sul ramo `funzione/codec-immagini`; la riga resta com'era perché le righe si aggiungono soltanto | | 2026-11-18 | `Febe.exe` pubblicato senza SkiaSharp (`dotnet publish` come `installer/costruisci.sh`, un file solo e compresso): 85.583.840 byte, circa 86 MB come prima | Misurato di nuovo per `docs/windows.md`; la libreria nativa di Skia, compressa nel file solo, pesava poco | | 2026-11-25 | **«File danneggiato o incompleto» nel visualizzatore** (risposta 3 di Alberto del 25 novembre; §4.6, §8.4): `MediaDto` ha `damaged`, vero per una foto sul disco senza miniatura che i codec di casa riconoscono ma non riescono a decodificare (`DamagedImage` in `Febe.Core.Library`: un errore di decodifica che non sia «formato non letto» né «troppo grande»). Il visualizzatore mostra «File danneggiato o incompleto» al posto dell'immagine, con le azioni sul file che restano; il mosaico ha già la tessera neutra (nessuna miniatura). Il controllo si fa quando il visualizzatore apre l'elemento, solo per le sue foto senza miniatura, decodificando un JPEG alla riduzione più piccola; nulla nel database. HEIC, i formati sconosciuti e le immagini oltre i limiti non sono «danneggiati». Il file si legge soltanto (§2 regola 12) | Il ramo dei codec rifiutava già le immagini troncate (niente miniatura, niente impronta, file tenuto con il suo SHA-256), ma il visualizzatore mostrava il file a metà come lo disegna il browser. Calcolarlo al volo evita una colonna e una migrazione e vale anche per le librerie già scaricate; con 200.000 elementi non pesa, perché riguarda solo le poche foto senza miniatura e solo quando si aprono. Restano da fare la revisione e il resoconto dell'importazione (§9.3) e l'anteprima della Dashboard (D1) | +| 2026-11-18 | Video senza programmi esterni: ffmpeg e ffprobe tolti dall'immagine Docker, dalla CI e dal codice. I metadati vengono dai lettori di contenitori scritti in casa (`Febe.Core.Codecs.Containers`: ISO BMFF anche frammentato, Matroska/WebM, AVI; `ContainerVideoMetadataProbe` è la sonda predefinita), i fotogrammi delle miniature dal decodificatore H.264 scritto in casa (`Febe.Core.Codecs.H264`, `VideoFrameDecoder`, BMP ruotato come il video), che dice anche se un video mostra solo un'immagine ferma; c'è uno scrittore MP4 (moov in testa) per rimpacchettare. Le tabelle CABAC sono trascritte dal testo della Raccomandazione ITU-T H.264, non a memoria; il decodificatore è provato fotogramma per fotogramma sugli MD5 dei flussi di conformità ITU-T H.264.1 | Decisione di Alberto del 18 novembre 2026 (niente componenti esterni, tutto il codice in casa). Limiti: si decodifica solo H.264 a immagini intere, 4:2:0, 8 bit; HEVC, VP9 e AV1 si leggono nei contenitori ma restano senza fotogramma (tessera neutra) | +| 2026-11-18 | Limiti dei lettori di contenitori e del decodificatore H.264 contro i file danneggiati: al più 2.000.000 di campioni per traccia, un campione al più di 64 MB, ogni tabella o elemento controllato contro la lunghezza del file prima di allocare, un SPS oltre il MaxFS del livello 6.2 (139.264 macroblocchi) o con un ritaglio che non lascia immagine rifiutato, mai più riferimenti di Max(max_num_ref_frames, 1) nel buffer. Una traccia MP4 con tabelle danneggiate o oltre il limite resta senza campioni e le altre si leggono lo stesso | I lettori leggono ogni file della libreria e delle importazioni: prima un `stsz` di pochi byte poteva chiedere 800 MB, un SPS danneggiato immagini da 16384×16384, un `trex` letto con i campi scambiati dava durate sbagliate ai video frammentati. L'audio PCM di QuickTime conta ogni campione e supera il limite: perderne i campioni non toglie i metadati né il video | +| 2026-11-18 | Il fotogramma per la miniatura di un video si riduce a 960 pixel sul lato lungo (fattore intero) prima di diventare BMP; la durata di un MP4 frammentato viene da `mehd` o, se manca, dai frammenti, anche nella sola lettura dei metadati | Un fotogramma 4K intero è un BMP da 24 MB per una miniatura di 480 pixel; senza i frammenti la sonda dava a un MP4 frammentato una durata ignota, che ffprobe sapeva dire | +| 2026-11-18 | Il fotogramma di un video parte sempre da un punto da cui si può decodificare: dei campioni segnati come chiave si guarda il contenuto, dal più vicino all'indietro, e si prende un'immagine IDR entro 300 campioni, altrimenti un'immagine di sole slice I, altrimenti il primo campione. Più lontano di 300 campioni (una tabella dei tempi danneggiata, una sola chiave in un video lungo) vale il fotogramma del punto di partenza. Ogni fotogramma o analisi ha al più 30 secondi, poi dà niente come un file illeggibile; l'annullamento di chi chiama resta un annullamento. Il decodificatore H.264 rifiuta una slice P o B senza immagini di riferimento invece di predirla da sé stessa | Un AVI senza `idx1` (registrazione interrotta) o OpenDML oltre il primo gigabyte segna ogni campione come chiave: si partiva dal fotogramma P cercato, e con i parametri ripetuti in ogni campione usciva una miniatura rovinata data per buona. L'estrattore con ffmpeg veniva fermato dopo 30 secondi; senza limite un file danneggiato poteva tenere ferma un'importazione per ore | +| 2026-11-18 | Il decodificatore H.264 non ricostruisce le immagini che nessuno usa come riferimento e che non sono chieste (ne legge solo l'intestazione), salta le immagini ridondanti (`redundant_pic_cnt` > 0), riconosce l'inizio di un'immagine con le condizioni di §7.4.1.2.4, rifiuta un SPS i cui riferimenti non stanno nel buffer più grande di ogni livello (MaxDpbMbs del livello 6.2, 696.320 macroblocchi), dà ai fotogrammi mancanti di un salto di `frame_num` il loro FrameNumOffset; CABAC legge i bit da una finestra di 64 bit e rinormalizza in un passo; le unità NAL si leggono una per volta in un solo buffer | Prestazioni della miniatura a 1 s (le B non di riferimento fra la chiave e il fotogramma) e difetti trovati in revisione: un SPS di pochi byte poteva chiedere 1,4 GB, un salto di `frame_num` a cavallo del giro perdeva il giro nel POC (tipi 1 e 2), un'immagine ridondante usciva come fotogramma in più. Le parti verificate con MD5 ufficiali sono solo quelle dei 12 flussi di conformità: predizione pesata, operazioni di gestione della memoria, riferimenti a lungo termine, POC di tipo 1, I_PCM e CABAC con più slice per immagine non hanno un riferimento ufficiale (i flussi di prova ITU-T in più sono dati di terzi: decide Alberto) | +| 2026-11-18 | Lettori di contenitori più tolleranti: un blocco Matroska danneggiato o troncato, o oltre il limite dei campioni, ferma la lettura e i blocchi letti restano; una traccia MP4 con `tkhd`, `elst`, `mdhd`, `hdlr` o `esds` danneggiati si scarta e le altre restano; la durata AVI oltre 10⁹ secondi è ignota senza perdere la data; i tempi Matroska usano come unità il massimo comun divisore fra TimecodeScale e un secondo, così la scala dei tempi è esatta per ogni TimecodeScale; la sonda dei metadati legge su un thread del pool e controlla l'annullamento fra i frammenti, e senza campioni non copia le tabelle né conserva i campioni dei frammenti | Come per il lettore ISO già prima: un file con un solo punto rovinato dopo il primo secondo non deve restare senza miniatura né perdere la data. La divisione intera 10⁹ / TimecodeScale spostava i tempi dello 0,1% con 3 ms e sbagliava fotogramma oltre il secondo | +| 2026-11-18 | Ciò che il decodificatore dei fotogrammi offre ma la produzione non usa ancora: `AnalyseStillnessAsync` (video di un'immagine ferma) e `Mp4Writer` (rimpacchettare con moov in testa) sono pronti per una tappa successiva e oggi servono solo alle prove; la miniatura di un video passa ancora da un BMP decodificato da SkiaSharp (tappa C1: dare `VideoImage` direttamente al ridimensionamento e al codificatore JPEG scritti in casa, senza BMP) | La riga del 18 novembre sui video li descriveva come se fossero già usati. Il passaggio per BMP resta finché SkiaSharp è nel programma | +| 2026-11-18 | Flussi di conformità ITU-T H.264.1 anche per le parti che il decodificatore non gestisce ancora (campi, PAFF, MBAFF, FMO e ASO, slice SP, 4:2:2 a 8 e 10 bit, 4:0:0, SVC, MVC), 37 in tutto e 8,3 MB, in `tests/Febe.Tests/Media/H264/Conformita` con il loro `riferimento.md5`: la prova è inconclusiva («da fare: …») finché la parte manca e fallisce apposta quando un flusso coincide senza essere passato fra i verificati. L'MD5 è quello dei campioni come stanno nel file YUV ufficiale (due byte little-endian oltre gli 8 bit, 4:2:2 com'è, il 4:0:0 con i piani a 128 del file); per SVC uno per lo strato più alto e uno per lo strato base, che si prova già; per MVC la serie non ha ricostruzioni e il file lo dice. Restano fuori partizionamento dei dati, slice ridondanti e SI (nessun flusso della serie li usa), High 10 in 4:2:0, 4:2:2 Intra e 4:4:4 con piani separati e senza perdita (i flussi non hanno la ricostruzione e pesano da 2 a 113 MB) | Alberto ha permesso il 18 novembre di scaricare i flussi ufficiali di conformità: il vuoto del decodificatore deve vedersi nella serie di prove senza farla diventare rossa, e chi scrive una parte ha già pronto il riferimento ufficiale. Le ricostruzioni restano fuori dal repository (sono decine di MB); i flussi sono stati scelti piccoli, uno o due per parte. Il dettaglio di che cosa copre ciascun flusso e di che cosa manca è in `LEGGIMI.md` della cartella. Il riepilogo delle prove della CI (`riepilogo-prove.sh`) conta e elenca a parte le inconclusive «da fare: …» e non le somma alle saltate, che restano a zero ammesse: senza, la verifica sarebbe rossa per 37 prove che segnano parti mancanti, non un ambiente rotto | +| 2026-11-18 | Il decodificatore H.264 gestisce le immagini interlacciate (campi, PAFF, MBAFF) su una sola griglia di fotogramma: un campo è l'insieme delle sue righe pari o dispari, e ogni macroblocco ricostruisce con un'origine e un passo (doppio per i macroblocchi di campo) invece di copiare i campi in piani separati; liste dei riferimenti e marcatura per campi secondo §8.2.4 e §8.2.5, vicini MBAFF secondo la tabella 6-4, filtro di deblocking per i campi e per le coppie MBAFF come lo fa il decodificatore di riferimento dell'ITU-T (il bordo superiore di un macroblocco di fotogramma sotto una coppia di campi filtrato due volte, il bordo sinistro misto riga per riga). Due campi fanno un fotogramma se hanno parità opposte, lo stesso `frame_num` e sono entrambi di riferimento o entrambi no; un campo rimasto solo esce come fotogramma con le righe dell'altro campo a 128 | I 17 flussi interlacciati della serie di conformità coincidono così con la ricostruzione ufficiale fotogramma per fotogramma, e i flussi a immagini intere non rallentano (la griglia unica evita copie e doppi percorsi). Il grigio per il campo mancante non inventa righe che il flusso non ha | +| 2026-11-18 | Il decodificatore H.264 gestisce gli strumenti di Baseline ed Extended: gruppi di slice (FMO, tipi da 0 a 6 e cambio con `slice_group_change_cycle`), slice in ordine qualunque (ASO), slice ridondanti (si decodifica la primaria, le ridondanti si saltano), partizionamento dei dati (NAL 2, 3 e 4, solo CAVLC come vuole lo standard) e slice SP e SI con QS (§8.6). Una partizione B o C che manca lascia a zero il residuo che porta e, da quel macroblocco in poi, anche quello della partizione che ne dipende (il nC delle due partizioni conta i coefficienti dei vicini dell'altra, tranne che con la predizione intra vincolata). I macroblocchi delle slice SP e SI contano come intra per il filtro di deblocking. Dove la serie ITU-T non ha flussi (partizionamento, slice ridondanti, SI, `sp_for_switch_flag`) la prova riscrive flussi verificati lasciando intatti i bit dei macroblocchi (`StreamRewriter`) e chiede di nuovo il riferimento ufficiale; le SI con un flusso sintetico i cui valori sono calcolati a mano | I cinque flussi FMO, ASO e SP della serie coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Riscrivere flussi già verificati dà un riferimento vero anche alle parti che nessun flusso ufficiale usa, senza inventare formati né scaricare altro; restano senza riferimento ufficiale le slice SI, `sp_for_switch_flag` a 1 e il ripiego per le partizioni mancanti, che segue la dipendenza dello standard invece di un decodificatore di riferimento | +| 2026-11-18 | Il decodificatore H.264 gestisce i formati dei profili High: 4:2:2 (DC della crominanza 2×4 con qP + 3, tabelle CAVLC di nC −2, contesti CABAC per NumC8x8, predizione intra 8×16, compensazione con il vettore verticale a piena risoluzione, bordi orizzontali della crominanza alle righe 4, 8 e 12 anche con la trasformata 8×8 della luminanza), 4:4:4 con Cb e Cr codificati come la luminanza (solo CAVLC) e con `separate_colour_plane_flag` (tre immagini monocromatiche, una per `colour_plane_id`, ciascuna con i suoi dati di macroblocco e di moto e le matrici di quantizzazione del suo componente), 4:0:0, profondità da 8 a 14 bit (QP da −QpBdOffset, soglie del deblocking e scarti dei pesi scalati) e la codifica senza perdita (`qpprime_y_zero_transform_bypass_flag` a QP′Y 0, con la DPCM della predizione intra orizzontale e verticale). I campioni stanno in piani di byte, uno o due per campione: i nuclei di predizione, trasformata e filtro sono generici su `byte` e `ushort` e il JIT li specializza, così a 8 bit nulla rallenta (stessi tempi di prima sui flussi di conformità). Oltre gli 8 bit `H264Frame` ha due byte little-endian per campione, come i file di riferimento; un 4:0:0 esce con la crominanza 4:2:0 al valore medio, un 4:4:4 a piani separati come 4:4:4 con la profondità della luminanza; la conversione in RGB usa nero, ampiezza e centro della crominanza alla profondità del fotogramma e campiona la crominanza secondo il formato. Il CABAC in 4:4:4 con i piani insieme si rifiuta con un'`H264Exception`, come le slice SP e SI fuori da 4:2:0 a 8 bit | I dieci flussi 4:2:2 (8 e 10 bit, CABAC e CAVLC) e 4:0:0 della serie di conformità coincidono ora fotogramma per fotogramma con la ricostruzione ufficiale. Per il CABAC in 4:4:4 servono i valori iniziali dei contesti 460–1023 (tabelle 9-24–9-33), non ancora trascritti dallo standard: rifiutare è meglio che decodificare male. Senza flussi ufficiali con ricostruzione per 4:4:4, piani separati, senza perdita e 11–14 bit, quelle parti si provano con flussi sintetici di I_PCM e di Intra_16x16 i cui campioni si conoscono. Scelte non verificate su un riferimento: nel 4:4:4 il bS 2 conta anche i coefficienti di Cb e Cr, nel bordo sinistro misto di MBAFF in 4:2:2 e 4:4:4 ogni riga di crominanza prende il bS della riga di luminanza omonima, un macroblocco senza perdita usa per il deblocking della crominanza il QPC di QPY 0 come gli I_PCM | +| 2026-11-18 | Il decodificatore H.264 gestisce MVC (Annex H) e la parte di SVC (Annex G) delle qualità MGS. MVC: SPS di sottoinsieme, prefissi NAL 14, slice NAL 20, un decodificatore per vista con stato proprio, predizione fra viste (riferimenti della stessa unità di accesso aggiunti alle liste dopo quelli temporali, modifiche 4 e 5, né a breve né a lungo termine), tutte le viste in uscita con `H264Frame.ViewId`; `VideoFrameDecoder` chiede solo la vista base (`DecodeAllViews = false`), che è il video 2D, per le miniature. SVC: lo strato base sempre; sopra, gli strati di qualità della stessa risoluzione in CAVLC, decodificati uno sull'altro nello stesso fotogramma: un macroblocco intra con `base_mode_flag` non si predice di nuovo, ma somma il residuo accumulato nei coefficienti alla ricostruzione dello strato in cui era intra, e per i vicini conta come I_BL (modo DC); un macroblocco inter riprende il moto e somma i coefficienti dello strato sotto quando `residual_prediction_flag` lo dice. Ciò che non è scritto (spaziale, CGS, CABAC negli strati di miglioramento, immagini chiave, sottoinsiemi di coefficienti) lascia lo strato base e lo dice in `EnhancementLayersSkipped` | `SVCBMT-13` coincide ora con lo strato L2 ufficiale in tutti i 20 fotogrammi; la regola per i macroblocchi intra si è ricavata provando contro il riferimento. Per `SVCBST-19` e `SVCBCT-1` mancano la predizione fra risoluzioni e i contesti CABAC di SVC, non ancora trascritti: lasciare lo strato base esatto è meglio che dare uno strato alto sbagliato. MVC non ha ricostruzioni ufficiali nella serie ITU-T: le viste non base non sono verificate al bit, e la scelta di trattare i riferimenti fra viste come né a breve né a lungo termine (per la diretta temporale e il filtro) segue la lettura di §H.8 senza un riferimento | +| 2026-11-18 | Lettori in casa di ASF/WMV, FLV e flusso di programma MPEG, scritti dalle specifiche pubbliche (ASF 01.20.03, FLV 10.1 con AMF0, ISO/IEC 11172-1 e 13818-1, H.262 per l'intestazione di sequenza), dietro `ContainerReader` e quindi dietro la sonda dei metadati e `VideoFrameDecoder`. ASF: proprietà del file (data, durata meno il preroll, niente durata per le trasmissioni), proprietà dei flussi anche dentro l'estensione dell'intestazione, titolo, `WM/EncodingTime` se manca la data; nessun campione. FLV: `onMetaData`, dimensioni dall'SPS (che vince sui metadati) o dall'intestazione H.263 di Sorenson, durata dall'ultimo tag quando i metadati non la dicono, i tag H.264 come campioni (così anche gli FLV hanno la miniatura), il codec degli FLV «enhanced» dal FourCC. MPEG: si leggono solo i primi 2 MB e l'ultimo MB; codec e dimensioni dalla mappa del flusso di programma, dall'intestazione di sequenza MPEG-1/MPEG-2 (con l'estensione) o dall'SPS H.264; durata dal primo all'ultimo PTS del video più un'immagine, attraverso il giro dell'orologio a 33 bit; nessun campione, perché quelli di un MPEG stanno spezzati nei pacchetti PES. `MediaSniffer` non tratta più come video un WMA o un FLV di solo audio quando l'intestazione intera nei primi byte lo dimostra | Prima questi formati si riconoscevano ma la sonda non ne sapeva nulla: data, durata e dimensioni venivano solo dal nome e dalla data di modifica. Leggere solo le intestazioni (e per MPEG due finestre fisse) costa poco anche su librerie grandi; elencare i campioni di WMV e MPEG non servirebbe, perché VC-1 e MPEG-2 non si decodificano, e un elenco di pezzi PES chiederebbe un altro modello di campione. Un WMA o un FLV di solo audio non è un video, come l'M4A; nel dubbio (intestazione non intera) il file resta un video | +| 2026-11-18 | Flussi di conformità ITU-T nel repository: **solo i flussi e i loro MD5** (`riferimento*.md5`), mai i `readme` degli autori, le schede degli strati SVC o le uscite decodificate; tolti i 48 file `.txt` di terzi aggiunti con i flussi. Ciò che le prove ne usano (profilo, formato, numero di fotogrammi, che cosa prova ogni flusso) sta nelle tabelle di `tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md`, con la fonte | Risposta di Alberto del 18 novembre 2026 alla domanda sui flussi ITU-T in più: «sì, scaricarli; nel repository solo flussi e MD5». Nessuna prova leggeva i `readme`, ed erano dati di terzi | +| 2026-11-18 | Nella CI resta zero il numero di prove saltate ammesse, con una sola eccezione, la categoria «da fare»: le inconclusive di `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: » subito dopo la cornice di MSTest. `riepilogo-prove.sh` vincola sia il nome della prova sia l'inizio del motivo; i due flussi MVC senza ricostruzione ufficiale passano da «da verificare: …» a «da fare: …» | Con lo schema di prima (`Inconclusive.*da fare: ` in qualunque punto del messaggio) qualunque prova poteva saltarsi in silenzio scrivendo quelle parole, e i due flussi MVC, che non le avevano, contavano come saltate e facevano fallire ogni verifica del ramo. Ora `PipelineTests` prova lo script su file `.trx` con le cornici inglese e italiana | +| 2026-11-18 | Provenienza del filtro di deblocking per campi e coppie MBAFF: la riga del 18 novembre che dice «come lo fa il decodificatore di riferimento dell'ITU-T» va letta come «come vuole §8.7 (§8.7.1, `fieldModeInFrameFilteringFlag`, `mixedModeEdgeFlag`), confermato dalla ricostruzione ufficiale dei flussi MBAFF»: il codice cita §8.7 e non nasce da sorgenti di terzi. Le uscite che H.264 non fissa (due byte little-endian oltre gli 8 bit, crominanza al valore medio per il 4:0:0, righe grigie per un campo senza compagno) seguono i file di ricostruzione ufficiali della serie H.264.1 o, per il campo solo, la scelta di non inventare righe; i commenti nel codice ora lo dicono così | Le regole sono «dalle specifiche pubbliche, mai copiando sorgenti di terzi»: citare il decodificatore di riferimento faceva pensare il contrario. Se nelle sessioni precedenti siano stati letti sorgenti di JM, JSVM o JMVC non si ricava dal repository (nessun identificatore di JM nel codice): lo può dire solo chi ha scritto il codice | +| 2026-11-18 | Correzioni dopo la revisione del decodificatore H.264 e dei lettori FLV: una partizione B o C si copia solo se `slice_id` e `redundant_pic_cnt` sono quelli della slice in attesa e se arriva nell'ordine A, B, C (una sperduta non tocca più le partizioni già tenute); le viste MVC tengono insieme al massimo due volte `MaxDpbMbs` di immagini (il fattore 2 dell'allegato H) e il decodificatore di una vista nuova si tiene solo dopo il controllo dell'SPS di sottoinsieme; `Wanted` vale per ogni vista, ciascuna con il suo indice di decodifica, e una componente con `inter_view_flag` si ricostruisce sempre; senza durata nei metadati un FLV dura fino alla fine dell'ultimo fotogramma (l'ultimo tag video più l'intervallo dal precedente, l'audio solo senza video), come fa il lettore MPEG; un FLV è di solo audio solo se la testa ha un tag audio intero, nessun tag video e arriva alla fine del file, a cinque secondi d'audio o a 4096 tag | Erano difetti veri: residui di un'altra slice in una slice con la partizione A persa, memoria moltiplicata per il numero di viste da un SPS rovinato, il filtro ignorato dalle viste non base, durate di un fotogramma più corte di quelle dei metadati, e video veri scartati come «Non riconosciuto» quando un `onMetaData` grande riempiva la testa. Ogni correzione ha una prova che fallisce con il codice di prima | | 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana | diff --git a/docs/docker.md b/docs/docker.md index b5241a1..f7e8f7f 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -11,9 +11,8 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b - Debian stabile ridotta (`debian:trixie-slim`). Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona. - Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET. -- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati, fino alla tappa C3 del traguardo - 0.3.0: regola 13), ICU, caratteri di sistema con le emoji (`fonts-noto-color-emoji`, `fonts-liberation`, - `fonts-dejavu-core`, per Chromium), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. +- `chromium` e `chromium-l10n`, `xvfb`, ICU, caratteri di sistema con le emoji (`fonts-noto-color-emoji`, + `fonts-liberation`, `fonts-dejavu-core`, per Chromium), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. - Nessuna libreria per le immagini: miniature, impronte e disegni li fanno i codec di Febe scritti in C# (`src/Febe.Core/Codecs/Images`, `src/Febe.Core/Drawing`). - `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per @@ -74,7 +73,8 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»). | `FEBE_CHIAVE_SESSIONE` | Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (`openssl rand -base64 32`) o 64 cifre esadecimali. Senza, Febe crea una volta `/dati/sessione/chiave.bin`, leggibile solo dal proprietario. Impostala se vuoi la chiave fuori da `/dati` (così una copia di `/dati` da sola non apre la sessione); se la cambi, la sessione salvata non si legge più e basta rifare l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega | `/dati/sessione/chiave.bin` | 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, Xvfb e ffmpeg (che c'è fino alla tappa C3 del traguardo 0.3.0). +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. ## Porte diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index 5016ac9..fbc29db 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -32,8 +32,8 @@ richieste configurate. incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori. - Se cambi la chiave, o il file si rovina, Febe la tratta come assente e lo scrive nel registro: basta rifare l'accesso. «Scollega» la cancella. -- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser, Xvfb, - ffmpeg): il browser esegue il codice del sito, e non deve poterle leggere. +- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser e + Xvfb): il browser esegue il codice del sito, e non deve poterle leggere. ## Docker: l'interfaccia non va esposta su Internet diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 7e2dabe..42a8d31 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -14,10 +14,11 @@ framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte pres specifiche pubbliche. Ammessi solo .NET, Microsoft.Data.Sqlite, il browser (Microsoft.Web.WebView2 su Windows) e MSTest (`Directory.Packages.props`); nella sola CI gitleaks e Trivy; nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb. Ciò che è ancora in uso esce con la sua tappa del traguardo 0.3.0, e intanto lo usa il - codice di prima: ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. SkiaSharp è già uscito, + codice di prima: NSIS, Node, il carattere Archivo e le icone Lucide con C6. SkiaSharp è già uscito, con la tappa C1: le immagini (PNG, JPEG, GIF, BMP, WebP) le leggono e scrivono codec di Febe - (`src/Febe.Core/Codecs/Images`), e icona, immagini dimostrative e riquadri li disegna `src/Febe.Core/Drawing`. Prima - di aggiungere qualunque cosa, si chiede. + (`src/Febe.Core/Codecs/Images`), e icona, immagini dimostrative e riquadri li disegna `src/Febe.Core/Drawing`. + Anche ffmpeg è già uscito, con la tappa C3: contenitori e H.264 li legge codice di Febe (`src/Febe.Core/Codecs/Containers`, + `src/Febe.Core/Codecs/H264`). Prima di aggiungere qualunque cosa, si chiede. ## Com'è fatto il repository @@ -205,8 +206,10 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz - `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in tutta la storia (gitleaks); - `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in - un contenitore Debian con Chromium e Xvfb veri, più ffmpeg (fino alla tappa C3 del traguardo 0.3.0), NSIS e - Node (fino alla tappa C6): nessuna prova si salta; + un contenitore Debian con Chromium e Xvfb veri, più NSIS e Node (fino alla tappa C6 del traguardo 0.3.0): + nessuna prova si salta. Fa eccezione solo la categoria «da fare»: le inconclusive di + `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: » (flussi di conformità delle parti + del decodificatore H.264 non ancora scritte), elencate a parte nel riepilogo; - `installatore`: `Febe-Setup--ci..exe` e lo zip portabile, fra gli artefatti per 14 giorni; - `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-`. Alla fine si toglie diff --git a/docs/processo.md b/docs/processo.md index a6bc90b..9abf0a0 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -87,7 +87,7 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget | Lavoro | Quando | Che cosa garantisce | |---|---|---| | `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) | -| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie` fino alla tappa C6 del traguardo 0.3.0, poi un'immagine Debian senza Node) con Chromium della distribuzione, Xvfb e la lingua italiana, più ffmpeg (fino alla tappa C3, regola 13), NSIS e Node (fino alla tappa C6): tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | +| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie` fino alla tappa C6 del traguardo 0.3.0, poi un'immagine Debian senza Node) con Chromium della distribuzione, Xvfb e la lingua italiana, più NSIS e Node (fino alla tappa C6, regola 13): tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi (unica eccezione la categoria «da fare»: le inconclusive di `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: », cioè i flussi di conformità delle parti del decodificatore non ancora scritte, che `riepilogo-prove.sh` elenca a parte e non conta fra le saltate); quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | | `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup--ci..exe` (con NSIS fino alla tappa C6, poi con l'installatore scritto in casa) e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni | | `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-` | @@ -255,7 +255,7 @@ lavoro. massimo 90 giorni) e, sulla riga sopra, il motivo e chi l'ha deciso. - Strumenti: gitleaks e Trivy sono gli unici strumenti esterni ammessi nella CI, approvati da Alberto, e girano solo lì (regola 13 della specifica, decisioni del 18 novembre 2026). Nel contenitore delle prove restano solo Chromium, i - pacchetti Debian che gli servono e Xvfb. ffmpeg esce con la tappa C3; NSIS (al suo posto l'installatore scritto in + pacchetti Debian che gli servono e Xvfb. ffmpeg è già uscito, con la tappa C3; NSIS (al suo posto l'installatore scritto in casa) e Node (al posto delle azioni che lo vogliono, passi di shell con git e curl verso l'API di Gitea) escono con la tappa C6. Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di unione con una riga in `docs/decisioni.md`, preferendo versioni uscite da almeno due settimane. diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index a3d17a8..ef7f100 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -250,8 +250,8 @@ public sealed class FebeApp : IAsyncDisposable Clock = Clock, Thumbnails = thumbnails, HashIndex = hashes, - Frames = VideoFrameExtractor.TryCreate(), - VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), + Frames = VideoFrameDecoder.Instance, + VideoProbe = new ContainerVideoMetadataProbe(Clock), SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), DataFolder = data.Root, diff --git a/src/Febe.Core/Codecs/Containers/AsfReader.cs b/src/Febe.Core/Codecs/Containers/AsfReader.cs new file mode 100644 index 0000000..08eabdd --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/AsfReader.cs @@ -0,0 +1,438 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of Advanced Systems Format files (WMV, WMA, ASF), written from the ASF specification (revision 01.20.03): the +/// objects of the header — file properties (creation date, duration), stream properties (codec, size, audio format), +/// also when they sit inside an extended stream properties object of the header extension, content description (title) +/// and extended content description (WM/EncodingTime when the file properties have no date). The data packets +/// are not read: Febe decodes no codec carried in ASF, so the tracks have no samples. +/// +public static class AsfReader +{ + private static readonly Guid HeaderObject = new("75B22630-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly Guid FilePropertiesObject = new("8CABDCA1-A947-11CF-8EE4-00C00C205365"); + private static readonly Guid StreamPropertiesObject = new("B7DC0791-A9B7-11CF-8EE6-00C00C205365"); + private static readonly Guid HeaderExtensionObject = new("5FBF03B5-A92E-11CF-8EE3-00C00C205365"); + private static readonly Guid ContentDescriptionObject = new("75B22633-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly Guid ExtendedContentDescriptionObject = new("D2D0A440-E307-11D2-97F0-00A0C95EA850"); + private static readonly Guid ExtendedStreamPropertiesObject = new("14E6A5CB-C672-4332-8399-A96952065B5A"); + private static readonly Guid VideoMedia = new("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B"); + private static readonly Guid AudioMedia = new("F8699E40-5B4D-11CF-A8FD-00805F5C442B"); + + private static readonly DateTimeOffset Epoch1601 = new(1601, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); + + /// Bytes of an object header: its GUID and its 64-bit size. + private const int ObjectHeader = 24; + + /// Header objects looked at, in all: a real header has a few dozen. + private const int MaxObjects = 4096; + + /// The largest header object read into memory; the extended content description may hold a cover picture, cut here. + private const int MaxObjectBytes = 4 * 1024 * 1024; + + /// True when the stream starts with the GUID of the ASF header object. + public static bool Looks(ReadOnlySpan start) => start.Length >= 16 && new Guid(start[..16]) == HeaderObject; + + /// + /// True only when the first bytes of a file hold its whole header object and that header lists audio streams and no + /// video stream: a WMA file. An incomplete header proves nothing. + /// + public static bool IsAudioOnly(ReadOnlySpan head) + { + if (!Looks(head) || head.Length < 30) + { + return false; + } + + var size = BinaryPrimitives.ReadUInt64LittleEndian(head[16..]); + if (size < 30 || size > (ulong)head.Length) + { + return false; + } + + var state = new State(); + try + { + Objects(head[30..(int)size], state, DateTimeOffset.MaxValue.AddDays(-1), depth: 0); + } + catch (ContainerException) + { + return false; + } + + return state.Complete && state.VideoStream < 0 && state.AudioStream >= 0; + } + + /// Reads a seekable stream from its start. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + _ = samples; // nothing in ASF is decoded: the tracks never have samples + Span top = stackalloc byte[30]; + stream.Position = 0; + stream.ReadExactly(top); + if (!Looks(top)) + { + throw new ContainerException("Non è un file ASF."); + } + + var size = BinaryPrimitives.ReadUInt64LittleEndian(top[16..]); + if (size < 30) + { + throw new ContainerException("Intestazione ASF danneggiata."); + } + + var end = (long)Math.Min(size, (ulong)stream.Length); // a file cut inside its header keeps the objects before the cut + var state = new State(); + var position = 30L; + Span head = stackalloc byte[ObjectHeader]; + while (position + ObjectHeader <= end && state.Objects < MaxObjects) + { + ct.ThrowIfCancellationRequested(); + stream.Position = position; + stream.ReadExactly(head); + var objectSize = BinaryPrimitives.ReadUInt64LittleEndian(head[16..]); + if (objectSize < ObjectHeader || objectSize > (ulong)(end - position)) + { + break; // a damaged size, or an object cut by the end of the file + } + + var id = new Guid(head[..16]); + if (id == FilePropertiesObject || id == StreamPropertiesObject || id == HeaderExtensionObject + || id == ContentDescriptionObject || id == ExtendedContentDescriptionObject) + { + var length = (int)Math.Min(objectSize, MaxObjectBytes); + var data = new byte[length]; + stream.Position = position; + stream.ReadExactly(data); + Objects(data, state, now, depth: 0); + } + else + { + state.Objects++; + } + + position += (long)objectSize; + } + + return state.Build(); + } + + /// The objects in , one after the other, up to its end or the first damaged one. + private static void Objects(ReadOnlySpan data, State state, DateTimeOffset now, int depth) + { + var p = 0; + while (p + ObjectHeader <= data.Length && state.Objects < MaxObjects) + { + state.Objects++; + var size = BinaryPrimitives.ReadUInt64LittleEndian(data[(p + 16)..]); + if (size < ObjectHeader) + { + state.Complete = false; + return; + } + + var cut = size > (ulong)(data.Length - p); + var body = data.Slice(p + ObjectHeader, (int)(cut ? data.Length - p : (long)size) - ObjectHeader); + var id = new Guid(data.Slice(p, 16)); + if (id == FilePropertiesObject) + { + FileProperties(body, state, now); + } + else if (id == StreamPropertiesObject) + { + StreamProperties(body, state); + } + else if (id == ContentDescriptionObject) + { + ContentDescription(body, state); + } + else if (id == ExtendedContentDescriptionObject) + { + ExtendedContentDescription(body, state, now); + } + else if (id == HeaderExtensionObject && depth == 0 && body.Length >= 22) + { + // Reserved GUID and field, then the size of the objects that follow. + var extension = BinaryPrimitives.ReadUInt32LittleEndian(body[18..]); + var inner = body[22..]; + Objects(inner[..(int)Math.Min(extension, (uint)inner.Length)], state, now, depth + 1); + } + else if (id == ExtendedStreamPropertiesObject) + { + ExtendedStreamProperties(body, state); + } + + if (cut) + { + state.Complete = false; + return; + } + + p += (int)size; + } + + state.Complete = p == data.Length; + } + + private static void FileProperties(ReadOnlySpan body, State state, DateTimeOffset now) + { + if (body.Length < 80) + { + return; + } + + state.Created ??= FileTime(BinaryPrimitives.ReadUInt64LittleEndian(body[24..]), now); + var play = BinaryPrimitives.ReadUInt64LittleEndian(body[40..]); // 100-nanosecond units, preroll included + var preroll = BinaryPrimitives.ReadUInt64LittleEndian(body[56..]); // milliseconds + var broadcast = (BinaryPrimitives.ReadUInt32LittleEndian(body[64..]) & 1) != 0; + if (!broadcast && play is > 0 and < 10_000_000UL * 1_000_000_000 && preroll < play / 10_000) + { + state.Duration = TimeSpan.FromTicks((long)(play - (preroll * 10_000))); + } + } + + private static void StreamProperties(ReadOnlySpan body, State state) + { + if (body.Length < 54) + { + return; + } + + var type = new Guid(body[..16]); + var specificLength = BinaryPrimitives.ReadUInt32LittleEndian(body[40..]); + var number = BinaryPrimitives.ReadUInt16LittleEndian(body[48..]) & 0x7F; + var specific = body[54..]; + specific = specific[..(int)Math.Min(specificLength, (uint)specific.Length)]; + if (type == VideoMedia && state.VideoStream < 0 && specific.Length >= 11) + { + state.VideoStream = number; + state.Width = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(specific), 65535); + state.Height = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(specific[4..]), 65535); + var format = specific[11..]; + if (format.Length >= 20) + { + // BITMAPINFOHEADER: its size when the encoded size is missing, and the compression code. + state.Width = state.Width > 0 ? state.Width : (int)Math.Min(Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(format[4..])), 65535); + state.Height = state.Height > 0 ? state.Height : (int)Math.Min(Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(format[8..])), 65535); + state.Compression = Encoding.Latin1.GetString(format.Slice(16, 4)); + } + } + else if (type == AudioMedia && state.AudioStream < 0 && specific.Length >= 16) + { + state.AudioStream = number; + state.AudioFormat = BinaryPrimitives.ReadUInt16LittleEndian(specific); + state.Channels = BinaryPrimitives.ReadUInt16LittleEndian(specific[2..]); + state.SampleRate = (int)Math.Min(BinaryPrimitives.ReadUInt32LittleEndian(specific[4..]), int.MaxValue); + } + } + + /// + /// The extended stream properties object (§4.1): fixed fields, stream names and payload extension systems, then the + /// stream properties object of a stream that the header itself does not list. + /// + private static void ExtendedStreamProperties(ReadOnlySpan body, State state) + { + if (body.Length < 64) + { + return; + } + + var names = BinaryPrimitives.ReadUInt16LittleEndian(body[60..]); + var systems = BinaryPrimitives.ReadUInt16LittleEndian(body[62..]); + var p = 64; + for (var i = 0; i < names; i++) + { + if (p + 4 > body.Length) + { + return; + } + + p += 4 + BinaryPrimitives.ReadUInt16LittleEndian(body[(p + 2)..]); + } + + for (var i = 0; i < systems; i++) + { + if (p + 22 > body.Length) + { + return; + } + + var info = BinaryPrimitives.ReadUInt32LittleEndian(body[(p + 18)..]); + if (info > (uint)(body.Length - p - 22)) + { + return; + } + + p += 22 + (int)info; + } + + if (p + ObjectHeader <= body.Length && new Guid(body.Slice(p, 16)) == StreamPropertiesObject) + { + var size = BinaryPrimitives.ReadUInt64LittleEndian(body[(p + 16)..]); + if (size >= ObjectHeader && size <= (ulong)(body.Length - p)) + { + StreamProperties(body.Slice(p + ObjectHeader, (int)size - ObjectHeader), state); + } + } + } + + private static void ContentDescription(ReadOnlySpan body, State state) + { + if (body.Length < 10) + { + return; + } + + var title = BinaryPrimitives.ReadUInt16LittleEndian(body); + if (10 + title <= body.Length) + { + var text = Encoding.Unicode.GetString(body.Slice(10, title & ~1)).TrimEnd('\0').Trim(); + state.Title ??= text.Length > 0 ? text : null; + } + } + + /// Name and value pairs (§3.11); only WM/EncodingTime is used, for the date. + private static void ExtendedContentDescription(ReadOnlySpan body, State state, DateTimeOffset now) + { + if (body.Length < 2) + { + return; + } + + var count = BinaryPrimitives.ReadUInt16LittleEndian(body); + var p = 2; + for (var i = 0; i < count; i++) + { + if (p + 2 > body.Length) + { + return; + } + + var nameLength = BinaryPrimitives.ReadUInt16LittleEndian(body[p..]); + if (p + 2 + nameLength + 4 > body.Length) + { + return; + } + + var name = body.Slice(p + 2, nameLength); + p += 2 + nameLength; + var type = BinaryPrimitives.ReadUInt16LittleEndian(body[p..]); + var valueLength = BinaryPrimitives.ReadUInt16LittleEndian(body[(p + 2)..]); + p += 4; + if (p + valueLength > body.Length) + { + return; + } + + if (type == 4 && valueLength == 8 && IsName(name, "WM/EncodingTime")) + { + state.EncodingTime ??= FileTime(BinaryPrimitives.ReadUInt64LittleEndian(body[p..]), now); + } + + p += valueLength; + } + } + + /// True when a null-terminated UTF-16LE name is . + private static bool IsName(ReadOnlySpan name, string expected) + { + if (name.Length < expected.Length * 2) + { + return false; + } + + for (var i = 0; i < expected.Length; i++) + { + if (name[2 * i] != expected[i] || name[(2 * i) + 1] != 0) + { + return false; + } + } + + return name.Length == expected.Length * 2 || (name.Length >= (expected.Length * 2) + 2 && name[expected.Length * 2] == 0 && name[(expected.Length * 2) + 1] == 0); + } + + /// A FILETIME (100-nanosecond units from 1601, UTC) from 1995 to a day past now; null otherwise. + private static DateTimeOffset? FileTime(ulong ticks, DateTimeOffset now) + { + if (ticks == 0 || ticks > (ulong)(DateTimeOffset.MaxValue - Epoch1601).Ticks) + { + return null; + } + + var instant = Epoch1601.AddTicks((long)ticks); + return instant >= Earliest && instant <= now.AddDays(1) ? instant : null; + } + + private sealed class State + { + internal int Objects; + internal bool Complete; + internal DateTimeOffset? Created; + internal DateTimeOffset? EncodingTime; + internal TimeSpan? Duration; + internal string? Title; + internal int VideoStream = -1; + internal int Width; + internal int Height; + internal string Compression = string.Empty; + internal int AudioStream = -1; + internal int AudioFormat; + internal int Channels; + internal int SampleRate; + + internal MediaContainer Build() + { + var tag = Compression.ToUpperInvariant(); + var video = VideoStream < 0 ? null : new VideoTrack + { + Codec = tag switch + { + "WMV1" or "WMV2" => VideoCodec.Wmv, + "WMV3" or "WMVA" or "WVC1" or "WMVP" or "WVP2" => VideoCodec.Vc1, + "H264" or "AVC1" or "X264" => VideoCodec.H264, + "MP4S" or "M4S2" or "XVID" or "DIVX" or "DX50" or "FMP4" => VideoCodec.Mpeg4Part2, + "MJPG" => VideoCodec.Mjpeg, + _ => VideoCodec.Unknown, + }, + CodecTag = Compression, + Width = Width, + Height = Height, + Timescale = 1000, + Duration = Duration is { } d ? (long)d.TotalMilliseconds : 0, + }; + var audio = AudioStream < 0 ? null : new AudioTrack + { + Codec = AudioFormat switch + { + 0x160 or 0x161 or 0x162 or 0x163 or 0x0A => AudioCodec.Wma, + 0x55 => AudioCodec.Mp3, + 0x50 => AudioCodec.Mp2, + 0xFF or 0x1610 => AudioCodec.Aac, + 0x2000 => AudioCodec.Ac3, + 1 => AudioCodec.Pcm, + _ => AudioCodec.Unknown, + }, + CodecTag = AudioFormat.ToString("X4", CultureInfo.InvariantCulture), + Channels = Channels, + SampleRate = SampleRate, + Timescale = Math.Max(1, SampleRate), + }; + return new MediaContainer + { + Format = ContainerFormat.Asf, + CreatedAt = Created ?? EncodingTime, + Duration = Duration, + Title = Title, + Video = video, + Audio = audio, + }; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/AviReader.cs b/src/Febe.Core/Codecs/Containers/AviReader.cs new file mode 100644 index 0000000..1f7a7b9 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/AviReader.cs @@ -0,0 +1,395 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF AVIX parts), +/// written from the format description: the main header, the first video and audio streams and the chunks of the +/// movi lists in file order. Key frames come from the idx1 index when there is one. +/// +public static class AviReader +{ + private const int MaxSamples = IsoBmffReader.MaxSamples; + private const int MaxHeaderBytes = 16 * 1024 * 1024; + + /// True when the stream starts like an AVI file. + public static bool Looks(ReadOnlySpan start) => + start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8); + + /// Reads a seekable stream from its start. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + var state = new State(); + long position = 0; + var length = stream.Length; + Span header = stackalloc byte[12]; + var first = true; + while (position + 12 <= length) + { + ct.ThrowIfCancellationRequested(); + stream.Position = position; + stream.ReadExactly(header); + if (!header[..4].SequenceEqual("RIFF"u8)) + { + break; + } + + var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]); + var form = header.Slice(8, 4); + if (first && !form.SequenceEqual("AVI "u8)) + { + throw new ContainerException("Non è un file AVI."); + } + + var end = Math.Min(length, position + 8 + size); + ParseList(stream, position + 12, end, state, samples, now, depth: 0); + if (!samples) + { + break; + } + + first = false; + position = position + 8 + size + (size & 1); + } + + if (!state.HaveHeader) + { + throw new ContainerException("Manca l'intestazione AVI."); + } + + return state.Build(); + } + + private static void ParseList(Stream stream, long start, long end, State state, bool samples, DateTimeOffset now, int depth) + { + Span header = stackalloc byte[12]; + var position = start; + while (position + 8 <= end) + { + stream.Position = position; + stream.ReadExactly(header[..8]); + var size = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]); + var body = position + 8; + var next = body + size + (size & 1); + if (next > end) + { + next = end; // truncated + size = (uint)Math.Max(0, end - body); + } + + if (state.InMovi && !header[..4].SequenceEqual("LIST"u8)) + { + AddChunk(header[..4], body, size, state); // the hot path: no string per chunk + position = next; + continue; + } + + var id = Encoding.Latin1.GetString(header[..4]); + if (id == "LIST" && size >= 4) + { + stream.ReadExactly(header.Slice(8, 4)); + var type = Encoding.Latin1.GetString(header.Slice(8, 4)); + if (type == "movi" && !samples) + { + return; + } + + if (type == "strl") + { + state.StreamIndex++; + } + + if (depth < 4 && type is "hdrl" or "strl" or "movi" or "rec " or "odml") + { + state.InMovi |= type == "movi"; + ParseList(stream, body + 4, body + size, state, samples, now, depth + 1); + if (type == "movi") + { + state.InMovi = false; + } + } + } + else + { + switch (id) + { + case "avih" when size >= 40: + { + var data = Read(stream, body, 40); + state.MicroSecondsPerFrame = BinaryPrimitives.ReadUInt32LittleEndian(data); + state.TotalFrames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16)); + state.Width = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32)); + state.Height = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(36)); + state.HaveHeader = true; + break; + } + + case "strh" when size >= 36: + { + var data = Read(stream, body, 36); + var type = Encoding.Latin1.GetString(data, 0, 4); + var handler = Encoding.Latin1.GetString(data, 4, 4); + var scale = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(20)); + var rate = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24)); + var frames = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(32)); + if (type == "vids" && state.VideoStream < 0) + { + state.VideoStream = state.StreamIndex - 1; + state.VideoHandler = handler; + (state.VideoScale, state.VideoRate, state.VideoLength) = (scale, rate, frames); + } + else if (type == "auds" && state.AudioStream < 0) + { + state.AudioStream = state.StreamIndex - 1; + (state.AudioScale, state.AudioRate) = (scale, rate); + } + + break; + } + + case "strf": + { + var data = Read(stream, body, (int)Math.Min(size, 4096)); + if (state.StreamIndex - 1 == state.VideoStream && data.Length >= 20) + { + state.VideoWidth = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4)); + state.VideoHeight = Math.Abs(BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(8))); + state.Compression = Encoding.Latin1.GetString(data, 16, 4); + } + else if (state.StreamIndex - 1 == state.AudioStream && data.Length >= 16) + { + state.AudioFormat = BinaryPrimitives.ReadUInt16LittleEndian(data); + state.Channels = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(2)); + state.SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4)); + if (data.Length >= 18) + { + var extra = BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(16)); + if (extra > 0 && 18 + extra <= data.Length) + { + state.AudioExtra = data[18..(18 + extra)]; + } + } + } + + break; + } + + case "IDIT" when size is > 0 and < 128: + state.Created = ParseDate(Encoding.ASCII.GetString(Read(stream, body, (int)size)), now); + break; + case "idx1" when samples: + // 16 bytes per entry: at most one entry per sample the reader keeps. + state.Index = Read(stream, body, (int)Math.Min(size, 16L * MaxSamples)); + break; + } + } + + position = next; + } + } + + private static byte[] Read(Stream stream, long offset, int count) + { + if (count < 0 || count > 16L * MaxSamples || count > stream.Length - offset) + { + throw new ContainerException("Intestazione AVI danneggiata."); + } + + var data = new byte[count]; + stream.Position = offset; + stream.ReadExactly(data); + return data; + } + + private static void AddChunk(ReadOnlySpan id, long body, uint size, State state) + { + if (!char.IsAsciiDigit((char)id[0]) || !char.IsAsciiDigit((char)id[1]) || size > int.MaxValue) + { + return; // JUNK, ix## indexes and the like + } + + var stream = ((id[0] - '0') * 10) + (id[1] - '0'); + if (stream == state.VideoStream && id[2] == 'd' && id[3] is (byte)'c' or (byte)'b') + { + if (state.Chunks.Count >= MaxSamples) + { + throw new ContainerException("Troppi campioni."); + } + + state.Chunks.Add((body, (int)size)); + } + else if (stream == state.AudioStream && id[2] == 'w' && id[3] == 'b' && state.AudioChunks.Count < MaxSamples) + { + state.AudioChunks.Add((body, (int)size)); // beyond the limit the audio chunks are not needed + } + } + + /// The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021». + internal static DateTimeOffset? ParseDate(string text, DateTimeOffset now) + { + var value = text.Trim('\0', ' ', '\r', '\n'); + foreach (var format in new[] { "ddd MMM dd HH:mm:ss yyyy", "ddd MMM d HH:mm:ss yyyy", "yyyy:MM:dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss" }) + { + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var local) + && local.Year >= 1995) + { + var instant = new DateTimeOffset(DateTime.SpecifyKind(local, DateTimeKind.Unspecified), TimeSpan.Zero); + return instant <= now.AddDays(1) ? instant : null; + } + } + + return null; + } + + private sealed class State + { + internal bool HaveHeader; + internal bool InMovi; + internal int StreamIndex; + internal uint MicroSecondsPerFrame; + internal uint TotalFrames; + internal int Width; + internal int Height; + internal int VideoStream = -1; + internal int AudioStream = -1; + internal string VideoHandler = string.Empty; + internal string Compression = string.Empty; + internal uint VideoScale; + internal uint VideoRate; + internal uint VideoLength; + internal int VideoWidth; + internal int VideoHeight; + internal uint AudioScale; + internal uint AudioRate; + internal int AudioFormat; + internal int Channels; + internal int SampleRate; + internal byte[]? AudioExtra; + internal DateTimeOffset? Created; + internal byte[]? Index; + internal readonly List<(long Offset, int Size)> Chunks = []; + internal readonly List<(long Offset, int Size)> AudioChunks = []; + + internal MediaContainer Build() + { + // Frame rate: the stream header first (rate / scale frames per second), then the main header. + long timescale = 1000; + long frameTicks = 40; + if (VideoRate > 0 && VideoScale > 0) + { + timescale = VideoRate; + frameTicks = VideoScale; + } + else if (MicroSecondsPerFrame > 0) + { + timescale = 1_000_000; + frameTicks = MicroSecondsPerFrame; + } + + var keys = KeyFrames(); + var samples = new List(Chunks.Count); + var n = 0; + for (var i = 0; i < Chunks.Count; i++) + { + var (offset, size) = Chunks[i]; + if (size == 0) + { + n++; // a dropped frame keeps its time slot + continue; + } + + var t = n * frameTicks; + samples.Add(new MediaSample(offset, size, t, t, keys is null || keys.Contains(i))); + n++; + } + + var tag = (Compression.Length == 4 ? Compression : VideoHandler).ToUpperInvariant(); + var frames = VideoLength > 0 ? VideoLength : TotalFrames; + + // Header values are taken as stored: a damaged one never gives an overflowing or negative duration. + var trackDuration = frames <= long.MaxValue / frameTicks ? frames * frameTicks : 0; + var video = VideoStream < 0 ? null : new VideoTrack + { + Codec = tag switch + { + "H264" or "X264" or "AVC1" or "DAVC" or "VSSH" => VideoCodec.H264, + "HEVC" or "H265" or "HVC1" => VideoCodec.Hevc, + "MJPG" => VideoCodec.Mjpeg, + "XVID" or "DIVX" or "DX50" or "FMP4" or "MP4V" => VideoCodec.Mpeg4Part2, + _ => VideoCodec.Unknown, + }, + CodecTag = Compression.Length == 4 ? Compression : VideoHandler, + Width = VideoWidth > 0 ? VideoWidth : Width, + Height = VideoHeight > 0 ? VideoHeight : Height, + AnnexB = true, + Timescale = timescale, + Duration = trackDuration, + Samples = samples, + }; + + AudioTrack? audio = null; + if (AudioStream >= 0) + { + var audioSamples = new List(AudioChunks.Count); + foreach (var (offset, size) in AudioChunks) + { + audioSamples.Add(new MediaSample(offset, size, 0, 0, true)); + } + + audio = new AudioTrack + { + Codec = AudioFormat switch + { + 0x55 => AudioCodec.Mp3, + 0xFF or 0x1600 or 0x706D => AudioCodec.Aac, + 1 => AudioCodec.Pcm, + _ => AudioCodec.Unknown, + }, + CodecTag = AudioFormat.ToString("X4", CultureInfo.InvariantCulture), + Channels = Channels, + SampleRate = SampleRate, + AacConfiguration = AudioFormat == 0xFF ? AudioExtra : null, + Timescale = Math.Max(1, SampleRate), + Samples = audioSamples, + }; + } + + // As the other readers: beyond what a video can last (a damaged header) there is no duration, and the rest stands. + var seconds = video is { Duration: > 0 } ? video.Seconds(video.Duration) : 0; + TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; + return new MediaContainer { Format = ContainerFormat.Avi, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; + } + + /// Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index. + private HashSet? KeyFrames() + { + if (Index is null || VideoStream < 0) + { + return null; + } + + var keys = new HashSet(); + var n = 0; + for (var p = 0; p + 16 <= Index.Length; p += 16) + { + var id = Index.AsSpan(p, 4); + if (!char.IsAsciiDigit((char)id[0]) || (id[0] - '0') * 10 + (id[1] - '0') != VideoStream || id[2] != 'd') + { + continue; + } + + if ((BinaryPrimitives.ReadUInt32LittleEndian(Index.AsSpan(p + 4)) & 0x10) != 0) + { + keys.Add(n); + } + + n++; + } + + return n == Chunks.Count ? keys : null; // an index that does not match the chunks is ignored + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/BitReader.cs b/src/Febe.Core/Codecs/Containers/BitReader.cs new file mode 100644 index 0000000..1b7c6f2 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/BitReader.cs @@ -0,0 +1,22 @@ +namespace Febe.Core.Codecs.Containers; + +/// A big-endian bit reader over the few bytes of a codec header; past the end it gives zeros. +internal ref struct BitReader(ReadOnlySpan data, int position) +{ + private readonly ReadOnlySpan data = data; + private int position = position; + + /// The next bits (at most 31) as an unsigned number. + internal int Read(int count) + { + var value = 0; + for (var i = 0; i < count; i++, position++) + { + var index = position >> 3; + var bit = index < data.Length ? (data[index] >> (7 - (position & 7))) & 1 : 0; + value = (value << 1) | bit; + } + + return value; + } +} diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs new file mode 100644 index 0000000..6aa585d --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -0,0 +1,100 @@ +namespace Febe.Core.Codecs.Containers; + +/// +/// Recognises the container of a video by its first bytes (MP4 and MOV, Matroska and WebM, AVI, ASF and WMV, FLV, MPEG +/// program stream) and reads it with the matching reader. +/// +public static class ContainerReader +{ + /// The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below. + public const int MaxSampleSize = 64 * 1024 * 1024; + + /// The format of a file from its first bytes; null when it is none of those read here. + public static ContainerFormat? Detect(ReadOnlySpan start) + { + if (MatroskaReader.Looks(start)) + { + return ContainerFormat.Matroska; + } + + if (AviReader.Looks(start)) + { + return ContainerFormat.Avi; + } + + if (AsfReader.Looks(start)) + { + return ContainerFormat.Asf; + } + + if (FlvReader.Looks(start)) + { + return ContainerFormat.Flv; + } + + if (MpegPsReader.Looks(start)) + { + return ContainerFormat.MpegPs; + } + + return IsoBmffReader.Looks(start) ? ContainerFormat.IsoBmff : null; + } + + /// + /// Reads a seekable stream; null when its format is not recognised. Damaged files raise + /// (or when truncated); is + /// checked between the top-level boxes, elements and fragments. + /// + public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + Span start = stackalloc byte[16]; + stream.Position = 0; + var read = stream.ReadAtLeast(start, start.Length, throwOnEndOfStream: false); + stream.Position = 0; + return Detect(start[..read]) switch + { + ContainerFormat.Matroska => MatroskaReader.Read(stream, now, samples, ct), + ContainerFormat.Avi => AviReader.Read(stream, now, samples, ct), + ContainerFormat.Asf => AsfReader.Read(stream, now, samples, ct), + ContainerFormat.Flv => FlvReader.Read(stream, now, samples, ct), + ContainerFormat.MpegPs => MpegPsReader.Read(stream, now, samples, ct), + ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples, ct), + _ => null, + }; + } + + /// Reads a file (read-only, shared); null when its format is not recognised. + public static MediaContainer? ReadFile(string path, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + using var stream = OpenRead(path); + return Read(stream, now, samples, ct); + } + + /// Opens a file for reading without blocking other readers or writers. + public static FileStream OpenRead(string path) => + new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess); + + /// The bytes of a sample, read into (grown when needed). + public static ReadOnlySpan ReadSample(Stream stream, in MediaSample sample, ref byte[] buffer) + { + if (sample.Size < 0 || sample.Offset < 0 || sample.Offset + sample.Size > stream.Length) + { + throw new ContainerException("Campione fuori dal file."); + } + + if (sample.Size > MaxSampleSize) + { + throw new ContainerException("Campione troppo grande."); // no real frame comes near: a damaged table + } + + if (buffer.Length < sample.Size) + { + buffer = new byte[Math.Max(sample.Size, buffer.Length * 2)]; + } + + stream.Position = sample.Offset; + stream.ReadExactly(buffer, 0, sample.Size); + return buffer.AsSpan(0, sample.Size); + } +} diff --git a/src/Febe.Core/Codecs/Containers/FlvReader.cs b/src/Febe.Core/Codecs/Containers/FlvReader.cs new file mode 100644 index 0000000..9dc2139 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/FlvReader.cs @@ -0,0 +1,751 @@ +using System.Buffers.Binary; +using System.Text; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of FLV files, written from the Adobe Flash Video File Format Specification (version 10.1, annex E): the header, +/// the onMetaData script tag (AMF0), the first audio and video tags, and for H.264 the AVC sequence header and every +/// NAL unit tag as a sample. HEVC, AV1 and VP9 stored with the enhanced video tag header are recognised by their FourCC. +/// Width and height come from the SPS when there is one, then from the metadata, then from a Sorenson H.263 picture header. +/// +public static class FlvReader +{ + private const int MaxSamples = IsoBmffReader.MaxSamples; + + /// The largest script tag read: metadata with a keyframe index of a long video stays far below. + private const int MaxScriptBytes = 4 * 1024 * 1024; + + /// The largest AVC sequence header or AAC configuration read. + private const int MaxConfigurationBytes = 64 * 1024; + + /// For the metadata alone, the tags looked at from the start (and their bytes) before giving up on the rest. + private const int HeadTags = 4096; + + private const long HeadBytes = 32L * 1024 * 1024; + + /// Audio without a single video tag that, at the start of a file, proves it has no video. + public const int AudioProofMilliseconds = 5000; + + /// Tags looked at back from the end of the file for its last time. + private const int TailTags = 64; + + private const int AmfMaxDepth = 16; + + private static readonly int[] AacRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + + /// True when the stream starts like an FLV file: «FLV», version 1 and a header of at least nine bytes. + public static bool Looks(ReadOnlySpan start) => + start.Length >= 9 && start[..3].SequenceEqual("FLV"u8) && start[3] == 1 && BinaryPrimitives.ReadUInt32BigEndian(start[5..]) >= 9; + + /// + /// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, the tags + /// in hold at least one whole audio tag and no video tag, and they reach far enough to rule + /// video out — the exact end of (it is the whole file), + /// of audio, or tags. Anything less (a head that ends inside a large onMetaData, a few tags, a + /// tag that is not one) proves nothing, and the file stays a video: header flags are often wrong. + /// + public static bool IsAudioOnly(ReadOnlySpan head) + { + if (!Looks(head) || (head[4] & 0x01) != 0 || (head[4] & 0x04) == 0) + { + return false; + } + + var position = (long)BinaryPrimitives.ReadUInt32BigEndian(head[5..]) + 4; + long? firstAudio = null; + long lastAudio = 0; + var tags = 0; + while (position + 11 <= head.Length && tags < HeadTags) + { + var tag = head.Slice((int)position, 11); + var type = tag[0] & 0x1F; + if (type == 9) + { + return false; + } + + if ((tag[0] & 0xC0) != 0 || type is not (8 or 18)) + { + return false; // not a tag: what follows proves nothing + } + + var next = position + 11 + ((tag[1] << 16) | (tag[2] << 8) | tag[3]) + 4; + if (next > head.Length) + { + break; // a tag cut by the end of the head is not seen whole + } + + if (type == 8) + { + var time = (long)(int)((uint)(tag[7] << 24) | (uint)(tag[4] << 16) | (uint)(tag[5] << 8) | tag[6]); + firstAudio ??= time; + lastAudio = time; + } + + tags++; + position = next; + } + + return firstAudio is { } first && (position == head.Length || tags >= HeadTags || lastAudio - first >= AudioProofMilliseconds); + } + + /// Reads a seekable stream from its start. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + var length = stream.Length; + Span header = stackalloc byte[16]; + stream.Position = 0; + stream.ReadExactly(header[..9]); + if (!Looks(header[..9])) + { + throw new ContainerException("Non è un file FLV."); + } + + var flags = header[4]; + var dataOffset = BinaryPrimitives.ReadUInt32BigEndian(header[5..]); + var state = new State { HasAudioFlag = (flags & 0x04) != 0, HasVideoFlag = (flags & 0x01) != 0 }; + var position = dataOffset + 4L; // after PreviousTagSize0 + var tags = 0; + while (position + 11 <= length) + { + if ((tags & 1023) == 0) + { + ct.ThrowIfCancellationRequested(); + } + + stream.Position = position; + var got = stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false); + if (got < 11) + { + break; + } + + var size = (header[1] << 16) | (header[2] << 8) | header[3]; + var body = position + 11; + if ((header[0] & 0xC0) != 0 || (header[0] & 0x1F) is not (8 or 9 or 18) || header[8] != 0 || header[9] != 0 || header[10] != 0) + { + break; // reserved bits, an unknown tag or a stream ID other than 0: what follows is not a tag + } + + if (body + size > length) + { + break; // a tag cut short: the ones before it stand + } + + var time = (long)(int)((uint)(header[7] << 24) | (uint)(header[4] << 16) | (uint)(header[5] << 8) | header[6]); + var data = header[11..Math.Min(got, 16)]; + if (size < data.Length) + { + data = data[..size]; + } + + if ((header[0] & 0x20) == 0) + { + switch (header[0] & 0x1F) + { + case 8: + Audio(stream, body, size, time, data, state); + break; + case 9: + Video(stream, body, size, time, data, state, samples); + break; + case 18 when !state.HaveScript && size is >= 13 and <= MaxScriptBytes && IsMetadata(stream, body): + state.HaveScript = Script(Read(stream, body, size), state, now); + break; + } + } + + tags++; + position = body + size + 4; + if (!samples && (state.HaveEverything || tags >= HeadTags || position > HeadBytes)) + { + break; + } + } + + if (state.MetadataSeconds is null && state.FirstTime is { } first && EndTime(stream, dataOffset + 4L) is { } end && end > first) + { + state.LastSeconds = (end - first) / 1000.0; + } + + return state.Build(); + } + + /// True when a script tag starts with the AMF0 string «onMetaData»: other script tags (cue points) are not read. + private static bool IsMetadata(Stream stream, long body) + { + Span start = stackalloc byte[13]; + stream.Position = body; + stream.ReadExactly(start); + return start[..3].SequenceEqual((ReadOnlySpan)[2, 0, 10]) && start[3..].SequenceEqual("onMetaData"u8); + } + + private static void Audio(Stream stream, long body, int size, long time, ReadOnlySpan data, State state) + { + if (data.Length < 1) + { + return; + } + + state.FirstTime ??= time; + var format = data[0] >> 4; + if (!state.HaveAudio) + { + state.HaveAudio = true; + state.AudioFormat = format; + state.SampleRate = format == 10 ? 44100 : ((data[0] >> 2) & 3) switch { 0 => 5512, 1 => 11025, 2 => 22050, _ => 44100 }; + state.Channels = (data[0] & 1) + 1; + if (format is 4 or 14) + { + state.SampleRate = format == 4 ? 16000 : 8000; // Nellymoser 16 kHz, MP3 8 kHz: fixed rates + } + } + + if (format == 10 && state.AacConfiguration is null && data.Length >= 2 && data[1] == 0 && size - 2 is > 0 and <= MaxConfigurationBytes) + { + var config = Read(stream, body + 2, size - 2); + state.AacConfiguration = config; + if (AacRateAndChannels(config) is { } aac) + { + state.SampleRate = aac.Rate; + state.Channels = aac.Channels > 0 ? aac.Channels : state.Channels; + } + } + } + + private static void Video(Stream stream, long body, int size, long time, ReadOnlySpan data, State state, bool samples) + { + if (data.Length < 1) + { + return; + } + + if ((data[0] & 0x80) != 0) + { + // Enhanced video tag header: frame type, packet type and a FourCC. Only the codec is taken. + if (data.Length >= 5 && state.Codec is null) + { + state.FirstTime ??= time; + state.CodecTag = Encoding.Latin1.GetString(data[1..5]); + state.Codec = state.CodecTag switch + { + "avc1" => VideoCodec.H264, + "hvc1" => VideoCodec.Hevc, + "av01" => VideoCodec.Av1, + "vp09" => VideoCodec.Vp9, + _ => VideoCodec.Unknown, + }; + } + + return; + } + + var frameType = data[0] >> 4; + var codecId = data[0] & 0x0F; + if (frameType == 5) + { + return; // video info or command frame: no picture + } + + state.FirstTime ??= time; + if (state.Codec is null) + { + state.CodecId = codecId; + state.CodecTag = codecId.ToString(System.Globalization.CultureInfo.InvariantCulture); + state.Codec = codecId switch + { + 2 => VideoCodec.H263, + 4 or 5 => VideoCodec.Vp6, + 7 => VideoCodec.H264, + 12 => VideoCodec.Hevc, // the codec ID that HEVC writers outside the specification use + _ => VideoCodec.Unknown, + }; + } + + if (codecId != state.CodecId) + { + return; // a second codec in the same file: only the first is followed + } + + if (codecId == 2 && state.PictureWidth == 0 && size >= 10) + { + (state.PictureWidth, state.PictureHeight) = SorensonSize(Read(stream, body + 1, Math.Min(size - 1, 16))); + } + + if (codecId != 7 || data.Length < 5) + { + return; + } + + var packetType = data[1]; + if (packetType == 0) + { + if (state.AvcConfiguration is null && size - 5 is > 0 and <= MaxConfigurationBytes) + { + var config = Read(stream, body + 5, size - 5); + if (config.Length >= 7 && config[0] == 1) + { + state.AvcConfiguration = config; + if (H264StreamInfo.TryPictureSizeFromConfiguration(config, out var w, out var h)) + { + (state.PictureWidth, state.PictureHeight) = (w, h); + } + } + } + } + else if (packetType == 1 && samples && size > 5) + { + if (state.Samples.Count >= MaxSamples) + { + throw new ContainerException("Troppi campioni."); + } + + var composition = (data[2] << 16) | (data[3] << 8) | data[4]; + composition = (composition << 8) >> 8; // SI24 + state.Samples.Add(new MediaSample(body + 5, size - 5, time, time + composition, frameType == 1)); + } + } + + /// The time of the last audio or video tag, walking back from the end with the PreviousTagSize fields. + /// + /// The time the file ends, in milliseconds, from the tags at its end (walked back through their PreviousTagSize): the + /// last video tag plus the interval from the video tag before it, that is one frame, as the MPEG reader adds one + /// frame to the last time of its video; the same for audio when the end of the file holds no video tag. Null when + /// the end of the file has no tag to trust. + /// + private static long? EndTime(Stream stream, long firstTag) + { + Span buffer = stackalloc byte[11]; + var end = stream.Length; + long? lastVideo = null, previousVideo = null, lastAudio = null, previousAudio = null; + for (var step = 0; step < TailTags && end - 4 >= firstTag && previousVideo is null; step++) + { + stream.Position = end - 4; + stream.ReadExactly(buffer[..4]); + var previous = BinaryPrimitives.ReadUInt32BigEndian(buffer); + var start = end - 4 - previous; + if (previous < 11 || start < firstTag) + { + break; // no PreviousTagSize to trust (a file cut short ends inside a tag) + } + + stream.Position = start; + stream.ReadExactly(buffer); + var size = (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; + if (size + 11 != previous || (buffer[0] & 0xC0) != 0) + { + break; + } + + var time = (long)(int)((uint)(buffer[7] << 24) | (uint)(buffer[4] << 16) | (uint)(buffer[5] << 8) | buffer[6]); + switch (buffer[0] & 0x1F) + { + case 9: + Note(ref lastVideo, ref previousVideo, time); + break; + case 8: + Note(ref lastAudio, ref previousAudio, time); + break; + } + + end = start; + } + + return lastVideo is { } video ? video + (video - (previousVideo ?? video)) + : lastAudio is { } audio ? audio + (audio - (previousAudio ?? audio)) + : null; + + // The first time seen walking back is the last of the track, the first earlier one the tag before it (a tag at the + // same time, such as the end of an AVC sequence, is no frame of its own). + static void Note(ref long? last, ref long? before, long time) + { + if (last is null) + { + last = time; + } + else if (before is null && time < last) + { + before = time; + } + } + } + + private static byte[] Read(Stream stream, long offset, int count) + { + if (count < 0 || count > stream.Length - offset) + { + throw new ContainerException("Etichetta FLV danneggiata."); + } + + var data = new byte[count]; + stream.Position = offset; + stream.ReadExactly(data); + return data; + } + + /// + /// Width and height of a Sorenson H.263 picture header (FLV specification, «H.263 video packet»): the 17-bit start + /// code, version, temporal reference, then a picture size code or the size itself. + /// + private static (int Width, int Height) SorensonSize(ReadOnlySpan data) + { + if (data.Length < 9 || data[0] != 0 || data[1] != 0 || (data[2] & 0x80) == 0) + { + return (0, 0); + } + + var bits = new BitReader(data, 17 + 5 + 8); + var code = bits.Read(3); + return code switch + { + 0 => (bits.Read(8), bits.Read(8)), + 1 => (bits.Read(16), bits.Read(16)), + 2 => (352, 288), + 3 => (176, 144), + 4 => (128, 96), + 5 => (320, 240), + 6 => (160, 120), + _ => (0, 0), + }; + } + + /// Sample rate and channels of an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1); null when damaged. + internal static (int Rate, int Channels)? AacRateAndChannels(ReadOnlySpan config) + { + if (config.Length < 2) + { + return null; + } + + var bits = new BitReader(config, 0); + if (bits.Read(5) == 31) + { + bits.Read(6); + } + + var index = bits.Read(4); + int rate; + if (index == 15) + { + if (config.Length < 5) + { + return null; + } + + rate = bits.Read(24); + } + else if (index < AacRates.Length) + { + rate = AacRates[index]; + } + else + { + return null; + } + + var channels = bits.Read(4); + return (rate, channels switch { 7 => 8, > 7 => 0, _ => channels }); + } + + /// Reads the onMetaData script tag; true when it was one (another script tag leaves the next to be read). + private static bool Script(ReadOnlySpan data, State state, DateTimeOffset now) + { + var p = 0; + if (!Byte(data, ref p, out var type) || type != 2 || !ShortString(data, ref p, out var name) || !name.SequenceEqual("onMetaData"u8)) + { + return false; + } + + if (!Byte(data, ref p, out type)) + { + return true; + } + + if (type == 8) + { + p += 4; // approximate count of an ECMA array: the end marker closes it + } + else if (type != 3) + { + return true; + } + + var metadata = new Metadata(now); + _ = Properties(data, ref p, 0, metadata); + state.MetadataSeconds = metadata.Duration is > 0 and < 1e9 ? metadata.Duration : null; + state.MetadataWidth = metadata.Width is > 0 and <= 65535 ? (int)metadata.Width : 0; + state.MetadataHeight = metadata.Height is > 0 and <= 65535 ? (int)metadata.Height : 0; + state.Created = metadata.Created; + return true; + } + + /// The properties of an AMF0 object up to its end marker; only the top level is kept. + private static bool Properties(ReadOnlySpan data, ref int p, int depth, Metadata? metadata) + { + while (p < data.Length) + { + if (p + 3 <= data.Length && data[p] == 0 && data[p + 1] == 0 && data[p + 2] == 9) + { + p += 3; + return true; + } + + if (!ShortString(data, ref p, out var name) || !Value(data, ref p, depth, metadata, name)) + { + return false; + } + } + + return true; // an ECMA array may end with the tag, without its marker + } + + /// One AMF0 value (Action Message Format AMF0, §2); false when the data is not AMF0 or runs out. + private static bool Value(ReadOnlySpan data, ref int p, int depth, Metadata? metadata, ReadOnlySpan name) + { + if (!Byte(data, ref p, out var type)) + { + return false; + } + + switch (type) + { + case 0: // number + if (p + 8 > data.Length) + { + return false; + } + + metadata?.Number(name, BinaryPrimitives.ReadDoubleBigEndian(data[p..])); + p += 8; + return true; + case 1: // boolean + return Skip(data, ref p, 1); + case 2: // string + if (!ShortString(data, ref p, out var text)) + { + return false; + } + + metadata?.Text(name, text); + return true; + case 3: // object + return depth < AmfMaxDepth && Properties(data, ref p, depth + 1, null); + case 5 or 6 or 13: // null, undefined, unsupported + return true; + case 7: // reference + return Skip(data, ref p, 2); + case 8: // ECMA array + return depth < AmfMaxDepth && Skip(data, ref p, 4) && Properties(data, ref p, depth + 1, null); + case 10: // strict array + { + if (depth >= AmfMaxDepth || p + 4 > data.Length) + { + return false; + } + + var count = BinaryPrimitives.ReadUInt32BigEndian(data[p..]); + p += 4; + if (count > (uint)(data.Length - p)) + { + return false; // every value takes at least a byte + } + + for (var i = 0u; i < count; i++) + { + if (!Value(data, ref p, depth + 1, null, default)) + { + return false; + } + } + + return true; + } + + case 11: // date: milliseconds from 1970 and a time zone that the specification says to ignore + if (p + 10 > data.Length) + { + return false; + } + + metadata?.Date(name, BinaryPrimitives.ReadDoubleBigEndian(data[p..])); + p += 10; + return true; + case 12 or 15: // long string, XML document + { + if (p + 4 > data.Length) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt32BigEndian(data[p..]); + p += 4; + return length <= (uint)(data.Length - p) && Skip(data, ref p, (int)length); + } + + case 16: // typed object: a class name, then the properties + return depth < AmfMaxDepth && ShortString(data, ref p, out _) && Properties(data, ref p, depth + 1, null); + default: + return false; // movie clip and record set are reserved; anything else is not AMF0 + } + } + + private static bool Byte(ReadOnlySpan data, ref int p, out byte value) + { + value = p < data.Length ? data[p] : (byte)0; + p++; + return p <= data.Length; + } + + private static bool Skip(ReadOnlySpan data, ref int p, int count) + { + p += count; + return p <= data.Length; + } + + private static bool ShortString(ReadOnlySpan data, ref int p, out ReadOnlySpan text) + { + text = default; + if (p + 2 > data.Length) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(data[p..]); + p += 2; + if (p + length > data.Length) + { + return false; + } + + text = data.Slice(p, length); + p += length; + return true; + } + + /// The onMetaData properties Febe uses. + private sealed class Metadata(DateTimeOffset now) + { + internal double? Duration; + internal double? Width; + internal double? Height; + internal DateTimeOffset? Created; + + internal void Number(ReadOnlySpan name, double value) + { + if (!double.IsFinite(value)) + { + return; + } + + if (name.SequenceEqual("duration"u8)) + { + Duration = value; + } + else if (name.SequenceEqual("width"u8)) + { + Width = value; + } + else if (name.SequenceEqual("height"u8)) + { + Height = value; + } + } + + internal void Text(ReadOnlySpan name, ReadOnlySpan value) + { + if (name.SequenceEqual("creationdate"u8) && value.Length is > 0 and < 128) + { + Created = AviReader.ParseDate(Encoding.UTF8.GetString(value), now) ?? Created; + } + } + + internal void Date(ReadOnlySpan name, double milliseconds) + { + // From 1995 to a day past now, as the other readers. + if (name.SequenceEqual("creationdate"u8) && double.IsFinite(milliseconds) && milliseconds >= 788_918_400_000d + && milliseconds <= now.AddDays(1).ToUnixTimeMilliseconds()) + { + Created = DateTimeOffset.FromUnixTimeMilliseconds((long)milliseconds); + } + } + } + + private sealed class State + { + internal bool HasAudioFlag; + internal bool HasVideoFlag; + internal bool HaveScript; + internal bool HaveAudio; + internal int AudioFormat; + internal int SampleRate; + internal int Channels; + internal byte[]? AacConfiguration; + internal VideoCodec? Codec; + internal int CodecId = -1; + internal string CodecTag = string.Empty; + internal byte[]? AvcConfiguration; + internal int PictureWidth; + internal int PictureHeight; + internal double? MetadataSeconds; + internal int MetadataWidth; + internal int MetadataHeight; + internal double? LastSeconds; + internal DateTimeOffset? Created; + internal long? FirstTime; + internal readonly List Samples = []; + + /// For the metadata alone: the script, the video codec (with its sequence header for H.264) and the audio are known. + internal bool HaveEverything => + HaveScript + && (!HasVideoFlag || (Codec is not null && (Codec != VideoCodec.H264 || CodecId != 7 || AvcConfiguration is not null))) + && (!HasAudioFlag || HaveAudio); + + internal MediaContainer Build() + { + var seconds = MetadataSeconds ?? LastSeconds; + TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds.Value) : null; + VideoTrack? video = null; + if (Codec is { } codec) + { + var (width, height) = PictureWidth > 0 && PictureHeight > 0 ? (PictureWidth, PictureHeight) : (MetadataWidth, MetadataHeight); + video = new VideoTrack + { + Codec = codec, + CodecTag = CodecTag, + Width = width, + Height = height, + AvcConfiguration = CodecId == 7 ? AvcConfiguration : null, + Timescale = 1000, + Duration = duration is { } d ? (long)d.TotalMilliseconds : 0, + Samples = Samples, + }; + } + else if (MetadataWidth > 0 && MetadataHeight > 0) + { + video = new VideoTrack { Width = MetadataWidth, Height = MetadataHeight, Timescale = 1000 }; // only the metadata knows it + } + + AudioTrack? audio = HaveAudio + ? new AudioTrack + { + Codec = AudioFormat switch + { + 10 => AudioCodec.Aac, + 2 or 14 => AudioCodec.Mp3, + 0 or 3 => AudioCodec.Pcm, + _ => AudioCodec.Unknown, + }, + CodecTag = AudioFormat.ToString(System.Globalization.CultureInfo.InvariantCulture), + SampleRate = SampleRate, + Channels = Channels, + AacConfiguration = AudioFormat == 10 ? AacConfiguration : null, + Timescale = 1000, + } + : null; + return new MediaContainer { Format = ContainerFormat.Flv, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs new file mode 100644 index 0000000..79ad9f7 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -0,0 +1,978 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of the ISO base media file format (ISO/IEC 14496-12: MP4, MOV, 3GP), written from the standard: the movie +/// header, the first video and audio tracks with their sample tables, and the fragments (moof) of fragmented +/// files. Only boxes are read into memory; media data is never loaded here. +/// +public static class IsoBmffReader +{ + private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private const long MaxBoxInMemory = 128L * 1024 * 1024; + private const int MaxTopLevelBoxes = 1_000_000; + + /// Samples of one track at most (about 18 hours at 30 frames per second; 40 bytes each in memory). + internal const int MaxSamples = 2_000_000; + + /// True when the stream starts like an ISO media file (an ftyp, moov, mdat... box). + public static bool Looks(ReadOnlySpan start) => + start.Length >= 8 && (start.Slice(4, 4).SequenceEqual("ftyp"u8) || start.Slice(4, 4).SequenceEqual("moov"u8) + || start.Slice(4, 4).SequenceEqual("mdat"u8) || start.Slice(4, 4).SequenceEqual("wide"u8) + || start.Slice(4, 4).SequenceEqual("free"u8) || start.Slice(4, 4).SequenceEqual("skip"u8)); + + /// Reads a seekable stream from its start. + /// The file. + /// Current time: later creation times are ignored. + /// + /// False to stop at the metadata: no sample tables, and fragments only when they alone tell the duration (then only + /// their durations are added up). + /// + /// Checked between the top-level boxes (each fragment of a fragmented file). + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + var length = stream.Length; + long position = 0; + Span header = stackalloc byte[16]; + Movie? movie = null; + var pending = new List<(long Start, byte[] Body)>(); + for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) + { + ct.ThrowIfCancellationRequested(); + 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) + { + if (movie is not null) + { + break; // a truncated last box (often mdat): what was read stands + } + + throw new ContainerException("Box ISO danneggiato."); + } + + var type = header.Slice(4, 4); + if (type.SequenceEqual("moov"u8) && movie is null) + { + movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length); + foreach (var (start, body) in pending) + { + movie.AddFragment(start, body); + } + + pending.Clear(); + + // Metadata only: a fragmented file whose headers do not tell its duration is read on through its fragments. + if (!samples && !movie.NeedsFragmentsForDuration) + { + break; + } + } + else if (type.SequenceEqual("moof"u8) && (samples || movie is null || movie.NeedsFragmentsForDuration)) + { + var body = ReadBody(stream, position + headerSize, size - headerSize); + if (movie is null) + { + pending.Add((position, body)); // fragments before the moov: unusual, but kept + } + else + { + movie.AddFragment(position, body); // at once: the fragments of a long file are never all in memory + } + } + + position += size; + } + + if (movie is null) + { + throw new ContainerException("Manca il box moov."); + } + + return movie.Build(); + } + + private static byte[] ReadBody(Stream stream, long offset, long count) + { + if (count > MaxBoxInMemory) + { + throw new ContainerException("Box ISO troppo grande."); + } + + var body = new byte[count]; + stream.Position = offset; + stream.ReadExactly(body); + return body; + } + + private static Movie ParseMoov(byte[] moov, DateTimeOffset now, bool samples, long fileLength) + { + var movie = new Movie(samples, fileLength); + try + { + foreach (var (type, start, count) in Children(moov, 0, moov.Length)) + { + var body = moov.AsSpan(start, count); + switch (type) + { + case "mvhd": + movie.ParseMvhd(body, now); + break; + case "trak": + try + { + movie.ParseTrak(moov, start, count); + } + catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException + or ContainerException) + { + // A damaged track header, edit list or description (often of the audio track): that track is + // dropped, the others are still read. + } + + break; + case "mvex": + movie.Fragmented = true; + foreach (var (t, s, c) in Children(moov, start, count)) + { + if (t == "trex" && c >= 24) + { + // version/flags, track_ID, default_sample_description_index, then the three defaults + // (ISO/IEC 14496-12 §8.8.3): duration, size, flags. + var id = BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4)); + movie.TrackDefaults[id] = ( + BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 12)), + BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 16)), + BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 20))); + } + else if (t == "mehd" && c >= 8) + { + movie.FragmentDuration = moov[s] == 1 && c >= 12 + ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(moov.AsSpan(s + 4)), long.MaxValue) + : BinaryPrimitives.ReadUInt32BigEndian(moov.AsSpan(s + 4)); + } + } + + break; + } + } + } + catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException) + { + throw new ContainerException("Box moov danneggiato."); + } + + return movie; + } + + /// Child boxes of the box body data[start..start+count]: type, body start and body length. + internal static List<(string Type, int Start, int Length)> Children(byte[] data, int start, int count) + { + var list = new List<(string, int, int)>(); + var offset = start; + var end = start + count; + while (offset + 8 <= end && list.Count < 100_000) + { + long size = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(offset)); + var type = System.Text.Encoding.Latin1.GetString(data, offset + 4, 4); + var headerSize = 8; + if (size == 1) + { + if (offset + 16 > end) + { + break; + } + + size = (long)BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(offset + 8)); + headerSize = 16; + } + else if (size == 0) + { + size = end - offset; + } + + if (size < headerSize || size > end - offset) + { + break; + } + + list.Add((type, offset + headerSize, (int)size - headerSize)); + offset += (int)size; + } + + return list; + } + + private static int Rotation(ReadOnlySpan matrix) + { + var a = BinaryPrimitives.ReadInt32BigEndian(matrix); + var b = BinaryPrimitives.ReadInt32BigEndian(matrix[4..]); + var c = BinaryPrimitives.ReadInt32BigEndian(matrix[12..]); + var d = BinaryPrimitives.ReadInt32BigEndian(matrix[16..]); + const int One = 0x10000; + if (a == 0 && d == 0 && b == One && c == -One) + { + return 90; + } + + if (a == -One && d == -One && b == 0 && c == 0) + { + return 180; + } + + if (a == 0 && d == 0 && b == -One && c == One) + { + return 270; + } + + return 0; + } + + private sealed class Track + { + internal uint Id; + internal string Handler = string.Empty; + internal long Timescale; + internal long Duration; + internal int Rotation; + internal int TkhdWidth; + internal int TkhdHeight; + internal string Format = string.Empty; + internal int Width; + internal int Height; + internal int Channels; + internal int SampleRate; + internal byte[]? Avcc; + internal byte[]? Asc; + internal long EditOffset; + internal List Samples = []; + internal long FragmentTime = -1; + } + + private sealed class Movie(bool samples, long fileLength) + { + /// The trex defaults of each track: sample duration, size and flags. + internal readonly Dictionary TrackDefaults = []; + private readonly List tracks = []; + private DateTimeOffset? created; + private long timescale; + private long duration; + + /// True when the movie has an mvex box: its samples are in fragments. + internal bool Fragmented; + + /// fragment_duration of the mehd box, in movie units; 0 when absent. + internal long FragmentDuration; + + /// A fragmented movie whose headers give no duration: only its fragments tell it. + internal bool NeedsFragmentsForDuration => + Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0); + + internal void ParseMvhd(ReadOnlySpan body, DateTimeOffset now) + { + ulong creation; + if (body[0] == 1) + { + creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]); + timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); + duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); + } + else + { + creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); + duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); + if (duration == uint.MaxValue) + { + duration = 0; + } + } + + if (creation > 0 && creation < 400UL * 366 * 86400) + { + var instant = Epoch1904.AddSeconds(creation); + if (instant >= Earliest && instant <= now.AddDays(1)) + { + created = instant; + } + } + } + + internal void ParseTrak(byte[] data, int start, int count) + { + var track = new Track(); + foreach (var (type, s, c) in Children(data, start, count)) + { + var body = data.AsSpan(s, c); + switch (type) + { + case "tkhd": + { + var v1 = body[0] == 1; + track.Id = BinaryPrimitives.ReadUInt32BigEndian(body[(v1 ? 20 : 12)..]); + var offset = (v1 ? 36 : 24) + 16; + track.Rotation = Rotation(body.Slice(offset, 36)); + track.TkhdWidth = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 36)..]) >> 16); + track.TkhdHeight = (int)(BinaryPrimitives.ReadUInt32BigEndian(body[(offset + 40)..]) >> 16); + break; + } + + case "edts": + foreach (var (t, es, ec) in Children(data, s, c)) + { + if (t == "elst") + { + ParseElst(data.AsSpan(es, ec), track); + } + } + + break; + case "mdia": + ParseMdia(data, s, c, track); + break; + } + } + + tracks.Add(track); + } + + private static void ParseElst(ReadOnlySpan body, Track track) + { + var v1 = body[0] == 1; + var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + var offset = 8; + for (var i = 0; i < entries && i < 16; i++) + { + long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]); + offset += v1 ? 20 : 12; + if (mediaTime >= 0) + { + track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero + return; + } + } + } + + private void ParseMdia(byte[] data, int start, int count, Track track) + { + foreach (var (type, s, c) in Children(data, start, count)) + { + var body = data.AsSpan(s, c); + switch (type) + { + case "mdhd": + if (body[0] == 1) + { + track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); + track.Duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); + } + else + { + track.Timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); + var d = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); + track.Duration = d == uint.MaxValue ? 0 : d; + } + + break; + case "hdlr": + track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4)); + break; + case "minf": + foreach (var (t, ms, mc) in Children(data, s, c)) + { + if (t == "stbl") + { + ParseStbl(data, ms, mc, track); + } + } + + break; + } + } + } + + private void ParseStbl(byte[] data, int start, int count, Track track) + { + byte[]? stts = null, ctts = null, stsc = null, stsz = null, stco = null, stss = null; + var co64 = false; + var stz2 = false; + foreach (var (type, s, c) in Children(data, start, count)) + { + if (!samples && type != "stsd") + { + continue; // metadata only: the tables are not even copied + } + + switch (type) + { + case "stsd": + ParseStsd(data, s, c, track); + break; + case "stts": + stts = data[s..(s + c)]; + break; + case "ctts": + ctts = data[s..(s + c)]; + break; + case "stsc": + stsc = data[s..(s + c)]; + break; + case "stsz": + stsz = data[s..(s + c)]; + break; + case "stz2": + stsz = data[s..(s + c)]; + stz2 = true; + break; + case "stco": + stco = data[s..(s + c)]; + break; + case "co64": + stco = data[s..(s + c)]; + co64 = true; + break; + case "stss": + stss = data[s..(s + c)]; + break; + } + } + + if (!samples || stts is null || stsc is null || stsz is null || stco is null) + { + return; + } + + try + { + BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss); + } + catch (Exception ex) when (ex is ContainerException or ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException) + { + // Damaged tables, or more samples than the limit (QuickTime PCM counts every audio sample): the track + // keeps its description without samples, and the other tracks are still read. + track.Samples = []; + } + } + + private static void ParseStsd(byte[] data, int start, int count, Track track) + { + if (count < 16) + { + return; + } + + // version/flags, entry count, then the first sample entry. + var entry = start + 8; + var size = (int)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(entry)); + if (size < 16 || entry + size > start + count) + { + return; + } + + track.Format = System.Text.Encoding.Latin1.GetString(data, entry + 4, 4); + var body = entry + 8; + var bodyEnd = entry + size; + if (track.Handler == "vide" && size >= 8 + 78) + { + track.Width = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 24)); + track.Height = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 26)); + foreach (var (t, s, c) in Children(data, body + 78, bodyEnd - body - 78)) + { + if (t == "avcC") + { + track.Avcc = data[s..(s + c)]; + } + } + } + else if (track.Handler == "soun" && size >= 8 + 28) + { + var version = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 8)); + track.Channels = BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(body + 16)); + track.SampleRate = (int)(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(body + 24)) >> 16); + var children = body + 28 + (version == 1 ? 16 : version == 2 ? 36 : 0); + if (children < bodyEnd) + { + foreach (var (t, s, c) in Children(data, children, bodyEnd - children)) + { + if (t == "esds") + { + track.Asc = EsdsConfig(data.AsSpan(s, c)); + } + } + } + } + } + + /// The DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 descriptors). + private static byte[]? EsdsConfig(ReadOnlySpan body) + { + var p = 4; // version and flags + while (p + 2 <= body.Length) + { + var tag = body[p++]; + var length = 0; + for (var i = 0; i < 4 && p < body.Length; i++) + { + var b = body[p++]; + length = (length << 7) | (b & 0x7F); + if ((b & 0x80) == 0) + { + break; + } + } + + switch (tag) + { + case 0x03: // ES_Descriptor + { + if (p + 3 > body.Length) + { + return null; + } + + var flags = body[p + 2]; + p += 3; + if ((flags & 0x80) != 0) + { + p += 2; + } + + if ((flags & 0x40) != 0) + { + if (p >= body.Length) + { + return null; + } + + p += 1 + body[p]; + } + + if ((flags & 0x20) != 0) + { + p += 2; + } + + break; + } + + case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children + p += 13; + break; + case 0x05: + return p + length <= body.Length ? body.Slice(p, length).ToArray() : null; + default: + p += length; + break; + } + } + + return null; + } + + private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss) + { + int count; + uint fixedSize = 0; + var fieldSize = 32; + if (stz2) + { + fieldSize = stsz[7]; + count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8)); + } + else + { + fixedSize = BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(4)); + count = (int)BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8)); + } + + if (count < 0 || count > MaxSamples) + { + throw new ContainerException("Troppi campioni."); + } + + // The table must be able to describe that many samples and the samples must fit in the file: a few damaged + // bytes never make the reader allocate more than the file can hold. + var tableBytes = stz2 ? 12 + ((((long)count * fieldSize) + 7) / 8) : fixedSize != 0 ? 12 : 12 + (4L * count); + if (stsz.Length < tableBytes || (fixedSize != 0 && (long)count * fixedSize > fileLength) || (stz2 && fieldSize is not (4 or 8 or 16))) + { + throw new ContainerException("Tabella delle dimensioni danneggiata."); + } + + int SizeOf(int i) + { + if (!stz2) + { + return (int)(fixedSize != 0 ? fixedSize : BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(12 + (i * 4)))); + } + + return fieldSize switch + { + 4 => (stsz[12 + (i / 2)] >> ((i & 1) == 0 ? 4 : 0)) & 15, + 8 => stsz[12 + i], + _ => BinaryPrimitives.ReadUInt16BigEndian(stsz.AsSpan(12 + (i * 2))), + }; + } + + var chunkCount = (int)BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(4)); + long ChunkOffset(int i) => co64 + ? (long)BinaryPrimitives.ReadUInt64BigEndian(stco.AsSpan(8 + (i * 8))) + : BinaryPrimitives.ReadUInt32BigEndian(stco.AsSpan(8 + (i * 4))); + + // Sync samples (stss, 1-based); without the box every sample is one. At most one flag per sample. + bool[]? keys = null; + if (stss is not null) + { + keys = new bool[count]; + var n = Math.Min(BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4)), (uint)Math.Max(0, (stss.Length - 8) / 4)); + for (var i = 0; i < n; i++) + { + var number = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4))); + if (number >= 1 && number <= (uint)count) + { + keys[number - 1] = true; + } + } + } + + var list = new List(count); + + // Decode times (stts) and composition offsets (ctts) run along the samples. + var sttsEntries = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(4)); + int sttsIndex = 0, sttsLeft = 0; + uint delta = 0; + var cttsEntries = ctts is null ? 0 : BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(4)); + var cttsSigned = ctts is not null && ctts[0] == 1; + int cttsIndex = 0, cttsLeft = 0; + long offsetCt = 0; + long dts = 0; + + var stscEntries = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(4)); + var sample = 0; + for (var e = 0; e < stscEntries && sample < count; e++) + { + var firstChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + (e * 12))) - 1; + var perChunk = (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(12 + (e * 12))); + var nextFirst = e + 1 < stscEntries ? (int)BinaryPrimitives.ReadUInt32BigEndian(stsc.AsSpan(8 + ((e + 1) * 12))) - 1 : chunkCount; + for (var chunk = firstChunk; chunk < nextFirst && chunk < chunkCount && sample < count; chunk++) + { + var offset = ChunkOffset(chunk); + for (var k = 0; k < perChunk && sample < count; k++) + { + while (sttsLeft == 0 && sttsIndex < sttsEntries) + { + sttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(8 + (sttsIndex * 8))); + delta = BinaryPrimitives.ReadUInt32BigEndian(stts.AsSpan(12 + (sttsIndex * 8))); + sttsIndex++; + } + + while (ctts is not null && cttsLeft == 0 && cttsIndex < cttsEntries) + { + cttsLeft = (int)BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(8 + (cttsIndex * 8))); + offsetCt = cttsSigned + ? BinaryPrimitives.ReadInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8))) + : BinaryPrimitives.ReadUInt32BigEndian(ctts.AsSpan(12 + (cttsIndex * 8))); + cttsIndex++; + } + + var size = SizeOf(sample); + list.Add(new MediaSample(offset, size, dts, dts + offsetCt - track.EditOffset, keys is null || keys[sample])); + offset += size; + dts += delta; + sttsLeft = Math.Max(0, sttsLeft - 1); + cttsLeft = Math.Max(0, cttsLeft - 1); + sample++; + } + } + } + + track.Samples = list; + track.FragmentTime = dts; + } + + /// Adds the samples of one movie fragment (ISO/IEC 14496-12 §8.8). + internal void AddFragment(long moofStart, byte[] moof) + { + try + { + foreach (var (type, s, c) in Children(moof, 0, moof.Length)) + { + if (type == "traf") + { + AddTrackFragment(moofStart, moof, s, c); + } + } + } + catch (Exception ex) when (ex is ArgumentOutOfRangeException or IndexOutOfRangeException or OverflowException or ContainerException) + { + // A damaged fragment (or one beyond the sample limit): the samples read so far stand. + } + } + + private void AddTrackFragment(long moofStart, byte[] data, int start, int count) + { + Track? track = null; + var dataBase = moofStart; // base_data_offset, or the start of the moof (default-base-is-moof, §8.8.7.1) + var nextData = moofStart; + uint defDuration = 0, defSize = 0, defFlags = 0; + long? decodeTime = null; + foreach (var (type, s, c) in Children(data, start, count)) + { + var body = data.AsSpan(s, c); + switch (type) + { + case "tfhd": + { + var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF; + var id = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + track = tracks.Find(t => t.Id == id); + if (TrackDefaults.TryGetValue(id, out var d)) + { + (defDuration, defSize, defFlags) = d; + } + + var p = 8; + if ((flags & 0x1) != 0) + { + var wide = BinaryPrimitives.ReadUInt64BigEndian(body[p..]); + dataBase = wide > (ulong)fileLength ? fileLength : (long)wide; + p += 8; + } + + nextData = dataBase; + + if ((flags & 0x2) != 0) + { + p += 4; + } + + if ((flags & 0x8) != 0) + { + defDuration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + if ((flags & 0x10) != 0) + { + defSize = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + if ((flags & 0x20) != 0) + { + defFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + } + + break; + } + + case "tfdt": + decodeTime = body[0] == 1 + ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[4..]), long.MaxValue / 2) + : BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + break; + case "trun" when track is not null: + { + var flags = BinaryPrimitives.ReadUInt32BigEndian(body) & 0xFFFFFF; + var signed = body[0] == 1; + var n = (int)BinaryPrimitives.ReadUInt32BigEndian(body[4..]); + var p = 8; + var offset = nextData; + if ((flags & 0x1) != 0) + { + offset = dataBase + BinaryPrimitives.ReadInt32BigEndian(body[p..]); // from the base, not from the run before + p += 4; + } + + uint? firstFlags = null; + if ((flags & 0x4) != 0) + { + firstFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + // The samples either have their fields in the box or take the default size: the box or the + // file bounds how many there can be, before anything is allocated. + var perSample = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1)); + var bounded = perSample > 0 + ? (long)n * perSample <= body.Length - p + : (long)n * Math.Max(1u, defSize) <= fileLength; + if (n < 0 || !bounded || (samples && track.Samples.Count + n > MaxSamples)) + { + throw new ContainerException("Troppi campioni."); + } + + var dts = decodeTime ?? Math.Max(0, track.FragmentTime); + if (!samples) + { + // Metadata only: the fragments are read for the duration, so only durations add up. + var run = RunDuration(body[p..], flags, n, defDuration); + dts = run > (long.MaxValue / 2) - dts ? long.MaxValue / 2 : dts + run; + track.FragmentTime = dts; + decodeTime = dts; + break; + } + + for (var i = 0; i < n; i++) + { + var duration = defDuration; + var size = defSize; + var sampleFlags = i == 0 && firstFlags is { } ff ? ff : defFlags; + long ct = 0; + if ((flags & 0x100) != 0) + { + duration = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + if ((flags & 0x200) != 0) + { + size = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + if ((flags & 0x400) != 0) + { + sampleFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + if ((flags & 0x800) != 0) + { + ct = signed ? BinaryPrimitives.ReadInt32BigEndian(body[p..]) : BinaryPrimitives.ReadUInt32BigEndian(body[p..]); + p += 4; + } + + var key = (sampleFlags & 0x10000) == 0; // sample_is_non_sync_sample + track.Samples.Add(new MediaSample(offset, (int)Math.Min(size, int.MaxValue), dts, dts + ct - track.EditOffset, key)); + offset += size; + dts += duration; + } + + track.FragmentTime = dts; + decodeTime = dts; + nextData = offset; // a later trun without data_offset continues the data + break; + } + } + } + } + + /// The total duration of the samples of a trun, from their fields after the header. + private static long RunDuration(ReadOnlySpan fields, uint flags, int count, uint defaultDuration) + { + if ((flags & 0x100) == 0) + { + return (long)count * defaultDuration; + } + + var stride = 4 * (int)(((flags >> 8) & 1) + ((flags >> 9) & 1) + ((flags >> 10) & 1) + ((flags >> 11) & 1)); + long total = 0; + for (var i = 0; i < count; i++) + { + total += BinaryPrimitives.ReadUInt32BigEndian(fields[(i * stride)..]); // the duration comes first + } + + return total; + } + + internal MediaContainer Build() + { + var video = tracks.Find(t => t.Handler == "vide"); + var audio = tracks.Find(t => t.Handler == "soun"); + VideoTrack? v = null; + if (video is not null) + { + v = new VideoTrack + { + Codec = video.Format switch + { + "avc1" or "avc3" => VideoCodec.H264, + "hvc1" or "hev1" => VideoCodec.Hevc, + "vp08" => VideoCodec.Vp8, + "vp09" => VideoCodec.Vp9, + "av01" => VideoCodec.Av1, + "mp4v" => VideoCodec.Mpeg4Part2, + "jpeg" or "mjpa" => VideoCodec.Mjpeg, + _ => VideoCodec.Unknown, + }, + CodecTag = video.Format, + Width = video.Width > 0 ? video.Width : video.TkhdWidth, + Height = video.Height > 0 ? video.Height : video.TkhdHeight, + Rotation = video.Rotation, + Timescale = video.Timescale > 0 ? video.Timescale : 1, + Duration = DurationOf(video), + AvcConfiguration = video.Avcc, + Samples = video.Samples, + }; + } + + AudioTrack? a = null; + if (audio is not null) + { + a = new AudioTrack + { + Codec = audio.Format switch + { + "mp4a" => AudioCodec.Aac, + ".mp3" => AudioCodec.Mp3, + "Opus" => AudioCodec.Opus, + "lpcm" or "sowt" or "twos" => AudioCodec.Pcm, + _ => AudioCodec.Unknown, + }, + CodecTag = audio.Format, + Channels = audio.Channels, + SampleRate = audio.SampleRate, + AacConfiguration = audio.Asc, + Timescale = audio.Timescale > 0 ? audio.Timescale : 1, + Duration = DurationOf(audio), + Samples = audio.Samples, + }; + } + + var movieDuration = duration > 0 ? duration : FragmentDuration; + TimeSpan? total = timescale > 0 && movieDuration > 0 ? Seconds((double)movieDuration / timescale) : null; + if (total is null && v is { Duration: > 0 }) + { + total = Seconds(v.Seconds(v.Duration)); + } + + return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a }; + } + + /// A duration in seconds; null when it is beyond what a video can last (a damaged header). + private static TimeSpan? Seconds(double seconds) => seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; + + private static long DurationOf(Track track) + { + if (track.FragmentTime > track.Duration) + { + return track.FragmentTime; // fragmented: the header says 0 + } + + return track.Duration; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs new file mode 100644 index 0000000..f04168e --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -0,0 +1,766 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of Matroska and WebM (EBML, RFC 8794, and the Matroska specification, RFC 9559), written from the +/// specifications: segment information, the first video and audio tracks and, when asked, the blocks of the clusters. +/// Elements are read one by one from the stream; the frames are never loaded here. +/// +public static class MatroskaReader +{ + private static readonly DateTimeOffset Epoch2001 = new(2001, 1, 1, 0, 0, 0, TimeSpan.Zero); + private static readonly DateTimeOffset Earliest = new(1995, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private const uint EbmlId = 0x1A45DFA3; + private const uint SegmentId = 0x18538067; + private const uint InfoId = 0x1549A966; + private const uint TracksId = 0x1654AE6B; + private const uint ClusterId = 0x1F43B675; + private const uint CuesId = 0x1C53BB6B; + private const uint TagsId = 0x1254C367; + private const uint AttachmentsId = 0x1941A469; + private const uint ChaptersId = 0x1043A770; + private const uint SeekHeadId = 0x114D9B74; + private const long UnknownSize = -1; + private const int MaxSamples = IsoBmffReader.MaxSamples; + private const long MaxElementInMemory = 64L * 1024 * 1024; + + /// True when the stream starts with an EBML header. + public static bool Looks(ReadOnlySpan start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId; + + /// Reads a seekable stream from its start. + /// The file. + /// Current time: later creation times are ignored. + /// False to stop before the first cluster. + /// Checked between the top-level elements. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + var reader = new Reader(stream); + stream.Position = 0; + var (id, size) = reader.Header(); + if (id != EbmlId || size < 0) + { + throw new ContainerException("Intestazione EBML mancante."); + } + + var docType = "matroska"; + var end = stream.Position + size; + while (stream.Position < end) + { + var (cid, csize) = reader.Header(); + if (cid == 0x4282) + { + docType = reader.String(csize); + } + else + { + reader.Skip(csize); + } + } + + if (docType is not ("matroska" or "webm")) + { + throw new ContainerException("Documento EBML che non è Matroska."); + } + + stream.Position = Math.Min(end, stream.Length); + (id, size) = reader.Header(); + while (id != SegmentId) + { + if (size < 0) + { + throw new ContainerException("Segmento Matroska mancante."); + } + + reader.Skip(size); + (id, size) = reader.Header(); + } + + var segmentEnd = size < 0 ? stream.Length : Math.Min(stream.Length, stream.Position + size); + var state = new State(); + while (stream.Position < segmentEnd) + { + ct.ThrowIfCancellationRequested(); + var elementStart = stream.Position; + if (segmentEnd - elementStart < 2) + { + break; + } + + try + { + (id, size) = reader.Header(); + var bodyEnd = size < 0 ? segmentEnd : stream.Position + size; + if (bodyEnd > segmentEnd) + { + bodyEnd = segmentEnd; // truncated file + } + + switch (id) + { + case InfoId: + ParseInfo(reader, bodyEnd, state, now); + break; + case TracksId: + ParseTracks(reader, bodyEnd, state); + break; + case ClusterId: + if (!samples) + { + return state.Build(); + } + + ParseCluster(reader, bodyEnd, size < 0, state); + continue; // the position is already past the cluster + default: + if (size < 0) + { + throw new ContainerException("Elemento Matroska di lunghezza ignota."); + } + + break; + } + + stream.Position = bodyEnd; + } + catch (Exception ex) when ((ex is ContainerException or EndOfStreamException) && state.HasSamples) + { + // A damaged or truncated block after the first ones, or more samples than the limit: what was read + // stands, as in the ISO reader. + break; + } + } + + return state.Build(); + } + + private static void ParseInfo(Reader reader, long end, State state, DateTimeOffset now) + { + var stream = reader.Stream; + while (stream.Position < end) + { + var (id, size) = reader.Header(); + switch (id) + { + case 0x2AD7B1: + state.TimecodeScale = (long)reader.Unsigned(size); + break; + case 0x4489: + { + var ticks = reader.Float(size); + state.DurationTicks = double.IsFinite(ticks) && ticks > 0 ? ticks : 0; + break; + } + + case 0x4461: + { + // Nanoseconds from 2001: about ±292 years, always inside the range of a date. + var ns = reader.Signed(size); + var instant = Epoch2001.AddTicks(ns / 100); + if (instant >= Earliest && instant <= now.AddDays(1)) + { + state.Created = instant; + } + + break; + } + + default: + reader.Skip(size); + break; + } + } + } + + private static void ParseTracks(Reader reader, long end, State state) + { + var stream = reader.Stream; + while (stream.Position < end) + { + var (id, size) = reader.Header(); + if (id != 0xAE) + { + reader.Skip(size); + continue; + } + + if (size < 0) + { + throw new ContainerException("Elemento Matroska di lunghezza ignota."); + } + + var entryEnd = stream.Position + size; + var track = new TrackEntry(); + while (stream.Position < entryEnd) + { + var (tid, tsize) = reader.Header(); + switch (tid) + { + case 0xD7: + track.Number = (long)reader.Unsigned(tsize); + break; + case 0x83: + track.Type = (int)reader.Unsigned(tsize); + break; + case 0x86: + track.CodecId = reader.String(tsize); + break; + case 0x63A2: + track.CodecPrivate = reader.Bytes(tsize); + break; + case 0x23E383: + track.DefaultDuration = (long)reader.Unsigned(tsize); + break; + case 0x55EE: // MaxBlockAdditionID, and others: ignored + reader.Skip(tsize); + break; + case 0xE0: + { + var videoEnd = stream.Position + tsize; + while (stream.Position < videoEnd) + { + var (vid, vsize) = reader.Header(); + switch (vid) + { + case 0xB0: + track.Width = (int)reader.Unsigned(vsize); + break; + case 0xBA: + track.Height = (int)reader.Unsigned(vsize); + break; + case 0x7670: // Projection + { + var projectionEnd = stream.Position + vsize; + while (stream.Position < projectionEnd) + { + var (pid, psize) = reader.Header(); + if (pid == 0x7675) + { + track.Roll = reader.Float(psize); + } + else + { + reader.Skip(psize); + } + } + + break; + } + + default: + reader.Skip(vsize); + break; + } + } + + break; + } + + case 0xE1: + { + var audioEnd = stream.Position + tsize; + while (stream.Position < audioEnd) + { + var (aid, asize) = reader.Header(); + switch (aid) + { + case 0xB5: + track.SampleRate = (int)reader.Float(asize); + break; + case 0x9F: + track.Channels = (int)reader.Unsigned(asize); + break; + default: + reader.Skip(asize); + break; + } + } + + break; + } + + default: + reader.Skip(tsize); + break; + } + } + + stream.Position = Math.Min(entryEnd, stream.Length); + if (track.Type == 1 && state.Video is null) + { + state.Video = track; + } + else if (track.Type == 2 && state.Audio is null) + { + state.Audio = track; + } + } + } + + private static void ParseCluster(Reader reader, long end, bool unknownSize, State state) + { + var stream = reader.Stream; + long clusterTime = 0; + while (stream.Position < end) + { + var start = stream.Position; + if (end - start < 2) + { + stream.Position = end; + return; + } + + var (id, size) = reader.Header(); + if (unknownSize && id is ClusterId or CuesId or TagsId or AttachmentsId or ChaptersId or SeekHeadId or InfoId or TracksId) + { + stream.Position = start; // the next top-level element ends a cluster of unknown size + return; + } + + if (size < 0) + { + throw new ContainerException("Elemento Matroska di lunghezza ignota."); + } + + var bodyEnd = Math.Min(stream.Position + size, end); + switch (id) + { + case 0xE7: + clusterTime = (long)reader.Unsigned(size); + break; + case 0xA3: // SimpleBlock + AddBlock(reader, stream.Position, bodyEnd, clusterTime, simple: true, hasReference: false, state); + break; + case 0xA0: // BlockGroup + { + long blockStart = -1, blockEnd = -1; + var reference = false; + while (stream.Position < bodyEnd) + { + var (gid, gsize) = reader.Header(); + if (gid == 0xA1) + { + blockStart = stream.Position; + blockEnd = Math.Min(blockStart + gsize, bodyEnd); + } + else if (gid == 0xFB) + { + reference = true; + } + + reader.Skip(gsize); + } + + if (blockStart >= 0) + { + AddBlock(reader, blockStart, blockEnd, clusterTime, simple: false, reference, state); + } + + break; + } + } + + stream.Position = bodyEnd; + } + } + + private static void AddBlock(Reader reader, long start, long end, long clusterTime, bool simple, bool hasReference, State state) + { + var stream = reader.Stream; + stream.Position = start; + var track = (long)reader.VintValue(); + Span fixedPart = stackalloc byte[3]; + stream.ReadExactly(fixedPart); + var relative = BinaryPrimitives.ReadInt16BigEndian(fixedPart); + var flags = fixedPart[2]; + var key = simple ? (flags & 0x80) != 0 : !hasReference; + var target = track == state.Video?.Number ? state.Video : track == state.Audio?.Number ? state.Audio : null; + if (target is null) + { + return; + } + + if (target.Samples.Count >= MaxSamples) + { + throw new ContainerException("Troppi campioni."); + } + + var time = state.ToUnits(clusterTime + relative); + var lacing = (flags >> 1) & 3; + var dataStart = stream.Position; + if (lacing == 0) + { + if (end - dataStart is <= 0 or > int.MaxValue) + { + throw new ContainerException("Blocco Matroska danneggiato."); + } + + target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key)); + return; + } + + var count = stream.ReadByte(); + if (count < 0 || dataStart >= end) + { + throw new ContainerException("Blocco Matroska troncato."); + } + + var frames = count + 1; + Span sizes = stackalloc long[frames]; + switch (lacing) + { + case 1: // Xiph + for (var i = 0; i < frames - 1; i++) + { + long value = 0; + int b; + do + { + b = stream.ReadByte(); + if (b < 0) + { + throw new ContainerException("Blocco Matroska troncato."); + } + + value += b; + } + while (b == 255); + sizes[i] = value; + } + + break; + case 3: // EBML + { + sizes[0] = (long)reader.VintValue(); + for (var i = 1; i < frames - 1; i++) + { + var (raw, length) = reader.VintRaw(); + var bias = (1L << ((7 * length) - 1)) - 1; + sizes[i] = sizes[i - 1] + ((long)raw - bias); + } + + break; + } + } + + var dataBegin = stream.Position; + var total = end - dataBegin; + if (lacing == 2) + { + for (var i = 0; i < frames; i++) + { + sizes[i] = total / frames; + } + } + else + { + long used = 0; + for (var i = 0; i < frames - 1; i++) + { + used += sizes[i]; + } + + sizes[frames - 1] = total - used; + } + + var offset = dataBegin; + var frameDuration = target.DefaultDuration > 0 ? target.DefaultDuration / state.UnitNanoseconds : 0; + for (var i = 0; i < frames; i++) + { + if (sizes[i] < 0 || sizes[i] > int.MaxValue || offset + sizes[i] > end) + { + throw new ContainerException("Blocco Matroska danneggiato."); + } + + var t = time + (i * frameDuration); + if (sizes[i] == 0) + { + continue; // an empty frame has nothing to decode (and costs no memory) + } + + target.Samples.Add(new MediaSample(offset, (int)sizes[i], t, t, key)); + offset += sizes[i]; + } + } + + private sealed class TrackEntry + { + internal long Number = -1; + internal int Type; + internal string CodecId = string.Empty; + internal byte[]? CodecPrivate; + internal long DefaultDuration; + internal int Width; + internal int Height; + internal double Roll; + internal int SampleRate; + internal int Channels; + internal readonly List Samples = []; + } + + private sealed class State + { + internal long TimecodeScale = 1_000_000; + internal double DurationTicks; + internal DateTimeOffset? Created; + internal TrackEntry? Video; + internal TrackEntry? Audio; + + /// Nanoseconds of one unit of the sample times; fixed by the first block, 0 before. + private long unit; + + internal bool HasSamples => Video?.Samples.Count > 0 || Audio?.Samples.Count > 0; + + /// + /// Nanoseconds of one unit of the sample times: the greatest common divisor of TimecodeScale and a second, so + /// that the timescale of the tracks (a second in units) is exact for any TimecodeScale (3 ms gives units of + /// 1 ms, 2 s units of 1 s) and the block times are whole units. + /// + internal long UnitNanoseconds + { + get + { + if (unit == 0) + { + long a = Scale, b = 1_000_000_000; + while (b != 0) + { + (a, b) = (b, a % b); + } + + unit = a; + } + + return unit; + } + } + + /// TimecodeScale (nanoseconds of a tick of the block times); the default for a damaged value. + private long Scale => TimecodeScale > 0 ? TimecodeScale : 1_000_000; + + /// Units of in a tick (at least 1, should Info come after the first block). + private long Factor => Math.Max(1, Scale / UnitNanoseconds); + + /// A time in TimecodeScale ticks as a time in units of . + internal long ToUnits(long ticks) + { + var limit = long.MaxValue / 4 / Factor; + return Math.Clamp(ticks, -limit, limit) * Factor; // a damaged cluster time stays a (wrong) number + } + + internal MediaContainer Build() + { + var timescale = 1_000_000_000L / UnitNanoseconds; + var trackDuration = DurationTicks * Factor; + var trackUnits = trackDuration is > 0 and < long.MaxValue / 2 ? (long)trackDuration : 0; + VideoTrack? video = null; + if (Video is { } v) + { + var samples = v.Samples; + if (samples.Count > 0) + { + // Blocks carry presentation times in decoding order; decoding times are those times sorted. + var times = new long[samples.Count]; + for (var i = 0; i < times.Length; i++) + { + times[i] = samples[i].PresentationTime; + } + + Array.Sort(times); + for (var i = 0; i < times.Length; i++) + { + samples[i] = samples[i] with { DecodeTime = times[i] }; + } + } + + var roll = ((int)Math.Round(-v.Roll) % 360 + 360) % 360; + video = new VideoTrack + { + Codec = v.CodecId switch + { + "V_MPEG4/ISO/AVC" => VideoCodec.H264, + "V_MPEGH/ISO/HEVC" => VideoCodec.Hevc, + "V_VP8" => VideoCodec.Vp8, + "V_VP9" => VideoCodec.Vp9, + "V_AV1" => VideoCodec.Av1, + "V_MJPEG" => VideoCodec.Mjpeg, + _ when v.CodecId.StartsWith("V_MPEG4/ISO/", StringComparison.Ordinal) => VideoCodec.Mpeg4Part2, + _ => VideoCodec.Unknown, + }, + CodecTag = v.CodecId, + Width = v.Width, + Height = v.Height, + Rotation = roll is 90 or 180 or 270 ? roll : 0, + AvcConfiguration = v.CodecId == "V_MPEG4/ISO/AVC" ? v.CodecPrivate : null, + Timescale = timescale, + Duration = trackUnits, + Samples = samples, + }; + } + + AudioTrack? audio = null; + if (Audio is { } a) + { + audio = new AudioTrack + { + Codec = a.CodecId switch + { + _ when a.CodecId.StartsWith("A_AAC", StringComparison.Ordinal) => AudioCodec.Aac, + "A_MPEG/L3" => AudioCodec.Mp3, + "A_OPUS" => AudioCodec.Opus, + "A_VORBIS" => AudioCodec.Vorbis, + _ when a.CodecId.StartsWith("A_PCM", StringComparison.Ordinal) => AudioCodec.Pcm, + _ => AudioCodec.Unknown, + }, + CodecTag = a.CodecId, + SampleRate = a.SampleRate, + Channels = a.Channels, + AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null, + Timescale = timescale, + Duration = trackUnits, + Samples = a.Samples, + }; + } + + var seconds = DurationTicks * TimecodeScale / 1e9; + TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; + return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; + } + } + + /// EBML primitives over the stream. + private sealed class Reader(Stream stream) + { + internal Stream Stream => stream; + + internal (uint Id, long Size) Header() + { + var first = stream.ReadByte(); + if (first <= 0) + { + throw new ContainerException("Elemento EBML non valido."); + } + + var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24); + if (length > 4) + { + throw new ContainerException("Identificatore EBML non valido."); + } + + var id = (uint)first; + for (var i = 1; i < length; i++) + { + id = (id << 8) | (uint)ReadByteOrThrow(); + } + + var (raw, sizeLength) = VintRaw(); + var allOnes = (1UL << (7 * sizeLength)) - 1; + return (id, raw == allOnes ? UnknownSize : (long)raw); + } + + internal (ulong Raw, int Length) VintRaw() + { + var first = ReadByteOrThrow(); + if (first == 0) + { + throw new ContainerException("Intero EBML non valido."); + } + + var length = 1 + System.Numerics.BitOperations.LeadingZeroCount((uint)first << 24); + ulong value = (ulong)(first & (0xFF >> length)); + for (var i = 1; i < length; i++) + { + value = (value << 8) | (uint)ReadByteOrThrow(); + } + + return (value, length); + } + + internal ulong VintValue() => VintRaw().Raw; + + internal ulong Unsigned(long size) + { + if (size is < 0 or > 8) + { + throw new ContainerException("Intero EBML troppo lungo."); + } + + ulong value = 0; + for (var i = 0; i < size; i++) + { + value = (value << 8) | (uint)ReadByteOrThrow(); + } + + return value; + } + + internal long Signed(long size) + { + var value = Unsigned(size); + if (size is > 0 and < 8 && (value & (1UL << (int)((size * 8) - 1))) != 0) + { + value |= ulong.MaxValue << (int)(size * 8); + } + + return (long)value; + } + + internal double Float(long size) + { + Span buffer = stackalloc byte[8]; + if (size == 4) + { + stream.ReadExactly(buffer[..4]); + return BinaryPrimitives.ReadSingleBigEndian(buffer); + } + + if (size == 8) + { + stream.ReadExactly(buffer); + return BinaryPrimitives.ReadDoubleBigEndian(buffer); + } + + Skip(size); + return 0; + } + + internal string String(long size) => Encoding.UTF8.GetString(Bytes(size)).TrimEnd('\0'); + + internal byte[] Bytes(long size) + { + if (size < 0 || size > MaxElementInMemory) + { + throw new ContainerException("Elemento Matroska troppo grande."); + } + + if (size > stream.Length - stream.Position) + { + throw new ContainerException("File Matroska troncato."); // before allocating what the file cannot hold + } + + var data = new byte[size]; + stream.ReadExactly(data); + return data; + } + + internal void Skip(long size) + { + if (size < 0) + { + throw new ContainerException("Elemento Matroska di lunghezza ignota."); + } + + // Past the end of a truncated or damaged file the reading simply ends there. + stream.Position = size > stream.Length - stream.Position ? stream.Length : stream.Position + size; + } + + private int ReadByteOrThrow() + { + var b = stream.ReadByte(); + return b < 0 ? throw new ContainerException("File Matroska troncato.") : b; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/MediaContainer.cs b/src/Febe.Core/Codecs/Containers/MediaContainer.cs new file mode 100644 index 0000000..442d177 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/MediaContainer.cs @@ -0,0 +1,161 @@ +namespace Febe.Core.Codecs.Containers; + +/// The container formats Febe reads without external programs. +public enum ContainerFormat +{ + /// ISO base media file format: MP4, MOV, 3GP, M4V (also fragmented). + IsoBmff, + + /// Matroska and WebM. + Matroska, + + /// RIFF AVI (also OpenDML). + Avi, + + /// Advanced Systems Format: WMV, WMA and ASF files (metadata only). + Asf, + + /// Flash Video (FLV). + Flv, + + /// MPEG program stream (ISO/IEC 11172-1 and 13818-1): MPG, MPEG, VOB (metadata only). + MpegPs, +} + +/// Video codecs recognised in a container; only can be decoded. +public enum VideoCodec +{ + Unknown, + H264, + Hevc, + Vp8, + Vp9, + Av1, + Mpeg4Part2, + Mjpeg, + + /// MPEG-1 video (ISO/IEC 11172-2). + Mpeg1, + + /// MPEG-2 video (ITU-T H.262). + Mpeg2, + + /// Windows Media Video 7 and 8 (WMV1, WMV2). + Wmv, + + /// Windows Media Video 9 and VC-1 (WMV3, WMVA, WVC1). + Vc1, + + /// H.263 and its Sorenson Spark variant of FLV. + H263, + + /// On2 VP6 of FLV. + Vp6, +} + +/// Audio codecs recognised in a container. +public enum AudioCodec +{ + Unknown, + Aac, + Mp3, + Opus, + Vorbis, + Pcm, + + /// MPEG audio layer I or II. + Mp2, + + /// AC-3 (Dolby Digital). + Ac3, + + /// Windows Media Audio (all versions). + Wma, +} + +/// +/// One sample (an access unit) of a track: where its bytes are in the file and when it is decoded and shown, in units of +/// the track's . Samples are listed in decoding order. +/// +public readonly record struct MediaSample(long Offset, int Size, long DecodeTime, long PresentationTime, bool Key); + +/// A track of a container. +public abstract class MediaTrack +{ + /// Ticks per second of the sample times. + public long Timescale { get; init; } = 1000; + + /// Duration of the track in units; 0 when unknown. + public long Duration { get; init; } + + /// Samples in decoding order (empty when the container was read for its metadata only). + public IReadOnlyList Samples { get; init; } = []; + + /// The four-character code or codec identifier of the container, for messages. + public string CodecTag { get; init; } = string.Empty; + + /// Time in seconds of a value in track units. + public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0; +} + +/// The video track of a container. +public sealed class VideoTrack : MediaTrack +{ + public VideoCodec Codec { get; init; } + + /// Coded width in pixels (before rotation). + public int Width { get; init; } + + /// Coded height in pixels (before rotation). + public int Height { get; init; } + + /// Clockwise rotation to apply when showing the frames: 0, 90, 180 or 270. + public int Rotation { get; init; } + + /// The AVCDecoderConfigurationRecord (avcC) of an H.264 track stored with length prefixes. + public byte[]? AvcConfiguration { get; init; } + + /// True when the samples are an Annex B byte stream (start codes), as in AVI. + public bool AnnexB { get; init; } + + /// Width as shown (rotation applied). + public int DisplayWidth => Rotation % 180 == 0 ? Width : Height; + + /// Height as shown (rotation applied). + public int DisplayHeight => Rotation % 180 == 0 ? Height : Width; +} + +/// The audio track of a container. +public sealed class AudioTrack : MediaTrack +{ + public AudioCodec Codec { get; init; } + + public int SampleRate { get; init; } + + public int Channels { get; init; } + + /// The AudioSpecificConfig of an AAC track. + public byte[]? AacConfiguration { get; init; } +} + +/// What a container says: its creation time, duration and first video and audio tracks. +public sealed class MediaContainer +{ + public ContainerFormat Format { get; init; } + + /// Creation time written in the container, when plausible. + public DateTimeOffset? CreatedAt { get; init; } + + /// Duration of the whole presentation. + public TimeSpan? Duration { get; init; } + + /// The title written in the container (ASF content description), when there is one. + public string? Title { get; init; } + + public VideoTrack? Video { get; init; } + + public AudioTrack? Audio { get; init; } +} + +/// A container that cannot be read: damaged, truncated or of a shape Febe does not handle. +public sealed class ContainerException(string message) : Exception(message); diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs new file mode 100644 index 0000000..9cf4406 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -0,0 +1,647 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Core.Codecs.Containers; + +/// A sample to write: its size, its times in track units, whether it is a sync sample. +public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key); + +/// A track to write: H.264 video (with its avcC) or AAC audio (with its AudioSpecificConfig). +public sealed class Mp4OutputTrack +{ + public required bool IsVideo { get; init; } + + public required long Timescale { get; init; } + + public required IReadOnlyList Samples { get; init; } + + /// Writes the bytes of sample i (exactly its ) into the stream. + public required Action WriteSample { get; init; } + + public int Width { get; init; } + + public int Height { get; init; } + + /// Clockwise rotation written in the track matrix: 0, 90, 180 or 270. + public int Rotation { get; init; } + + public byte[]? AvcConfiguration { get; init; } + + public byte[]? AacConfiguration { get; init; } + + public int SampleRate { get; init; } + + public int Channels { get; init; } + + /// Duration of the last sample, when the times cannot tell it (0: as the one before it). + public long LastSampleDuration { get; init; } +} + +/// +/// Writer of MP4 files (ISO/IEC 14496-12 and 14496-14/15), written from the standards: ftyp, then the +/// moov box (so the file plays while it downloads), then one mdat with the tracks interleaved about every +/// half second. +/// +public static class Mp4Writer +{ + private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero); + private const int MovieTimescale = 1000; + + /// Writes the tracks into (from its current position). + public static void Write(Stream output, IReadOnlyList tracks, DateTimeOffset? created = null) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(tracks); + if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0)) + { + throw new ArgumentException("Servono tracce con campioni.", nameof(tracks)); + } + + foreach (var track in tracks) + { + if (track.IsVideo ? track.AvcConfiguration is null : track.AacConfiguration is null) + { + throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks)); + } + } + + var timing = tracks.Select(Timing.Of).ToArray(); + var chunks = Interleave(tracks); + long payload = 0; + foreach (var track in tracks) + { + foreach (var s in track.Samples) + { + payload += s.Size; + } + } + + var wideMdat = payload + 8 > uint.MaxValue; + var ftyp = Ftyp(); + var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL; + + // The moov box has the same size whatever the chunk offsets: build it once to know where the data starts. + var co64 = false; + var moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time); + var dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8); + if (dataStart + payload > uint.MaxValue) + { + co64 = true; + moov = Moov(tracks, timing, chunks, new long[chunks.Count], co64, time); + dataStart = ftyp.Length + moov.Length + (wideMdat ? 16 : 8); + } + + var offsets = new long[chunks.Count]; + var position = (long)dataStart; + for (var i = 0; i < chunks.Count; i++) + { + offsets[i] = position; + var (track, first, count) = chunks[i]; + for (var k = first; k < first + count; k++) + { + position += tracks[track].Samples[k].Size; + } + } + + moov = Moov(tracks, timing, chunks, offsets, co64, time); + output.Write(ftyp); + output.Write(moov); + Span header = stackalloc byte[16]; + if (wideMdat) + { + BinaryPrimitives.WriteUInt32BigEndian(header, 1); + "mdat"u8.CopyTo(header[4..]); + BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16)); + output.Write(header); + } + else + { + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8)); + "mdat"u8.CopyTo(header[4..]); + output.Write(header[..8]); + } + + foreach (var (track, first, count) in chunks) + { + for (var k = first; k < first + count; k++) + { + var before = output.CanSeek ? output.Position : -1; + tracks[track].WriteSample(k, output); + if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size) + { + throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata."); + } + } + } + } + + /// Times of a track as the boxes need them. + private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey) + { + internal static Timing Of(Mp4OutputTrack track) + { + var samples = track.Samples; + var n = samples.Count; + var durations = new long[n]; + for (var i = 0; i < n - 1; i++) + { + durations[i] = Math.Max(0, samples[i + 1].DecodeTime - samples[i].DecodeTime); + } + + durations[n - 1] = track.LastSampleDuration > 0 ? track.LastSampleDuration : n > 1 ? durations[n - 2] : 1; + + // Decoding must not come after presentation: delay the decoding times when it would. + long shift = 0; + var minPts = long.MaxValue; + foreach (var s in samples) + { + shift = Math.Max(shift, s.DecodeTime - s.PresentationTime); + minPts = Math.Min(minPts, s.PresentationTime); + } + + var first = samples[0].DecodeTime; + var offsets = new int[n]; + var allKey = true; + for (var i = 0; i < n; i++) + { + offsets[i] = (int)Math.Clamp(samples[i].PresentationTime - samples[i].DecodeTime + shift, 0, int.MaxValue); + allKey &= samples[i].Key; + } + + long total = 0; + foreach (var d in durations) + { + total += d; + } + + // The edit list starts the presentation at the first shown sample. + var editTime = minPts - first + shift; + return new Timing(durations, offsets, total, editTime, allKey); + } + } + + private static List<(int Track, int First, int Count)> Interleave(IReadOnlyList tracks) + { + var list = new List<(int Track, int First, int Count, double Start)>(); + for (var t = 0; t < tracks.Count; t++) + { + var track = tracks[t]; + var samples = track.Samples; + var first = 0; + var limit = track.Timescale / 2; + var start = 0.0; + for (var i = 1; i <= samples.Count; i++) + { + if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024) + { + // Never earlier than the chunk before: the chunks of a track stay in sample order whatever its times. + start = Math.Max(start, (double)(samples[first].DecodeTime - samples[0].DecodeTime) / track.Timescale); + list.Add((t, first, i - first, start)); + first = i; + } + } + } + + // Ties (equal times, as tracks without times have) keep each track's chunks in order: the sort is not stable. + list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track != b.Track ? a.Track.CompareTo(b.Track) : a.First.CompareTo(b.First)); + return list.ConvertAll(c => (c.Track, c.First, c.Count)); + } + + private static byte[] Ftyp() + { + var box = new Box("ftyp"); + box.Bytes("isom"u8); + box.U32(512); + box.Bytes("isomiso2avc1mp41"u8); + return box.ToArray(); + } + + private static byte[] Moov(IReadOnlyList tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + { + long movieDuration = 0; + for (var t = 0; t < tracks.Count; t++) + { + movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale)); + } + + var moov = new Box("moov"); + var mvhd = new Box("mvhd"); + var wide = movieDuration > uint.MaxValue || time > uint.MaxValue; + mvhd.U32(wide ? 0x01000000u : 0); + Times(mvhd, wide, time, MovieTimescale, movieDuration); + mvhd.U32(0x00010000); + mvhd.U16(0x0100); + mvhd.Zero(10); + Matrix(mvhd, 0, 0, 0); + mvhd.Zero(24); + mvhd.U32((uint)tracks.Count + 1); + moov.Child(mvhd); + + for (var t = 0; t < tracks.Count; t++) + { + moov.Child(Trak(tracks[t], timing[t], t, chunks, offsets, co64, time)); + } + + return moov.ToArray(); + } + + private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale); + + private static void Times(Box box, bool wide, ulong time, long timescale, long duration) + { + if (wide) + { + box.U64(time); + box.U64(time); + box.U32((uint)timescale); + box.U64((ulong)duration); + } + else + { + box.U32((uint)time); + box.U32((uint)time); + box.U32((uint)timescale); + box.U32((uint)duration); + } + } + + private static void Matrix(Box box, int rotation, int width, int height) + { + int a = 0x10000, b = 0, c = 0, d = 0x10000, x = 0, y = 0; + switch (rotation) + { + case 90: + (a, b, c, d, x) = (0, 0x10000, -0x10000, 0, height << 16); + break; + case 180: + (a, d, x, y) = (-0x10000, -0x10000, width << 16, height << 16); + break; + case 270: + (a, b, c, d, y) = (0, -0x10000, 0x10000, 0, width << 16); + break; + } + + foreach (var v in new[] { a, b, 0, c, d, 0, x, y, 0x40000000 }) + { + box.U32((uint)v); + } + } + + private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + { + var trak = new Box("trak"); + var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale); + var wide = duration > uint.MaxValue || time > uint.MaxValue; + var tkhd = new Box("tkhd"); + tkhd.U32((wide ? 0x01000000u : 0) | 3); + if (wide) + { + tkhd.U64(time); + tkhd.U64(time); + tkhd.U32((uint)index + 1); + tkhd.U32(0); + tkhd.U64((ulong)duration); + } + else + { + tkhd.U32((uint)time); + tkhd.U32((uint)time); + tkhd.U32((uint)index + 1); + tkhd.U32(0); + tkhd.U32((uint)duration); + } + + tkhd.Zero(8); + tkhd.U16(0); + tkhd.U16(0); + tkhd.U16(track.IsVideo ? (ushort)0 : (ushort)0x0100); + tkhd.U16(0); + Matrix(tkhd, track.IsVideo ? track.Rotation : 0, track.Width, track.Height); + tkhd.U32(track.IsVideo ? (uint)track.Width << 16 : 0); + tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0); + trak.Child(tkhd); + + if (timing.EditMediaTime != 0) + { + var edts = new Box("edts"); + var elst = new Box("elst"); + elst.U32(0x01000000); + elst.U32(1); + elst.U64((ulong)duration); + elst.U64((ulong)timing.EditMediaTime); + elst.U16(1); + elst.U16(0); + edts.Child(elst); + trak.Child(edts); + } + + var mdia = new Box("mdia"); + var mdhd = new Box("mdhd"); + var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue; + mdhd.U32(mediaWide ? 0x01000000u : 0); + Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration); + mdhd.U16(0x55C4); // «und» + mdhd.U16(0); + mdia.Child(mdhd); + + var hdlr = new Box("hdlr"); + hdlr.U32(0); + hdlr.U32(0); + hdlr.Bytes(track.IsVideo ? "vide"u8 : "soun"u8); + hdlr.Zero(12); + hdlr.Bytes(track.IsVideo ? "VideoHandler\0"u8 : "SoundHandler\0"u8); + mdia.Child(hdlr); + + var minf = new Box("minf"); + if (track.IsVideo) + { + var vmhd = new Box("vmhd"); + vmhd.U32(1); + vmhd.Zero(8); + minf.Child(vmhd); + } + else + { + var smhd = new Box("smhd"); + smhd.U32(0); + smhd.Zero(4); + minf.Child(smhd); + } + + var dinf = new Box("dinf"); + var dref = new Box("dref"); + dref.U32(0); + dref.U32(1); + var url = new Box("url "); + url.U32(1); + dref.Child(url); + dinf.Child(dref); + minf.Child(dinf); + minf.Child(Stbl(track, timing, index, chunks, offsets, co64)); + mdia.Child(minf); + trak.Child(mdia); + return trak; + } + + private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64) + { + var stbl = new Box("stbl"); + var stsd = new Box("stsd"); + stsd.U32(0); + stsd.U32(1); + stsd.Child(track.IsVideo ? Avc1(track) : Mp4a(track)); + stbl.Child(stsd); + + // stts: runs of equal durations. + var stts = new Box("stts"); + var runs = new List<(int Count, long Delta)>(); + foreach (var d in timing.Durations) + { + if (runs.Count > 0 && runs[^1].Delta == d) + { + runs[^1] = (runs[^1].Count + 1, d); + } + else + { + runs.Add((1, d)); + } + } + + stts.U32(0); + stts.U32((uint)runs.Count); + foreach (var (count, delta) in runs) + { + stts.U32((uint)count); + stts.U32((uint)delta); + } + + stbl.Child(stts); + + var anyOffset = false; + foreach (var o in timing.CompositionOffsets) + { + anyOffset |= o != 0; + } + + if (anyOffset) + { + var ctts = new Box("ctts"); + var cruns = new List<(int Count, int Offset)>(); + foreach (var o in timing.CompositionOffsets) + { + if (cruns.Count > 0 && cruns[^1].Offset == o) + { + cruns[^1] = (cruns[^1].Count + 1, o); + } + else + { + cruns.Add((1, o)); + } + } + + ctts.U32(0); + ctts.U32((uint)cruns.Count); + foreach (var (count, offset) in cruns) + { + ctts.U32((uint)count); + ctts.U32((uint)offset); + } + + stbl.Child(ctts); + } + + if (track.IsVideo && !timing.AllKey) + { + var stss = new Box("stss"); + var keys = new List(); + for (var i = 0; i < track.Samples.Count; i++) + { + if (track.Samples[i].Key) + { + keys.Add(i + 1); + } + } + + stss.U32(0); + stss.U32((uint)keys.Count); + foreach (var k in keys) + { + stss.U32((uint)k); + } + + stbl.Child(stss); + } + + // stsc and the chunk offsets of this track, in file order. + var stsc = new Box("stsc"); + var entries = new List<(int FirstChunk, int PerChunk)>(); + var mine = new List(); + for (var c = 0; c < chunks.Count; c++) + { + if (chunks[c].Track != index) + { + continue; + } + + mine.Add(offsets[c]); + if (entries.Count == 0 || entries[^1].PerChunk != chunks[c].Count) + { + entries.Add((mine.Count, chunks[c].Count)); + } + } + + stsc.U32(0); + stsc.U32((uint)entries.Count); + foreach (var (firstChunk, perChunk) in entries) + { + stsc.U32((uint)firstChunk); + stsc.U32((uint)perChunk); + stsc.U32(1); + } + + stbl.Child(stsc); + + var stsz = new Box("stsz"); + stsz.U32(0); + stsz.U32(0); + stsz.U32((uint)track.Samples.Count); + foreach (var s in track.Samples) + { + stsz.U32((uint)s.Size); + } + + stbl.Child(stsz); + + var stco = new Box(co64 ? "co64" : "stco"); + stco.U32(0); + stco.U32((uint)mine.Count); + foreach (var o in mine) + { + if (co64) + { + stco.U64((ulong)o); + } + else + { + stco.U32((uint)o); + } + } + + stbl.Child(stco); + return stbl; + } + + private static Box Avc1(Mp4OutputTrack track) + { + var entry = new Box("avc1"); + entry.Zero(6); + entry.U16(1); + entry.Zero(16); + entry.U16((ushort)track.Width); + entry.U16((ushort)track.Height); + entry.U32(0x00480000); + entry.U32(0x00480000); + entry.U32(0); + entry.U16(1); + entry.Zero(32); + entry.U16(0x0018); + entry.U16(0xFFFF); + var avcC = new Box("avcC"); + avcC.Bytes(track.AvcConfiguration); + entry.Child(avcC); + return entry; + } + + private static Box Mp4a(Mp4OutputTrack track) + { + var entry = new Box("mp4a"); + entry.Zero(6); + entry.U16(1); + entry.Zero(8); + entry.U16((ushort)Math.Max(1, track.Channels)); + entry.U16(16); + entry.U16(0); + entry.U16(0); + entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16); + + var asc = track.AacConfiguration!; + var decoderSpecific = Descriptor(0x05, asc); + var config = new byte[13 + decoderSpecific.Length]; + config[0] = 0x40; // MPEG-4 audio + config[1] = 0x15; // audio stream + decoderSpecific.CopyTo(config, 13); + byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])]; + var esds = new Box("esds"); + esds.U32(0); + esds.Bytes(Descriptor(0x03, es)); + entry.Child(esds); + return entry; + } + + private static byte[] Descriptor(byte tag, ReadOnlySpan body) + { + var data = new byte[5 + body.Length]; + data[0] = tag; + var length = body.Length; + data[1] = (byte)(0x80 | ((length >> 21) & 0x7F)); + data[2] = (byte)(0x80 | ((length >> 14) & 0x7F)); + data[3] = (byte)(0x80 | ((length >> 7) & 0x7F)); + data[4] = (byte)(length & 0x7F); + body.CopyTo(data.AsSpan(5)); + return data; + } + + /// A box being built in memory. + private sealed class Box + { + private readonly MemoryStream body = new(); + + internal Box(string type) => Type = type; + + internal string Type { get; } + + internal void U16(ushort v) + { + Span b = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16BigEndian(b, v); + body.Write(b); + } + + internal void U32(uint v) + { + Span b = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(b, v); + body.Write(b); + } + + internal void U64(ulong v) + { + Span b = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(b, v); + body.Write(b); + } + + internal void Zero(int count) + { + for (var i = 0; i < count; i++) + { + body.WriteByte(0); + } + } + + internal void Bytes(ReadOnlySpan data) => body.Write(data); + + internal void Child(Box child) => body.Write(child.ToArray()); + + internal byte[] ToArray() + { + var size = body.Length + 8; + var result = new byte[size]; + BinaryPrimitives.WriteUInt32BigEndian(result, (uint)size); + Encoding.Latin1.GetBytes(Type, result.AsSpan(4, 4)); + body.Position = 0; + body.ReadExactly(result, 8, (int)body.Length); + return result; + } + } +} diff --git a/src/Febe.Core/Codecs/Containers/MpegPsReader.cs b/src/Febe.Core/Codecs/Containers/MpegPsReader.cs new file mode 100644 index 0000000..736a015 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/MpegPsReader.cs @@ -0,0 +1,696 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Codecs.Containers; + +/// +/// Reader of MPEG program streams (MPG, MPEG, VOB), written from ISO/IEC 13818-1 §2.5 and, for the MPEG-1 system layer, +/// ISO/IEC 11172-1: pack headers (MPEG-1 and MPEG-2), the system header, the program stream map and the PES packets. Only +/// the first megabytes and the last megabyte of the file are read. The duration runs from the first presentation time of +/// the video (or the audio, or the clock of the packs) to the last one, plus a frame; codec and size come from the +/// program stream map and the start of the video stream: the sequence header of MPEG-1 and MPEG-2 video (ISO/IEC +/// 11172-2 §2.4.2.3, ITU-T H.262 §6.2.2), the SPS of H.264. The samples of a program stream are cut into PES packets and +/// are not listed: the tracks have no samples. +/// +public static class MpegPsReader +{ + /// Bytes read from the start of the file. + private const int HeadWindow = 2 * 1024 * 1024; + + /// Bytes read from the end of the file, for the last time. + private const int TailWindow = 1024 * 1024; + + /// Bytes of the video stream gathered to find its headers. + private const int MaxVideoProbe = 1024 * 1024; + + /// Presentation times are 33-bit numbers of a 90 kHz clock. + private const long TimeWrap = 1L << 33; + + private const int ClockRate = 90_000; + + /// Ticks of 90 kHz per frame for each frame_rate_code of MPEG-1 and MPEG-2 video (0 = forbidden or reserved). + private static readonly int[] FrameTicks = [0, 3754, 3750, 3600, 3003, 3000, 1800, 1502, 1500]; + + private static readonly int[] MpegAudioRates = [44100, 48000, 32000]; + + private static readonly int[] AacRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; + + /// True when the stream starts with an MPEG-1 or MPEG-2 pack header. + public static bool Looks(ReadOnlySpan start) => + start.Length >= 5 && start[0] == 0 && start[1] == 0 && start[2] == 1 && start[3] == 0xBA + && ((start[4] & 0xC0) == 0x40 || (start[4] & 0xF0) == 0x20); + + /// Reads a seekable stream: its first megabytes and its last. + public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(stream); + _ = now; // a program stream carries no date + _ = samples; // nor samples that sit whole in the file + var length = stream.Length; + var headLength = (int)Math.Min(length, HeadWindow); + var state = new State(); + var buffer = ArrayPool.Shared.Rent(Math.Max(1, headLength)); + try + { + stream.Position = 0; + stream.ReadExactly(buffer, 0, headLength); + if (!Looks(buffer.AsSpan(0, headLength))) + { + throw new ContainerException("Non è un flusso di programma MPEG."); + } + + Scan(buffer.AsSpan(0, headLength), state, head: true, ct); + state.FinishVideo(final: true, whole: headLength == length); + if (length > headLength) + { + var tailStart = Math.Max(headLength, length - TailWindow); + var tailLength = (int)(length - tailStart); + stream.Position = tailStart; + stream.ReadExactly(buffer, 0, tailLength); + Scan(buffer.AsSpan(0, tailLength), state, head: false, ct); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + state.Release(); + } + + return state.Build(); + } + + /// The packs and packets of a window of the file; anything else is skipped up to the next start code. + private static void Scan(ReadOnlySpan data, State state, bool head, CancellationToken ct) + { + ReadOnlySpan startCode = [0, 0, 1]; + var p = 0; + var count = 0; + while (p + 4 <= data.Length) + { + if ((++count & 1023) == 0) + { + ct.ThrowIfCancellationRequested(); + } + + if (data[p] != 0 || data[p + 1] != 0 || data[p + 2] != 1) + { + var next = data[(p + 1)..].IndexOf(startCode); + if (next < 0) + { + return; + } + + p += 1 + next; + continue; + } + + var id = data[p + 3]; + if (id == 0xBA) + { + if (p + 12 > data.Length) + { + return; + } + + if ((data[p + 4] & 0xC0) == 0x40) + { + if (p + 14 > data.Length) + { + return; + } + + state.Mpeg2System = true; + state.Clocks.Add(Scr(data.Slice(p + 4, 6)), head); + p += 14 + (data[p + 13] & 7); + } + else if ((data[p + 4] & 0xF0) == 0x20) + { + state.Clocks.Add(Timestamp(data.Slice(p + 4, 5)), head); + p += 12; + } + else + { + p += 4; + } + + continue; + } + + if (id < 0xBB) + { + p += 3; // the end code, or a start code of an elementary stream met while looking for a packet + continue; + } + + if (p + 6 > data.Length) + { + return; + } + + var size = BinaryPrimitives.ReadUInt16BigEndian(data[(p + 4)..]); + var available = Math.Min(size, data.Length - p - 6); + var body = data.Slice(p + 6, available); + var whole = available == size; + if (id == 0xBC) + { + if (whole) + { + StreamMap(body, state); + } + } + else if (id is >= 0xC0 and <= 0xEF or 0xBD) + { + Packet(id, body, state, head); + } + + if (!whole) + { + return; + } + + p += 6 + size; + } + } + + /// A PES packet of an audio or video stream: its presentation time and, at the start of the file, its payload. + private static void Packet(int id, ReadOnlySpan body, State state, bool head) + { + if (!PesHeader(body, out var pts, out var payloadStart)) + { + return; + } + + var payload = body[payloadStart..]; + var key = id; + if (id == 0xBD) + { + if (payload.Length < 1) + { + return; + } + + key = 0x100 | payload[0]; // private stream 1: the sub-stream number (DVD: AC-3, DTS, LPCM) + if (payload[0] is not (>= 0x80 and <= 0x8F or >= 0xA0 and <= 0xA7)) + { + return; // subtitles and the like + } + } + + if (head) + { + if (id is >= 0xE0 and <= 0xEF && state.VideoId < 0) + { + state.VideoId = id; + } + else if (id is >= 0xC0 and <= 0xDF or 0xBD && state.AudioId < 0) + { + state.AudioId = key; + Audio(id, payload, state); + } + } + + if (key == state.VideoId) + { + state.VideoTimes.Add(pts, head); + if (head) + { + state.AddVideo(payload); + } + } + else if (key == state.AudioId) + { + state.AudioTimes.Add(pts, head); + } + } + + /// + /// The header of a PES packet, MPEG-2 (§2.4.3.7, «10» first) or MPEG-1 (stuffing, buffer size, then the times): + /// its presentation time (-1 without one) and where its payload starts; false when it is not a header. + /// + private static bool PesHeader(ReadOnlySpan b, out long pts, out int payload) + { + pts = -1; + payload = 0; + if (b.Length < 1) + { + return false; + } + + if ((b[0] & 0xC0) == 0x80) + { + if (b.Length < 3 || 3 + b[2] > b.Length) + { + return false; + } + + payload = 3 + b[2]; + if ((b[1] & 0x80) != 0) + { + if (b[2] < 5) + { + return false; + } + + pts = Timestamp(b.Slice(3, 5)); + return pts >= 0; + } + + return true; + } + + var i = 0; + while (i < b.Length && i < 16 && b[i] == 0xFF) + { + i++; + } + + if (i < b.Length && (b[i] & 0xC0) == 0x40) + { + i += 2; // STD buffer scale and size + } + + if (i >= b.Length) + { + return false; + } + + if ((b[i] & 0xF0) is 0x20 or 0x30) + { + var fields = (b[i] & 0xF0) == 0x20 ? 5 : 10; + if (i + fields > b.Length) + { + return false; + } + + pts = Timestamp(b.Slice(i, 5)); + payload = i + fields; + return pts >= 0; + } + + if (b[i] != 0x0F) + { + return false; + } + + payload = i + 1; + return true; + } + + /// A 33-bit time in five bytes with three marker bits (PTS, DTS, SCR of MPEG-1); -1 when a marker is wrong. + private static long Timestamp(ReadOnlySpan b) + { + if ((b[0] & 1) == 0 || (b[2] & 1) == 0 || (b[4] & 1) == 0) + { + return -1; + } + + return ((long)((b[0] >> 1) & 7) << 30) | ((long)b[1] << 22) | ((long)(b[2] >> 1) << 15) | ((long)b[3] << 7) | ((long)b[4] >> 1); + } + + /// The base of the system clock reference of an MPEG-2 pack header (§2.5.3.4); -1 when a marker is wrong. + private static long Scr(ReadOnlySpan b) + { + if ((b[0] & 4) == 0 || (b[2] & 4) == 0 || (b[4] & 4) == 0 || (b[5] & 1) == 0) + { + return -1; + } + + return ((long)((b[0] >> 3) & 7) << 30) | ((long)(b[0] & 3) << 28) | ((long)b[1] << 20) | ((long)(b[2] >> 3) << 15) + | ((long)(b[2] & 3) << 13) | ((long)b[3] << 5) | ((long)b[4] >> 3); + } + + /// The stream types of the program stream map (§2.5.4), by elementary stream ID. + private static void StreamMap(ReadOnlySpan body, State state) + { + if (body.Length < 6) + { + return; + } + + var info = BinaryPrimitives.ReadUInt16BigEndian(body[2..]); + var p = 4 + info; + if (p + 2 > body.Length) + { + return; + } + + var end = Math.Min(body.Length, p + 2 + BinaryPrimitives.ReadUInt16BigEndian(body[p..])); + p += 2; + while (p + 4 <= end) + { + state.StreamTypes[body[p + 1]] = body[p]; + p += 4 + BinaryPrimitives.ReadUInt16BigEndian(body[(p + 2)..]); + } + } + + /// Codec, sample rate and channels of the first payload of the audio stream. + private static void Audio(int id, ReadOnlySpan payload, State state) + { + if (id == 0xBD) + { + var sub = payload[0]; + if (sub is >= 0xA0 and <= 0xA7) + { + state.AudioCodec = AudioCodec.Pcm; // DVD LPCM: frequency and channels in its sixth byte + state.AudioTag = "LPCM"; + if (payload.Length >= 6) + { + state.SampleRate = ((payload[5] >> 4) & 3) == 1 ? 96000 : 48000; + state.Channels = (payload[5] & 7) + 1; + } + } + else if (sub <= 0x87) + { + state.AudioCodec = AudioCodec.Ac3; + state.AudioTag = "AC-3"; + if (payload.Length > 4) + { + Ac3(payload[4..], state); + } + } + else + { + state.AudioTag = "DTS"; + } + + return; + } + + state.AudioTag = "MPEG"; + for (var i = 0; i + 4 <= payload.Length; i++) + { + var b = payload.Slice(i, 4); + if (b[0] != 0xFF || (b[1] & 0xE0) != 0xE0) + { + continue; + } + + if ((b[1] & 0xF6) == 0xF0) + { + // ADTS (ISO/IEC 13818-7): AAC in an MPEG-2 audio stream. + var index = (b[2] >> 2) & 0xF; + if (index < AacRates.Length) + { + state.AudioCodec = AudioCodec.Aac; + state.SampleRate = AacRates[index]; + var channels = ((b[2] & 1) << 2) | (b[3] >> 6); + state.Channels = channels == 7 ? 8 : channels; + return; + } + + continue; + } + + var version = (b[1] >> 3) & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5 + var layer = (b[1] >> 1) & 3; // 3 layer I, 2 layer II, 1 layer III + var rate = (b[2] >> 2) & 3; + if (version == 1 || layer == 0 || rate == 3 || (b[2] >> 4) == 15) + { + continue; + } + + state.AudioCodec = layer == 1 ? AudioCodec.Mp3 : AudioCodec.Mp2; + state.SampleRate = MpegAudioRates[rate] >> (version == 3 ? 0 : version == 2 ? 1 : 2); + state.Channels = (b[3] >> 6) == 3 ? 1 : 2; + return; + } + } + + /// Sample rate and channels of an AC-3 sync frame (ATSC A/52 §5.3): fscod, acmod and lfeon. + private static void Ac3(ReadOnlySpan data, State state) + { + var sync = data.IndexOf((ReadOnlySpan)[0x0B, 0x77]); + if (sync < 0 || sync + 8 > data.Length) + { + return; + } + + var frame = data[sync..]; + var fscod = frame[4] >> 6; + if (fscod == 3) + { + return; + } + + state.SampleRate = fscod switch { 0 => 48000, 1 => 44100, _ => 32000 }; + var bits = new BitReader(frame, (5 * 8) + 8); // after syncword, crc1, fscod and frmsizecod, bsid and bsmod + var acmod = bits.Read(3); + if ((acmod & 1) != 0 && acmod != 1) + { + bits.Read(2); // cmixlev + } + + if ((acmod & 4) != 0) + { + bits.Read(2); // surmixlev + } + + if (acmod == 2) + { + bits.Read(2); // dsurmod + } + + state.Channels = (acmod switch { 0 => 2, 1 => 1, 2 => 2, 3 or 4 => 3, 5 or 6 => 4, _ => 5 }) + bits.Read(1); + } + + private sealed class State + { + internal readonly byte[] StreamTypes = new byte[256]; + internal bool Mpeg2System; + internal int VideoId = -1; + internal int AudioId = -1; + + internal readonly Timeline Clocks = new(); + internal readonly Timeline VideoTimes = new(); + internal readonly Timeline AudioTimes = new(); + + internal VideoCodec Codec = VideoCodec.Unknown; + internal int Width; + internal int Height; + internal int FrameDuration; + internal bool VideoDone; + private byte[]? probe; + private int probed; + private int nextLook = 16 * 1024; + + internal AudioCodec AudioCodec = AudioCodec.Unknown; + internal string AudioTag = string.Empty; + internal int SampleRate; + internal int Channels; + + /// Gathers the start of the video stream and looks at it now and then, until its headers are found. + internal void AddVideo(ReadOnlySpan payload) + { + if (VideoDone || payload.IsEmpty) + { + return; + } + + probe ??= ArrayPool.Shared.Rent(MaxVideoProbe); + var take = Math.Min(payload.Length, MaxVideoProbe - probed); + payload[..take].CopyTo(probe.AsSpan(probed)); + probed += take; + if (probed >= nextLook || probed == MaxVideoProbe) + { + nextLook = probed * 4; + FinishVideo(final: probed == MaxVideoProbe, whole: false); + } + } + + /// + /// Codec and size from what was gathered; with nothing more will come, and with + /// the stream ends there. + /// + internal void FinishVideo(bool final, bool whole) + { + if (VideoDone || VideoId < 0) + { + return; + } + + var data = probe is null ? ReadOnlySpan.Empty : probe.AsSpan(0, probed); + var type = StreamTypes[VideoId]; + if (type is 0 or 1 or 2 && MpegVideo(data, type, final)) + { + VideoDone = true; + return; + } + + if (type is 0 or 0x1B && H264StreamInfo.TryPictureSizeFromAnnexB(data, whole, out var width, out var height)) + { + (Codec, Width, Height, VideoDone) = (VideoCodec.H264, width, height, true); + return; + } + + if (final) + { + Codec = type switch + { + 1 => VideoCodec.Mpeg1, + 2 => VideoCodec.Mpeg2, + 0x10 => VideoCodec.Mpeg4Part2, + 0x1B => VideoCodec.H264, + 0x24 => VideoCodec.Hevc, + 0xEA => VideoCodec.Vc1, + _ => VideoCodec.Unknown, + }; + VideoDone = true; + } + } + + /// The sequence header of MPEG-1 or MPEG-2 video and, for MPEG-2, its sequence extension right after it. + private bool MpegVideo(ReadOnlySpan data, byte type, bool final) + { + ReadOnlySpan sequence = [0, 0, 1, 0xB3]; + ReadOnlySpan startCode = [0, 0, 1]; + var at = data.IndexOf(sequence); + if (at < 0 || at + 12 > data.Length) + { + return false; + } + + var width = (data[at + 4] << 4) | (data[at + 5] >> 4); + var height = ((data[at + 5] & 0xF) << 8) | data[at + 6]; + var rate = data[at + 7] & 0xF; + var next = data[(at + 12)..].IndexOf(startCode); + bool mpeg2; + if (next >= 0 && at + 12 + next + 7 <= data.Length) + { + // Sequence extension (H.262 §6.2.2.3): extension ID 1, then the two high bits of each size. + var e = data[(at + 12 + next)..]; + mpeg2 = e[3] == 0xB5 && (e[4] >> 4) == 1; + if (mpeg2) + { + width |= (((e[5] & 1) << 1) | (e[6] >> 7)) << 12; + height |= ((e[6] >> 5) & 3) << 12; + } + } + else if (final) + { + mpeg2 = type == 2 || (type == 0 && Mpeg2System); + } + else + { + return false; + } + + if (width == 0 || height == 0) + { + return false; + } + + (Codec, Width, Height) = (mpeg2 ? VideoCodec.Mpeg2 : VideoCodec.Mpeg1, width, height); + FrameDuration = rate < FrameTicks.Length ? FrameTicks[rate] : 0; + return true; + } + + internal void Release() + { + if (probe is not null) + { + ArrayPool.Shared.Return(probe); + probe = null; + } + } + + internal MediaContainer Build() + { + long? ticks = null; + if (VideoTimes.Elapsed() is { } video) + { + ticks = video + FrameDuration; + } + else if (AudioTimes.Elapsed() is { } audio) + { + ticks = audio; + } + else if (Clocks.Elapsed() is { } clock) + { + ticks = clock; + } + + TimeSpan? duration = ticks is > 0 ? TimeSpan.FromSeconds((double)ticks.Value / ClockRate) : null; + var videoTrack = VideoId < 0 ? null : new VideoTrack + { + Codec = Codec, + CodecTag = StreamTypes[VideoId] != 0 + ? "0x" + StreamTypes[VideoId].ToString("X2", CultureInfo.InvariantCulture) + : Codec.ToString(), + Width = Width, + Height = Height, + AnnexB = Codec == VideoCodec.H264, + Timescale = ClockRate, + Duration = ticks ?? 0, + }; + var audioTrack = AudioId < 0 ? null : new AudioTrack + { + Codec = AudioCodec, + CodecTag = AudioTag, + SampleRate = SampleRate, + Channels = Channels, + Timescale = ClockRate, + }; + return new MediaContainer { Format = ContainerFormat.MpegPs, Duration = duration, Video = videoTrack, Audio = audioTrack }; + } + } + + /// + /// The times of one stream, as distances from the first one seen, across the wrap of the 33-bit clock: at the start of + /// the file a time up to half the clock (13 hours) away either way, at the end any time up to ten seconds before. + /// + private sealed class Timeline + { + private const long Mask = TimeWrap - 1; + private const long TailSlack = 10L * ClockRate; + private long reference = -1; + private long headFirst; + private long headLast; + private long tailLast = long.MinValue; + + internal void Add(long time, bool head) + { + if (time < 0) + { + return; + } + + if (reference < 0) + { + if (!head) + { + return; // nothing seen at the start: the end alone tells no length + } + + reference = time; + return; + } + + var distance = (time - reference) & Mask; + if (head) + { + distance = distance >= TimeWrap / 2 ? distance - TimeWrap : distance; + headFirst = Math.Min(headFirst, distance); + headLast = Math.Max(headLast, distance); + } + else + { + distance = distance > TimeWrap - TailSlack ? distance - TimeWrap : distance; + tailLast = Math.Max(tailLast, distance); + } + } + + /// Ticks from the earliest time at the start to the latest at the end; null without two times. + internal long? Elapsed() + { + if (reference < 0) + { + return null; + } + + var last = tailLast != long.MinValue ? tailLast : headLast; + return last > headFirst ? last - headFirst : null; + } + } +} diff --git a/src/Febe.Core/Codecs/H264/CabacEngine.cs b/src/Febe.Core/Codecs/H264/CabacEngine.cs new file mode 100644 index 0000000..645db82 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/CabacEngine.cs @@ -0,0 +1,169 @@ +using System.Buffers.Binary; +using System.Numerics; + +namespace Febe.Core.Codecs.H264; + +/// +/// The arithmetic decoding engine of CABAC (§9.3.1.2 and §9.3.3.2), with the context variables of the slice. The slice +/// data is read through a 64-bit window refilled four bytes at a time, and renormalisation shifts all its bits at once +/// (the count of leading zeros of the range): the arithmetic is the one of the standard, bit for bit. +/// +internal sealed class CabacEngine +{ + private readonly byte[] state = new byte[CabacTables.ContextCount]; + private readonly byte[] mps = new byte[CabacTables.ContextCount]; + private RbspReader reader = null!; + private byte[] data = []; + private int range; + private int offset; + + /// The next bits of the slice data, from the most significant bit. + private ulong window; + + /// Valid bits at the top of . + private int bits; + + /// The next byte of to load into the window. + private int next; + + /// Initialises the context variables (§9.3.1.1). + internal void InitContexts(SliceHeader header, int sliceQp) + { + var table = header.IsIntra ? CabacTables.InitI : CabacTables.InitPB[header.CabacInitIdc]; + var qp = Math.Clamp(sliceQp, 0, 51); + for (var i = 0; i < CabacTables.ContextCount; i++) + { + int m = table[i * 2], n = table[(i * 2) + 1]; + var pre = Math.Clamp(((m * qp) >> 4) + n, 1, 126); + if (pre <= 63) + { + state[i] = (byte)(63 - pre); + mps[i] = 0; + } + else + { + state[i] = (byte)(pre - 64); + mps[i] = 1; + } + } + } + + /// Initialises the decoding engine at the current, byte-aligned position (§9.3.1.2). + internal void Start(RbspReader source) + { + reader = source; + data = source.Data; + var position = source.Position; + next = position >> 3; + window = 0; + bits = 0; + Refill(); + var skip = position & 7; + window <<= skip; + bits -= skip; + + range = 510; + offset = Take(9); + if (offset >= range) + { + throw new H264Exception("Dati CABAC non validi."); + } + } + + internal int Decision(int ctx) + { + var s = state[ctx]; + var lps = CabacTables.RangeLps[(s << 2) + ((range >> 6) & 3)]; + range -= lps; + int bin; + if (offset >= range) + { + bin = mps[ctx] ^ 1; + offset -= range; + range = lps; + if (s == 0) + { + mps[ctx] ^= 1; + } + + state[ctx] = CabacTables.NextStateLps[s]; + } + else + { + bin = mps[ctx]; + if (s < 62) + { + state[ctx] = (byte)(s + 1); + } + } + + if (range < 256) + { + // RenormD (§9.3.3.2.2): as many single-bit steps as the range has leading zeros below bit 8. + var shift = BitOperations.LeadingZeroCount((uint)range) - 23; + range <<= shift; + offset = (offset << shift) | Take(shift); + } + + return bin; + } + + internal int Bypass() + { + offset = (offset << 1) | Take(1); + if (offset >= range) + { + offset -= range; + return 1; + } + + return 0; + } + + internal int Terminate() + { + range -= 2; + if (offset >= range) + { + // The end of the slice or an I_PCM macroblock: the reader goes on exactly after the bits read here. + reader.Position = (next * 8) - bits; + return 1; + } + + if (range < 256) + { + range <<= 1; + offset = (offset << 1) | Take(1); + } + + return 0; + } + + /// The next bits (1 to 32) of the slice data. + private int Take(int count) + { + if (bits < count) + { + Refill(); + } + + var value = (int)(window >> (64 - count)); + window <<= count; + bits -= count; + return value; + } + + /// + /// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see + /// ); a damaged slice that reads beyond the padding fails as the bit reader would. + /// + private void Refill() + { + while (bits <= 32) + { + window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits); + next += 4; + bits += 32; + } + } +} diff --git a/src/Febe.Core/Codecs/H264/CabacTables.cs b/src/Febe.Core/Codecs/H264/CabacTables.cs new file mode 100644 index 0000000..0186420 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/CabacTables.cs @@ -0,0 +1,248 @@ +namespace Febe.Core.Codecs.H264; + +/// +/// Tables of the CABAC engine (ITU-T H.264 §9.3): rangeTabLPS, the state transitions and the (m, n) pairs that +/// initialise the context variables (tables 9-12 to 9-24, transcribed from the text of ITU-T H.264 03/2005). The +/// contexts of field coding are included for completeness, though Febe decodes progressive frames only. +/// +internal static class CabacTables +{ + /// Number of context variables kept by the decoder. + internal const int ContextCount = 460; + + /// rangeTabLPS[pStateIdx * 4 + qCodIRangeIdx] (table 9-44). + internal static readonly byte[] RangeLps = + [ + 128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195, + 111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166, 95, 116, 137, 158, 90, 110, 130, 150, + 85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116, + 66, 80, 95, 110, 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89, + 51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72, 41, 50, 59, 69, + 39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53, + 30, 37, 43, 50, 29, 35, 41, 48, 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41, + 23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31, + 18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24, + 14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21, 12, 14, 17, 20, 11, 14, 16, 19, + 11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14, + 8, 10, 12, 14, 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11, + 6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2, + ]; + + /// transIdxLPS (table 9-45). + internal static readonly byte[] NextStateLps = + [ + 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, + 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, + 38, 63, + ]; + + + + // Tables 9-12 to 9-24 of ITU-T H.264 (03/2005), every ctxIdx from 0 to 459 in order, each as m, n. Context 276 + // (end_of_slice_flag) has no initialisation; contexts 11-59 do not occur in I slices. + private static readonly sbyte[] I = + [ + 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, + 7, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, + 0, 11, 1, 55, 0, 69, -17, 127, -13, 102, 0, 82, -7, 74, -21, 107, -27, 127, -31, 127, + -24, 127, -18, 95, -27, 127, -21, 114, -30, 127, -17, 123, -12, 115, -16, 122, -11, 115, -12, 63, + -2, 68, -15, 84, -13, 104, -3, 70, -8, 93, -10, 90, -30, 127, -1, 74, -6, 97, -7, 91, + -20, 127, -4, 56, -5, 82, -7, 76, -22, 125, -7, 93, -11, 87, -3, 77, -5, 71, -4, 63, + -4, 68, -12, 84, -7, 62, -7, 65, 8, 61, 5, 56, -2, 66, 1, 64, 0, 61, -2, 78, + 1, 50, 7, 52, 10, 35, 0, 44, 11, 38, 1, 45, 0, 46, 5, 44, 31, 17, 1, 51, + 7, 50, 28, 19, 16, 33, 14, 62, -13, 108, -15, 100, -13, 101, -13, 91, -12, 94, -10, 88, + -16, 84, -10, 86, -7, 83, -13, 87, -19, 94, 1, 70, 0, 72, -5, 74, 18, 59, -8, 102, + -15, 100, 0, 95, -4, 75, 2, 72, -11, 75, -3, 71, 15, 46, -13, 69, 0, 62, 0, 65, + 21, 37, -15, 72, 9, 57, 16, 54, 0, 62, 12, 72, 24, 0, 15, 9, 8, 25, 13, 18, + 15, 9, 13, 19, 10, 37, 12, 18, 6, 29, 20, 33, 15, 30, 4, 45, 1, 58, 0, 62, + 7, 61, 12, 38, 11, 45, 15, 39, 11, 42, 13, 44, 16, 45, 12, 41, 10, 49, 30, 34, + 18, 42, 10, 55, 17, 51, 17, 46, 0, 89, 26, -19, 22, -17, 26, -17, 30, -25, 28, -20, + 33, -23, 37, -27, 33, -23, 40, -28, 38, -17, 33, -11, 40, -15, 41, -6, 38, 1, 41, 17, + 30, -6, 27, 3, 26, 22, 37, -16, 35, -4, 38, -8, 38, -3, 37, 3, 38, 5, 42, 0, + 35, 16, 39, 22, 14, 48, 27, 37, 21, 60, 12, 68, 2, 97, -3, 71, -6, 42, -5, 50, + -3, 54, -2, 62, 0, 58, 1, 63, -2, 72, -1, 74, -9, 91, -5, 67, -5, 27, -3, 39, + -2, 44, 0, 46, -16, 64, -8, 68, -10, 78, -6, 77, -10, 86, -12, 92, -15, 55, -10, 60, + -6, 62, -4, 65, -12, 73, -8, 76, -7, 80, -9, 88, -17, 110, -11, 97, -20, 84, -11, 79, + -6, 73, -4, 74, -13, 86, -13, 96, -11, 97, -19, 117, -8, 78, -5, 33, -4, 48, -2, 53, + -3, 62, -13, 71, -10, 79, -12, 86, -13, 90, -14, 97, 0, 0, -6, 93, -6, 84, -8, 79, + 0, 66, -1, 71, 0, 62, -2, 60, -2, 59, -5, 75, -3, 62, -4, 58, -9, 66, -1, 79, + 0, 71, 3, 68, 10, 44, -7, 62, 15, 36, 14, 40, 16, 27, 12, 29, 1, 44, 20, 36, + 18, 32, 5, 42, 1, 48, 10, 62, 17, 46, 9, 64, -12, 104, -11, 97, -16, 96, -7, 88, + -8, 85, -7, 85, -9, 85, -13, 88, 4, 66, -3, 77, -3, 76, -6, 76, 10, 58, -1, 76, + -1, 83, -7, 99, -14, 95, 2, 95, 0, 76, -5, 74, 0, 70, -11, 75, 1, 68, 0, 65, + -14, 73, 3, 62, 4, 62, -1, 68, -13, 75, 11, 55, 5, 64, 12, 70, 15, 6, 6, 19, + 7, 16, 12, 14, 18, 13, 13, 11, 13, 15, 15, 16, 12, 23, 13, 23, 15, 20, 14, 26, + 14, 44, 17, 40, 17, 47, 24, 17, 21, 21, 25, 22, 31, 27, 22, 29, 19, 35, 14, 50, + 10, 57, 7, 63, -2, 77, -4, 82, -3, 94, 9, 69, -12, 109, 36, -35, 36, -34, 32, -26, + 37, -30, 44, -32, 34, -18, 34, -15, 40, -15, 33, -7, 35, -5, 33, 0, 38, 2, 33, 13, + 23, 35, 13, 58, 29, -3, 26, 0, 22, 30, 31, -7, 35, -15, 34, -3, 34, 3, 36, -1, + 34, 5, 32, 11, 35, 5, 34, 12, 39, 11, 30, 29, 34, 26, 29, 39, 19, 66, 31, 21, + 31, 31, 25, 50, -17, 120, -20, 112, -18, 114, -11, 85, -15, 92, -14, 89, -26, 71, -15, 81, + -14, 80, 0, 68, -14, 70, -24, 56, -23, 68, -24, 50, -11, 74, 23, -13, 26, -13, 40, -15, + 49, -14, 44, 3, 45, 6, 44, 34, 33, 54, 19, 82, -3, 75, -1, 23, 1, 34, 1, 43, + 0, 54, -2, 55, 0, 61, 1, 64, 0, 68, -9, 92, -14, 106, -13, 97, -15, 90, -12, 90, + -18, 88, -10, 73, -9, 79, -14, 86, -10, 73, -10, 70, -10, 69, -5, 66, -9, 64, -5, 58, + 2, 59, 21, -10, 24, -11, 28, -8, 28, -1, 29, 3, 29, 9, 35, 20, 29, 36, 14, 67, + ]; + + private static readonly sbyte[] P0 = + [ + 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, + 7, 51, 23, 33, 23, 2, 21, 0, 1, 9, 0, 49, -37, 118, 5, 57, -13, 78, -11, 65, + 1, 62, 12, 49, -4, 73, 17, 50, 18, 64, 9, 43, 29, 0, 26, 67, 16, 90, 9, 104, + -46, 127, -20, 104, 1, 67, -13, 78, -11, 65, 1, 62, -6, 86, -17, 95, -6, 61, 9, 45, + -3, 69, -6, 81, -11, 96, 6, 55, 7, 67, -5, 86, 2, 88, 0, 58, -3, 76, -10, 94, + 5, 54, 4, 69, -3, 81, 0, 88, -7, 67, -5, 74, -4, 74, -5, 80, -7, 72, 1, 58, + 0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, + 0, 45, -4, 78, -3, 96, -27, 126, -28, 98, -25, 101, -23, 67, -28, 82, -20, 94, -16, 83, + -22, 110, -21, 91, -18, 102, -13, 93, -29, 127, -7, 92, -5, 89, -7, 96, -13, 108, -3, 46, + -1, 65, -1, 57, -9, 93, -3, 74, -9, 92, -8, 87, -23, 126, 5, 54, 6, 60, 6, 59, + 6, 69, -1, 48, 0, 68, -4, 69, -8, 88, -2, 85, -6, 78, -1, 75, -7, 77, 2, 54, + 5, 50, -3, 68, 1, 50, 6, 42, -4, 81, 1, 63, -4, 70, 0, 67, 2, 57, -2, 76, + 11, 35, 4, 64, 1, 61, 11, 35, 18, 25, 12, 24, 13, 29, 13, 36, -10, 93, -7, 73, + -2, 73, 13, 46, 9, 49, -7, 100, 9, 53, 2, 53, 5, 53, -2, 61, 0, 56, 0, 56, + -13, 63, -5, 60, -1, 62, 4, 57, -6, 69, 4, 57, 14, 39, 4, 51, 13, 68, 3, 64, + 1, 61, 9, 63, 7, 50, 16, 39, 5, 44, 4, 52, 11, 48, -5, 60, -1, 59, 0, 59, + 22, 33, 5, 44, 14, 43, -1, 78, 0, 60, 9, 69, 11, 28, 2, 40, 3, 44, 0, 49, + 0, 46, 2, 44, 2, 51, 0, 47, 4, 39, 2, 62, 6, 46, 0, 54, 3, 54, 2, 58, + 4, 63, 6, 51, 6, 57, 7, 53, 6, 52, 6, 55, 11, 45, 14, 36, 8, 53, -1, 82, + 7, 55, -3, 78, 15, 46, 22, 31, -1, 84, 25, 7, 30, -7, 28, 3, 28, 4, 32, 0, + 34, -1, 30, 6, 30, 6, 32, 9, 31, 19, 26, 27, 26, 30, 37, 20, 28, 34, 17, 70, + 1, 67, 5, 59, 9, 67, 16, 30, 18, 32, 18, 35, 22, 29, 24, 31, 23, 38, 18, 43, + 20, 41, 11, 63, 9, 59, 9, 64, -1, 94, -2, 89, -9, 108, -6, 76, -2, 44, 0, 45, + 0, 52, -3, 64, -2, 59, -4, 70, -4, 75, -8, 82, -17, 102, -9, 77, 3, 24, 0, 42, + 0, 48, 0, 55, -6, 59, -7, 71, -12, 83, -11, 87, -30, 119, 1, 58, -3, 29, -1, 36, + 1, 38, 2, 43, -6, 55, 0, 58, 0, 64, -3, 74, -10, 90, 0, 70, -4, 29, 5, 31, + 7, 42, 1, 59, -2, 58, -3, 72, -3, 81, -11, 97, 0, 58, 8, 5, 10, 14, 14, 18, + 13, 27, 2, 40, 0, 58, -3, 70, -6, 79, -8, 85, 0, 0, -13, 106, -16, 106, -10, 87, + -21, 114, -18, 110, -14, 98, -22, 110, -21, 106, -18, 103, -21, 107, -23, 108, -26, 112, -10, 96, + -12, 95, -5, 91, -9, 93, -22, 94, -5, 86, 9, 67, -4, 80, -10, 85, -1, 70, 7, 60, + 9, 58, 5, 61, 12, 50, 15, 50, 18, 49, 17, 54, 10, 41, 7, 46, -1, 51, 7, 49, + 8, 52, 9, 41, 6, 47, 2, 55, 13, 41, 10, 44, 6, 50, 5, 53, 13, 49, 4, 63, + 6, 64, -2, 69, -2, 59, 6, 70, 10, 44, 9, 31, 12, 43, 3, 53, 14, 34, 10, 38, + -3, 52, 13, 40, 17, 32, 7, 44, 7, 38, 13, 50, 10, 57, 26, 43, 14, 11, 11, 14, + 9, 11, 18, 11, 21, 9, 23, -2, 32, -15, 32, -15, 34, -21, 39, -23, 42, -33, 41, -31, + 46, -28, 38, -12, 21, 29, 45, -24, 53, -45, 48, -26, 65, -43, 43, -19, 39, -10, 30, 9, + 18, 26, 20, 27, 0, 57, -14, 82, -5, 75, -19, 97, -35, 125, 27, 0, 28, 0, 31, -4, + 27, 6, 34, 8, 30, 10, 24, 22, 33, 19, 22, 32, 26, 31, 21, 41, 26, 44, 23, 47, + 16, 65, 14, 71, 8, 60, 6, 63, 17, 65, 21, 24, 23, 20, 26, 23, 27, 32, 28, 23, + 28, 24, 23, 40, 24, 32, 28, 29, 23, 42, 19, 57, 22, 53, 22, 61, 11, 86, 12, 40, + 11, 51, 14, 59, -4, 79, -7, 71, -5, 69, -9, 70, -8, 66, -10, 68, -19, 73, -12, 69, + -16, 70, -15, 67, -20, 62, -19, 70, -16, 66, -22, 65, -20, 63, 9, -2, 26, -9, 33, -9, + 39, -7, 41, -2, 45, 3, 49, 9, 45, 27, 36, 59, -6, 66, -7, 35, -7, 42, -8, 45, + -5, 48, -12, 56, -6, 60, -5, 62, -8, 66, -8, 76, -5, 85, -6, 81, -10, 77, -7, 81, + -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59, + 2, 59, 21, -13, 33, -14, 39, -7, 46, -2, 51, 2, 60, 6, 61, 17, 55, 34, 42, 62, + ]; + + private static readonly sbyte[] P1 = + [ + 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, + 7, 51, 22, 25, 34, 0, 16, 0, -2, 9, 4, 41, -29, 118, 2, 65, -6, 71, -13, 79, + 5, 52, 9, 50, -3, 70, 10, 54, 26, 34, 19, 22, 40, 0, 57, 2, 41, 36, 26, 69, + -45, 127, -15, 101, -4, 76, -6, 71, -13, 79, 5, 52, 6, 69, -13, 90, 0, 52, 8, 43, + -2, 69, -5, 82, -10, 96, 2, 59, 2, 75, -3, 87, -3, 100, 1, 56, -3, 74, -6, 85, + 0, 59, -3, 81, -7, 86, -5, 95, -1, 66, -1, 77, 1, 70, -2, 86, -5, 72, 0, 61, + 0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, + 13, 15, 7, 51, 2, 80, -39, 127, -18, 91, -17, 96, -26, 81, -35, 98, -24, 102, -23, 97, + -27, 119, -24, 99, -21, 110, -18, 102, -36, 127, 0, 80, -5, 89, -7, 94, -4, 92, 0, 39, + 0, 65, -15, 84, -35, 127, -2, 73, -12, 104, -9, 91, -31, 127, 3, 55, 7, 56, 7, 55, + 8, 61, -3, 53, 0, 68, -7, 74, -9, 88, -13, 103, -13, 91, -9, 89, -14, 92, -8, 76, + -12, 87, -23, 110, -24, 105, -10, 78, -20, 112, -17, 99, -78, 127, -70, 127, -50, 127, -46, 127, + -4, 66, -5, 78, -4, 71, -8, 72, 2, 59, -1, 55, -7, 70, -6, 75, -8, 89, -34, 119, + -3, 75, 32, 20, 30, 22, -44, 127, 0, 54, -5, 61, 0, 58, -1, 60, -3, 61, -8, 67, + -25, 84, -14, 74, -5, 65, 5, 52, 2, 57, 0, 61, -9, 69, -11, 70, 18, 55, -4, 71, + 0, 58, 7, 61, 9, 41, 18, 25, 9, 32, 5, 43, 9, 47, 0, 44, 0, 51, 2, 46, + 19, 38, -4, 66, 15, 38, 12, 42, 9, 34, 0, 89, 4, 45, 10, 28, 10, 31, 33, -11, + 52, -43, 18, 15, 28, 0, 35, -22, 38, -25, 34, 0, 39, -18, 32, -12, 102, -94, 0, 0, + 56, -15, 33, -4, 29, 10, 37, -5, 51, -29, 39, -9, 52, -34, 69, -58, 67, -63, 44, -5, + 32, 7, 55, -29, 32, 1, 0, 0, 27, 36, 33, -25, 34, -30, 36, -28, 38, -28, 38, -27, + 34, -18, 35, -16, 34, -14, 32, -8, 37, -6, 35, 0, 30, 10, 28, 18, 26, 25, 29, 41, + 0, 75, 2, 72, 8, 77, 14, 35, 18, 31, 17, 35, 21, 30, 17, 45, 20, 42, 18, 45, + 27, 26, 16, 54, 7, 66, 16, 56, 11, 73, 10, 67, -10, 116, -23, 112, -15, 71, -7, 61, + 0, 53, -5, 66, -11, 77, -9, 80, -9, 84, -10, 87, -34, 127, -21, 101, -3, 39, -5, 53, + -7, 61, -11, 75, -15, 77, -17, 91, -25, 107, -25, 111, -28, 122, -11, 76, -10, 44, -10, 52, + -10, 57, -9, 58, -16, 72, -7, 69, -4, 69, -5, 74, -9, 86, 2, 66, -9, 34, 1, 32, + 11, 31, 5, 52, -2, 55, -2, 67, 0, 73, -8, 89, 3, 52, 7, 4, 10, 8, 17, 8, + 16, 19, 3, 37, -1, 61, -5, 73, -1, 70, -4, 78, 0, 0, -21, 126, -23, 124, -20, 110, + -26, 126, -25, 124, -17, 105, -27, 121, -27, 117, -17, 102, -26, 117, -27, 116, -33, 122, -10, 95, + -14, 100, -8, 95, -17, 111, -28, 114, -6, 89, -2, 80, -4, 82, -9, 85, -8, 81, -1, 72, + 5, 64, 1, 67, 9, 56, 0, 69, 1, 69, 7, 69, -7, 69, -6, 67, -16, 77, -2, 64, + 2, 61, -6, 67, -3, 64, 2, 57, -3, 65, -3, 66, 0, 62, 9, 51, -1, 66, -2, 71, + -2, 75, -1, 70, -9, 72, 14, 60, 16, 37, 0, 47, 18, 35, 11, 37, 12, 41, 10, 41, + 2, 48, 12, 41, 13, 41, 0, 59, 3, 50, 19, 40, 3, 66, 18, 50, 19, -6, 18, -6, + 14, 0, 26, -12, 31, -16, 33, -25, 33, -22, 37, -28, 39, -30, 42, -30, 47, -42, 45, -36, + 49, -34, 41, -17, 32, 9, 69, -71, 63, -63, 66, -64, 77, -74, 54, -39, 52, -35, 41, -10, + 36, 0, 40, -1, 30, 14, 28, 26, 23, 37, 12, 55, 11, 65, 37, -33, 39, -36, 40, -37, + 38, -30, 46, -33, 42, -30, 40, -24, 49, -29, 38, -12, 40, -10, 38, -3, 46, -5, 31, 20, + 29, 30, 25, 44, 12, 48, 11, 49, 26, 45, 22, 22, 23, 22, 27, 21, 33, 20, 26, 28, + 30, 24, 27, 34, 18, 42, 25, 39, 18, 50, 12, 70, 21, 54, 14, 71, 11, 83, 25, 32, + 21, 49, 21, 54, -5, 85, -6, 81, -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, + -9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59, 2, 59, 17, -10, 32, -13, 42, -9, + 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, -5, 71, 0, 24, -1, 36, -2, 42, + -2, 52, -9, 57, -6, 63, -4, 65, -4, 67, -7, 82, -3, 81, -3, 76, -7, 72, -6, 78, + -12, 72, -14, 68, -3, 70, -6, 76, -5, 66, -5, 62, 0, 57, -4, 61, -9, 60, 1, 54, + 2, 58, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, + ]; + + private static readonly sbyte[] P2 = + [ + 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, + 7, 51, 29, 16, 25, 0, 14, 0, -10, 51, -3, 62, -27, 99, 26, 16, -4, 85, -24, 102, + 5, 57, 6, 57, -17, 73, 14, 57, 20, 40, 20, 10, 29, 0, 54, 0, 37, 42, 12, 97, + -32, 127, -22, 117, -2, 74, -4, 85, -24, 102, 5, 57, -6, 93, -14, 88, -6, 44, 4, 55, + -11, 89, -15, 103, -21, 116, 19, 57, 20, 58, 4, 84, 6, 96, 1, 63, -5, 85, -13, 106, + 5, 63, 6, 75, -3, 90, -1, 101, 3, 55, -4, 79, -2, 75, -12, 97, -7, 50, 1, 60, + 0, 41, 0, 63, 0, 63, 0, 63, -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, + 7, 34, -9, 88, -20, 127, -36, 127, -17, 91, -14, 95, -25, 84, -25, 86, -12, 89, -17, 91, + -31, 127, -14, 76, -18, 103, -13, 90, -37, 127, 11, 80, 5, 76, 2, 84, 5, 78, -6, 55, + 4, 61, -14, 83, -37, 127, -5, 79, -11, 104, -11, 91, -30, 127, 0, 65, -2, 79, 0, 72, + -4, 92, -6, 56, 3, 68, -8, 71, -13, 98, -4, 86, -12, 88, -5, 82, -3, 72, -4, 67, + -8, 72, -16, 89, -9, 69, -1, 59, 5, 66, 4, 57, -4, 71, -2, 71, 2, 58, -1, 74, + -4, 44, -1, 69, 0, 62, -7, 51, -4, 47, -6, 42, -3, 41, -6, 53, 8, 76, -9, 78, + -11, 83, 9, 52, 0, 67, -5, 90, 1, 67, -15, 72, -5, 75, -8, 80, -21, 83, -21, 64, + -13, 31, -25, 64, -29, 94, 9, 75, 17, 63, -8, 74, -5, 35, -2, 27, 13, 91, 3, 65, + -7, 69, 8, 77, -10, 66, 3, 62, -3, 68, -20, 81, 0, 30, 1, 7, -3, 23, -21, 74, + 16, 66, -23, 124, 17, 37, 44, -18, 50, -34, -22, 127, 4, 39, 0, 42, 7, 34, 11, 29, + 8, 31, 6, 37, 7, 42, 3, 40, 8, 33, 13, 43, 13, 36, 4, 47, 3, 55, 2, 58, + 6, 60, 8, 44, 11, 44, 14, 42, 7, 48, 4, 56, 4, 52, 13, 37, 9, 49, 19, 58, + 10, 48, 12, 45, 0, 69, 20, 33, 8, 63, 35, -18, 33, -25, 28, -3, 24, 10, 27, 0, + 34, -14, 52, -44, 39, -24, 19, 17, 31, 25, 36, 29, 24, 33, 34, 15, 30, 20, 22, 73, + 20, 34, 19, 31, 27, 44, 19, 16, 15, 36, 15, 36, 21, 28, 25, 21, 30, 20, 31, 12, + 27, 16, 24, 42, 0, 93, 14, 56, 15, 57, 26, 38, -24, 127, -24, 115, -22, 82, -9, 62, + 0, 53, 0, 59, -14, 85, -13, 89, -13, 94, -11, 92, -29, 127, -21, 100, -14, 57, -12, 67, + -11, 71, -10, 77, -21, 85, -16, 88, -23, 104, -15, 98, -37, 127, -10, 82, -8, 48, -8, 61, + -8, 66, -7, 70, -14, 75, -10, 79, -9, 83, -12, 92, -18, 108, -4, 79, -22, 69, -16, 75, + -2, 58, 1, 58, -13, 78, -9, 83, -4, 81, -13, 99, -13, 81, -6, 38, -13, 62, -6, 58, + -2, 59, -16, 73, -10, 76, -13, 86, -9, 83, -10, 87, 0, 0, -22, 127, -25, 127, -25, 120, + -27, 127, -19, 114, -23, 117, -25, 118, -26, 117, -24, 113, -28, 118, -31, 120, -37, 124, -10, 94, + -15, 102, -10, 99, -13, 106, -50, 127, -5, 92, 17, 57, -5, 86, -13, 94, -12, 91, -2, 77, + 0, 71, -1, 73, 4, 64, -7, 81, 5, 64, 15, 57, 1, 67, 0, 68, -10, 67, 1, 68, + 0, 77, 2, 64, 0, 68, -5, 78, 7, 55, 5, 59, 2, 65, 14, 54, 15, 44, 5, 60, + 2, 70, -2, 76, -18, 86, 12, 70, 5, 64, -12, 70, 11, 55, 5, 56, 0, 69, 2, 65, + -6, 74, 5, 54, 7, 54, -6, 76, -11, 82, -2, 77, -2, 77, 25, 42, 17, -13, 16, -9, + 17, -12, 27, -21, 37, -30, 41, -40, 42, -41, 48, -47, 39, -32, 46, -40, 52, -51, 46, -41, + 52, -39, 43, -19, 32, 11, 61, -55, 56, -46, 62, -50, 81, -67, 45, -20, 35, -2, 28, 15, + 34, 1, 39, 1, 30, 17, 20, 38, 18, 45, 15, 54, 0, 79, 36, -16, 37, -14, 37, -17, + 32, 1, 34, 15, 29, 15, 24, 25, 34, 22, 31, 16, 35, 18, 31, 28, 33, 41, 36, 28, + 27, 47, 21, 62, 18, 31, 19, 26, 36, 24, 24, 23, 27, 16, 24, 30, 31, 29, 22, 41, + 22, 42, 16, 60, 15, 52, 14, 60, 3, 78, -16, 123, 21, 53, 22, 56, 25, 61, 21, 33, + 19, 50, 17, 61, -3, 78, -8, 74, -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, + -17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52, -11, 68, 9, -2, 30, -10, 31, -4, + 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, -9, 71, -7, 37, -8, 44, -11, 49, + -10, 56, -12, 59, -8, 63, -9, 67, -6, 68, -10, 79, -3, 78, -8, 74, -9, 72, -10, 72, + -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52, + -11, 68, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, + ]; + + /// (m, n) pairs for I slices, [ctxIdx * 2]. + internal static readonly sbyte[] InitI = I; + + /// (m, n) pairs for P and B slices by cabac_init_idc, [idc][ctxIdx * 2]. + internal static readonly sbyte[][] InitPB = [P0, P1, P2]; +} diff --git a/src/Febe.Core/Codecs/H264/CavlcTables.cs b/src/Febe.Core/Codecs/H264/CavlcTables.cs new file mode 100644 index 0000000..5178c84 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/CavlcTables.cs @@ -0,0 +1,255 @@ +namespace Febe.Core.Codecs.H264; + +/// +/// The variable-length codes of CAVLC (ITU-T H.264, tables 9-5, 9-7, 9-8, 9-9 and 9-10, with the columns of the +/// 4:2:2 chroma DC: nC = −2 and table 9-9 (b)), written as bit strings and +/// turned once into lookup tables indexed by the next 16 bits of the stream. +/// +internal static class CavlcTables +{ + /// coeff_token for 0 ≤ nC < 2, indexed [TotalCoeff * 4 + TrailingOnes]. + private static readonly string?[] CoeffToken0 = + [ + "1", null, null, null, + "000101", "01", null, null, + "00000111", "000100", "001", null, + "000000111", "00000110", "0000101", "00011", + "0000000111", "000000110", "00000101", "000011", + "00000000111", "0000000110", "000000101", "0000100", + "0000000001111", "00000000110", "0000000101", "00000100", + "0000000001011", "0000000001110", "00000000101", "000000100", + "0000000001000", "0000000001010", "0000000001101", "0000000100", + "00000000001111", "00000000001110", "0000000001001", "00000000100", + "00000000001011", "00000000001010", "00000000001101", "0000000001100", + "000000000001111", "000000000001110", "00000000001001", "00000000001100", + "000000000001011", "000000000001010", "000000000001101", "00000000001000", + "0000000000001111", "000000000000001", "000000000001001", "000000000001100", + "0000000000001011", "0000000000001110", "0000000000001101", "000000000001000", + "0000000000000111", "0000000000001010", "0000000000001001", "0000000000001100", + "0000000000000100", "0000000000000110", "0000000000000101", "0000000000001000", + ]; + + /// coeff_token for 2 ≤ nC < 4. + private static readonly string?[] CoeffToken1 = + [ + "11", null, null, null, + "001011", "10", null, null, + "000111", "00111", "011", null, + "0000111", "001010", "001001", "0101", + "00000111", "000110", "000101", "0100", + "00000100", "0000110", "0000101", "00110", + "000000111", "00000110", "00000101", "001000", + "00000001111", "000000110", "000000101", "000100", + "00000001011", "00000001110", "00000001101", "0000100", + "000000001111", "00000001010", "00000001001", "000000100", + "000000001011", "000000001110", "000000001101", "00000001100", + "000000001000", "000000001010", "000000001001", "00000001000", + "0000000001111", "0000000001110", "0000000001101", "000000001100", + "0000000001011", "0000000001010", "0000000001001", "0000000001100", + "0000000000111", "00000000001011", "0000000000110", "0000000001000", + "00000000001001", "00000000001000", "00000000001010", "0000000000001", + "00000000000111", "00000000000110", "00000000000101", "00000000000100", + ]; + + /// coeff_token for 4 ≤ nC < 8. + private static readonly string?[] CoeffToken2 = + [ + "1111", null, null, null, + "001111", "1110", null, null, + "001011", "01111", "1101", null, + "001000", "01100", "01110", "1100", + "0001111", "01010", "01011", "1011", + "0001011", "01000", "01001", "1010", + "0001001", "001110", "001101", "1001", + "0001000", "001010", "001001", "1000", + "00001111", "0001110", "0001101", "01101", + "00001011", "00001110", "0001010", "001100", + "000001111", "00001010", "00001101", "0001100", + "000001011", "000001110", "00001001", "00001100", + "000001000", "000001010", "000001101", "00001000", + "0000001101", "000000111", "000001001", "000001100", + "0000001001", "0000001100", "0000001011", "0000001010", + "0000000101", "0000001000", "0000000111", "0000000110", + "0000000001", "0000000100", "0000000011", "0000000010", + ]; + + /// coeff_token for the chroma DC of 4:2:0 (nC = −1). + private static readonly string?[] CoeffTokenChromaDc = + [ + "01", null, null, null, + "000111", "1", null, null, + "000100", "000110", "001", null, + "000011", "0000011", "0000010", "000101", + "000010", "00000011", "00000010", "0000000", + ]; + + /// coeff_token for the chroma DC of 4:2:2 (nC = −2, eight coefficients). + private static readonly string?[] CoeffTokenChroma422Dc = + [ + "1", null, null, null, + "0001111", "01", null, null, + "0001110", "0001101", "001", null, + "000000111", "0001100", "0001011", "00001", + "000000110", "000000101", "0001010", "000001", + "0000000111", "0000000110", "000000100", "0001001", + "00000000111", "00000000110", "0000000101", "0001000", + "000000000111", "000000000110", "00000000101", "0000000100", + "0000000000111", "000000000101", "000000000100", "00000000100", + ]; + + /// total_zeros of 4×4 blocks, indexed [TotalCoeff − 1][total_zeros]. + private static readonly string[][] TotalZeros4x4 = + [ + ["1", "011", "010", "0011", "0010", "00011", "00010", "000011", "000010", "0000011", "0000010", "00000011", "00000010", "000000011", "000000010", "000000001"], + ["111", "110", "101", "100", "011", "0101", "0100", "0011", "0010", "00011", "00010", "000011", "000010", "000001", "000000"], + ["0101", "111", "110", "101", "0100", "0011", "100", "011", "0010", "00011", "00010", "000001", "00001", "000000"], + ["00011", "111", "0101", "0100", "110", "101", "100", "0011", "011", "0010", "00010", "00001", "00000"], + ["0101", "0100", "0011", "111", "110", "101", "100", "011", "0010", "00001", "0001", "00000"], + ["000001", "00001", "111", "110", "101", "100", "011", "010", "0001", "001", "000000"], + ["000001", "00001", "101", "100", "011", "11", "010", "0001", "001", "000000"], + ["000001", "0001", "00001", "011", "11", "10", "010", "001", "000000"], + ["000001", "000000", "0001", "11", "10", "001", "01", "00001"], + ["00001", "00000", "001", "11", "10", "01", "0001"], + ["0000", "0001", "001", "010", "1", "011"], + ["0000", "0001", "01", "1", "001"], + ["000", "001", "1", "01"], + ["00", "01", "1"], + ["0", "1"], + ]; + + /// total_zeros of the 4:2:0 chroma DC, indexed [TotalCoeff − 1][total_zeros]. + private static readonly string[][] TotalZerosChromaDc = + [ + ["1", "01", "001", "000"], + ["1", "01", "00"], + ["1", "0"], + ]; + + /// total_zeros of the 4:2:2 chroma DC (table 9-9 (b)), indexed [TotalCoeff − 1][total_zeros]. + private static readonly string[][] TotalZerosChroma422Dc = + [ + ["1", "010", "011", "0010", "0011", "0001", "00001", "00000"], + ["000", "01", "001", "100", "101", "110", "111"], + ["000", "001", "01", "10", "110", "111"], + ["110", "00", "01", "10", "111"], + ["00", "01", "10", "11"], + ["00", "01", "1"], + ["0", "1"], + ]; + + /// run_before, indexed [Min(zerosLeft, 7) − 1][run_before]. + private static readonly string[][] RunBefore = + [ + ["1", "0"], + ["1", "01", "00"], + ["11", "10", "01", "00"], + ["11", "10", "01", "001", "000"], + ["11", "10", "011", "010", "001", "000"], + ["11", "000", "001", "011", "010", "101", "100"], + ["111", "110", "101", "100", "011", "010", "001", "0001", "00001", "000001", "0000001", "00000001", "000000001", "0000000001", "00000000001"], + ]; + + /// + /// Lookup tables of coeff_token: [0..2] by nC class, [3] for nC ≥ 8 (fixed 6 bits), [4] for the 4:2:0 chroma DC, [5] + /// for the 4:2:2 one. + /// + internal static readonly ushort[][] CoeffTokenLookup = BuildCoeffTokenLookups(); + + internal static readonly ushort[][] TotalZerosLookup = BuildLookups(TotalZeros4x4); + + internal static readonly ushort[][] TotalZerosChromaDcLookup = BuildLookups(TotalZerosChromaDc); + + internal static readonly ushort[][] TotalZerosChroma422DcLookup = BuildLookups(TotalZerosChroma422Dc); + + internal static readonly ushort[][] RunBeforeLookup = BuildLookups(RunBefore); + + /// All the code tables, for the self-checks of the tests (prefix-free, complete where the standard is). + internal static IEnumerable<(string Name, string?[] Codes)> AllCodeTables() + { + yield return ("coeff_token 0", CoeffToken0); + yield return ("coeff_token 1", CoeffToken1); + yield return ("coeff_token 2", CoeffToken2); + yield return ("coeff_token -1", CoeffTokenChromaDc); + yield return ("coeff_token -2", CoeffTokenChroma422Dc); + for (var i = 0; i < TotalZeros4x4.Length; i++) + { + yield return ($"total_zeros {i + 1}", TotalZeros4x4[i]); + } + + for (var i = 0; i < TotalZerosChromaDc.Length; i++) + { + yield return ($"total_zeros DC {i + 1}", TotalZerosChromaDc[i]); + } + + for (var i = 0; i < TotalZerosChroma422Dc.Length; i++) + { + yield return ($"total_zeros DC 4:2:2 {i + 1}", TotalZerosChroma422Dc[i]); + } + + for (var i = 0; i < RunBefore.Length; i++) + { + yield return ($"run_before {i + 1}", RunBefore[i]); + } + } + + /// + /// A 65536-entry table: for the next 16 bits of the stream, (code length << 8) | value; zero when no code + /// matches. + /// + private static ushort[] Build(string?[] codes) + { + var table = new ushort[1 << 16]; + for (var value = 0; value < codes.Length; value++) + { + var code = codes[value]; + if (code is null) + { + continue; + } + + var bits = 0; + foreach (var c in code) + { + bits = (bits << 1) | (c == '1' ? 1 : 0); + } + + var shift = 16 - code.Length; + var first = bits << shift; + var count = 1 << shift; + var entry = (ushort)((code.Length << 8) | value); + for (var i = 0; i < count; i++) + { + table[first + i] = entry; + } + } + + return table; + } + + private static ushort[][] BuildLookups(string[][] tables) + { + var result = new ushort[tables.Length][]; + for (var i = 0; i < tables.Length; i++) + { + result[i] = Build(tables[i]); + } + + return result; + } + + private static ushort[][] BuildCoeffTokenLookups() + { + var fixedLength = new string?[17 * 4]; + fixedLength[0] = "000011"; + for (var total = 1; total <= 16; total++) + { + for (var ones = 0; ones <= Math.Min(3, total); ones++) + { + var code = ((total - 1) << 2) | ones; + fixedLength[(total * 4) + ones] = Convert.ToString(code, 2).PadLeft(6, '0'); + } + } + + return [Build(CoeffToken0), Build(CoeffToken1), Build(CoeffToken2), Build(fixedLength), Build(CoeffTokenChromaDc), Build(CoeffTokenChroma422Dc)]; + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs new file mode 100644 index 0000000..87f52d9 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Deblock.cs @@ -0,0 +1,632 @@ +using static Febe.Core.Codecs.H264.Samples; + +namespace Febe.Core.Codecs.H264; + +public sealed partial class H264Decoder +{ + /// The luma-like plane the deblocking filter is working on: Y, or one colour plane coded separately. + private byte[] deblockLuma = []; + + /// + /// Deblocking filter (§8.7) of the picture just decoded, macroblock by macroblock in address order: a frame, one + /// field (its rows only, as a picture of its own), or an MBAFF frame (pairs, top then bottom macroblock). Colour planes + /// coded separately are filtered one by one, each as a monochrome picture with its own macroblock data. + /// + private void Deblock(Picture picture) + { + var any = false; + foreach (var filter in sliceFilters) + { + any |= filter.Disable != 1; + } + + if (!any) + { + return; + } + + if (!separatePlanes) + { + DeblockPlane(picture, picture.Y); + return; + } + + for (var k = 0; k < 3; k++) + { + SelectColourPlane(k); + picture.SelectPlane(k); + DeblockPlane(picture, picture.Plane(k)); + } + + SelectColourPlane(0); + picture.SelectPlane(0); + } + + private void DeblockPlane(Picture picture, byte[] luma) + { + deblockLuma = luma; + if (wide) + { + DeblockPicture(picture); + } + else + { + DeblockPicture(picture); + } + } + + private void DeblockPicture(Picture picture) + where T : unmanaged + { + if (curStructure != 0) + { + DeblockRows(picture, 2, curStructure - 1); + } + else if (activeSps!.MbAdaptiveFrameField) + { + DeblockPairs(picture); + } + else + { + DeblockRows(picture, 1, 0); + } + } + + /// A frame ( 1) or the field of ( 2). + private void DeblockRows(Picture picture, int rowStep, int parity) + where T : unmanaged + { + var w = widthInMbs; + int width = picture.Width, cwidth = picture.ChromaWidth; + int stride = width * rowStep, cstride = cwidth * rowStep; + Span bs = stackalloc byte[4]; + var rows = heightInMbs / rowStep; + for (var row = 0; row < rows; row++) + { + for (var mx = 0; mx < w; mx++) + { + var m = (((row * rowStep) + parity) * w) + mx; + var s = mbSlice[m]; + if (s < 0) + { + continue; + } + + var (disable, alphaOffset, betaOffset) = sliceFilters[s]; + if (disable == 1) + { + continue; + } + + var lumaOrigin = (((row * 16 * rowStep) + parity) * width) + (mx * 16); + var chromaOrigin = (((row * mbHeightC * rowStep) + parity) * cwidth) + (mx * mbWidthC); + if (mx > 0 && mbSlice[m - 1] >= 0 && (disable != 2 || mbSlice[m - 1] == s)) + { + MbEdge(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + + InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + var up = m - (rowStep * w); + if (row > 0 && mbSlice[up] >= 0 && (disable != 2 || mbSlice[up] == s)) + { + MbEdge(picture, up, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + + InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + } + } + + /// + /// An MBAFF frame. Between a frame and a field pair the left edge is filtered row by row, each row against the + /// macroblock that holds it; the top edge of a frame macroblock under a field pair twice, once per field (§8.7.1). + /// + private void DeblockPairs(Picture picture) + where T : unmanaged + { + var w = widthInMbs; + int width = picture.Width, cwidth = picture.ChromaWidth; + Span bs = stackalloc byte[4]; + Span rowBs = stackalloc byte[16]; + Span rowMb = stackalloc int[16]; + var field = picture.MbField; + for (var pairY = 0; pairY < heightInMbs / 2; pairY++) + { + for (var mx = 0; mx < w; mx++) + { + for (var bottom = 0; bottom < 2; bottom++) + { + var m = (((2 * pairY) + bottom) * w) + mx; + var s = mbSlice[m]; + if (s < 0) + { + continue; + } + + var (disable, alphaOffset, betaOffset) = sliceFilters[s]; + if (disable == 1) + { + continue; + } + + var isField = field[m]; + int lumaOrigin, stride, chromaOrigin, cstride; + if (isField) + { + lumaOrigin = (((pairY * 32) + bottom) * width) + (mx * 16); + chromaOrigin = (((pairY * 2 * mbHeightC) + bottom) * cwidth) + (mx * mbWidthC); + stride = 2 * width; + cstride = 2 * cwidth; + } + else + { + lumaOrigin = ((((2 * pairY) + bottom) * 16) * width) + (mx * 16); + chromaOrigin = ((((2 * pairY) + bottom) * mbHeightC) * cwidth) + (mx * mbWidthC); + stride = width; + cstride = cwidth; + } + + // Left edge. + var leftTop = (2 * pairY * w) + mx - 1; + if (mx > 0 && mbSlice[leftTop] >= 0 && (disable != 2 || mbSlice[leftTop] == s)) + { + var leftField = field[leftTop]; + if (leftField == isField) + { + MbEdge(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + else + { + MixedLeftEdge(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb); + } + } + + InnerEdges(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + + // Top edge. + if (!isField && bottom == 1) + { + MbEdge(picture, m - w, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + else if (pairY > 0) + { + var aboveTop = (((2 * pairY) - 2) * w) + mx; + if (mbSlice[aboveTop] >= 0 && (disable != 2 || mbSlice[aboveTop] == s)) + { + if (!isField && field[aboveTop]) + { + // A frame macroblock under a field pair: each field of its top rows against that field. + for (var j = 0; j < 2; j++) + { + MbEdge(picture, aboveTop + (j * w), m, false, lumaOrigin + (j * width), 2 * width, chromaOrigin + (j * cwidth), 2 * cwidth, alphaOffset, betaOffset, bs); + } + } + else + { + var pm = isField && bottom == 0 && field[aboveTop] ? aboveTop : aboveTop + w; + MbEdge(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + } + } + + InnerEdges(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs); + } + } + } + } + + /// + /// The left edge of an MBAFF macroblock whose left pair is of the other kind (frame and field): bS and qP row by + /// row, from the macroblock holding each row of the left pair. A chroma row takes the bS of a luma row: in 4:2:0 the + /// mapping of §8.7.2.1, in 4:2:2 and 4:4:4 (as many chroma rows as luma rows) the row itself. + /// + private void MixedLeftEdge( + Picture picture, int m, int leftTop, bool isField, bool bottom, int lumaOrigin, int stride, int chromaOrigin, int cstride, + int alphaOffset, int betaOffset, Span rowBs, Span rowMb) + where T : unmanaged + { + var w = widthInMbs; + var leftField = picture.MbField[leftTop]; + for (var r = 0; r < 16; r++) + { + var pm = LeftOfPair(leftTop, w, leftField, isField, bottom, r, 16, out var yM); + rowMb[r] = pm; + rowBs[r] = (byte)BoundaryStrength(picture, pm, (((yM & 15) >> 2) * 4) + 3, m, (r >> 2) * 4, true, true); + } + + var luma = Plane(deblockLuma); + for (var r = 0; r < 16; r++) + { + if (rowBs[r] == 0) + { + continue; + } + + if (Thresholds(mbQp[rowMb[r]], mbQp[m], alphaOffset, betaOffset, bitDepthY, out var alpha, out var beta, out var indexA)) + { + FilterLuma(luma, lumaOrigin + (r * stride), 1, rowBs[r], alpha, beta, indexA, bitDepthY - 8, maxY); + } + } + + if (chromaArrayType == 0) + { + return; + } + + var cb = Plane(picture.Cb); + var cr = Plane(picture.Cr); + for (var k = 0; k < mbHeightC; k++) + { + var lumaRow = mbHeightC == 16 ? k : isField && !leftField ? 2 * k : (4 * (k >> 1)) + (k & 1); + var strength = rowBs[lumaRow]; + if (strength == 0) + { + continue; + } + + var pm = rowMb[lumaRow]; + for (var c = 0; c < 2; c++) + { + if (!Thresholds(mbQpC[(pm * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, out var alpha, out var beta, out var indexA)) + { + continue; + } + + var plane = c == 0 ? cb : cr; + if (chromaArrayType == 3) + { + FilterLuma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC); + } + else + { + FilterChroma(plane, chromaOrigin + (k * cstride), 1, strength, alpha, beta, indexA, bitDepthC - 8, maxC); + } + } + } + } + + /// A macroblock edge between (left or above) and , luma and chroma. + private void MbEdge( + Picture picture, int pm, int qm, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span bs) + where T : unmanaged + { + for (var i = 0; i < 4; i++) + { + int qb = vertical ? i * 4 : i, pb = vertical ? (i * 4) + 3 : 12 + i; + bs[i] = (byte)BoundaryStrength(picture, pm, pb, qm, qb, true, vertical); + } + + if ((bs[0] | bs[1] | bs[2] | bs[3]) == 0) + { + return; + } + + int along = vertical ? stride : 1, across = vertical ? 1 : stride; + Edge(Plane(deblockLuma), lumaOrigin, along, across, bs, 16, mbQp[pm], mbQp[qm], alphaOffset, betaOffset, bitDepthY, chromaStyle: false); + if (chromaArrayType == 0) + { + return; + } + + int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride; + var count = vertical ? mbHeightC : mbWidthC; + for (var c = 0; c < 2; c++) + { + Edge(Plane(c == 0 ? picture.Cb : picture.Cr), chromaOrigin, calong, cacross, bs, count, mbQpC[(pm * 2) + c], mbQpC[(qm * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3); + } + } + + /// + /// The internal edges of macroblock in one direction: luma 4, 8, 12 (only 8 with the 8×8 + /// transform); chroma at the same luma positions where they fall on a 4×4 chroma block edge — 4 for 4:2:0, the + /// rows 4, 8 and 12 of 4:2:2 (whatever the transform of luma), all the luma edges in 4:4:4. + /// + private void InnerEdges( + Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span bs) + where T : unmanaged + { + var t8 = mbT8[m]; + int along = vertical ? stride : 1, across = vertical ? 1 : stride; + int calong = vertical ? cstride : 1, cacross = vertical ? 1 : cstride; + var chromaSize = vertical ? mbWidthC : mbHeightC; + var count = vertical ? mbHeightC : mbWidthC; + for (var edge = 1; edge < 4; edge++) + { + var lumaEdge = !t8 || (edge & 1) == 0; + var chromaEdge = chromaArrayType switch + { + 0 => false, + 3 => lumaEdge, + _ => chromaSize == 16 || edge == 2, + }; + if (!lumaEdge && !chromaEdge) + { + continue; + } + + for (var i = 0; i < 4; i++) + { + var qb = vertical ? (i * 4) + edge : (edge * 4) + i; + bs[i] = (byte)BoundaryStrength(picture, m, qb - (vertical ? 1 : 4), m, qb, false, vertical); + } + + if ((bs[0] | bs[1] | bs[2] | bs[3]) == 0) + { + continue; + } + + if (lumaEdge) + { + var offset = edge * 4 * (vertical ? 1 : stride); + Edge(Plane(deblockLuma), lumaOrigin + offset, along, across, bs, 16, mbQp[m], mbQp[m], alphaOffset, betaOffset, bitDepthY, chromaStyle: false); + } + + if (chromaEdge) + { + var position = edge * chromaSize / 4; + var coffset = position * (vertical ? 1 : cstride); + for (var c = 0; c < 2; c++) + { + Edge(Plane(c == 0 ? picture.Cb : picture.Cr), chromaOrigin + coffset, calong, cacross, bs, count, mbQpC[(m * 2) + c], mbQpC[(m * 2) + c], alphaOffset, betaOffset, bitDepthC, chromaStyle: chromaArrayType != 3); + } + } + } + } + + /// + /// α, β and indexA of an edge (§8.7.2.2) from the qP of its two sides, scaled to the bit depth (equations 8-466, + /// 8-467); false when the edge is not filtered. + /// + private static bool Thresholds(int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, out int alpha, out int beta, out int indexA) + { + var qpav = (qpP + qpQ + 1) >> 1; + indexA = Math.Clamp(qpav + alphaOffset, 0, 51); + alpha = H264Tables.Alpha[indexA] << (bitDepth - 8); + beta = H264Tables.Beta[Math.Clamp(qpav + betaOffset, 0, 51)] << (bitDepth - 8); + return alpha != 0 && beta != 0; + } + + /// + /// The samples along one edge (16 in luma; 8 or 16 in chroma), each with the bS of its 4×4 + /// luma block; the filter of chroma (chromaStyleFilteringFlag) or that of luma, which 4:4:4 uses for Cb and Cr. + /// + private static void Edge(Span plane, int origin, int along, int across, ReadOnlySpan bs, int count, int qpP, int qpQ, int alphaOffset, int betaOffset, int bitDepth, bool chromaStyle) + where T : unmanaged + { + if (!Thresholds(qpP, qpQ, alphaOffset, betaOffset, bitDepth, out var alpha, out var beta, out var indexA)) + { + return; + } + + var shift = count == 16 ? 2 : 1; + var bdShift = bitDepth - 8; + var max = (1 << bitDepth) - 1; + for (var k = 0; k < count; k++) + { + var strength = bs[k >> shift]; + if (strength == 0) + { + continue; + } + + if (chromaStyle) + { + FilterChroma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max); + } + else + { + FilterLuma(plane, origin + (k * along), across, strength, alpha, beta, indexA, bdShift, max); + } + } + } + + /// + /// bS of the edge between 4×4 luma blocks of and of + /// (§8.7.2.1). Field macroblocks (all those of a field picture) take 4 only across vertical + /// edges and compare vertical vectors in field units; between a frame and a field macroblock (mixed edges of MBAFF + /// frames) it is at least 1. + /// + private int BoundaryStrength(Picture picture, int pm, int pb, int qm, int qb, bool mbEdge, bool vertical) + { + bool fieldP = picture.MbField[pm], fieldQ = picture.MbField[qm]; + if (picture.MbIntra[pm] || picture.MbIntra[qm] || (anySwitching && (sliceSwitching[mbSlice[pm]] || sliceSwitching[mbSlice[qm]]))) + { + return mbEdge && (vertical || (!fieldP && !fieldQ)) ? 4 : 3; + } + + if (HasCoefficients(pm, pb) || HasCoefficients(qm, qb)) + { + return 2; + } + + if (fieldP != fieldQ) + { + return 1; + } + + var limit = fieldQ ? 2 : 4; + int pi = (pm * 4) + B8OfRaster(pb), qi = (qm * 4) + B8OfRaster(qb); + var l1 = mbCount * 4; + var p0 = UsedReference(picture, pi); + var p1 = UsedReference(picture, l1 + pi); + var q0 = UsedReference(picture, qi); + var q1 = UsedReference(picture, l1 + qi); + var countP = (p0.Pic is null ? 0 : 1) + (p1.Pic is null ? 0 : 1); + var countQ = (q0.Pic is null ? 0 : 1) + (q1.Pic is null ? 0 : 1); + if (countP != countQ) + { + return 1; + } + + var mv = picture.Mv; + var l1Mv = mbCount * 32; + int pv0 = ((pm * 16) + pb) * 2, qv0 = ((qm * 16) + qb) * 2; + int pv1 = l1Mv + pv0, qv1 = l1Mv + qv0; + if (countP == 1) + { + var refP = p0.Pic is not null ? p0 : p1; + var refQ = q0.Pic is not null ? q0 : q1; + if (refP != refQ) + { + return 1; + } + + return MvFar(mv, p0.Pic is not null ? pv0 : pv1, q0.Pic is not null ? qv0 : qv1, limit) ? 1 : 0; + } + + if (countP == 0) + { + return 0; + } + + var sameSet = (p0 == q0 && p1 == q1) || (p0 == q1 && p1 == q0); + if (!sameSet) + { + return 1; + } + + if (p0 != p1) + { + return p0 == q0 + ? (MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit) ? 1 : 0) + : (MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit) ? 1 : 0); + } + + // Both motion vectors of both blocks refer to the same picture. + var straight = MvFar(mv, pv0, qv0, limit) || MvFar(mv, pv1, qv1, limit); + var crossed = MvFar(mv, pv0, qv1, limit) || MvFar(mv, pv1, qv0, limit); + return straight && crossed ? 1 : 0; + } + + /// The picture (frame, or field of a frame store) a block refers to in a list; empty when the list is not used. + private static RefEntry UsedReference(Picture picture, int index) => + picture.RefIdx[index] < 0 ? default : new RefEntry(picture.RefPic[index] ?? picture, picture.RefPar[index]); + + private static bool MvFar(short[] mv, int a, int b, int verticalLimit) => + Math.Abs(mv[a] - mv[b]) >= 4 || Math.Abs(mv[a + 1] - mv[b + 1]) >= verticalLimit; + + /// + /// The transform block holding the 4×4 luma block has coefficients; in 4:4:4 (not coded as + /// separate planes) those of the Cb and Cr blocks at the same place count too. + /// + private bool HasCoefficients(int m, int blk) + { + var planes = chromaArrayType == 3 ? 3 : 1; + for (var plane = 0; plane < planes; plane++) + { + var baseIndex = (m * NzPerMb) + (plane * 16); + if (!mbT8[m]) + { + if (nz[baseIndex + blk] != 0) + { + return true; + } + + continue; + } + + // The 8×8 transform block containing the 4×4 block. + var r0 = ((blk >> 3) * 8) + (((blk & 3) >> 1) * 2); + if ((nz[baseIndex + r0] | nz[baseIndex + r0 + 1] | nz[baseIndex + r0 + 4] | nz[baseIndex + r0 + 5]) != 0) + { + return true; + } + } + + return false; + } + + /// The filter of luma edges (§8.7.2.3, §8.7.2.4), also that of Cb and Cr in 4:4:4; tC0 scaled by . + private static void FilterLuma(Span s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max) + where T : unmanaged + { + int p0 = Get(s[o - step]), q0 = Get(s[o]); + if (Math.Abs(p0 - q0) >= alpha) + { + return; + } + + int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]); + if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta) + { + return; + } + + int p2 = Get(s[o - (3 * step)]), q2 = Get(s[o + (2 * step)]); + var ap = Math.Abs(p2 - p0) < beta; + var aq = Math.Abs(q2 - q0) < beta; + if (bS < 4) + { + var tc0 = H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift; + var tc = tc0 + (ap ? 1 : 0) + (aq ? 1 : 0); + var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc); + s[o - step] = Make(Clip(p0 + delta, max)); + s[o] = Make(Clip(q0 - delta, max)); + if (ap) + { + s[o - (2 * step)] = Make(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0)); + } + + if (aq) + { + s[o + step] = Make(q1 + Math.Clamp((q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1, -tc0, tc0)); + } + + return; + } + + var strong = Math.Abs(p0 - q0) < ((alpha >> 2) + 2); + if (ap && strong) + { + var p3 = Get(s[o - (4 * step)]); + s[o - step] = Make((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3); + s[o - (2 * step)] = Make((p2 + p1 + p0 + q0 + 2) >> 2); + s[o - (3 * step)] = Make(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3); + } + else + { + s[o - step] = Make(((2 * p1) + p0 + q1 + 2) >> 2); + } + + if (aq && strong) + { + var q3 = Get(s[o + (3 * step)]); + s[o] = Make((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3); + s[o + step] = Make((p0 + q0 + q1 + q2 + 2) >> 2); + s[o + (2 * step)] = Make(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3); + } + else + { + s[o] = Make(((2 * q1) + q0 + p1 + 2) >> 2); + } + } + + /// The filter of the chroma edges of 4:2:0 and 4:2:2 (chromaStyleFilteringFlag). + private static void FilterChroma(Span s, int o, int step, int bS, int alpha, int beta, int indexA, int bdShift, int max) + where T : unmanaged + { + int p0 = Get(s[o - step]), q0 = Get(s[o]); + if (Math.Abs(p0 - q0) >= alpha) + { + return; + } + + int p1 = Get(s[o - (2 * step)]), q1 = Get(s[o + step]); + if (Math.Abs(p1 - p0) >= beta || Math.Abs(q1 - q0) >= beta) + { + return; + } + + if (bS < 4) + { + var tc = (H264Tables.Tc0[(indexA * 3) + bS - 1] << bdShift) + 1; + var delta = Math.Clamp((((q0 - p0) << 2) + (p1 - q1) + 4) >> 3, -tc, tc); + s[o - step] = Make(Clip(p0 + delta, max)); + s[o] = Make(Clip(q0 - delta, max)); + return; + } + + s[o - step] = Make(((2 * p1) + p0 + q1 + 2) >> 2); + s[o] = Make(((2 * q1) + q0 + p1 + 2) >> 2); + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs new file mode 100644 index 0000000..7aa4b1a --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Entropy.cs @@ -0,0 +1,871 @@ +namespace Febe.Core.Codecs.H264; + +public sealed partial class H264Decoder +{ + private static readonly byte[] CbfCatOffset = [0, 4, 8, 12, 16]; + private static readonly byte[] SigCatOffset = [0, 15, 29, 44, 47]; + private static readonly byte[] AbsCatOffset = [0, 10, 20, 30, 39]; + + private static int B8OfRaster(int blk) => ((blk >> 3) << 1) | ((blk >> 1) & 1); + + private int ReadMbSkip() + { + var inc = (mbA >= 0 && !IsSkip(mbA) ? 1 : 0) + (mbB >= 0 && !IsSkip(mbB) ? 1 : 0); + return cabac.Decision((sh.IsB ? 24 : 11) + inc); + } + + private int ReadMbType() + { + if (!cabacMode) + { + return rd.ReadUe(48); + } + + switch (sh.Type) + { + case SliceType.I: + return ReadIntraSliceMbType(); + case SliceType.SI: + { + // The prefix says SI or not (ctxIdx 0–2), then an I slice mb_type follows (§9.3.2.5). + var inc = (mbA >= 0 && mbKind[mbA] != MbKind.SI ? 1 : 0) + (mbB >= 0 && mbKind[mbB] != MbKind.SI ? 1 : 0); + return cabac.Decision(inc) == 0 ? 0 : 1 + ReadIntraSliceMbType(); + } + + case SliceType.P: + case SliceType.SP: + if (cabac.Decision(14) == 0) + { + if (cabac.Decision(15) == 0) + { + return 3 * cabac.Decision(16); + } + + return 2 - cabac.Decision(17); + } + + return 5 + (cabac.Decision(17) == 0 ? 0 : IntraMbTypeSuffix(17, intraSlice: false)); + default: + { + var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0) + + (mbB >= 0 && mbKind[mbB] is not (MbKind.BSkip or MbKind.BDirect) ? 1 : 0); + if (cabac.Decision(27 + inc) == 0) + { + return 0; + } + + if (cabac.Decision(27 + 3) == 0) + { + return 1 + cabac.Decision(27 + 5); + } + + var bits = cabac.Decision(27 + 4) << 3; + bits |= cabac.Decision(27 + 5) << 2; + bits |= cabac.Decision(27 + 5) << 1; + bits |= cabac.Decision(27 + 5); + if (bits < 8) + { + return bits + 3; + } + + if (bits == 13) + { + return 23 + (cabac.Decision(32) == 0 ? 0 : IntraMbTypeSuffix(32, intraSlice: false)); + } + + if (bits == 14) + { + return 11; + } + + if (bits == 15) + { + return 22; + } + + bits = (bits << 1) | cabac.Decision(27 + 5); + return bits - 4; + } + } + } + + /// mb_type of an I slice (ctxIdxOffset 3). + private int ReadIntraSliceMbType() + { + var inc = (mbA >= 0 && mbKind[mbA] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0) + + (mbB >= 0 && mbKind[mbB] is not (MbKind.I4x4 or MbKind.I8x8) ? 1 : 0); + if (cabac.Decision(3 + inc) == 0) + { + return 0; + } + + return IntraMbTypeSuffix(3, intraSlice: true); + } + + /// + /// The part of an intra mb_type after its first bin (which said «not I_NxN»): I_PCM or one of the I_16x16 types. + /// + private int IntraMbTypeSuffix(int offset, bool intraSlice) + { + if (cabac.Terminate() != 0) + { + return 25; + } + + var state = intraSlice ? offset + 2 : offset; + var type = 1 + (12 * cabac.Decision(state + 1)); + if (cabac.Decision(state + 2) != 0) + { + type += 4 + (4 * cabac.Decision(state + 2 + (intraSlice ? 1 : 0))); + } + + type += 2 * cabac.Decision(state + 3 + (intraSlice ? 1 : 0)); + type += cabac.Decision(state + 3 + (intraSlice ? 2 : 0)); + return type; + } + + private int ReadSubMbType() + { + if (!cabacMode) + { + return rd.ReadUe(12); + } + + if (!sh.IsB) + { + if (cabac.Decision(21) != 0) + { + return 0; + } + + if (cabac.Decision(22) == 0) + { + return 1; + } + + return cabac.Decision(23) != 0 ? 2 : 3; + } + + if (cabac.Decision(36) == 0) + { + return 0; + } + + if (cabac.Decision(37) == 0) + { + return 1 + cabac.Decision(39); + } + + var type = 3; + if (cabac.Decision(38) != 0) + { + if (cabac.Decision(39) != 0) + { + return 11 + cabac.Decision(39); + } + + type += 4; + } + + type += 2 * cabac.Decision(39); + type += cabac.Decision(39); + return type; + } + + private int ReadRefIdx(int list, int px, int py, int active) + { + if (!cabacMode) + { + return active == 2 ? 1 - rd.ReadBit() : rd.ReadUe(31); + } + + var inc = RefIdxCond(list, px - 1, py) + (2 * RefIdxCond(list, px, py - 1)); + var value = 0; + var ctx = 54 + inc; + while (cabac.Decision(ctx) != 0) + { + value++; + ctx = value == 1 ? 58 : 59; + if (value > 31) + { + throw new H264Exception("ref_idx non valido."); + } + } + + return value; + } + + private int RefIdxCond(int list, int xN, int yN) + { + if (Neighbor(xN, yN, out var n, out var blk) == 0) + { + return 0; + } + + if (IsSkip(n) || IsIntra(n) || mbKind[n] == MbKind.BDirect) + { + return 0; + } + + var b8 = B8OfRaster(blk); + if (subDirect[(n * 4) + b8]) + { + return 0; + } + + // A field neighbour of a frame macroblock counts in fields: index 1 is still the first frame (§9.3.3.1.1.6). + var zero = mbaff && !mbField && cur!.MbField[n] ? 1 : 0; + return cur!.RefIdx[(((list * mbCount) + n) * 4) + b8] > zero ? 1 : 0; + } + + private int ReadMvd(int list, int comp, int px, int py) + { + if (!cabacMode) + { + return rd.ReadSe(); + } + + var sum = MvdAbs(list, comp, px - 1, py) + MvdAbs(list, comp, px, py - 1); + var baseCtx = comp == 0 ? 40 : 47; + var inc = sum < 3 ? 0 : sum <= 32 ? 1 : 2; + if (cabac.Decision(baseCtx + inc) == 0) + { + return 0; + } + + var value = 1; + var k = 1; + while (value < 9 && cabac.Decision(baseCtx + (k < 4 ? k + 2 : 6)) != 0) + { + value++; + k++; + } + + if (value >= 9) + { + var bits = 3; + while (cabac.Bypass() != 0) + { + value += 1 << bits; + if (++bits > 24) + { + throw new H264Exception("mvd non valido."); + } + } + + while (bits-- > 0) + { + value += cabac.Bypass() << bits; + } + } + + return cabac.Bypass() != 0 ? -value : value; + } + + private int MvdAbs(int list, int comp, int xN, int yN) + { + if (Neighbor(xN, yN, out var n, out var blk) == 0) + { + return 0; + } + + int value = mvdAbs[(((((list * mbCount) + n) * 16) + blk) * 2) + comp]; + if (comp == 1 && mbaff && cur!.MbField[n] != mbField) + { + // Vertical differences in the units of the current macroblock (§9.3.3.1.1.7). + value = mbField ? value / 2 : value * 2; + } + + return value; + } + + private bool ReadTransform8x8() + { + if (!cabacMode) + { + return rd.ReadFlag(); + } + + var inc = (mbA >= 0 && mbT8[mbA] ? 1 : 0) + (mbB >= 0 && mbT8[mbB] ? 1 : 0); + return cabac.Decision(399 + inc) != 0; + } + + private (bool Prev, int Rem) ReadIntraPredMode() + { + if (!cabacMode) + { + return rd.ReadFlag() ? (true, 0) : (false, (int)rd.Read(3)); + } + + if (cabac.Decision(68) != 0) + { + return (true, 0); + } + + var rem = cabac.Decision(69); + rem |= cabac.Decision(69) << 1; + rem |= cabac.Decision(69) << 2; + return (false, rem); + } + + private int ReadChromaPredMode() + { + if (!cabacMode) + { + return rd.ReadUe(3); + } + + var inc = ChromaModeCond(mbA) + ChromaModeCond(mbB); + if (cabac.Decision(64 + inc) == 0) + { + return 0; + } + + if (cabac.Decision(67) == 0) + { + return 1; + } + + return cabac.Decision(67) == 0 ? 2 : 3; + } + + private int ChromaModeCond(int n) => + n >= 0 && IsIntra(n) && mbKind[n] != MbKind.IPcm && chromaModes[n] != 0 ? 1 : 0; + + private int ReadCbp(bool intra) + { + if (!cabacMode) + { + if (numC8x8 == 0) + { + // Without chroma syntax (monochrome, 4:4:4, separate planes) the code covers the luma bits only. + var luma = rd.ReadUe(15); + return intra ? H264Tables.CbpIntraNoChroma[luma] : H264Tables.CbpInterNoChroma[luma]; + } + + var code = rd.ReadUe(47); + return intra ? H264Tables.CbpIntra[code] : H264Tables.CbpInter[code]; + } + + var cbp = 0; + for (var b8 = 0; b8 < 4; b8++) + { + int bx = b8 & 1, by = b8 >> 1; + int condA, condB; + if (bx == 1) + { + condA = ((cbp >> (b8 - 1)) & 1) == 0 ? 1 : 0; + } + else + { + var n = Locate(-1, by * 8, 16, out var yM); + condA = n >= 0 && ((mbCbp[n] >> ((((yM & 15) >> 3) * 2) + 1)) & 1) == 0 ? 1 : 0; + } + + if (by == 1) + { + condB = ((cbp >> (b8 - 2)) & 1) == 0 ? 1 : 0; + } + else + { + var n = Locate(bx * 8, -1, 16, out _); + condB = n >= 0 && ((mbCbp[n] >> (b8 + 2)) & 1) == 0 ? 1 : 0; + } + + cbp |= cabac.Decision(73 + condA + (2 * condB)) << b8; + } + + if (numC8x8 == 0) + { + return cbp; + } + + var a =mbA >= 0 ? mbCbp[mbA] >> 4 : 0; + var b = mbB >= 0 ? mbCbp[mbB] >> 4 : 0; + var inc = (a != 0 ? 1 : 0) + (b != 0 ? 2 : 0); + if (cabac.Decision(77 + inc) != 0) + { + inc = (a == 2 ? 1 : 0) + (b == 2 ? 2 : 0); + cbp |= (1 + cabac.Decision(77 + 4 + inc)) << 4; + } + + return cbp; + } + + private int ReadQpDelta() + { + if (!cabacMode) + { + return rd.ReadSe(); + } + + var ctx = 60 + (lastQpDelta != 0 ? 1 : 0); + var k = 0; + while (cabac.Decision(ctx) != 0) + { + k++; + ctx = k == 1 ? 62 : 63; + if (k > 104) + { + throw new H264Exception("mb_qp_delta non valido."); + } + } + + return (k & 1) != 0 ? (k + 1) / 2 : -(k / 2); + } + + /// + /// residual_block() of category (0 luma DC, 1 luma AC, 2 luma 4×4, 3 chroma DC, 4 chroma AC, + /// 5 luma 8×8): the levels by coefficient index into ; returns the number of non-zero ones. + /// + private int ReadBlock(int cat, int blk, int comp, int[] output, int maxNum) + { + Array.Clear(output, 0, maxNum); + return cabacMode ? ReadCabacBlock(cat, blk, comp, output, maxNum) : ReadCavlcBlock(cat, blk, comp, output, maxNum); + } + + private int ReadCavlcBlock(int cat, int blk, int comp, int[] output, int maxNum) + { + int nC; + if (cat == 3) + { + nC = numC8x8 == 2 ? -2 : -1; + } + else if (cat == 4) + { + nC = ChromaNc(blk, comp); + } + else + { + nC = LumaNc(blk, comp); + } + + var table = nC switch + { + -2 => CavlcTables.CoeffTokenLookup[5], + -1 => CavlcTables.CoeffTokenLookup[4], + < 2 => CavlcTables.CoeffTokenLookup[0], + < 4 => CavlcTables.CoeffTokenLookup[1], + < 8 => CavlcTables.CoeffTokenLookup[2], + _ => CavlcTables.CoeffTokenLookup[3], + }; + var entry = table[rd.Peek(16)]; + if (entry == 0) + { + throw new H264Exception("coeff_token non valido."); + } + + rd.Skip(entry >> 8); + var token = entry & 0xFF; + var total = token >> 2; + var ones = token & 3; + if (total == 0) + { + return 0; + } + + if (total > maxNum) + { + throw new H264Exception("Troppi coefficienti."); + } + + Span levelVal = stackalloc int[16]; + var suffixLength = total > 10 && ones < 3 ? 1 : 0; + for (var i = 0; i < total; i++) + { + if (i < ones) + { + levelVal[i] = rd.ReadBit() != 0 ? -1 : 1; + continue; + } + + var prefix = 0; + while (rd.ReadBit() == 0) + { + if (++prefix > 32) + { + throw new H264Exception("level_prefix non valido."); + } + } + + var levelCode = Math.Min(15, prefix) << suffixLength; + if (suffixLength > 0 || prefix >= 14) + { + var size = prefix == 14 && suffixLength == 0 ? 4 : prefix >= 15 ? prefix - 3 : suffixLength; + if (size > 0) + { + levelCode += (int)rd.Read(size); + } + } + + if (prefix >= 15 && suffixLength == 0) + { + levelCode += 15; + } + + if (prefix >= 16) + { + levelCode += (1 << (prefix - 3)) - 4096; + } + + if (i == ones && ones < 3) + { + levelCode += 2; + } + + levelVal[i] = (levelCode & 1) == 0 ? (levelCode + 2) >> 1 : (-levelCode - 1) >> 1; + if (suffixLength == 0) + { + suffixLength = 1; + } + + if (Math.Abs(levelVal[i]) > (3 << (suffixLength - 1)) && suffixLength < 6) + { + suffixLength++; + } + } + + var zerosLeft = 0; + if (total < maxNum) + { + var tz = cat != 3 ? CavlcTables.TotalZerosLookup[total - 1] + : numC8x8 == 2 ? CavlcTables.TotalZerosChroma422DcLookup[total - 1] : CavlcTables.TotalZerosChromaDcLookup[total - 1]; + var e = tz[rd.Peek(16)]; + if (e == 0) + { + throw new H264Exception("total_zeros non valido."); + } + + rd.Skip(e >> 8); + zerosLeft = e & 0xFF; + } + + if (total + zerosLeft > maxNum) + { + throw new H264Exception("total_zeros fuori dal blocco."); + } + + Span run = stackalloc int[16]; + for (var i = 0; i < total - 1; i++) + { + if (zerosLeft > 0) + { + var rb = CavlcTables.RunBeforeLookup[Math.Min(zerosLeft, 7) - 1][rd.Peek(16)]; + if (rb == 0) + { + throw new H264Exception("run_before non valido."); + } + + rd.Skip(rb >> 8); + run[i] = rb & 0xFF; + if (run[i] > zerosLeft) + { + throw new H264Exception("run_before fuori dal blocco."); + } + + zerosLeft -= run[i]; + } + else + { + run[i] = 0; + } + } + + run[total - 1] = zerosLeft; + var coeffNum = -1; + for (var i = total - 1; i >= 0; i--) + { + coeffNum += run[i] + 1; + output[coeffNum] = levelVal[i]; + } + + return total; + } + + /// + /// §9.2.1: in a partitioned slice with constrained_intra_pred_flag, an inter neighbour of an intra macroblock counts + /// as available with nN = 0 (its residual is in partition C, which the intra macroblock must not depend on). + /// + private bool HiddenByPartitioning(int n) => partitioned && pps.ConstrainedIntraPred && !IsIntra(n) && IsIntra(mb); + + /// nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1). + private int LumaNc(int raster, int plane) + { + int bx = raster & 3, by = raster >> 2; + bool hasA = true, hasB = true; + int nA = 0, nB = 0; + if (bx > 0) + { + nA = nz[(mb * NzPerMb) + (plane * 16) + raster - 1]; + } + else if (Locate(-1, by * 4, 16, out var yM) is var a and >= 0) + { + nA = HiddenByPartitioning(a) ? 0 : nz[(a * NzPerMb) + (plane * 16) + (((yM & 15) >> 2) * 4) + 3]; + } + else + { + hasA = false; + } + + if (by > 0) + { + nB = nz[(mb * NzPerMb) + (plane * 16) + raster - 4]; + } + else if (Locate(bx * 4, -1, 16, out _) is var b and >= 0) + { + nB = HiddenByPartitioning(b) ? 0 : nz[(b * NzPerMb) + (plane * 16) + 12 + bx]; + } + else + { + hasB = false; + } + + return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0; + } + + /// nC of a chroma AC block of 4:2:0 or 4:2:2 (blocks in raster order, two per row). + private int ChromaNc(int b, int comp) + { + int bx = b & 1, by = b >> 1; + var baseIndex = 16 + (comp * 16); + bool hasA = true, hasB = true; + int nA = 0, nB = 0; + if (bx > 0) + { + nA = nz[(mb * NzPerMb) + baseIndex + b - 1]; + } + else if (Locate(-1, by * 4, mbHeightC, out var yM) is var a and >= 0) + { + nA = HiddenByPartitioning(a) ? 0 : nz[(a * NzPerMb) + baseIndex + (((yM & (mbHeightC - 1)) >> 2) * 2) + 1]; + } + else + { + hasA = false; + } + + if (by > 0) + { + nB = nz[(mb * NzPerMb) + baseIndex + b - 2]; + } + else if (Locate(bx * 4, -1, mbHeightC, out _) is var n and >= 0) + { + nB = HiddenByPartitioning(n) ? 0 : nz[(n * NzPerMb) + baseIndex + (mbHeightC / 2) - 2 + bx]; + } + else + { + hasB = false; + } + + return hasA && hasB ? (nA + nB + 1) >> 1 : hasA ? nA : hasB ? nB : 0; + } + + private int ReadCabacBlock(int cat, int blk, int comp, int[] output, int maxNum) + { + if (cat != 5) + { + var inc = CbfCond(cat, blk, comp, left: true) + (2 * CbfCond(cat, blk, comp, left: false)) + CbfCatOffset[cat]; + if (cabac.Decision(85 + inc) == 0) + { + return 0; + } + + if (cat == 0) + { + cbfDc[mb] |= 1; + } + else if (cat == 3) + { + cbfDc[mb] |= (byte)(2 << comp); + } + } + + // Blocks of field macroblocks have their own significance contexts (Table 9-34). + int sigBase, lastBase, absBase; + if (cat == 5) + { + (sigBase, lastBase, absBase) = mbField ? (436, 451, 426) : (402, 417, 426); + } + else + { + sigBase = (mbField ? 277 : 105) + SigCatOffset[cat]; + lastBase = (mbField ? 338 : 166) + SigCatOffset[cat]; + absBase = 227 + AbsCatOffset[cat]; + } + + var sig8x8 = mbField ? H264Tables.SignificantContext8x8Field : H264Tables.SignificantContext8x8; + Span significant = stackalloc bool[64]; + significant.Clear(); + var last = -1; + for (var i = 0; i < maxNum - 1; i++) + { + var ctx = cat == 5 ? sig8x8[i] : cat == 3 ? Math.Min(i / numC8x8, 2) : i; + if (cabac.Decision(sigBase + ctx) == 0) + { + continue; + } + + significant[i] = true; + var lastCtx = cat == 5 ? H264Tables.LastContext8x8[i] : cat == 3 ? Math.Min(i / numC8x8, 2) : i; + if (cabac.Decision(lastBase + lastCtx) != 0) + { + last = i; + break; + } + } + + if (last < 0) + { + last = maxNum - 1; + significant[last] = true; + } + + int gt1 = 0, eq1 = 0, count = 0; + var maxGt1 = cat == 3 ? 3 : 4; + for (var i = last; i >= 0; i--) + { + if (!significant[i]) + { + continue; + } + + int abs; + if (cabac.Decision(absBase + (gt1 != 0 ? 0 : Math.Min(4, 1 + eq1))) == 0) + { + abs = 1; + } + else + { + var ctx = absBase + 5 + Math.Min(maxGt1, gt1); + var v = 1; + while (v < 14 && cabac.Decision(ctx) != 0) + { + v++; + } + + if (v == 14) + { + var k = 0; + while (cabac.Bypass() != 0) + { + v += 1 << k; + if (++k > 24) + { + throw new H264Exception("coeff_abs_level_minus1 non valido."); + } + } + + while (k-- > 0) + { + v += cabac.Bypass() << k; + } + } + + abs = v + 1; + } + + if (abs == 1) + { + eq1++; + } + else + { + gt1++; + } + + output[i] = cabac.Bypass() != 0 ? -abs : abs; + count++; + } + + return count; + } + + /// condTermFlagN of coded_block_flag (§9.3.3.1.1.9) for the block to the left or above. + private int CbfCond(int cat, int blk, int comp, bool left) + { + var currentIntra = IsIntra(mb); + int n; + int index; + switch (cat) + { + case 0: + n = left ? mbA : mbB; + if (n < 0) + { + return currentIntra ? 1 : 0; + } + + if (mbKind[n] == MbKind.IPcm) + { + return 1; + } + + return mbKind[n] == MbKind.I16x16 ? cbfDc[n] & 1 : 0; + case 3: + n = left ? mbA : mbB; + if (n < 0) + { + return currentIntra ? 1 : 0; + } + + if (mbKind[n] == MbKind.IPcm) + { + return 1; + } + + return (cbfDc[n] >> (1 + comp)) & 1; + case 4: + { + int bx = blk & 1, by = blk >> 1; + if (left ? bx > 0 : by > 0) + { + n = mb; + index = left ? blk - 1 : blk - 2; + } + else + { + n = left ? Locate(-1, by * 4, mbHeightC, out var yM) : Locate(bx * 4, -1, mbHeightC, out yM); + if (n < 0) + { + return currentIntra ? 1 : 0; + } + + index = left ? ((((yM & (mbHeightC - 1)) >> 2) * 2) + 1) : (mbHeightC / 2) - 2 + bx; + } + + if (mbKind[n] == MbKind.IPcm) + { + return 1; + } + + return nz[(n * NzPerMb) + 16 + (comp * 16) + index] != 0 ? 1 : 0; + } + + default: + { + int bx = blk & 3, by = blk >> 2; + if (left ? bx > 0 : by > 0) + { + n = mb; + index = left ? blk - 1 : blk - 4; + } + else + { + n = left ? Locate(-1, by * 4, 16, out var yM) : Locate(bx * 4, -1, 16, out yM); + if (n < 0) + { + return currentIntra ? 1 : 0; + } + + index = left ? ((((yM & 15) >> 2) * 4) + 3) : 12 + bx; + } + + if (mbKind[n] == MbKind.IPcm) + { + return 1; + } + + return nz[(n * NzPerMb) + index] != 0 ? 1 : 0; + } + } + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs new file mode 100644 index 0000000..e2d074d --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Motion.cs @@ -0,0 +1,721 @@ +namespace Febe.Core.Codecs.H264; + +public sealed partial class H264Decoder +{ + private int weightMode; + + /// Implicit weights w0 of the slice by (refIdxL0, refIdxL1): frames, or the fields of a field picture. + private int[] implicitW0 = []; + + /// MBAFF: implicit weights of the field macroblocks, by parity of the macroblock. + private int[][] implicitField = [[], []]; + + /// + /// The neighbouring 4×4 luma block covering (, ) relative to the current + /// macroblock (§6.4.12): 0 not available, 1 in another macroblock, 2 in the current one (its availability then + /// depends on the decoding order, ). + /// + private int Neighbor(int xN, int yN, out int n, out int blk) + { + if ((uint)xN < 16 && (uint)yN < 16) + { + n = mb; + blk = ((yN >> 2) * 4) + (xN >> 2); + return 2; + } + + n = Locate(xN, yN, 16, out var yM); + if (n < 0) + { + blk = 0; + return 0; + } + + blk = (((yM & 15) >> 2) * 4) + ((xN & 15) >> 2); + return 1; + } + + /// + /// Motion of a neighbouring block (§8.4.1.3.2); in an MBAFF frame brought to the units of the current macroblock: + /// a frame neighbour of a field macroblock has its vertical vector halved and its index doubled, a field neighbour + /// of a frame macroblock the reverse. + /// + private (bool Available, int RefIdx, int X, int Y) MotionNeighbor(int list, int xN, int yN) + { + var where = Neighbor(xN, yN, out var n, out var blk); + if (where == 0 || (where == 2 && !blkDone[blk])) + { + return (false, -1, 0, 0); + } + + var picture = cur!; + int refIdx = picture.RefIdx[(((list * mbCount) + n) * 4) + B8OfRaster(blk)]; + if (refIdx < 0 || picture.MbIntra[n]) + { + return (true, -1, 0, 0); + } + + var i = ((((list * mbCount) + n) * 16) + blk) * 2; + int x = picture.Mv[i], y = picture.Mv[i + 1]; + if (mbaff && picture.MbField[n] != mbField) + { + if (mbField) + { + y /= 2; + refIdx *= 2; + } + else + { + y *= 2; + refIdx >>= 1; + } + } + + return (true, refIdx, x, y); + } + + /// + /// Luma motion vector prediction (§8.4.1.3). : 0 none, 1/2 the upper/lower 16×8 + /// partition, 3/4 the left/right 8×16 partition. + /// + private (int X, int Y) Mvp(int list, int refIdx, int px, int py, int w, int directional) + { + var a = MotionNeighbor(list, px - 1, py); + var b = MotionNeighbor(list, px, py - 1); + var c = MotionNeighbor(list, px + w, py - 1); + if (!c.Available) + { + c = MotionNeighbor(list, px - 1, py - 1); + } + + switch (directional) + { + case 1 when b.RefIdx == refIdx: + return (b.X, b.Y); + case 2 when a.RefIdx == refIdx: + return (a.X, a.Y); + case 3 when a.RefIdx == refIdx: + return (a.X, a.Y); + case 4 when c.RefIdx == refIdx: + return (c.X, c.Y); + } + + if (!b.Available && !c.Available && a.Available) + { + b = a; + c = a; + } + + var matches = (a.RefIdx == refIdx ? 1 : 0) + (b.RefIdx == refIdx ? 1 : 0) + (c.RefIdx == refIdx ? 1 : 0); + if (matches == 1) + { + return a.RefIdx == refIdx ? (a.X, a.Y) : b.RefIdx == refIdx ? (b.X, b.Y) : (c.X, c.Y); + } + + return (Median(a.X, b.X, c.X), Median(a.Y, b.Y, c.Y)); + } + + private static int Median(int a, int b, int c) => Math.Max(Math.Min(a, b), Math.Min(Math.Max(a, b), c)); + + private void DeriveMv(int list, int px, int py, int w, int h, int directional) + { + var picture = cur!; + var b8 = ((py >> 3) * 2) + (px >> 3); + var refIdx = picture.RefIdx[(((list * mbCount) + mb) * 4) + b8]; + var blk = ((py >> 2) * 4) + (px >> 2); + + // SVC motion_prediction_flag: the motion vector of the layer below is the predictor (§G.8.4.1). + var (x, y) = MotionFromBase(list, b8) ? BaseMv(list, blk) : Mvp(list, refIdx, px, py, w, directional); + x += mvdValue[((list * 16) + blk) * 2]; + y += mvdValue[(((list * 16) + blk) * 2) + 1]; + FillMv(list, px, py, w, h, x, y); + } + + private void FillMv(int list, int px, int py, int w, int h, int x, int y) + { + var mv = cur!.Mv; + for (var by = py; by < py + h; by += 4) + { + for (var bx = px; bx < px + w; bx += 4) + { + var i = ((((list * mbCount) + mb) * 16) + ((by >> 2) * 4) + (bx >> 2)) * 2; + mv[i] = (short)x; + mv[i + 1] = (short)y; + } + } + } + + private void PredictPSkip() + { + for (var b8 = 0; b8 < 4; b8++) + { + SetRefIdx(0, b8, 0); + } + + var a = MotionNeighbor(0, -1, 0); + var b = MotionNeighbor(0, 0, -1); + int x = 0, y = 0; + if (a.Available && b.Available && !(a.RefIdx == 0 && a.X == 0 && a.Y == 0) && !(b.RefIdx == 0 && b.X == 0 && b.Y == 0)) + { + (x, y) = Mvp(0, 0, 0, 0, 16, 0); + } + + FillMv(0, 0, 0, 16, 16, x, y); + MarkDone(0, 0, 16, 16); + } + + private static int MinPositive(int a, int b) => a >= 0 && b >= 0 ? Math.Min(a, b) : Math.Max(a, b); + + /// Direct prediction (§8.4.1.2) of the sub-macroblocks to − 1. + private void PredictDirect(int first, int end) + { + var picture = cur!; + var colEntry = Reference(1, 0); + var col = colEntry.Pic!; + var inference = sps.Direct8x8Inference; + + int ref0 = -1, ref1 = -1; + int mvp0x = 0, mvp0y = 0, mvp1x = 0, mvp1y = 0; + var directZero = false; + if (sh.DirectSpatialMvPred) + { + for (var list = 0; list < 2; list++) + { + var a = MotionNeighbor(list, -1, 0); + var b = MotionNeighbor(list, 0, -1); + var c = MotionNeighbor(list, 16, -1); + if (!c.Available) + { + c = MotionNeighbor(list, -1, -1); + } + + var r = MinPositive(a.RefIdx, MinPositive(b.RefIdx, c.RefIdx)); + if (list == 0) + { + ref0 = r; + } + else + { + ref1 = r; + } + } + + if (ref0 < 0 && ref1 < 0) + { + ref0 = ref1 = 0; + directZero = true; + } + else + { + if (ref0 >= 0) + { + (mvp0x, mvp0y) = Mvp(0, ref0, 0, 0, 16, 0); + } + + if (ref1 >= 0) + { + (mvp1x, mvp1y) = Mvp(1, ref1, 0, 0, 16, 0); + } + } + } + + // The co-located macroblock (§8.4.1.2.1, Tables 8-6 and 8-8), on the frame grid of RefPicList1[0]: a field + // macroblock of a frame macroblock takes the field of the pair closer in order (Fld_To_Frm), a field one of a + // frame macroblock the frame macroblock covering its rows (Frm_To_Fld). + var w = widthInMbs; + var colInterlaced = col.MbField[(mbY * w) + mbX]; + int colParity = 0; + if (colInterlaced) + { + if (!mbField) + { + var poc = picture.Poc; + colParity = Math.Abs(col.TopPoc - poc) < Math.Abs(col.BottomPoc - poc) ? 0 : 1; + } + else + { + colParity = fieldPic && col.CodedAsFields ? colEntry.Parity : mbY & 1; + } + } + + // An inter-view reference (MVC) is neither short-term nor long-term: no colZeroFlag. + var colShort = !colEntry.IsLongTerm && !colEntry.InterView; + for (var sub = first; sub < end; sub++) + { + for (var k = 0; k < 4; k++) + { + var blk = ((((sub >> 1) * 2) + (k >> 1)) * 4) + ((sub & 1) * 2) + (k & 1); + int xCol, yCol; + if (inference) + { + xCol = (sub & 1) * 12; + yCol = (sub >> 1) * 12; + } + else + { + xCol = (blk & 3) * 4; + yCol = (blk >> 2) * 4; + } + + int colRow, yM, vertical; + if (colInterlaced) + { + colRow = (mbY & ~1) + colParity; + if (!mbField) + { + yM = (8 * (mbY & 1)) + (4 * (yCol / 8)); + vertical = 2; // Fld_To_Frm + } + else + { + yM = yCol; + vertical = 0; + } + } + else if (mbField) + { + colRow = (mbY & ~1) + (yCol / 8); + yM = (2 * yCol) % 16; + vertical = 1; // Frm_To_Fld + } + else + { + colRow = mbY; + yM = yCol; + vertical = 0; + } + + var colMb = (colRow * w) + mbX; + var colBlk = ((yM >> 2) * 4) + (xCol >> 2); + int colX = 0, colY = 0, colRef = -1, colRefPar = -1; + Picture? colRefPic = null; + if (!col.MbIntra[colMb]) + { + var colB8 = B8OfRaster(colBlk); + var list = col.RefIdx[(colMb * 4) + colB8] >= 0 ? 0 : 1; + var index = (((list * mbCount) + colMb) * 4) + colB8; + colRef = col.RefIdx[index]; + colRefPic = col.RefPic[index]; + colRefPar = col.RefPar[index]; + var i = ((((list * mbCount) + colMb) * 16) + colBlk) * 2; + colX = col.Mv[i]; + colY = col.Mv[i + 1]; + } + + int r0, r1, m0x, m0y, m1x, m1y; + if (sh.DirectSpatialMvPred) + { + var colZero = colShort && colRef == 0 && colX is >= -1 and <= 1 && colY is >= -1 and <= 1; + r0 = ref0; + r1 = ref1; + if (directZero || (r0 == 0 && colZero)) + { + (m0x, m0y) = (0, 0); + } + else + { + (m0x, m0y) = (mvp0x, mvp0y); + } + + if (directZero || (r1 == 0 && colZero)) + { + (m1x, m1y) = (0, 0); + } + else + { + (m1x, m1y) = (mvp1x, mvp1y); + } + } + else + { + if (vertical == 1) + { + colY /= 2; + } + else if (vertical == 2) + { + colY *= 2; + } + + r0 = colRef < 0 ? 0 : MapColToList0(colRefPic, colRefPar); + r1 = 0; + var pic0 = Reference(0, r0); + var pic1 = Reference(1, 0); + var td = Math.Clamp(pic1.Poc - pic0.Poc, -128, 127); + if (pic0.IsLongTerm || td == 0) + { + (m0x, m0y) = (colX, colY); + (m1x, m1y) = (0, 0); + } + else + { + var curPoc = mbField ? picture.PocOf(mbY & 1) : picture.Poc; + var tb = Math.Clamp(curPoc - pic0.Poc, -128, 127); + var tx = (16384 + Math.Abs(td / 2)) / td; + var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023); + m0x = ((scale * colX) + 128) >> 8; + m0y = ((scale * colY) + 128) >> 8; + m1x = m0x - colX; + m1y = m0y - colY; + } + } + + if (k == 0) + { + SetDirectRef(0, sub, r0); + SetDirectRef(1, sub, r1); + } + + var mv = picture.Mv; + var i0 = (((0 * mbCount) + mb) * 16) + blk; + var i1 = (((1 * mbCount) + mb) * 16) + blk; + mv[i0 * 2] = (short)(r0 >= 0 ? m0x : 0); + mv[(i0 * 2) + 1] = (short)(r0 >= 0 ? m0y : 0); + mv[i1 * 2] = (short)(r1 >= 0 ? m1x : 0); + mv[(i1 * 2) + 1] = (short)(r1 >= 0 ? m1y : 0); + blkDone[blk] = true; + } + } + } + + private void SetDirectRef(int list, int b8, int refIdx) + { + var index = (((list * mbCount) + mb) * 4) + b8; + if (refIdx < 0 || refIdx >= RefIdxRange(list)) + { + cur!.RefIdx[index] = -1; + cur.RefPic[index] = null; + cur.RefPar[index] = -1; + return; + } + + var entry = Reference(list, refIdx); + cur!.RefIdx[index] = (sbyte)refIdx; + cur.RefPic[index] = entry.Pic; + cur.RefPar[index] = (sbyte)entry.Parity; + } + + /// + /// The lowest index of list 0 referring to the picture the co-located block referred to (§8.4.1.2.3): for a field + /// macroblock that field, or the field of that frame with the parity of the macroblock; for a frame macroblock the + /// frame (or the frame containing that field). + /// + private int MapColToList0(Picture? picture, int parity) + { + if (picture is null) + { + return 0; + } + + var fieldOf = MbFieldOf; + var target = mbField ? (parity >= 0 ? parity : mbY & 1) : -1; + var count = RefIdxRange(0); + for (var i = 0; i < count; i++) + { + var e = ListEntry(0, i, fieldOf); + if (ReferenceEquals(e.Pic, picture) && e.Parity == target) + { + return i; + } + } + + return 0; + } + + /// For a field macroblock of an MBAFF frame its parity (its references are fields of the frame lists), else −1. + private int MbFieldOf => mbaff && mbField ? mbY & 1 : -1; + + /// + /// The entry of a list for a reference index: as built, or ( ≥ 0) for a field macroblock + /// of that parity in an MBAFF frame, the field of frame refIdx / 2 with the same parity for even indices, the + /// opposite for odd ones (§8.4.2.1). Empty when missing. + /// + private RefEntry ListEntry(int list, int refIdx, int fieldOf) + { + var l = refList[list]; + if (fieldOf < 0) + { + return (uint)refIdx < (uint)l.Length ? l[refIdx] : default; + } + + var i = refIdx >> 1; + if ((uint)i >= (uint)l.Length || l[i].Pic is null) + { + return default; + } + + return new RefEntry(l[i].Pic, (refIdx & 1) == 0 ? fieldOf : 1 - fieldOf); + } + + /// A reference picture of the current macroblock; a substitute when the stream refers to a missing one. + private RefEntry Reference(int list, int refIdx) + { + var fieldOf = MbFieldOf; + var entry = ListEntry(list, refIdx, fieldOf); + if (entry.Pic is not null) + { + return entry; + } + + foreach (var q in refList[list]) + { + if (q.Pic is not null) + { + return fieldOf < 0 ? q : new RefEntry(q.Pic, fieldOf); + } + } + + foreach (var q in dpb) + { + if (q.IsReference && !ReferenceEquals(q, cur)) + { + var parity = fieldOf >= 0 ? fieldOf : fieldPic ? (((q.ShortMask | q.LongMask) & 1) != 0 ? 0 : 1) : -1; + return new RefEntry(q, parity); + } + } + + // The first field of the frame, for its second field. + if (fieldPic && cur is { } picture && ((picture.ShortMask | picture.LongMask) & (1 << (1 - curParity))) != 0) + { + return new RefEntry(picture, 1 - curParity); + } + + // Never the picture itself: a frame predicted from its own unfinished samples is corrupt, not damaged. + throw new H264Exception("Slice P o B senza immagini di riferimento."); + } + + private void PrepareWeights() + { + weightMode = sh.IsP ? (pps.WeightedPred ? 1 : 0) : sh.IsB ? pps.WeightedBipredIdc : 0; + if (weightMode != 2) + { + return; + } + + int n0 = sh.NumRefIdxActiveL0, n1 = sh.NumRefIdxActiveL1; + var picture = cur!; + FillImplicit(ref implicitW0, n0, n1, fieldPic ? picture.PocOf(curParity) : picture.Poc, -1); + if (mbaff) + { + for (var parity = 0; parity < 2; parity++) + { + FillImplicit(ref implicitField[parity], 2 * n0, 2 * n1, picture.PocOf(parity), parity); + } + } + } + + /// Implicit weights (§8.4.2.3.1) for every pair of indices, with the order counts of frames or of fields. + private void FillImplicit(ref int[] table, int n0, int n1, int poc, int fieldOf) + { + if (table.Length < n0 * n1) + { + table = new int[Math.Max(n0 * n1, 1)]; + } + + for (var i = 0; i < n0; i++) + { + var p0 = ListEntry(0, i, fieldOf); + for (var j = 0; j < n1; j++) + { + var p1 = ListEntry(1, j, fieldOf); + var w0 = 32; + if (p0.Pic is not null && p1.Pic is not null) + { + var td = Math.Clamp(p1.Poc - p0.Poc, -128, 127); + if (td != 0 && !p0.IsLongTerm && !p1.IsLongTerm) + { + var tb = Math.Clamp(poc - p0.Poc, -128, 127); + var tx = (16384 + Math.Abs(td / 2)) / td; + var scale = Math.Clamp(((tb * tx) + 32) >> 6, -1024, 1023); + if ((scale >> 2) is >= -64 and <= 128) + { + w0 = 64 - (scale >> 2); + } + } + } + + table[(i * n1) + j] = w0; + } + } + } + + private void MotionCompensateDirect(int first, int end) + { + for (var sub = first; sub < end; sub++) + { + int ox = (sub & 1) * 8, oy = (sub >> 1) * 8; + if (sps.Direct8x8Inference) + { + MotionCompensate(ox, oy, 8, 8); + } + else + { + for (var k = 0; k < 4; k++) + { + MotionCompensate(ox + ((k & 1) * 4), oy + ((k >> 1) * 4), 4, 4); + } + } + } + } + + /// + /// Inter prediction of one partition with its motion (§8.4.2), written into the current picture. A field macroblock + /// predicts from fields: rows of one parity of a frame store, in field coordinates. + /// + /// + /// Inter prediction of one partition with its motion (§8.4.2), written into the current picture. A field macroblock + /// predicts from fields: rows of one parity of a frame store, in field coordinates. + /// + private void MotionCompensate(int px, int py, int w, int h) + { + if (wide) + { + MotionCompensate(px, py, w, h); + } + else + { + MotionCompensate(px, py, w, h); + } + } + + private void MotionCompensate(int px, int py, int w, int h) + where T : unmanaged + { + var picture = cur!; + var b8 = ((py >> 3) * 2) + (px >> 3); + var blk = ((py >> 2) * 4) + (px >> 2); + int r0 = picture.RefIdx[(mb * 4) + b8]; + int r1 = picture.RefIdx[((mbCount + mb) * 4) + b8]; + var i0 = ((mb * 16) + blk) * 2; + var i1 = (((mbCount + mb) * 16) + blk) * 2; + var x = (mbX * 16) + px; + var y = ((mbField ? mbY >> 1 : mbY) * 16) + py; + + Span a = stackalloc T[256]; + Span b = stackalloc T[256]; + var size = w * h; + var pa = a[..size]; + var pb = b[..size]; + var use0 = r0 >= 0; + var use1 = r1 >= 0; + if (!use0 && !use1) + { + use0 = true; + r0 = 0; + } + + var e0 = use0 ? Reference(0, r0) : default; + var e1 = use1 ? Reference(1, r1) : default; + int mv0x = picture.Mv[i0], mv0y = picture.Mv[i0 + 1], mv1x = picture.Mv[i1], mv1y = picture.Mv[i1 + 1]; + int width = picture.Width, height = picture.Height; + + // Luma, or the colour plane of the slice; in 4:4:4 Cb and Cr too, with the same interpolation (§8.4.2.2). + for (var plane = 0; plane < LumaLikePlanes; plane++) + { + var source = plane == 0 ? colourPlane : plane; + var max = plane == 0 ? maxY : maxC; + if (use0) + { + var field = e0.Parity >= 0; + InterPrediction.Luma(Samples.Plane(e0.Pic!.Plane(source)), field ? e0.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv0x, (y * 4) + mv0y, w, h, pa, max); + } + + if (use1) + { + var field = e1.Parity >= 0; + InterPrediction.Luma(Samples.Plane(e1.Pic!.Plane(source)), field ? e1.Parity * width : 0, field ? 2 * width : width, width, field ? height / 2 : height, (x * 4) + mv1x, (y * 4) + mv1y, w, h, use0 ? pb : pa, max); + } + + Combine(pa, pb, use0, use1, r0, r1, plane, plane == 0 ? bitDepthY : bitDepthC); + var target = Samples.Plane(picture.Plane(source)); + for (var row = 0; row < h; row++) + { + pa.Slice(row * w, w).CopyTo(target.Slice(lumaO + ((py + row) * lumaStride) + px, w)); + } + } + + if (numC8x8 == 0) + { + return; + } + + // Chroma of 4:2:0 and 4:2:2 in eighths of a chroma sample: 4:2:2 has full vertical resolution, so its vertical + // vector is in eighths already doubled (§8.4.1.4, §8.4.2.2.2); between fields of opposite parity the vertical + // vector of 4:2:0 moves by a quarter of a chroma row (Table 8-9). + var full = chromaArrayType == 2; + int cw = w / 2, ch = full ? h : h / 2, cwidth = picture.ChromaWidth, cheight = picture.ChromaHeight; + var csize = cw * ch; + var ca = a[..csize]; + var cb = b[..csize]; + var parity = mbY & 1; + var adjust0 = full || e0.Parity < 0 || e0.Parity == parity ? 0 : parity == 0 ? -2 : 2; + var adjust1 = full || e1.Parity < 0 || e1.Parity == parity ? 0 : parity == 0 ? -2 : 2; + var ey0 = full ? ((y * 4) + mv0y) * 2 : (y * 4) + mv0y + adjust0; + var ey1 = full ? ((y * 4) + mv1y) * 2 : (y * 4) + mv1y + adjust1; + var cy = full ? py : py / 2; + for (var comp = 1; comp <= 2; comp++) + { + if (use0) + { + var field = e0.Parity >= 0; + InterPrediction.Chroma(Samples.Plane(comp == 1 ? e0.Pic!.Cb : e0.Pic!.Cr), field ? e0.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv0x, ey0, cw, ch, ca); + } + + if (use1) + { + var field = e1.Parity >= 0; + InterPrediction.Chroma(Samples.Plane(comp == 1 ? e1.Pic!.Cb : e1.Pic!.Cr), field ? e1.Parity * cwidth : 0, field ? 2 * cwidth : cwidth, cwidth, field ? cheight / 2 : cheight, (x * 4) + mv1x, ey1, cw, ch, use0 ? cb : ca); + } + + Combine(ca, cb, use0, use1, r0, r1, comp, bitDepthC); + var plane = Samples.Plane(comp == 1 ? picture.Cb : picture.Cr); + for (var row = 0; row < ch; row++) + { + ca.Slice(row * cw, cw).CopyTo(plane.Slice(chromaO + ((cy + row) * chromaStride) + (px / 2), cw)); + } + } + } + + /// + /// The weighted sample prediction (§8.4.2.3) of component (0 luma, 1 Cb, 2 Cr): the offsets + /// are in units of 8-bit samples, scaled to . + /// + private void Combine(Span a, ReadOnlySpan b, bool use0, bool use1, int r0, int r1, int comp, int bitDepth) + where T : unmanaged + { + // Explicit weights are by frame for the field macroblocks of an MBAFF frame (refIdxWP = refIdx >> 1). + var fieldMb = mbaff && mbField; + int w0Index = fieldMb ? r0 >> 1 : r0, w1Index = fieldMb ? r1 >> 1 : r1; + var shift = bitDepth - 8; + var max = (1 << bitDepth) - 1; + if (use0 && use1) + { + if (weightMode == 1 && sh.Weights is { } weights && sh.Offsets is { } offsets) + { + var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; + InterPrediction.WeightTwo(a, b, logWd, weights[0][(w0Index * 3) + comp], weights[1][(w1Index * 3) + comp], offsets[0][(w0Index * 3) + comp] << shift, offsets[1][(w1Index * 3) + comp] << shift, max); + } + else if (weightMode == 2) + { + var w0 = fieldMb + ? implicitField[mbY & 1][(r0 * 2 * sh.NumRefIdxActiveL1) + r1] + : implicitW0[(r0 * sh.NumRefIdxActiveL1) + r1]; + InterPrediction.WeightTwo(a, b, 5, w0, 64 - w0, 0, 0, max); + } + else + { + InterPrediction.Average(a, b); + } + + return; + } + + if (weightMode == 1 && sh.Weights is { } w && sh.Offsets is { } o) + { + var list = use0 ? 0 : 1; + var r = use0 ? w0Index : w1Index; + var logWd = comp == 0 ? sh.LumaLog2WeightDenom : sh.ChromaLog2WeightDenom; + InterPrediction.WeightOne(a, logWd, w[list][(r * 3) + comp], o[list][(r * 3) + comp] << shift, max); + } + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Mvc.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Mvc.cs new file mode 100644 index 0000000..62a91f3 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Mvc.cs @@ -0,0 +1,319 @@ +namespace Febe.Core.Codecs.H264; + +/// +/// Multiview video coding (MVC, Annex H): the base view is decoded by this decoder as plain H.264 (its prefix NAL units +/// 14 only say which view it is and whether the other views refer to it); each other view by a decoder of its own, +/// created on its first view component (NAL unit 20 with svc_extension_flag 0), with its own picture order, frame_num, +/// marking and reference frames, as §H.8 wants them per view. A view component may also predict from the view +/// components of the same access unit that come before it in view order (inter-view prediction): they are appended to +/// its reference lists (§H.8.2.1) and can be moved by the list modifications 4 and 5 (§H.8.2.2.3). +/// +public sealed partial class H264Decoder +{ + /// Subset sequence parameter sets (NAL unit 15) of the root decoder; the view decoders use them as their SPSs. + private readonly Dictionary subsetSequences = []; + + /// The decoder of the base view, for the decoder of another view; null for the root decoder itself. + private readonly H264Decoder? root; + + /// The decoders of the non-base views (root decoder only), in the order they appeared. + private readonly List viewDecoders = []; + + /// view_id of the view this decoder decodes. + private int viewId; + + /// Root decoder: access units started so far (one per picture of the base view). + private long accessUnit; + + /// The frame store of the view component of the latest access unit, its access unit and its inter_view_flag. + private Picture? auPicture; + + private long auPictureUnit = -1; + private bool auPictureInterView; + + /// The view component being decoded is an anchor picture (anchor_pic_flag): it uses the anchor references. + private bool anchorPicture; + + /// inter_view_flag of the view component whose slices come next (from its prefix or extension header). + private bool pendingInterView = true; + + /// A subset SPS with the multiview extension was read: the stream is MVC. + private bool multiview; + + /// + /// The frame stores of all views together are kept within twice the largest buffer of any level (MaxDpbMbs of level + /// 6.2, table A-1, times the mvcScaleFactor 2 that Annex H applies to the buffer of a multiview stream): a damaged + /// subset SPS that lists up to 1,024 views cannot make the decoder allocate one buffer per view beyond it. + /// + internal const long MaxAllViewsMbs = 2L * Sps.MaxDpbMbs; + + public H264Decoder() + { + } + + /// The decoder of a non-base view: it shares the parameter sets of the root decoder. + private H264Decoder(H264Decoder root, int viewId) + { + this.root = root; + this.viewId = viewId; + sequences = root.subsetSequences; + pictures = root.pictures; + FrameDecoded += frame => root.FrameDecoded?.Invoke(frame); + // Wanted is read from the root decoder (see Wanted): a filter set there applies to every view. + } + + /// + /// Whether the non-base views of an MVC stream are decoded too (the default), each frame carrying its + /// ; false keeps only the base view, which is plain H.264, and skips the rest. + /// + public bool DecodeAllViews { get; set; } = true; + + /// A prefix NAL unit (14, §7.3.2.12): with the MVC header it says the view and inter_view_flag of the base view. + private void ReadPrefix(NalUnit nal) + { + if (nal.HeaderLength != 4 || nal.IsSvc) + { + return; + } + + viewId = (nal.Rbsp[2] << 2) | (nal.Rbsp[3] >> 6); + pendingInterView = (nal.Rbsp[3] & 2) != 0; + } + + /// A slice of a non-base view (NAL unit 20 with the MVC header, §H.7.3.1.1), given to the decoder of its view. + private void DecodeViewSlice(NalUnit nal) + { + if (!DecodeAllViews || nal.HeaderLength != 4) + { + return; + } + + var nonIdr = (nal.Rbsp[1] & 0x40) != 0; + var id = (nal.Rbsp[2] << 2) | (nal.Rbsp[3] >> 6); + if (id == viewId && auPicture is not null) + { + throw new H264Exception("Vista non base con lo stesso view_id della vista base."); + } + + // The view components before this one in the access unit are finished: deblocked, they can be referred to. + FinishPicture(); + H264Decoder? decoder = null; + foreach (var other in viewDecoders) + { + if (other.viewId == id) + { + decoder = other; + } + else + { + other.FinishPicture(); + } + } + + // A view seen for the first time gets a decoder of its own, kept only once its first slice has shown that the + // subset SPS lists the view and that the buffers of all views fit (RegisterView): until then it holds nothing. + var seen = decoder is not null; + if (decoder is null) + { + if (viewDecoders.Count >= 1023) + { + throw new H264Exception("Troppe viste."); + } + + decoder = new H264Decoder(this, id); + } + + decoder.anchorPicture = (nal.Rbsp[3] & 4) != 0; + decoder.pendingInterView = (nal.Rbsp[3] & 2) != 0; + decoder.DecodeViewComponentSlice(nal, idr: !nonIdr, register: !seen); + } + + /// + /// Keeps the decoder of a new view, when the frame stores of the base view and of every view decoded so far, this one + /// included, stay within : each view holds at most max_num_ref_frames reference frames + /// and the picture being decoded. + /// + private void RegisterView(H264Decoder decoder, Sps sps) + { + var views = viewDecoders.Count + 2L; + var perView = (long)(Math.Max(1, sps.MaxNumRefFrames) + 1) * sps.WidthInMbs * sps.HeightInMbs; + if (views * perView > MaxAllViewsMbs) + { + throw new H264Exception("Troppe viste per la memoria di ogni livello H.264."); + } + + viewDecoders.Add(decoder); + } + + /// + /// One slice of the view of this decoder: parsed with the subset SPS, decoded like a slice of the base view. The first + /// slice of a new view () also has the root decoder keep this decoder. + /// + private void DecodeViewComponentSlice(NalUnit nal, bool idr, bool register) + { + var reader = nal.Reader(); + + // The rest of the decoder tells IDR pictures by NAL unit type: the view component stands as a unit 5 or 1. + var unit = nal with { Type = idr ? 5 : 1 }; + var header = SliceHeader.Parse(reader, unit, sequences, pictures, out var sps, out var pps, multiview: true); + if (sps.Mvc is null || sps.Mvc.OrderOf(viewId) <= 0) + { + throw new H264Exception("Vista assente dall'SPS di sottoinsieme."); + } + + if (register) + { + root!.RegisterView(this, sps); + } + + if (header.RedundantPicCnt > 0) + { + return; + } + + DecodeParsedSlice(unit, reader, header, sps, pps); + } + + /// Finishes the pictures of the other views (at the end of an access unit, or before the next base view one). + private void FinishViews() + { + foreach (var decoder in viewDecoders) + { + decoder.FinishPicture(); + } + } + + /// Flushes the decoders of the other views. + private void FlushViews() + { + foreach (var decoder in viewDecoders) + { + decoder.Flush(); + } + } + + /// Records the frame store of the view component starting now, for the views that refer to it. + private void NoteViewComponent(Picture picture) + { + if (root is null) + { + accessUnit++; + } + + auPicture = picture; + auPictureUnit = (root ?? this).accessUnit; + auPictureInterView = pendingInterView; + } + + /// + /// A view component that nobody refers to in time may still be needed by the views after it in the same access unit + /// (inter_view_flag): it is then always reconstructed, whatever says. + /// + private bool NeededByOtherViews => (root ?? this) is { multiview: true, DecodeAllViews: true } && pendingInterView; + + /// The view_ids of the inter-view references of list of the current view component. + private int[] InterViewRefs(int list) + { + if (root is null || activeSps?.Mvc is not { } mvc) + { + return []; + } + + var order = mvc.OrderOf(viewId); + if (order <= 0) + { + return []; + } + + return (anchorPicture ? mvc.AnchorRefs : mvc.NonAnchorRefs)[list][order]; + } + + /// + /// The view component of view in the current access unit, as an inter-view reference of the + /// current picture (the field of the same parity for a field); empty when it is missing or not for inter-view use. + /// + private RefEntry InterViewPicture(int id) + { + var top = root!; + H264Decoder? decoder = top.viewId == id ? top : null; + if (decoder is null) + { + foreach (var other in top.viewDecoders) + { + if (other.viewId == id) + { + decoder = other; + break; + } + } + } + + if (decoder is null || decoder == this || decoder.auPicture is not { } picture || decoder.auPictureUnit != top.accessUnit + || !decoder.auPictureInterView || picture.Skipped) + { + return default; + } + + var parity = curStructure == 0 ? -1 : curStructure - 1; + var bit = parity < 0 ? 3 : 1 << parity; + if ((picture.Decoded & bit) != bit || !picture.Fits(widthInMbs, heightInMbs, activeSps!.ChromaFormatIdc, BytesPerSample, PlaneCount(activeSps))) + { + return default; + } + + return new RefEntry(picture, parity, InterView: true); + } + + /// Whether some inter-view reference of the current view component is there. + private bool HasInterViewReference() + { + for (var list = 0; list < 2; list++) + { + foreach (var id in InterViewRefs(list)) + { + if (InterViewPicture(id).Pic is not null) + { + return true; + } + } + } + + return false; + } + + /// §H.8.2.1: the inter-view references of the list, in the order of the SPS, after the temporal ones. + private void AppendInterView(List list, int index) + { + foreach (var id in InterViewRefs(index)) + { + var entry = InterViewPicture(id); + if (entry.Pic is not null) + { + list.Add(entry); + } + } + } + + /// + /// The inter-view reference picked by modification_of_pic_nums_idc 4 (subtract) or 5 (add) with + /// abs_diff_view_idx_minus1 (§H.8.2.2.3); is picViewIdxPred. + /// + private RefEntry ModifiedInterView(int list, int idc, int value, ref int pred) + { + var refs = InterViewRefs(list); + var max = refs.Length; + if (max == 0) + { + return default; + } + + if ((uint)value >= (uint)max) + { + return default; + } + + var abs = value + 1; + pred = idc == 4 ? (pred - abs < 0 ? pred - abs + max : pred - abs) : (pred + abs >= max ? pred + abs - max : pred + abs); + return (uint)pred < (uint)max ? InterViewPicture(refs[pred]) : default; + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Partitions.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Partitions.cs new file mode 100644 index 0000000..8a8d60a --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Partitions.cs @@ -0,0 +1,171 @@ +namespace Febe.Core.Codecs.H264; + +public sealed partial class H264Decoder +{ + // Slice data partitioning (§7.3.2.9, §7.3.2.10, §7.4.2.9): partition A (NAL unit 2) holds the slice header and the + // category 2 syntax elements (macroblock types, prediction, coded_block_pattern, mb_qp_delta), partition B (3) the + // residual of the intra macroblocks (category 3), partition C (4) the residual of the inter ones (category 4). The + // three NAL units come one after the other: A is kept until its B and C have arrived, then the slice is decoded with + // one reader per partition. + + /// A partition A is waiting for its partitions B and C. + private bool partitionPending; + + private byte[] partitionA = []; + private byte[] partitionB = []; + private byte[] partitionC = []; + private NalUnit pendingNal; + private RbspReader? pendingReader; + private SliceHeader? pendingHeader; + private Sps? pendingSps; + private Pps? pendingPps; + private int pendingSliceId; + private RbspReader? pendingB; + private RbspReader? pendingC; + + /// The slice being decoded is partitioned: the residual comes from and . + private bool partitioned; + + /// Partition B of the slice being decoded, null when it is missing. + private RbspReader? intraResidual; + + /// Partition C of the slice being decoded, null when it is missing. + private RbspReader? interResidual; + + /// + /// For the tests: called after the residual (or the I_PCM samples) of a macroblock has been read, with its first and + /// past-the-end bit in the RBSP of the slice, whether the macroblock is intra and whether it is I_PCM. + /// + internal Action? ResidualRead { get; set; } + + /// Partition A (§7.3.2.9): the slice header and slice_id, kept until partitions B and C have arrived. + private void StorePartitionA(NalUnit nal) + { + var copy = Keep(nal, ref partitionA); + var reader = copy.Reader(); + var header = ParseSliceHeader(reader, copy, out var sps, out var pps); + if (pps.Cabac) + { + throw new H264Exception("Partizionamento dei dati con CABAC: combinazione non ammessa."); + } + + var sliceId = reader.ReadUe(Sps.MaxFrameMbs - 1); + if (header.RedundantPicCnt > 0) + { + return; // a redundant picture, skipped with its partitions B and C (no partition is pending for them) + } + + pendingNal = copy; + pendingReader = reader; + pendingHeader = header; + pendingSps = sps; + pendingPps = pps; + pendingSliceId = sliceId; + pendingB = pendingC = null; + partitionPending = true; + } + + /// + /// Partition B or C (§7.3.2.10) of the slice waiting in partition A. One of another slice (its partition A lost), + /// of a redundant picture, a second B or C, or a B after the C (§7.4.1.2.5 puts them in the order A, B, C) is + /// ignored, and never touches the partitions already kept for the waiting slice. + /// + private void StorePartition(NalUnit nal) + { + if (!partitionPending || pendingC is not null || (nal.Type == 3 && pendingB is not null)) + { + return; + } + + // slice_id and redundant_pic_cnt are read from the unit as it came: only a partition of the waiting slice is + // copied, so a stray one cannot overwrite the buffer the reader of an earlier partition still reads. + var probe = nal.Reader(); + var sliceId = probe.ReadUe(Sps.MaxFrameMbs - 1); + var redundant = pendingPps!.RedundantPicCntPresent ? probe.ReadUe(127) : 0; + if (sliceId != pendingSliceId || redundant != 0) + { + return; + } + + var copy = nal.Type == 3 ? Keep(nal, ref partitionB) : Keep(nal, ref partitionC); + var reader = copy.Reader(); + reader.ReadUe(Sps.MaxFrameMbs - 1); + if (pendingPps.RedundantPicCntPresent) + { + reader.ReadUe(127); + } + + if (nal.Type == 3) + { + pendingB = reader; + } + else + { + pendingC = reader; + } + } + + /// Decodes the slice of the partitions received; a missing B or C leaves the residual it carries at zero. + private void DecodePartitionedSlice() + { + partitionPending = false; + partitioned = true; + intraResidual = pendingB; + interResidual = pendingC; + try + { + DecodeParsedSlice(pendingNal, pendingReader!, pendingHeader!, pendingSps!, pendingPps!); + } + finally + { + partitioned = false; + intraResidual = interResidual = null; + pendingB = pendingC = null; + pendingReader = null; + } + } + + /// A copy of the RBSP of a partition, which must outlive the shared buffer of the stream. + private static NalUnit Keep(NalUnit nal, ref byte[] buffer) + { + if (buffer.Length < nal.Length + NalUnits.Padding) + { + buffer = new byte[nal.Length + NalUnits.Padding]; + } + + nal.Rbsp.AsSpan(0, nal.Length + NalUnits.Padding).CopyTo(buffer); + return nal with { Rbsp = buffer }; + } + + /// + /// The reader of the residual of the current macroblock: the slice data, or the partition B (intra) or C (inter) of a + /// partitioned slice — null when that partition is missing. + /// + /// + /// Asked only for a macroblock that has residual. When its partition is missing, the other one can no longer be read + /// from here on: the nC of an inter block counts the coefficients of its intra neighbours, and the nC of an intra + /// block those of its inter neighbours unless constrained_intra_pred makes them count as empty (§9.2.1). + /// + private RbspReader? ResidualReader(bool intra) + { + if (!partitioned) + { + return rd; + } + + var source = intra ? intraResidual : interResidual; + if (source is null) + { + if (intra) + { + interResidual = null; + } + else if (!pps.ConstrainedIntraPred) + { + intraResidual = null; + } + } + + return source; + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs new file mode 100644 index 0000000..f5bba35 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Slice.cs @@ -0,0 +1,2250 @@ +using static Febe.Core.Codecs.H264.Samples; + +namespace Febe.Core.Codecs.H264; + +public sealed partial class H264Decoder +{ + private enum MbKind : byte + { + None, + I4x4, + I8x8, + I16x16, + IPcm, + PSkip, + BSkip, + BDirect, + PInter, + BInter, + + /// The SI macroblock of SI slices: Intra_4x4 prediction, reconstructed in QS (§8.6.2). + SI, + } + + // Shapes of inter macroblocks and sub-macroblocks. + private const int Shape16x16 = 0; + private const int Shape16x8 = 1; + private const int Shape8x16 = 2; + private const int Shape8x8 = 3; + + /// + /// Entries of per macroblock: the 16 luma 4×4 blocks, then 16 for Cb and 16 for Cr (4:2:0 uses 4 of + /// them, 4:2:2 8, 4:4:4 all, as luma). + /// + private const int NzPerMb = 48; + + /// Prediction lists of the two partitions of B_16x8 and B_8x16 (mb_type 4–21): 1 L0, 2 L1, 3 both. + private static readonly byte[] BPartPred = + [ + 1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 3, 1, 3, 2, 3, 2, 3, 3, 1, 3, 1, 3, 2, 3, 2, 3, 3, 3, 3, + ]; + + /// B sub-macroblock types 0–12: prediction lists (0 = direct). + private static readonly byte[] BSubPred = [0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3]; + + /// B sub-macroblock types 0–12: shape (0 8×8, 1 8×4, 2 4×8, 3 4×4). + private static readonly byte[] BSubShape = [0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3]; + + /// + /// The raster position (row × 2 + column) of the chroma DC coefficients of 4:2:2 in parsing order (equation 8-330: + /// c = [c0 c2; c1 c5; c3 c6; c4 c7]). + /// + private static readonly byte[] ChromaDc422Scan = [0, 2, 1, 4, 6, 3, 5, 7]; + + private readonly List<(int Disable, int Alpha, int Beta)> sliceFilters = []; + private readonly RefEntry[][] refList = [[], []]; + private readonly CabacEngine cabac = new(); + + private int widthInMbs; + private int heightInMbs; + private int mbCount; + + // The data of the macroblocks of the colour plane being decoded (see MacroblockState). + private int[] mbSlice = []; + private MbKind[] mbKind = []; + private byte[] mbCbp = []; + + /// QPY of each macroblock for the deblocking filter (0 for I_PCM and lossless macroblocks); negative above 8 bits. + private sbyte[] mbQp = []; + + /// QPC of Cb and Cr of each macroblock (from QPY, before QpBdOffsetC: negative values above 8 bits). + private sbyte[] mbQpC = []; + private bool[] mbT8 = []; + private sbyte[] intraModes = []; + private byte[] chromaModes = []; + private byte[] nz = []; + private byte[] cbfDc = []; + private byte[] mvdAbs = []; + private bool[] subDirect = []; + + /// One per colour plane when the planes of 4:4:4 are coded separately, else one. + private MacroblockState[] planeStates = []; + + // The format of the active sequence (§6.2, §7.4.2.1.1). + private int chromaArrayType = 1; + private int mbWidthC = 8; + private int mbHeightC = 8; + + /// NumC8x8 of §7.4.5: chroma 8×8 blocks of each component (1 in 4:2:0, 2 in 4:2:2; 0 without that chroma). + private int numC8x8 = 1; + + private int bitDepthY = 8; + private int bitDepthC = 8; + private int maxY = 255; + private int maxC = 255; + private int qpBdOffsetY; + private int qpBdOffsetC; + private bool transformBypass; + + /// Samples of two bytes: some component has more than 8 bits. + private bool wide; + + /// separate_colour_plane_flag: each slice codes one colour plane as a monochrome picture. + private bool separatePlanes; + + /// The colour plane the current slice codes (0 unless the planes are separate): its samples are the «luma». + private int colourPlane; + + // Slice state. + private SliceHeader sh = null!; + private Sps sps = null!; + private Pps pps = null!; + private RbspReader rd = null!; + private bool cabacMode; + private int sliceNum; + + /// QPY of the macroblock being decoded (QPY,PRED before its mb_qp_delta): −QpBdOffsetY to 51. + private int qp; + private int lastQpDelta; + private Pps? scalePps; + private int[][] ls4 = []; + private int[][] ls8 = []; + + /// The picture is an MBAFF frame: macroblock pairs, each of two frame or two field macroblocks. + private bool mbaff; + + /// The picture is a field: its macroblocks are on every other row of the frame grid. + private bool fieldPic; + + /// The parity of the field being decoded (0 top, 1 bottom). + private int curParity; + + // Macroblock state: mb is the index on the frame grid (see Picture), mbY its row there. + private int mb; + private int mbX; + private int mbY; + + /// The current macroblock is a field macroblock (of a field picture or a field pair). + private bool mbField; + + /// The current macroblock is lossless: TransformBypassModeFlag (qpprime_y_zero_transform_bypass_flag and QP′Y 0). + private bool bypass; + + private int lumaO; + private int lumaStride; + private int chromaO; + private int chromaStride; + + // Neighbouring macroblocks A (left), B (above), C (above right), D (above left) on the frame grid, −1 when not + // available; in an MBAFF frame A and B are those of the luma locations (−1, 0) and (0, −1), C and D are not used. + private int mbA; + private int mbB; + private int mbC; + private int mbD; + + // MBAFF: the top macroblocks of the pairs to the left, above, above right and above left, −1 when not available. + private int pairA; + private int pairB; + private int pairC; + private int pairD; + + private readonly bool[] blkDone = new bool[16]; + + /// The coefficients of the luma-like planes: Y, and Cb and Cr in 4:4:4 (plane × 256 + block × 16 + position). + private readonly int[] lumaCoef = new int[3 * 256]; + private readonly bool[] lumaHas = new bool[3 * 16]; + + /// The coefficients of 4:2:0 and 4:2:2 chroma: (component × 8 + block) × 16 + raster position. + private readonly int[] chromaCoef = new int[2 * 8 * 16]; + private readonly bool[] chromaHas = new bool[16]; + + /// The chroma DC levels as parsed (component × 8), for the macroblocks reconstructed in QS. + private readonly int[] chromaDcLevels = new int[16]; + + /// The residual being parsed is kept as levels, not scaled: P macroblocks of SP slices and SI macroblocks. + private bool rawLevels; + + /// Per slice of the picture: an SP or SI slice, whose macroblocks the deblocking filter treats as intra (§8.7.2.1). + private readonly List sliceSwitching = []; + + /// Some slice of the picture is an SP or SI slice. + private bool anySwitching; + private readonly int[] levels = new int[64]; + private readonly int[] levels4 = new int[64]; + private readonly int[] subType = new int[4]; + private readonly int[] partPred = new int[4]; + private readonly int[] mvdValue = new int[2 * 16 * 2]; + private int shape; + + /// Planes coded like luma in the current macroblock: 3 in 4:4:4 (Y, Cb, Cr), else 1. + private int LumaLikePlanes => chromaArrayType == 3 ? 3 : 1; + + /// The macroblock data of one colour plane: the whole of it when the planes are not separate. + private sealed class MacroblockState(int mbCount) + { + internal readonly int[] Slice = new int[mbCount]; + internal readonly MbKind[] Kind = new MbKind[mbCount]; + internal readonly byte[] Cbp = new byte[mbCount]; + internal readonly sbyte[] Qp = new sbyte[mbCount]; + internal readonly sbyte[] QpC = new sbyte[mbCount * 2]; + internal readonly bool[] T8 = new bool[mbCount]; + internal readonly sbyte[] IntraModes = new sbyte[mbCount * 16]; + internal readonly byte[] ChromaModes = new byte[mbCount]; + internal readonly byte[] Nz = new byte[mbCount * NzPerMb]; + internal readonly byte[] CbfDc = new byte[mbCount]; + internal readonly byte[] MvdAbs = new byte[2 * mbCount * 16 * 2]; + internal readonly bool[] SubDirect = new bool[mbCount * 4]; + } + + private void AllocateMacroblockState(int width, int height, int planes) + { + widthInMbs = width; + heightInMbs = height; + mbCount = width * height; + planeStates = new MacroblockState[planes]; + for (var i = 0; i < planes; i++) + { + planeStates[i] = new MacroblockState(mbCount); + } + + UsePlaneState(0); + } + + private void UsePlaneState(int k) + { + var s = planeStates[k]; + mbSlice = s.Slice; + mbKind = s.Kind; + mbCbp = s.Cbp; + mbQp = s.Qp; + mbQpC = s.QpC; + mbT8 = s.T8; + intraModes = s.IntraModes; + chromaModes = s.ChromaModes; + nz = s.Nz; + cbfDc = s.CbfDc; + mvdAbs = s.MvdAbs; + subDirect = s.SubDirect; + } + + /// + /// Separate colour planes: the macroblock data of plane , in the decoder and in every picture a + /// slice can refer to (direct prediction reads the motion of the co-located plane). + /// + private void SelectColourPlane(int k) + { + colourPlane = k; + UsePlaneState(Math.Min(k, planeStates.Length - 1)); + cur?.SelectPlane(k); + foreach (var p in dpb) + { + p.SelectPlane(k); + } + } + + /// The format of a sequence that becomes active: chroma geometry, bit depths, lossless coding. + private void ConfigureFormat(Sps s) + { + chromaArrayType = s.ChromaArrayType; + separatePlanes = s.SeparateColourPlane; + mbWidthC = chromaArrayType == 0 ? 0 : 16 / s.SubWidthC; + mbHeightC = chromaArrayType == 0 ? 0 : 16 / s.SubHeightC; + numC8x8 = chromaArrayType is 1 or 2 ? 4 / (s.SubWidthC * s.SubHeightC) : 0; + bitDepthY = s.BitDepthLuma; + + // The colour planes coded separately are monochrome pictures: all three have the luma bit depth. + bitDepthC = separatePlanes ? s.BitDepthLuma : s.BitDepthChroma; + maxY = (1 << bitDepthY) - 1; + maxC = (1 << bitDepthC) - 1; + qpBdOffsetY = s.QpBdOffsetY; + qpBdOffsetC = 6 * (bitDepthC - 8); + transformBypass = s.TransformBypass; + wide = bitDepthY > 8 || (s.ChromaFormatIdc != 0 && bitDepthC > 8); + colourPlane = 0; + } + + private bool IsIntra(int m) => mbKind[m] is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm or MbKind.SI; + + /// + /// A neighbour whose samples intra prediction may use under constrained_intra_pred_flag: an intra macroblock, but not + /// an SI one for a macroblock that is not SI (§8.3.1.2). + /// + private bool IntraUsable(int m) => IsIntra(m) && (mbKind[m] != MbKind.SI || mbKind[mb] == MbKind.SI); + + private bool IsSkip(int m) => mbKind[m] is MbKind.PSkip or MbKind.BSkip; + + /// QPC of a chroma component (0 Cb, 1 Cr) for (§8.5.8, Table 8-15): from −QpBdOffsetC up. + private int ChromaQpFor(int qpY, int comp) + { + var qpi = Math.Clamp(qpY + (comp == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset), -qpBdOffsetC, 51); + return qpi < 0 ? qpi : H264Tables.ChromaQp[qpi]; + } + + private void DecodeSliceData(RbspReader reader, NalUnit nal, SliceHeader header, Sps s, Pps p) + { + _ = nal; + sh = header; + sps = s; + pps = p; + rd = reader; + cabacMode = p.Cabac; + fieldPic = header.FieldPic; + curParity = header.BottomField ? 1 : 0; + mbaff = s.MbAdaptiveFrameField && !header.FieldPic; + sliceNum = sliceCounter++; + sliceFilters.Add((header.DisableDeblocking, header.AlphaOffset, header.BetaOffset)); + sliceSwitching.Add(header.IsSwitching); + anySwitching |= header.IsSwitching; + if (header.IsSwitching && (p.Transform8x8Mode || wide || chromaArrayType != 1)) + { + // SP and SI slices exist only in the Extended profile: 4:2:0, 8 bits, no 8×8 transform. + throw new H264Exception("Slice SP o SI fuori dal profilo Extended (trasformata 8×8, 4:2:2/4:4:4 o più di 8 bit): combinazione non ammessa."); + } + + if (cabacMode && chromaArrayType == 3) + { + // The residual of Cb and Cr of 4:4:4 uses the contexts 460–1023 (block categories 6–13), whose initial + // values (tables 9-24 to 9-33) are not transcribed yet; the separate colour planes use those of luma. + throw new H264Exception("CABAC in 4:4:4 senza piani separati non gestito: mancano i contesti 460–1023."); + } + + qp = p.PicInitQp + header.QpDelta; + if (qp < -qpBdOffsetY || qp > 51) + { + throw new H264Exception("QP della slice non valido."); + } + + lastQpDelta = 0; + if (!ReferenceEquals(scalePps, p) || ls4.Length == 0) + { + var lists = p.ScalingLists ?? s.ScalingLists; + ls4 = ScalingMatrix.LevelScale4x4(lists); + ls8 = ScalingMatrix.LevelScale8x8(lists); + scalePps = p; + } + + if (svcSlice is not null) + { + // A quality refinement predicts from the lists of the layer below, built for the same picture. + if (header.IsIntra) + { + refList[0] = []; + refList[1] = []; + } + } + else if (!header.IsIntra) + { + BuildReferenceLists(header, s); + PrepareWeights(); + } + else + { + refList[0] = []; + refList[1] = []; + } + + if (cabacMode) + { + while (!rd.ByteAligned) + { + rd.Skip(1); // cabac_alignment_one_bit + } + + cabac.InitContexts(header, qp); + cabac.Start(rd); + } + + // Macroblock addresses of the slice: those of the field, or of the pairs (two per pair) in an MBAFF frame; with + // slice groups only those of the group of the first one, in order. + var total = fieldPic ? mbCount / 2 : mbCount; + var addr = header.FirstMb * (mbaff ? 2 : 1); + if (addr >= total) + { + throw new H264Exception("Primo macroblocco fuori dall'immagine."); + } + + PrepareSliceGroups(header, s, p); + + if (svcSlice is { SliceSkip: true }) + { + DecodeSkippedSlice(addr, total); + } + else if (RecordLayers && mbaff) + { + throw new H264Exception("SVC con MBAFF non gestito."); + } + else if (!mbaff) + { + DecodeMacroblocks(addr, total); + } + else if (cabacMode) + { + DecodePairsCabac(addr, total); + } + else + { + DecodePairsCavlc(addr, total); + } + } + + private void DecodeMacroblocks(int addr, int total) + { + var isIntraSlice = sh.IsIntra; + var record = RecordLayers; + var scalableSlice = svcSlice is not null; + while (addr < total) + { + if (!isIntraSlice && !cabacMode) + { + var run = rd.ReadUe(); + if (run > (uint)(total - addr)) + { + throw new H264Exception("mb_skip_run fuori dall'immagine."); + } + + for (var i = 0; i < (int)run; i++) + { + if (addr >= total) + { + throw new H264Exception("mb_skip_run fuori dal gruppo di slice."); + } + + BeginMacroblock(addr); + addr = NextAddress(addr); + if (scalableSlice) + { + DecodeScalableSkip(); + } + else + { + DecodeSkip(); + } + + if (record) + { + RecordLayer(); + } + } + + if ((run > 0 && !rd.MoreRbspData) || addr >= total) + { + break; + } + } + + BeginMacroblock(addr); + addr = NextAddress(addr); + if (!isIntraSlice && cabacMode && ReadMbSkip() != 0) + { + DecodeSkip(); + } + else if (scalableSlice) + { + DecodeScalableMacroblock(); + } + else + { + DecodeMacroblock(); + } + + if (record) + { + RecordLayer(); + } + + var more = cabacMode ? cabac.Terminate() == 0 : rd.MoreRbspData; + if (!more) + { + break; + } + } + } + + /// + /// The macroblock pairs of an MBAFF slice with CAVLC (§7.3.4): mb_field_decoding_flag comes with the top macroblock, + /// or with the bottom one when the top one is skipped — right after the mb_skip_run that skips it, so it is read + /// there, before the skipped top macroblock is predicted. + /// + private void DecodePairsCavlc(int addr, int total) + { + var isIntraSlice = sh.IsIntra; + while (addr < total) + { + if (!isIntraSlice) + { + var run = rd.ReadUe(); + if (run > (uint)(total - addr)) + { + throw new H264Exception("mb_skip_run fuori dall'immagine."); + } + + for (var i = 0; i < (int)run; i++) + { + if (addr >= total) + { + throw new H264Exception("mb_skip_run fuori dal gruppo di slice."); + } + + if ((addr & 1) == 0) + { + SetPairField(addr, InferPairField(addr)); + if (i == run - 1 && rd.MoreRbspData) + { + SetPairField(addr, rd.ReadFlag()); + } + } + + BeginMacroblock(addr); + addr = NextAddress(addr); + DecodeSkip(); + } + + if ((run > 0 && !rd.MoreRbspData) || addr >= total) + { + break; + } + } + + if ((addr & 1) == 0) + { + SetPairField(addr, rd.ReadFlag()); + } + + BeginMacroblock(addr); + addr = NextAddress(addr); + DecodeMacroblock(); + if (!rd.MoreRbspData) + { + break; + } + } + } + + /// + /// The macroblock pairs of an MBAFF slice with CABAC (§7.3.4). When the top macroblock is skipped, the skip flag of + /// the bottom one follows, and then (if that one is not skipped) mb_field_decoding_flag: both are read before the + /// skipped top macroblock is predicted, the first with the inferred flag (§7.4.4). end_of_slice_flag follows the + /// bottom macroblock only. + /// + private void DecodePairsCabac(int addr, int total) + { + var isIntraSlice = sh.IsIntra; + var bottomSkipKnown = false; + var bottomSkip = false; + while (addr < total) + { + var top = (addr & 1) == 0; + bool skip; + if (top) + { + SetPairField(addr, InferPairField(addr)); + PlaceMacroblock(addr); + skip = !isIntraSlice && ReadMbSkip() != 0; + if (skip) + { + mbKind[mb] = sh.IsB ? MbKind.BSkip : MbKind.PSkip; + PlaceMacroblock(addr + 1); + bottomSkip = ReadMbSkip() != 0; + bottomSkipKnown = true; + if (!bottomSkip) + { + SetPairField(addr, ReadFieldFlag()); + } + } + else + { + SetPairField(addr, ReadFieldFlag()); + } + } + else + { + PlaceMacroblock(addr); + skip = bottomSkipKnown ? bottomSkip : !isIntraSlice && ReadMbSkip() != 0; + bottomSkipKnown = false; + } + + BeginMacroblock(addr); + addr = NextAddress(addr); + if (skip) + { + DecodeSkip(); + } + else + { + DecodeMacroblock(); + } + + if (!top && cabac.Terminate() != 0) + { + break; + } + } + } + + /// The flag of a pair whose mb_field_decoding_flag is not (yet) read (§7.4.4): the left pair's, else the one above. + private bool InferPairField(int addr) + { + var pair = addr >> 1; + int x = pair % widthInMbs, top = (2 * (pair / widthInMbs) * widthInMbs) + x; + if (x > 0 && mbSlice[top - 1] == sliceNum) + { + return cur!.MbField[top - 1]; + } + + return top >= 2 * widthInMbs && mbSlice[top - (2 * widthInMbs)] == sliceNum && cur!.MbField[top - (2 * widthInMbs)]; + } + + private void SetPairField(int addr, bool field) + { + var pair = addr >> 1; + var top = (2 * (pair / widthInMbs) * widthInMbs) + (pair % widthInMbs); + cur!.MbField[top] = field; + cur.MbField[top + widthInMbs] = field; + } + + private bool ReadFieldFlag() + { + if (!cabacMode) + { + return rd.ReadFlag(); + } + + var inc = (pairA >= 0 && cur!.MbField[pairA] ? 1 : 0) + (pairB >= 0 && cur!.MbField[pairB] ? 1 : 0); + return cabac.Decision(70 + inc) != 0; + } + + /// + /// Position of the macroblock of address in the slice: its place on the frame grid, its + /// samples, its neighbours (§6.4.9, §6.4.10). In an MBAFF frame the flag of its pair must be set. + /// + private void PlaceMacroblock(int addr) + { + var w = widthInMbs; + if (mbaff) + { + var pair = addr >> 1; + mbX = pair % w; + var pairRow = 2 * (pair / w); + mbY = pairRow + (addr & 1); + mb = (mbY * w) + mbX; + mbSlice[mb] = sliceNum; + var top = (pairRow * w) + mbX; + mbField = cur!.MbField[top]; + pairA = mbX > 0 && mbSlice[top - 1] == sliceNum ? top - 1 : -1; + var above = top - (2 * w); + var hasAbove = pairRow > 0; + pairB = hasAbove && mbSlice[above] == sliceNum ? above : -1; + pairC = hasAbove && mbX < w - 1 && mbSlice[above + 1] == sliceNum ? above + 1 : -1; + pairD = hasAbove && mbX > 0 && mbSlice[above - 1] == sliceNum ? above - 1 : -1; + mbC = mbD = -1; + mbA = Locate(-1, 0, 16, out _); + mbB = Locate(0, -1, 16, out _); + } + else + { + var rowStep = fieldPic ? 2 : 1; + mbX = addr % w; + var row = addr / w; + mbY = (row * rowStep) + (fieldPic ? curParity : 0); + mb = (mbY * w) + mbX; + mbField = fieldPic; + mbSlice[mb] = sliceNum; + var up = rowStep * w; + mbA = mbX > 0 && mbSlice[mb - 1] == sliceNum ? mb - 1 : -1; + mbB = row > 0 && mbSlice[mb - up] == sliceNum ? mb - up : -1; + mbC = row > 0 && mbX < w - 1 && mbSlice[mb - up + 1] == sliceNum ? mb - up + 1 : -1; + mbD = row > 0 && mbX > 0 && mbSlice[mb - up - 1] == sliceNum ? mb - up - 1 : -1; + } + + var width = cur!.Width; + var cwidth = cur.ChromaWidth; + if (mbField) + { + int pairY = mbY >> 1, parity = mbY & 1; + lumaO = (((pairY * 32) + parity) * width) + (mbX * 16); + lumaStride = 2 * width; + chromaO = (((pairY * 2 * mbHeightC) + parity) * cwidth) + (mbX * mbWidthC); + chromaStride = 2 * cwidth; + } + else + { + lumaO = (mbY * 16 * width) + (mbX * 16); + lumaStride = width; + chromaO = (mbY * mbHeightC * cwidth) + (mbX * mbWidthC); + chromaStride = cwidth; + } + } + + /// + /// The macroblock covering the luma ( 16) or chroma (MbHeightC) location (xN, yN) relative to + /// the current macroblock (§6.4.12), −1 when not available; is its row there (negative counts + /// from the bottom). In an MBAFF frame, Table 6-4. The chroma blocks are 8 wide unless they are of 4:4:4, which uses + /// the luma locations. + /// + private int Locate(int xN, int yN, int maxH, out int yM) + { + yM = yN; + var maxW = maxH == 16 ? 16 : 8; + if (yN >= maxH || (xN >= maxW && yN >= 0)) + { + return -1; + } + + if (!mbaff) + { + if (yN < 0) + { + return xN < 0 ? mbD : xN < maxW ? mbB : mbC; + } + + return xN < 0 ? mbA : mb; + } + + if (xN >= 0 && yN >= 0) + { + return mb; + } + + var w = widthInMbs; + var bottom = (mbY & 1) != 0; + var field = cur!.MbField; + if (yN < 0) + { + var x = xN < 0 ? (mbField || !bottom ? pairD : pairA) : xN < maxW ? pairB : pairC; + if (!mbField) + { + if (!bottom) + { + return x < 0 ? -1 : x + w; + } + + if (xN >= maxW) + { + return -1; + } + + if (xN >= 0) + { + return mb - w; + } + + // The left pair, from the bottom macroblock of a frame pair. + if (x < 0) + { + return -1; + } + + if (!field[x]) + { + return x; + } + + yM = (yN + maxH) >> 1; + return x + w; + } + + if (x < 0) + { + return -1; + } + + if (bottom || field[x]) + { + return bottom ? x + w : x; + } + + yM = 2 * yN; + return x + w; + } + + // xN < 0, 0 <= yN < maxH: the pair to the left. + return pairA < 0 ? -1 : LeftOfPair(pairA, w, field[pairA], mbField, bottom, yN, maxH, out yM); + } + + /// + /// MBAFF: the macroblock of the pair to the left (whose top macroblock is ) holding row + /// of the current macroblock, and its row there (Table 6-4, xN < 0). + /// + private static int LeftOfPair(int leftTop, int w, bool leftField, bool curField, bool bottom, int yN, int maxH, out int yM) + { + yM = yN; + if (!curField) + { + if (!leftField) + { + return bottom ? leftTop + w : leftTop; + } + + yM = (bottom ? yN + maxH : yN) >> 1; + return leftTop + ((yN & 1) * w); + } + + if (leftField) + { + return bottom ? leftTop + w : leftTop; + } + + var frameRow = (yN << 1) + (bottom ? 1 : 0); + if (frameRow < maxH) + { + yM = frameRow; + return leftTop; + } + + yM = frameRow - maxH; + return leftTop + w; + } + + /// Starts the macroblock of address : its position, and its data cleared. + private void BeginMacroblock(int addr) + { + PlaceMacroblock(addr); + mbResidualSet = false; + mbRefinedIntra = false; + Array.Clear(blkDone); + Array.Clear(nz, mb * NzPerMb, NzPerMb); + cbfDc[mb] = 0; + mbCbp[mb] = 0; + mbT8[mb] = false; + chromaModes[mb] = 0; + bypass = false; + intraModes.AsSpan(mb * 16, 16).Fill(2); + var picture = cur!; + for (var list = 0; list < 2; list++) + { + mvdAbs.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); + picture.Mv.AsSpan(((list * mbCount) + mb) * 32, 32).Clear(); + picture.RefIdx.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1); + picture.RefPic.AsSpan(((list * mbCount) + mb) * 4, 4).Clear(); + picture.RefPar.AsSpan(((list * mbCount) + mb) * 4, 4).Fill(-1); + } + + subDirect.AsSpan(mb * 4, 4).Clear(); + picture.MbIntra[mb] = false; + picture.MbField[mb] = mbField; + } + + private void DecodeMacroblock() + { + var type = ReadMbType(); + int intraType; + if (sh.Type == SliceType.I) + { + intraType = type; + } + else if (sh.Type == SliceType.SI) + { + if (type == 0) + { + DecodeSi(); + return; + } + + intraType = type - 1; + } + else if (sh.IsP) + { + intraType = type >= 5 ? type - 5 : -1; + } + else + { + intraType = type >= 23 ? type - 23 : -1; + } + + if (intraType > 25) + { + throw new H264Exception("mb_type non valido."); + } + + if (intraType >= 0) + { + DecodeIntra(intraType); + } + else + { + DecodeInter(type); + } + } + + private void DecodeSkip() + { + mbKind[mb] = sh.IsB ? MbKind.BSkip : MbKind.PSkip; + StoreQp(); + lastQpDelta = 0; + if (sh.IsB) + { + subDirect.AsSpan(mb * 4, 4).Fill(true); + PredictDirect(0, 4); + MotionCompensateDirect(0, 4); + } + else + { + PredictPSkip(); + MotionCompensate(0, 0, 16, 16); + if (sh.Type == SliceType.SP) + { + // Even without residual the prediction of an SP slice is quantised in QS (§8.6.1). + ClearResidual(); + ReconstructSwitchingInter(); + } + } + } + + /// + /// The QP of the macroblock for the deblocking filter, from the current QPY: 0 for a lossless macroblock as for + /// I_PCM (§8.7.2.2), and QPC of both chroma components from that value. + /// + private void StoreQp() + { + var filterQp = transformBypass && qp + qpBdOffsetY == 0 ? 0 : qp; + mbQp[mb] = (sbyte)filterQp; + mbQpC[mb * 2] = (sbyte)ChromaQpFor(filterQp, 0); + mbQpC[(mb * 2) + 1] = (sbyte)ChromaQpFor(filterQp, 1); + } + + private void DecodeIntra(int type) + { + cur!.MbIntra[mb] = true; + if (type == 25) + { + DecodePcm(); + return; + } + + var cbp = 0; + int predMode16 = 0; + if (type == 0) + { + var t8 = pps.Transform8x8Mode && ReadTransform8x8(); + mbT8[mb] = t8; + mbKind[mb] = t8 ? MbKind.I8x8 : MbKind.I4x4; + ReadIntraModes(t8); + } + else + { + mbKind[mb] = MbKind.I16x16; + predMode16 = (type - 1) % 4; + lastPred16 = predMode16; + cbp = ((((type - 1) / 4) % 3) << 4) | (type >= 13 ? 15 : 0); + } + + if (chromaArrayType is 1 or 2) + { + chromaModes[mb] = (byte)ReadChromaPredMode(); + if (chromaModes[mb] > 3) + { + throw new H264Exception("Modo di predizione della crominanza non valido."); + } + } + + if (type == 0) + { + cbp = ReadCbp(intra: true); + } + + mbCbp[mb] = (byte)cbp; + var intra16 = type != 0; + ClearResidual(); + if (cbp != 0 || intra16) + { + ApplyQpDelta(ReadQpDelta()); + ReadResidual(intra16, cbp, intra: true); + } + else + { + lastQpDelta = 0; + } + + StoreQp(); + if (wide) + { + ReconstructIntra(predMode16); + } + else + { + ReconstructIntra(predMode16); + } + } + + /// The SI macroblock (mb_type 0 of an SI slice): Intra_4x4 prediction, levels in QS (§7.4.5, §8.6.2). + private void DecodeSi() + { + cur!.MbIntra[mb] = true; + mbKind[mb] = MbKind.SI; + ReadIntraModes(false); + chromaModes[mb] = (byte)ReadChromaPredMode(); + if (chromaModes[mb] > 3) + { + throw new H264Exception("Modo di predizione della crominanza non valido."); + } + + var cbp = ReadCbp(intra: true); + mbCbp[mb] = (byte)cbp; + ClearResidual(); + if (cbp != 0) + { + ApplyQpDelta(ReadQpDelta()); + rawLevels = true; + ReadResidual(false, cbp, intra: true); + rawLevels = false; + } + else + { + lastQpDelta = 0; + } + + StoreQp(); + ReconstructIntra(0); + } + + /// mb_qp_delta (§7.4.5): QPY wraps within −QpBdOffsetY to 51. + private void ApplyQpDelta(int delta) + { + if (delta < -(26 + (qpBdOffsetY / 2)) || delta > 25 + (qpBdOffsetY / 2)) + { + throw new H264Exception("mb_qp_delta non valido."); + } + + lastQpDelta = delta; + qp = ((qp + delta + 52 + (2 * qpBdOffsetY)) % (52 + qpBdOffsetY)) - qpBdOffsetY; + bypass = transformBypass && qp + qpBdOffsetY == 0; + } + + private void ReadIntraModes(bool t8) + { + var count = t8 ? 4 : 16; + for (var i = 0; i < count; i++) + { + int raster, bx, by; + if (t8) + { + bx = (i & 1) * 2; + by = (i >> 1) * 2; + raster = (by * 4) + bx; + } + else + { + raster = H264Tables.BlockToRaster[i]; + bx = raster & 3; + by = raster >> 2; + } + + var predicted = PredictedIntraMode(bx, by); + var (prevFlag, rem) = ReadIntraPredMode(); + var mode = prevFlag ? predicted : rem < predicted ? rem : rem + 1; + if (t8) + { + intraModes[(mb * 16) + raster] = intraModes[(mb * 16) + raster + 1] = + intraModes[(mb * 16) + raster + 4] = intraModes[(mb * 16) + raster + 5] = (sbyte)mode; + } + else + { + intraModes[(mb * 16) + raster] = (sbyte)mode; + } + } + } + + /// predIntra4x4PredMode / predIntra8x8PredMode of the block at (bx, by) in 4×4 units (§8.3.1.1). + private int PredictedIntraMode(int bx, int by) + { + int modeA, modeB; + if (bx > 0) + { + modeA = intraModes[(mb * 16) + (by * 4) + bx - 1]; + } + else + { + var a = Locate(-1, by * 4, 16, out var yM); + if (a < 0 || (pps.ConstrainedIntraPred && !IsIntra(a))) + { + return 2; + } + + modeA = mbKind[a] is MbKind.I4x4 or MbKind.I8x8 or MbKind.SI ? intraModes[(a * 16) + (((yM & 15) >> 2) * 4) + 3] : 2; + } + + if (by > 0) + { + modeB = intraModes[(mb * 16) + ((by - 1) * 4) + bx]; + } + else + { + var b = Locate(bx * 4, -1, 16, out _); + if (b < 0 || (pps.ConstrainedIntraPred && !IsIntra(b))) + { + return 2; + } + + modeB = mbKind[b] is MbKind.I4x4 or MbKind.I8x8 or MbKind.SI ? intraModes[(b * 16) + 12 + bx] : 2; + } + + return Math.Min(modeA, modeB); + } + + private void DecodePcm() + { + mbKind[mb] = MbKind.IPcm; + if (wide) + { + DecodePcm(); + } + else + { + DecodePcm(); + } + + nz.AsSpan(mb * NzPerMb, NzPerMb).Fill(16); + mbCbp[mb] = 0x2F; + mbQp[mb] = 0; // the deblocking filter uses qP = 0 for I_PCM; the running QP is unchanged + mbQpC[mb * 2] = (sbyte)ChromaQpFor(0, 0); + mbQpC[(mb * 2) + 1] = (sbyte)ChromaQpFor(0, 1); + lastQpDelta = 0; + intraModes.AsSpan(mb * 16, 16).Fill(2); + if (cabacMode) + { + cabac.Start(rd); + } + } + + /// The samples of an I_PCM macroblock (§7.3.5): BitDepth bits each, luma then (if any) Cb and Cr. + private void DecodePcm() + where T : unmanaged + { + // The samples are category 3: in partition B of a partitioned slice (the middle value when it is missing). + var main = rd; + var source = ResidualReader(intra: true); + var picture = cur!; + var luma = Plane(picture.Plane(colourPlane)); + var cb = Plane(picture.Cb); + var cr = Plane(picture.Cr); + if (source is not null) + { + rd = source; + var start = rd.Position; + + // With CABAC the arithmetic decoder has read exactly up to the end of its flush (§9.3.1.2). + while (!rd.ByteAligned) + { + rd.Skip(1); // pcm_alignment_zero_bit + } + + for (var y = 0; y < 16; y++) + { + for (var x = 0; x < 16; x++) + { + luma[lumaO + (y * lumaStride) + x] = Make((int)rd.Read(bitDepthY)); + } + } + + if (chromaArrayType != 0) + { + for (var c = 0; c < 2; c++) + { + var plane = c == 0 ? cb : cr; + for (var y = 0; y < mbHeightC; y++) + { + for (var x = 0; x < mbWidthC; x++) + { + plane[chromaO + (y * chromaStride) + x] = Make((int)rd.Read(bitDepthC)); + } + } + } + } + + if (rd.BitsLeft < 0) + { + throw new H264Exception("Campioni I_PCM troncati."); + } + + ResidualRead?.Invoke(start, rd.Position, true, true); + rd = main; + return; + } + + for (var y = 0; y < 16; y++) + { + luma.Slice(lumaO + (y * lumaStride), 16).Fill(Make(1 << (bitDepthY - 1))); + } + + for (var y = 0; y < mbHeightC; y++) + { + cb.Slice(chromaO + (y * chromaStride), mbWidthC).Fill(Make(1 << (bitDepthC - 1))); + cr.Slice(chromaO + (y * chromaStride), mbWidthC).Fill(Make(1 << (bitDepthC - 1))); + } + } + + private void DecodeInter(int type) + { + var isB = sh.IsB; + var direct16 = isB && type == 0; + mbKind[mb] = direct16 ? MbKind.BDirect : isB ? MbKind.BInter : MbKind.PInter; + var noSubLessThan8x8 = true; + Array.Clear(mvdValue); + + if (direct16) + { + shape = Shape16x16; + subDirect.AsSpan(mb * 4, 4).Fill(true); + } + else if ((!isB && type >= 3) || (isB && type == 22)) + { + shape = Shape8x8; + for (var i = 0; i < 4; i++) + { + subType[i] = ReadSubMbType(); + if (subType[i] > (isB ? 12 : 3)) + { + throw new H264Exception("sub_mb_type non valido."); + } + + if (isB && subType[i] == 0) + { + subDirect[(mb * 4) + i] = true; + if (!sps.Direct8x8Inference) + { + noSubLessThan8x8 = false; + } + } + else if (isB ? BSubShape[subType[i]] != 0 : subType[i] != 0) + { + noSubLessThan8x8 = false; + } + + partPred[i] = isB ? BSubPred[subType[i]] : 1; + } + + if (svcOwnMb) + { + ReadMotionPredictionFlags(4, subPartitions: true); + } + + var ref0 = !isB && type == 4; + for (var list = 0; list < 2; list++) + { + var active = RefIdxRange(list); + for (var i = 0; i < 4; i++) + { + if ((partPred[i] & (1 << list)) == 0) + { + continue; + } + + var refIdx = MotionFromBase(list, i) ? BaseRefIdx(list, i) + : active > 1 && !ref0 ? ReadRefIdx(list, (i & 1) * 8, (i >> 1) * 8, active) : 0; + SetRefIdx(list, i, refIdx); + } + } + + for (var list = 0; list < 2; list++) + { + for (var i = 0; i < 4; i++) + { + if ((partPred[i] & (1 << list)) == 0) + { + continue; + } + + var subShape = isB ? BSubShape[subType[i]] : subType[i]; + var count = subShape == 0 ? 1 : subShape == 3 ? 4 : 2; + for (var j = 0; j < count; j++) + { + SubPartition(i, subShape, j, out var px, out var py, out var w, out var h); + var dx = ReadMvd(list, 0, px, py); + var dy = ReadMvd(list, 1, px, py); + StoreMvd(list, px, py, w, h, dx, dy); + } + } + } + } + else + { + int count; + if (!isB) + { + shape = type; + partPred[0] = partPred[1] = 1; + } + else if (type <= 3) + { + shape = Shape16x16; + partPred[0] = type; + } + else + { + shape = (type & 1) == 0 ? Shape16x8 : Shape8x16; + partPred[0] = BPartPred[(type - 4) * 2]; + partPred[1] = BPartPred[((type - 4) * 2) + 1]; + } + + count = shape == Shape16x16 ? 1 : 2; + if (svcOwnMb) + { + ReadMotionPredictionFlags(count, subPartitions: false); + } + + for (var list = 0; list < 2; list++) + { + var active = RefIdxRange(list); + for (var part = 0; part < count; part++) + { + if ((partPred[part] & (1 << list)) == 0) + { + continue; + } + + Partition(part, out var px, out var py, out _, out _); + var b8 = ((py >> 3) * 2) + (px >> 3); + var refIdx = MotionFromBase(list, b8) ? BaseRefIdx(list, b8) : active > 1 ? ReadRefIdx(list, px, py, active) : 0; + SetPartitionRefIdx(list, part, refIdx); + } + } + + for (var list = 0; list < 2; list++) + { + for (var part = 0; part < count; part++) + { + if ((partPred[part] & (1 << list)) == 0) + { + continue; + } + + Partition(part, out var px, out var py, out var w, out var h); + var dx = ReadMvd(list, 0, px, py); + var dy = ReadMvd(list, 1, px, py); + StoreMvd(list, px, py, w, h, dx, dy); + } + } + } + + var residualPrediction = svcOwnMb && ReadResidualPredictionFlag(); + var cbp = ReadCbp(intra: false); + mbCbp[mb] = (byte)cbp; + if ((cbp & 15) != 0 && pps.Transform8x8Mode && noSubLessThan8x8 && (!direct16 || sps.Direct8x8Inference)) + { + mbT8[mb] = ReadTransform8x8(); + } + + ClearResidual(); + var switching = sh.Type == SliceType.SP; + if (cbp != 0) + { + ApplyQpDelta(ReadQpDelta()); + rawLevels = switching; + ReadResidual(false, cbp, intra: false); + rawLevels = false; + } + else + { + lastQpDelta = 0; + } + + StoreQp(); + if (residualPrediction) + { + AddBaseCoefficients(); + } + + // Motion vectors, partition by partition in decoding order, then the prediction. + if (direct16) + { + PredictDirect(0, 4); + MotionCompensateDirect(0, 4); + } + else if (shape == Shape8x8) + { + for (var i = 0; i < 4; i++) + { + if (subDirect[(mb * 4) + i]) + { + PredictDirect(i, i + 1); + continue; + } + + var subShape = isB ? BSubShape[subType[i]] : subType[i]; + var count = subShape == 0 ? 1 : subShape == 3 ? 4 : 2; + for (var j = 0; j < count; j++) + { + SubPartition(i, subShape, j, out var px, out var py, out var w, out var h); + for (var list = 0; list < 2; list++) + { + if ((partPred[i] & (1 << list)) != 0) + { + DeriveMv(list, px, py, w, h, Shape16x16); + } + } + + MarkDone(px, py, w, h); + } + } + + for (var i = 0; i < 4; i++) + { + if (subDirect[(mb * 4) + i]) + { + MotionCompensateDirect(i, i + 1); + continue; + } + + var subShape = isB ? BSubShape[subType[i]] : subType[i]; + var count = subShape == 0 ? 1 : subShape == 3 ? 4 : 2; + for (var j = 0; j < count; j++) + { + SubPartition(i, subShape, j, out var px, out var py, out var w, out var h); + MotionCompensate(px, py, w, h); + } + } + } + else + { + var count = shape == Shape16x16 ? 1 : 2; + for (var part = 0; part < count; part++) + { + Partition(part, out var px, out var py, out var w, out var h); + var directional = shape == Shape16x8 ? 1 + part : shape == Shape8x16 ? 3 + part : 0; + for (var list = 0; list < 2; list++) + { + if ((partPred[part] & (1 << list)) != 0) + { + DeriveMv(list, px, py, w, h, directional); + } + } + + MarkDone(px, py, w, h); + } + + for (var part = 0; part < count; part++) + { + Partition(part, out var px, out var py, out var w, out var h); + MotionCompensate(px, py, w, h); + } + } + + if (switching) + { + ReconstructSwitchingInter(); + } + else if (wide) + { + AddInterResidual(); + } + else + { + AddInterResidual(); + } + } + + private void Partition(int part, out int px, out int py, out int w, out int h) + { + switch (shape) + { + case Shape16x16: + (px, py, w, h) = (0, 0, 16, 16); + break; + case Shape16x8: + (px, py, w, h) = (0, part * 8, 16, 8); + break; + default: + (px, py, w, h) = (part * 8, 0, 8, 16); + break; + } + } + + private static void SubPartition(int sub, int subShape, int j, out int px, out int py, out int w, out int h) + { + int ox = (sub & 1) * 8, oy = (sub >> 1) * 8; + switch (subShape) + { + case 0: + (px, py, w, h) = (ox, oy, 8, 8); + break; + case 1: + (px, py, w, h) = (ox, oy + (j * 4), 8, 4); + break; + case 2: + (px, py, w, h) = (ox + (j * 4), oy, 4, 8); + break; + default: + (px, py, w, h) = (ox + ((j & 1) * 4), oy + ((j >> 1) * 4), 4, 4); + break; + } + } + + /// + /// The number of reference indices of a list for the current macroblock: twice the active ones for a field + /// macroblock of an MBAFF frame, which refers to fields (§8.4.2.1). + /// + private int RefIdxRange(int list) + { + var active = list == 0 ? sh.NumRefIdxActiveL0 : sh.NumRefIdxActiveL1; + return mbaff && mbField ? 2 * active : active; + } + + private void SetRefIdx(int list, int b8, int refIdx) + { + if (refIdx >= RefIdxRange(list)) + { + throw new H264Exception("ref_idx fuori dalla lista."); + } + + var index = (((list * mbCount) + mb) * 4) + b8; + var entry = Reference(list, refIdx); + cur!.RefIdx[index] = (sbyte)refIdx; + cur.RefPic[index] = entry.Pic; + cur.RefPar[index] = (sbyte)entry.Parity; + } + + private void SetPartitionRefIdx(int list, int part, int refIdx) + { + switch (shape) + { + case Shape16x16: + for (var b = 0; b < 4; b++) + { + SetRefIdx(list, b, refIdx); + } + + break; + case Shape16x8: + SetRefIdx(list, part * 2, refIdx); + SetRefIdx(list, (part * 2) + 1, refIdx); + break; + default: + SetRefIdx(list, part, refIdx); + SetRefIdx(list, part + 2, refIdx); + break; + } + } + + private void StoreMvd(int list, int px, int py, int w, int h, int dx, int dy) + { + var ax = (byte)Math.Min(Math.Abs(dx), 127); + var ay = (byte)Math.Min(Math.Abs(dy), 127); + for (var y = py; y < py + h; y += 4) + { + for (var x = px; x < px + w; x += 4) + { + var b = ((y >> 2) * 4) + (x >> 2); + var i = ((((list * mbCount) + mb) * 16) + b) * 2; + mvdAbs[i] = ax; + mvdAbs[i + 1] = ay; + mvdValue[(((list * 16) + b) * 2)] = dx; + mvdValue[(((list * 16) + b) * 2) + 1] = dy; + } + } + } + + private void MarkDone(int px, int py, int w, int h) + { + for (var y = py; y < py + h; y += 4) + { + for (var x = px; x < px + w; x += 4) + { + blkDone[((y >> 2) * 4) + (x >> 2)] = true; + } + } + } + + private void ClearResidual() + { + mbResidualSet = true; + Array.Clear(lumaCoef, 0, 256 * LumaLikePlanes); + Array.Clear(lumaHas); + if (numC8x8 != 0) + { + Array.Clear(chromaCoef); + Array.Clear(chromaHas); + Array.Clear(chromaDcLevels); + } + } + + /// + /// The residual of the macroblock, from the slice data or from its partition (§7.3.2.10): a missing partition leaves + /// it at zero. + /// + private void ReadResidual(bool intra16, int cbp, bool intra) + { + var source = ResidualReader(intra); + if (source is null) + { + return; + } + + var main = rd; + rd = source; + var start = rd.Position; + ParseResidual(intra16, cbp, intra); + ResidualRead?.Invoke(start, rd.Position, intra, false); + rd = main; + } + + /// + /// residual() of §7.3.5.3, with the scaling of §8.5 applied as the levels are read: luma, then the chroma of 4:2:0 and + /// 4:2:2, or the Cb and Cr planes of 4:4:4 coded like luma. + /// + private void ParseResidual(bool intra16, int cbp, bool intra) + { + ParseLumaLike(0, intra16, cbp, intra); + if (numC8x8 != 0) + { + ParseChroma(cbp >> 4, intra); + } + else if (chromaArrayType == 3) + { + ParseLumaLike(1, intra16, cbp, intra); + ParseLumaLike(2, intra16, cbp, intra); + } + } + + /// + /// residual_luma() of one plane (0 Y; 1 Cb and 2 Cr of 4:4:4, with QP′C and their own scaling lists): the + /// Intra_16x16 DC, then each coded 8×8 block, as 8×8 or four 4×4 blocks. + /// + private void ParseLumaLike(int plane, bool intra16, int cbp, bool intra) + { + var t8 = mbT8[mb]; + int qP; + int[] scale4, scale8; + if (plane == 0) + { + // A colour plane coded separately has QP′Y and the scaling lists of its component (iYCbCr, §8.5.9). + qP = qp + qpBdOffsetY; + scale4 = ls4[(intra ? 0 : 3) + colourPlane]; + scale8 = ls8[(colourPlane * 2) + (intra ? 0 : 1)]; + } + else + { + qP = ChromaQpFor(qp, plane - 1) + qpBdOffsetC; + scale4 = ls4[(intra ? 1 : 4) + plane - 1]; + scale8 = ls8[(plane * 2) + (intra ? 0 : 1)]; + } + + var qpDiv = qP / 6; + var qpMod = qP % 6; + var coef = lumaCoef.AsSpan(plane * 256, 256); + var has = lumaHas.AsSpan(plane * 16, 16); + var nzBase = (mb * NzPerMb) + (plane * 16); + var raw = rawLevels || bypass; + + // Field macroblocks are scanned in field order (§8.5.6). + var scan4 = mbField ? H264Tables.FieldScan4x4 : H264Tables.ZigZag4x4; + + if (intra16) + { + var count = ReadBlock(0, 0, plane, levels, 16); + Span c = stackalloc int[16]; + c.Clear(); + for (var k = 0; k < 16; k++) + { + c[scan4[k]] = levels[k]; + } + + if (count > 0) + { + // Lossless: the DC levels are the DC residuals of the blocks (§8.5.10); else the Hadamard transform. + if (!bypass) + { + Transform.Hadamard4x4(c); + } + + var ls = scale4[qpMod * 16]; + for (var i = 0; i < 16; i++) + { + var v = bypass ? c[i] : qP >= 36 ? (c[i] * ls) << (qpDiv - 6) : ((c[i] * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); + coef[i * 16] = v; + if (v != 0) + { + has[i] = true; + } + } + } + } + + for (var b8 = 0; b8 < 4; b8++) + { + var coded = ((cbp >> b8) & 1) != 0; + if (t8 && cabacMode) + { + if (!coded) + { + continue; + } + + ReadBlock(5, b8, plane, levels, 64); + DequantizeInto8x8(coef, has, b8, levels, scale8, qP); + var r0 = ((b8 >> 1) * 8) + ((b8 & 1) * 2); + nz[nzBase + r0] = nz[nzBase + r0 + 1] = nz[nzBase + r0 + 4] = nz[nzBase + r0 + 5] = 1; + continue; + } + + if (t8) + { + Array.Clear(levels4); + } + + for (var b4 = 0; b4 < 4; b4++) + { + var blkIdx = (b8 * 4) + b4; + var raster = H264Tables.BlockToRaster[blkIdx]; + if (!coded) + { + continue; + } + + if (intra16) + { + var count = ReadBlock(1, raster, plane, levels, 15); + nz[nzBase + raster] = (byte)count; + for (var k = 0; k < 15; k++) + { + var level = levels[k]; + if (level != 0) + { + var pos = scan4[k + 1]; + coef[(raster * 16) + pos] = raw ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); + has[raster] = true; + } + } + } + else + { + var count = ReadBlock(2, raster, plane, levels, 16); + nz[nzBase + raster] = (byte)count; + if (t8) + { + for (var k = 0; k < 16; k++) + { + levels4[(4 * k) + b4] = levels[k]; + } + + continue; + } + + for (var k = 0; k < 16; k++) + { + var level = levels[k]; + if (level != 0) + { + var pos = scan4[k]; + coef[(raster * 16) + pos] = raw ? level : Scale4(level, scale4[(qpMod * 16) + pos], qpDiv); + has[raster] = true; + } + } + } + } + + if (t8 && coded) + { + DequantizeInto8x8(coef, has, b8, levels4, scale8, qP); + } + } + } + + /// + /// The chroma residual of 4:2:0 and 4:2:2 (§7.3.5.3): the DC of each component (4 or 8 coefficients, through the 2×2 + /// or 2×4 transform), then the AC of each 4×4 block (blocks in raster order, two per row). + /// + private void ParseChroma(int chromaCbp, bool intra) + { + var blocks = 4 * numC8x8; + var scan4 = mbField ? H264Tables.FieldScan4x4 : H264Tables.ZigZag4x4; + if (chromaCbp != 0) + { + Span dc = stackalloc int[8]; + for (var c = 0; c < 2; c++) + { + var count = ReadBlock(3, 0, c, levels, blocks); + if (count == 0) + { + continue; + } + + if (rawLevels) + { + levels.AsSpan(0, 4).CopyTo(chromaDcLevels.AsSpan(c * 8, 4)); + continue; + } + + var qpc = ChromaQpFor(qp, c) + qpBdOffsetC; + var ls4c = ls4[(intra ? 1 : 4) + c]; + if (blocks == 4) + { + int c0 = levels[0], c1 = levels[1], c2 = levels[2], c3 = levels[3]; + if (bypass) + { + (dc[0], dc[1], dc[2], dc[3]) = (c0, c1, c2, c3); + } + else + { + var ls = ls4c[(qpc % 6) * 16]; + dc[0] = (((c0 + c1 + c2 + c3) * ls) << (qpc / 6)) >> 5; + dc[1] = (((c0 - c1 + c2 - c3) * ls) << (qpc / 6)) >> 5; + dc[2] = (((c0 + c1 - c2 - c3) * ls) << (qpc / 6)) >> 5; + dc[3] = (((c0 - c1 - c2 + c3) * ls) << (qpc / 6)) >> 5; + } + } + else + { + for (var k = 0; k < 8; k++) + { + dc[ChromaDc422Scan[k]] = levels[k]; + } + + if (!bypass) + { + // §8.5.11.2: the DC of 4:2:2 is scaled with qP,DC = QP′C + 3. + Transform.ChromaDc422(dc); + var qpDc = qpc + 3; + var ls = ls4c[(qpDc % 6) * 16]; + for (var b = 0; b < 8; b++) + { + dc[b] = qpDc >= 36 ? (dc[b] * ls) << ((qpDc / 6) - 6) : ((dc[b] * ls) + (1 << (5 - (qpDc / 6)))) >> (6 - (qpDc / 6)); + } + } + } + + for (var b = 0; b < blocks; b++) + { + chromaCoef[((c * 8) + b) * 16] = dc[b]; + if (dc[b] != 0) + { + chromaHas[(c * 8) + b] = true; + } + } + } + } + + if ((chromaCbp & 2) != 0) + { + var raw = rawLevels || bypass; + for (var c = 0; c < 2; c++) + { + var qpc = ChromaQpFor(qp, c) + qpBdOffsetC; + var scale = ls4[(intra ? 1 : 4) + c]; + for (var b = 0; b < blocks; b++) + { + var count = ReadBlock(4, b, c, levels, 15); + nz[(mb * NzPerMb) + 16 + (c * 16) + b] = (byte)count; + for (var k = 0; k < 15; k++) + { + var level = levels[k]; + if (level != 0) + { + var pos = scan4[k + 1]; + chromaCoef[(((c * 8) + b) * 16) + pos] = raw ? level : Scale4(level, scale[((qpc % 6) * 16) + pos], qpc / 6); + chromaHas[(c * 8) + b] = true; + } + } + } + } + } + } + + private static int Scale4(int level, int ls, int qpDiv) => + qpDiv >= 4 ? (level * ls) << (qpDiv - 4) : ((level * ls) + (1 << (3 - qpDiv))) >> (4 - qpDiv); + + private void DequantizeInto8x8(Span coef, Span has, int b8, int[] source, int[] scale, int qP) + { + var qpDiv = qP / 6; + var qpMod = qP % 6; + var any = false; + var scan8 = mbField ? H264Tables.FieldScan8x8 : H264Tables.ZigZag8x8; + for (var k = 0; k < 64; k++) + { + var level = source[k]; + if (level == 0) + { + continue; + } + + var pos = scan8[k]; + if (bypass) + { + coef[(b8 * 64) + pos] = level; + } + else + { + var ls = scale[(qpMod * 64) + pos]; + coef[(b8 * 64) + pos] = qP >= 36 ? (level * ls) << (qpDiv - 6) : ((level * ls) + (1 << (5 - qpDiv))) >> (6 - qpDiv); + } + + any = true; + } + + if (any) + { + has[b8] = true; + } + } + + private int LumaOffset(int bx, int by) => lumaO + (by * lumaStride) + bx; + + /// + /// The rows of the left neighbour usable for intra prediction, one bit per row (16 luma rows, or MbHeightC chroma + /// ones): in an MBAFF frame they may belong to the two macroblocks of the pair, one intra and one not (constrained + /// intra prediction). + /// + private int LeftRows(int maxH, bool constrained) + { + var all = (1 << maxH) - 1; + if (!mbaff) + { + return mbA >= 0 && (!constrained || IntraUsable(mbA)) ? all : 0; + } + + if (pairA < 0) + { + return 0; + } + + if (!constrained) + { + return all; + } + + var mask = 0; + for (var r = 0; r < maxH; r++) + { + var n = Locate(-1, r, maxH, out _); + if (n >= 0 && IntraUsable(n)) + { + mask |= 1 << r; + } + } + + return mask; + } + + private static bool Rows(int mask, int first, int count) => ((mask >> first) & ((1 << count) - 1)) == (1 << count) - 1; + + /// + /// The intra macroblock: the luma-like planes (Y, or the colour plane; Cb and Cr too in 4:4:4, with the luma modes) + /// predicted and reconstructed block by block, then the chroma of 4:2:0 and 4:2:2. + /// + private void ReconstructIntra(int predMode16) + where T : unmanaged + { + var picture = cur!; + var constrained = pps.ConstrainedIntraPred; + var nB = Locate(0, -1, 16, out _); + var nC = Locate(16, -1, 16, out _); + var nD = Locate(-1, -1, 16, out _); + var b = nB >= 0 && (!constrained || IntraUsable(nB)); + var c = nC >= 0 && (!constrained || IntraUsable(nC)); + var d = nD >= 0 && (!constrained || IntraUsable(nD)); + var left = LeftRows(16, constrained); + if (mbKind[mb] == MbKind.SI) + { + ReconstructSi(picture, left, b, c, d); + return; + } + + IntraLumaLike(Plane(picture.Plane(colourPlane)), 0, predMode16, left, b, c, d, bitDepthY, maxY); + if (chromaArrayType == 3) + { + IntraLumaLike(Plane(picture.Cb), 1, predMode16, left, b, c, d, bitDepthC, maxC); + IntraLumaLike(Plane(picture.Cr), 2, predMode16, left, b, c, d, bitDepthC, maxC); + return; + } + + if (numC8x8 == 0) + { + return; + } + + var chromaLeft = LeftRows(mbHeightC, constrained); + var groups = 0; + for (var g = 0; g < mbHeightC / 4; g++) + { + groups |= Rows(chromaLeft, g * 4, 4) ? 1 << g : 0; + } + + var mode = chromaModes[mb]; + IntraPrediction.PredictChroma(Plane(picture.Cb), chromaO, chromaStride, mode, mbHeightC, groups, b, d, bitDepthC); + IntraPrediction.PredictChroma(Plane(picture.Cr), chromaO, chromaStride, mode, mbHeightC, groups, b, d, bitDepthC); + + // Lossless: under horizontal (1) and vertical (2) chroma prediction the residual is accumulated (§8.5.15). + AddChromaResidual(mode == 1 ? 1 : mode == 2 ? 2 : 0); + } + + /// + /// One luma-like plane of an intra macroblock: the plane at the luma location of the macroblock, with the + /// coefficients of (0 Y or colour plane, 1 Cb, 2 Cr of 4:4:4). + /// + private void IntraLumaLike(Span samples, int plane, int predMode16, int left, bool b, bool c, bool d, int bitDepth, int max) + where T : unmanaged + { + var stride = lumaStride; + var coef = lumaCoef.AsSpan(plane * 256, 256); + var has = lumaHas.AsSpan(plane * 16, 16); + Span block = stackalloc int[256]; + switch (mbKind[mb]) + { + case MbKind.I4x4: + for (var i = 0; i < 16; i++) + { + var raster = H264Tables.BlockToRaster[i]; + int bx = raster & 3, by = raster >> 2; + var hasLeft = bx > 0 || Rows(left, by * 4, 4); + var top = by > 0 || b; + var topLeft = (bx > 0 && by > 0) || (bx == 0 && by > 0 ? Rows(left, (by * 4) - 1, 1) : bx > 0 && by == 0 ? b : d); + bool topRight; + if (by == 0) + { + topRight = bx < 3 ? b : c; + } + else + { + // The block above right is available when it comes earlier in decoding order. + topRight = bx < 3 && H264Tables.RasterToBlock[((by - 1) * 4) + bx + 1] < i; + } + + var o = LumaOffset(bx * 4, by * 4); + var mode = intraModes[(mb * 16) + raster]; + IntraPrediction.Predict4x4(samples, o, stride, mode, hasLeft, top, topRight, topLeft, bitDepth); + if (has[raster]) + { + coef.Slice(raster * 16, 16).CopyTo(block); + if (bypass) + { + Transform.AddBypass(block[..16], 4, 4, mode == 0 ? 2 : mode == 1 ? 1 : 0, samples, o, stride, max); + } + else + { + Transform.Add4x4(block[..16], samples, o, stride, max); + } + } + + blkDone[raster] = true; + } + + break; + case MbKind.I8x8: + for (var i = 0; i < 4; i++) + { + int bx = i & 1, by = i >> 1; + var hasLeft = bx > 0 || Rows(left, by * 8, 8); + var top = by > 0 || b; + var topLeft = (bx > 0 && by > 0) || (bx == 0 && by > 0 ? Rows(left, 7, 1) : bx > 0 && by == 0 ? b : d); + var topRight = by == 0 ? (bx == 0 ? b : c) : bx == 0; + var o = LumaOffset(bx * 8, by * 8); + var mode = intraModes[(mb * 16) + (by * 8) + (bx * 2)]; + IntraPrediction.Predict8x8(samples, o, stride, mode, hasLeft, top, topRight, topLeft, bitDepth); + if (has[i]) + { + coef.Slice(i * 64, 64).CopyTo(block); + if (bypass) + { + Transform.AddBypass(block[..64], 8, 8, mode == 0 ? 2 : mode == 1 ? 1 : 0, samples, o, stride, max); + } + else + { + Transform.Add8x8(block[..64], samples, o, stride, max); + } + } + } + + break; + default: + { + IntraPrediction.Predict16x16(samples, LumaOffset(0, 0), stride, predMode16, Rows(left, 0, 16), b, d, bitDepth); + if (bypass) + { + // The residual of the whole macroblock, accumulated across the blocks under horizontal (1) or + // vertical (0) prediction (§8.5.15 with nW = nH = 16). + if (!has.Contains(true)) + { + break; + } + + GatherBlocks(coef, block, 16, 16); + Transform.AddBypass(block, 16, 16, predMode16 == 0 ? 2 : predMode16 == 1 ? 1 : 0, samples, LumaOffset(0, 0), stride, max); + break; + } + + for (var raster = 0; raster < 16; raster++) + { + if (has[raster]) + { + coef.Slice(raster * 16, 16).CopyTo(block); + Transform.Add4x4(block[..16], samples, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), stride, max); + } + } + + break; + } + } + } + + /// + /// The 4×4 blocks of (16 coefficients each, raster within the block; blocks in raster order, + /// / 4 per row) as one × raster. + /// + private static void GatherBlocks(ReadOnlySpan coef, Span output, int w, int h) + { + var perRow = w / 4; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var blk = ((y >> 2) * perRow) + (x >> 2); + output[(y * w) + x] = coef[(blk * 16) + ((y & 3) * 4) + (x & 3)]; + } + } + } + + /// The SI macroblock: Intra_4x4 prediction, each block rebuilt in QS (§8.6.2); 4:2:0 and 8 bits only. + private void ReconstructSi(Picture picture, int left, bool b, bool c, bool d) + { + var y = Plane(picture.Y); + for (var i = 0; i < 16; i++) + { + var raster = H264Tables.BlockToRaster[i]; + int bx = raster & 3, by = raster >> 2; + var hasLeft = bx > 0 || Rows(left, by * 4, 4); + var top = by > 0 || b; + var topLeft = (bx > 0 && by > 0) || (bx == 0 && by > 0 ? Rows(left, (by * 4) - 1, 1) : bx > 0 && by == 0 ? b : d); + var topRight = by == 0 ? (bx < 3 ? b : c) : bx < 3 && H264Tables.RasterToBlock[((by - 1) * 4) + bx + 1] < i; + var o = LumaOffset(bx * 4, by * 4); + IntraPrediction.Predict4x4(y, o, lumaStride, intraModes[(mb * 16) + raster], hasLeft, top, topRight, topLeft, 8); + SwitchingTransform.Luma4x4(picture.Y, o, lumaStride, lumaCoef.AsSpan(raster * 16, 16), sh.Qs, sh.Qs, levelInQs: true); + blkDone[raster] = true; + } + + var chromaLeft = LeftRows(8, pps.ConstrainedIntraPred); + var groups = (Rows(chromaLeft, 0, 4) ? 1 : 0) | (Rows(chromaLeft, 4, 4) ? 2 : 0); + IntraPrediction.PredictChroma(Plane(picture.Cb), chromaO, chromaStride, chromaModes[mb], 8, groups, b, d, 8); + IntraPrediction.PredictChroma(Plane(picture.Cr), chromaO, chromaStride, chromaModes[mb], 8, groups, b, d, 8); + SwitchingChroma(levelInQs: true); + } + + /// A P macroblock of an SP slice, its prediction in place: every block is rebuilt in QS (§8.6.1). + private void ReconstructSwitchingInter() + { + var picture = cur!; + for (var raster = 0; raster < 16; raster++) + { + SwitchingTransform.Luma4x4(picture.Y, LumaOffset((raster & 3) * 4, (raster >> 2) * 4), lumaStride, lumaCoef.AsSpan(raster * 16, 16), mbQp[mb], sh.Qs, sh.SpForSwitch); + } + + SwitchingChroma(sh.SpForSwitch); + } + + /// The chroma of a macroblock rebuilt in QS: QPc from the QP of the macroblock, QSc from QS (§8.6.1, §8.6.2). + private void SwitchingChroma(bool levelInQs) + { + var picture = cur!; + for (var c = 0; c < 2; c++) + { + var offset = c == 0 ? pps.ChromaQpIndexOffset : pps.SecondChromaQpIndexOffset; + var qsc = H264Tables.ChromaQp[Math.Clamp(sh.Qs + offset, 0, 51)]; + SwitchingTransform.Chroma(c == 0 ? picture.Cb : picture.Cr, chromaO, chromaStride, chromaCoef.AsSpan(c * 128, 64), chromaDcLevels.AsSpan(c * 8, 4), mbQpC[(mb * 2) + c], qsc, levelInQs); + } + } + + /// The residual of an inter macroblock, added to its prediction: every luma-like plane, then the chroma. + private void AddInterResidual() + where T : unmanaged + { + var picture = cur!; + Span block = stackalloc int[64]; + for (var plane = 0; plane < LumaLikePlanes; plane++) + { + var samples = Plane(plane == 0 ? picture.Plane(colourPlane) : picture.Plane(plane)); + var max = plane == 0 ? maxY : maxC; + var coef = lumaCoef.AsSpan(plane * 256, 256); + var has = lumaHas.AsSpan(plane * 16, 16); + if (mbT8[mb]) + { + for (var i = 0; i < 4; i++) + { + if (has[i]) + { + coef.Slice(i * 64, 64).CopyTo(block); + var o = LumaOffset((i & 1) * 8, (i >> 1) * 8); + if (bypass) + { + Transform.AddBypass(block, 8, 8, 0, samples, o, lumaStride, max); + } + else + { + Transform.Add8x8(block, samples, o, lumaStride, max); + } + } + } + } + else + { + for (var raster = 0; raster < 16; raster++) + { + if (has[raster]) + { + coef.Slice(raster * 16, 16).CopyTo(block); + var o = LumaOffset((raster & 3) * 4, (raster >> 2) * 4); + if (bypass) + { + Transform.AddBypass(block[..16], 4, 4, 0, samples, o, lumaStride, max); + } + else + { + Transform.Add4x4(block[..16], samples, o, lumaStride, max); + } + } + } + } + } + + if (numC8x8 != 0) + { + AddChromaResidual(0); + } + } + + /// + /// The chroma residual of 4:2:0 and 4:2:2, block by block; in a lossless macroblock the whole MbWidthC × MbHeightC + /// residual of each component, accumulated as says (1 horizontal, 2 vertical, §8.5.15). + /// + private void AddChromaResidual(int dpcm) + where T : unmanaged + { + var picture = cur!; + var blocks = 4 * numC8x8; + Span block = stackalloc int[128]; + for (var c = 0; c < 2; c++) + { + var plane = Plane(c == 0 ? picture.Cb : picture.Cr); + if (bypass) + { + if (!chromaHas.AsSpan(c * 8, blocks).Contains(true)) + { + continue; + } + + GatherBlocks(chromaCoef.AsSpan(c * 128, blocks * 16), block, 8, mbHeightC); + Transform.AddBypass(block[..(8 * mbHeightC)], 8, mbHeightC, dpcm, plane, chromaO, chromaStride, maxC); + continue; + } + + for (var b = 0; b < blocks; b++) + { + if (!chromaHas[(c * 8) + b]) + { + continue; + } + + chromaCoef.AsSpan(((c * 8) + b) * 16, 16).CopyTo(block); + var o = chromaO + ((b >> 1) * 4 * chromaStride) + ((b & 1) * 4); + Transform.Add4x4(block[..16], plane, o, chromaStride, maxC); + } + } + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.SliceGroups.cs b/src/Febe.Core/Codecs/H264/H264Decoder.SliceGroups.cs new file mode 100644 index 0000000..a15649f --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.SliceGroups.cs @@ -0,0 +1,245 @@ +namespace Febe.Core.Codecs.H264; + +public sealed partial class H264Decoder +{ + /// The picture has more than one slice group (FMO): a slice walks the macroblocks of its group only. + private bool fmo; + + /// The slice group of each map unit (mapUnitToSliceGroupMap, §8.2.2.1–§8.2.2.7). + private int[] mapUnitGroup = []; + + /// The slice group of each macroblock address of the picture (mbToSliceGroupMap, §8.2.2.8). + private byte[] mbGroup = []; + + /// NextMbAddress (§8.2.2): the next address of the same slice group, the picture size after the last one. + private int[] nextMb = []; + + // What the map in the arrays above was computed for. + private Pps? mapPps; + private Sps? mapSps; + private int mapCycle = -1; + private int mapLayout = -1; + + /// The address after in the slice (§7.3.4). + private int NextAddress(int addr) => fmo ? nextMb[addr] : addr + 1; + + /// + /// The slice group map of the slice about to be decoded (§8.2.2), computed again only when the parameter sets, + /// slice_group_change_cycle or the kind of picture (frame, field, MBAFF frame) change. + /// + private void PrepareSliceGroups(SliceHeader h, Sps s, Pps p) + { + fmo = p.NumSliceGroups > 1; + if (!fmo) + { + return; + } + + // 0 frame of frame macroblocks only or a field, 1 MBAFF frame, 2 frame of a stream with fields but no MBAFF. + var layout = s.FrameMbsOnly || h.FieldPic ? 0 : s.MbAdaptiveFrameField ? 1 : 2; + var cycle = p.SliceGroupMapType is >= 3 and <= 5 ? h.SliceGroupChangeCycle : -1; + if (ReferenceEquals(mapPps, p) && ReferenceEquals(mapSps, s) && mapCycle == cycle && mapLayout == layout) + { + return; + } + + var w = s.WidthInMbs; + var mapHeight = s.HeightInMapUnits; + var units = w * mapHeight; + if (mapUnitGroup.Length != units) + { + mapUnitGroup = new int[units]; + } + + BuildMapUnits(p, w, mapHeight, Math.Min(Math.Max(cycle, 0) * p.SliceGroupChangeRate, units)); + + var total = h.FieldPic ? s.WidthInMbs * s.HeightInMbs / 2 : s.WidthInMbs * s.HeightInMbs; + if (mbGroup.Length != total) + { + mbGroup = new byte[total]; + nextMb = new int[total]; + } + + for (var i = 0; i < total; i++) + { + var unit = layout switch + { + 0 => i, + 1 => i >> 1, + _ => ((i / (2 * w)) * w) + (i % w), + }; + mbGroup[i] = (byte)mapUnitGroup[unit]; + } + + Span last = stackalloc int[8]; + last.Fill(total); + for (var i = total - 1; i >= 0; i--) + { + var g = mbGroup[i]; + nextMb[i] = last[g]; + last[g] = i; + } + + mapPps = p; + mapSps = s; + mapCycle = cycle; + mapLayout = layout; + } + + /// mapUnitToSliceGroupMap for the map type of the PPS (§8.2.2.1–§8.2.2.7). + private void BuildMapUnits(Pps p, int w, int h, int unitsInGroup0) + { + var map = mapUnitGroup; + var units = map.Length; + var groups = p.NumSliceGroups; + var direction = p.SliceGroupChangeDirection ? 1 : 0; + switch (p.SliceGroupMapType) + { + case 0: + { + // Interleaved: runs of each group in turn. + var i = 0; + do + { + for (var g = 0; g < groups && i < units; i += p.RunLength[g++]) + { + for (var j = 0; j < p.RunLength[g] && i + j < units; j++) + { + map[i + j] = g; + } + } + } + while (i < units); + + break; + } + + case 1: + // Dispersed. + for (var i = 0; i < units; i++) + { + map[i] = ((i % w) + (((i / w) * groups) / 2)) % groups; + } + + break; + case 2: + // Foreground rectangles, the last group taking what is left. + Array.Fill(map, groups - 1); + for (var g = groups - 2; g >= 0; g--) + { + int topLeft = p.TopLeft[g], bottomRight = p.BottomRight[g]; + if (bottomRight >= units || topLeft > bottomRight || topLeft % w > bottomRight % w) + { + throw new H264Exception("Rettangolo di un gruppo di slice fuori dall'immagine."); + } + + for (var y = topLeft / w; y <= bottomRight / w; y++) + { + for (var x = topLeft % w; x <= bottomRight % w; x++) + { + map[(y * w) + x] = g; + } + } + } + + break; + case 3: + BoxOut(map, w, h, direction, unitsInGroup0); + break; + case 4: + { + // Raster scan. + var upperLeft = direction != 0 ? units - unitsInGroup0 : unitsInGroup0; + for (var i = 0; i < units; i++) + { + map[i] = i < upperLeft ? direction : 1 - direction; + } + + break; + } + + case 5: + { + // Wipe: column by column. + var upperLeft = direction != 0 ? units - unitsInGroup0 : unitsInGroup0; + var k = 0; + for (var x = 0; x < w; x++) + { + for (var y = 0; y < h; y++) + { + map[(y * w) + x] = k++ < upperLeft ? direction : 1 - direction; + } + } + + break; + } + + default: + // Explicit. + if (p.SliceGroupIds.Length != units) + { + throw new H264Exception("Mappa esplicita dei gruppi di slice di dimensione sbagliata."); + } + + for (var i = 0; i < units; i++) + { + map[i] = p.SliceGroupIds[i]; + } + + break; + } + } + + /// Box-out (§8.2.2.4): group 0 grows as a spiral from the centre, clockwise or counter-clockwise. + private static void BoxOut(int[] map, int w, int h, int direction, int unitsInGroup0) + { + Array.Fill(map, 1); + var x = (w - direction) / 2; + var y = (h - direction) / 2; + int left = x, top = y, right = x, bottom = y; + int xDir = direction - 1, yDir = direction; + for (var k = 0; k < unitsInGroup0;) + { + var vacant = map[(y * w) + x] == 1; + if (vacant) + { + map[(y * w) + x] = 0; + k++; + } + + if (xDir == -1 && x == left) + { + left = Math.Max(left - 1, 0); + x = left; + xDir = 0; + yDir = (2 * direction) - 1; + } + else if (xDir == 1 && x == right) + { + right = Math.Min(right + 1, w - 1); + x = right; + xDir = 0; + yDir = 1 - (2 * direction); + } + else if (yDir == -1 && y == top) + { + top = Math.Max(top - 1, 0); + y = top; + xDir = 1 - (2 * direction); + yDir = 0; + } + else if (yDir == 1 && y == bottom) + { + bottom = Math.Min(bottom + 1, h - 1); + y = bottom; + xDir = (2 * direction) - 1; + yDir = 0; + } + else + { + x += xDir; + y += yDir; + } + } + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.Svc.cs b/src/Febe.Core/Codecs/H264/H264Decoder.Svc.cs new file mode 100644 index 0000000..621fea7 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.Svc.cs @@ -0,0 +1,569 @@ +namespace Febe.Core.Codecs.H264; + +/// +/// Scalable video coding (SVC, Annex G), the part written so far: quality refinement within the base dependency +/// representation (dependency_id 0, quality_id above 0: MGS) with CAVLC. The layers of a picture are decoded one over the +/// other into the same frame store: the base layer (AVC, NAL units 1 and 5) as usual, then each refinement slice (NAL +/// unit 20) macroblock by macroblock, so the frame left by the highest layer is the target layer representation, and the +/// decoded picture buffer holds it, as the motion compensation of the target dependency wants it without key pictures. +/// A macroblock with base_mode_flag inherits type, intra modes and motion of the layer below. An inter one adds its +/// scaled transform coefficients to those of the layer below when residual_prediction_flag says so (§G.8.5) and is +/// predicted again with the inherited motion. An intra one is never predicted again: its residual, accumulated in the +/// coefficient domain over the refinements, is added to the samples of the layer where the macroblock was last coded as +/// intra; for the intra mode prediction of its neighbours it counts as I_BL (DC). A macroblock with base_mode_flag 0 is an +/// ordinary one of the current layer, which may take the motion of the layer below as predictor (motion_prediction_flag). +/// This reproduces the official reconstruction of SVCBMT-13 (three MGS levels) bit for bit. +/// Not written yet, and left to the base layer (the enhancement NAL units are then skipped for the rest of the stream, +/// says why): dependency_id above 0 (spatial scalability and CGS, with the +/// inter-layer prediction and upsampling of §G.8.6), enhancement slices with CABAC (the contexts of base_mode_flag, +/// motion_prediction_flag and residual_prediction_flag), key pictures (store_ref_base_pic_flag, use_ref_base_pic_flag), +/// coefficient subsets (scan_idx_start, scan_idx_end), tcoeff_level_prediction_flag, the 8×8 transform, interlace and +/// formats other than 4:2:0 at 8 bits in the refinements. +/// +public sealed partial class H264Decoder +{ + private const int CoefPerMb = 512; + + /// A subset SPS with the scalable extension was read: the stream is SVC. + private bool scalable; + + /// The enhancement layers of the stream use something not written yet: from then on only the base layer. + private string? svcUnsupported; + + /// DQId of the highest layer decoded into the current picture (0 the base layer). + private int picDqId; + + /// A layer of the current picture could not be decoded: the layers above it are skipped. + private bool picSvcStopped; + + /// The refinement slice being decoded, null for an AVC slice. + private SvcSliceFields? svcSlice; + + /// The macroblock being decoded is an ordinary one of a refinement slice (base_mode_flag 0). + private bool svcOwnMb; + + /// motion_prediction_flag_lX of the macroblock, by list and 8×8 block. + private readonly bool[] svcMotionPred = new bool[8]; + + /// The residual of the macroblock was cleared and read (else it is that of a skipped macroblock: none). + private bool mbResidualSet; + + /// Intra_16x16 prediction mode of the macroblock being decoded. + private int lastPred16; + + // The layer just decoded, macroblock by macroblock: scaled coefficients (luma 256, chroma 2 × 128) and the + // Intra_16x16 mode; and the same, with type, modes and motion, of the layer below the one being decoded. + private int[] layerCoef = []; + private byte[] layerPred16 = []; + private int[] baseCoef = []; + private byte[] basePred16 = []; + private MbKind[] baseKind = []; + private sbyte[] baseIntraModes = []; + private byte[] baseChromaModes = []; + private bool[] baseT8 = []; + private short[] baseMv = []; + private sbyte[] baseRefIdx = []; + private Picture?[] baseRefPic = []; + private sbyte[] baseRefPar = []; + + // The intra origin (see CopyIntraOrigin) and, per macroblock, whether it is a base_mode intra refinement in the layer + // just decoded and in the layer below. + private byte[] originY = [], originCb = [], originCr = []; + private bool[] mbIntraRefined = []; + + /// The macroblock being decoded is a base_mode intra refinement. + private bool mbRefinedIntra; + private bool[] baseIntraRefined = []; + + /// + /// Whether the enhancement layers of an SVC stream are decoded (the default): the frames are then those of the highest + /// layer the decoder handles; false gives the base layer, plain H.264, and skips the NAL units 14 and 20. + /// + public bool DecodeEnhancementLayers { get; set; } = true; + + /// Why the enhancement layers of the stream are not decoded (null when they are, or the stream has none). + public string? EnhancementLayersSkipped => svcUnsupported; + + /// The per-macroblock data of the layers is kept while the base layer is decoded. + private bool RecordLayers => scalable && DecodeEnhancementLayers && svcUnsupported is null && root is null; + + /// The SVC prefix NAL unit (§G.7.3.2.12.1) before a base layer slice: key pictures are not handled. + private void ReadSvcPrefix(NalUnit nal) + { + var ext = SvcNalHeader.Of(nal); + if (ext.UseRefBasePic) + { + SvcUnsupported("immagini chiave (use_ref_base_pic_flag)"); + } + + if (nal.RefIdc != 0 && nal.Length > 4 && nal.Reader().ReadFlag()) + { + SvcUnsupported("immagini chiave (store_ref_base_pic_flag)"); + } + } + + private void SvcUnsupported(string reason) + { + if (DecodeEnhancementLayers && svcUnsupported is null) + { + svcUnsupported = reason; + } + + picSvcStopped = true; + } + + /// A slice of an enhancement layer (NAL unit 20 with the SVC header): decoded over the current picture. + private void DecodeSvcSlice(NalUnit nal) + { + if (!DecodeEnhancementLayers || svcUnsupported is not null || nal.HeaderLength != 4 || root is not null) + { + return; + } + + var ext = SvcNalHeader.Of(nal); + if (ext.DependencyId != 0) + { + SvcUnsupported("scalabilità spaziale o CGS (dependency_id maggiore di 0)"); + return; + } + + if (cur is null || picHeader is null || picSkipped || picSvcStopped || ext.DqId < picDqId) + { + return; + } + + if (ext.DqId > picDqId + 1) + { + // A layer is missing: the ones above it cannot be decoded. + picSvcStopped = true; + return; + } + + if (ext.UseRefBasePic) + { + SvcUnsupported("immagini chiave (use_ref_base_pic_flag)"); + return; + } + + var reader = nal.Reader(); + var header = SliceHeader.ParseScalable(reader, nal, ext, subsetSequences, pictures, picHeader, out var s, out var p); + var svc = header.Svc!; + string? missing = null; + if (p.Cabac) + { + missing = "strati di miglioramento in CABAC"; + } + else if (svc.ScanIdxStart != 0 || svc.ScanIdxEnd != 15) + { + missing = "sottoinsiemi di coefficienti (scan_idx_start, scan_idx_end)"; + } + else if (svc.TcoeffLevelPrediction) + { + missing = "tcoeff_level_prediction_flag"; + } + else if (svc.StoreRefBasePic) + { + missing = "immagini chiave (store_ref_base_pic_flag)"; + } + else if (!s.FrameMbsOnly || s.WidthInMbs != activeSps!.WidthInMbs || s.HeightInMbs != activeSps.HeightInMbs || s.ChromaFormatIdc != 1 + || s.BitDepthLuma != 8 || s.BitDepthChroma != 8 || p.Transform8x8Mode) + { + missing = "strati di qualità interlacciati, con trasformata 8×8 o fuori dal 4:2:0 a 8 bit"; + } + + if (missing is not null) + { + SvcUnsupported(missing); + return; + } + + if (header.RedundantPicCnt > 0) + { + return; + } + + if (ext.DqId > picDqId) + { + SnapshotLayer(); + picDqId = ext.DqId; + } + + svcSlice = svc; + try + { + DecodeSliceData(reader, nal, header, s, p); + } + finally + { + svcSlice = null; + svcOwnMb = false; + } + } + + /// Makes room for the per-macroblock data of the layers. + private void EnsureLayerArrays() + { + if (layerCoef.Length == mbCount * CoefPerMb) + { + return; + } + + layerCoef = new int[mbCount * CoefPerMb]; + layerPred16 = new byte[mbCount]; + baseCoef = new int[mbCount * CoefPerMb]; + basePred16 = new byte[mbCount]; + baseKind = new MbKind[mbCount]; + baseIntraModes = new sbyte[mbCount * 16]; + baseChromaModes = new byte[mbCount]; + baseT8 = new bool[mbCount]; + mbIntraRefined = new bool[mbCount]; + baseIntraRefined = new bool[mbCount]; + baseMv = new short[2 * mbCount * 32]; + baseRefIdx = new sbyte[2 * mbCount * 4]; + baseRefPic = new Picture?[2 * mbCount * 4]; + baseRefPar = new sbyte[2 * mbCount * 4]; + } + + /// The coefficients and Intra_16x16 mode of the macroblock just decoded, for the layer above it. + private void RecordLayer() + { + EnsureLayerArrays(); + mbIntraRefined[mb] = mbRefinedIntra; + if (svcSlice is not null && !mbRefinedIntra && IsIntraKind(mbKind[mb])) + { + // An own intra macroblock of a refinement: the samples the layers above it refine. + CopyIntraOrigin(fromOrigin: false); + } + + var target = layerCoef.AsSpan(mb * CoefPerMb, CoefPerMb); + if (!mbResidualSet || mbKind[mb] == MbKind.IPcm) + { + target.Clear(); + } + else + { + lumaCoef.AsSpan(0, 256).CopyTo(target); + chromaCoef.AsSpan(0, 256).CopyTo(target[256..]); + } + + layerPred16[mb] = (byte)(mbKind[mb] == MbKind.I16x16 ? lastPred16 : 0); + } + + /// + /// Copies the samples of the current macroblock from the intra origin (the reconstruction an intra macroblock of a + /// refinement is built on) into the picture, or the other way round. + /// + private void CopyIntraOrigin(bool fromOrigin) + { + var picture = cur!; + CopyBlock(fromOrigin ? originY : picture.Y, fromOrigin ? picture.Y : originY, picture.Width, mbX * 16, mbY * 16, 16); + var cw = picture.ChromaWidth; + CopyBlock(fromOrigin ? originCb : picture.Cb, fromOrigin ? picture.Cb : originCb, cw, mbX * 8, mbY * 8, 8); + CopyBlock(fromOrigin ? originCr : picture.Cr, fromOrigin ? picture.Cr : originCr, cw, mbX * 8, mbY * 8, 8); + } + + private static void CopyBlock(byte[] source, byte[] target, int stride, int x, int y, int size) + { + for (var r = 0; r < size; r++) + { + var offset = ((y + r) * stride) + x; + source.AsSpan(offset, size).CopyTo(target.AsSpan(offset, size)); + } + } + + private static void CopyPlane(byte[] source, ref byte[] target) + { + if (target.Length != source.Length) + { + target = new byte[source.Length]; + } + + source.AsSpan().CopyTo(target); + } + + /// The layer decoded so far becomes the reference layer of the one starting (§G.8.1.5). + private void SnapshotLayer() + { + EnsureLayerArrays(); + var picture = cur!; + if (picDqId == 0) + { + // Quality 0 is the intra origin of all its intra macroblocks. + CopyPlane(picture.Y, ref originY); + CopyPlane(picture.Cb, ref originCb); + CopyPlane(picture.Cr, ref originCr); + } + + Array.Copy(layerCoef, baseCoef, layerCoef.Length); + Array.Copy(layerPred16, basePred16, mbCount); + Array.Copy(mbKind, baseKind, mbCount); + Array.Copy(intraModes, baseIntraModes, mbCount * 16); + Array.Copy(chromaModes, baseChromaModes, mbCount); + Array.Copy(mbT8, baseT8, mbCount); + Array.Copy(mbIntraRefined, baseIntraRefined, mbCount); + Array.Copy(picture.Mv, baseMv, baseMv.Length); + Array.Copy(picture.RefIdx, baseRefIdx, baseRefIdx.Length); + Array.Copy(picture.RefPic, baseRefPic, baseRefPic.Length); + Array.Copy(picture.RefPar, baseRefPar, baseRefPar.Length); + } + + private static bool IsIntraKind(MbKind kind) => kind is MbKind.I4x4 or MbKind.I8x8 or MbKind.I16x16 or MbKind.IPcm or MbKind.SI; + + /// A macroblock of a refinement slice (macroblock_layer_in_scalable_extension(), §G.7.3.6). + private void DecodeScalableMacroblock() + { + var s = svcSlice!; + var baseMode = s.AdaptiveBaseMode ? rd.ReadFlag() : s.DefaultBaseMode; + if (baseMode) + { + DecodeBaseModeMacroblock(readSyntax: true); + return; + } + + svcOwnMb = true; + try + { + DecodeMacroblock(); + } + finally + { + svcOwnMb = false; + } + } + + /// A skipped macroblock of a refinement slice: P_Skip or B_Skip of the current layer, with the residual of the layer below when residual_prediction_flag is inferred to 1. + private void DecodeScalableSkip() + { + DecodeSkip(); + var s = svcSlice!; + var residualPrediction = !s.AdaptiveResidualPrediction && s.DefaultResidualPrediction; + ClearResidual(); + if (residualPrediction) + { + AddBaseCoefficients(); + if (wide) + { + AddInterResidual(); + } + else + { + AddInterResidual(); + } + } + } + + /// + /// A macroblock with base_mode_flag 1 (or of a slice with slice_skip_flag): type, intra prediction modes and motion of + /// the layer below (§G.8.1.5.1, same resolution), its own residual added to that of the layer below in the scaled + /// coefficient domain. + /// + private void DecodeBaseModeMacroblock(bool readSyntax) + { + var s = svcSlice!; + var kind = baseKind[mb]; + if (kind is MbKind.IPcm or MbKind.SI) + { + throw new H264Exception("Strato di qualità sopra un macroblocco I_PCM: non gestito."); + } + + var intra = IsIntraKind(kind); + var residualPrediction = sh.Type != SliceType.I && (s.AdaptiveResidualPrediction ? readSyntax && rd.ReadFlag() : s.DefaultResidualPrediction || !readSyntax); + ClearResidual(); + mbT8[mb] = false; + if (readSyntax) + { + var cbp = ReadCbp(intra: false); + mbCbp[mb] = (byte)cbp; + if (cbp != 0) + { + ApplyQpDelta(ReadQpDelta()); + ReadResidual(false, cbp, intra); + } + else + { + lastQpDelta = 0; + } + } + else + { + lastQpDelta = 0; + } + + StoreQp(); + var picture = cur!; + if (intra) + { + // An intra macroblock is refined over the reconstruction of the layer where it was last coded as intra + // (quality 0, or an own intra macroblock of a refinement): the residual of each refinement since then is + // accumulated in the scaled coefficient domain and added to those samples, never predicted again. + if (baseIntraRefined[mb]) + { + AddBaseCoefficients(); + } + + mbKind[mb] = kind; + picture.MbIntra[mb] = true; + mbRefinedIntra = true; + + // For the prediction of the intra modes of the neighbours this is not an Intra_4x4 macroblock (I_BL): DC. + intraModes.AsSpan(mb * 16, 16).Fill(2); + chromaModes[mb] = baseChromaModes[mb]; + lastPred16 = basePred16[mb]; + CopyIntraOrigin(fromOrigin: true); + AddInterResidual(); + return; + } + + if (residualPrediction) + { + AddBaseCoefficients(); + } + + mbKind[mb] = sh.IsB ? MbKind.BInter : MbKind.PInter; + for (var list = 0; list < 2; list++) + { + baseMv.AsSpan(((list * mbCount) + mb) * 32, 32).CopyTo(picture.Mv.AsSpan(((list * mbCount) + mb) * 32, 32)); + var r = ((list * mbCount) + mb) * 4; + baseRefIdx.AsSpan(r, 4).CopyTo(picture.RefIdx.AsSpan(r, 4)); + baseRefPic.AsSpan(r, 4).CopyTo(picture.RefPic.AsSpan(r, 4)); + baseRefPar.AsSpan(r, 4).CopyTo(picture.RefPar.AsSpan(r, 4)); + } + + MarkDone(0, 0, 16, 16); + for (var blk = 0; blk < 16; blk++) + { + MotionCompensate((blk & 3) * 4, (blk >> 2) * 4, 4, 4); + } + + if (wide) + { + AddInterResidual(); + } + else + { + AddInterResidual(); + } + } + + /// Refinement (§G.8.5): the scaled coefficients of the layer below are added to those of this one. + private void AddBaseCoefficients() + { + var source = baseCoef.AsSpan(mb * CoefPerMb, CoefPerMb); + for (var raster = 0; raster < 16; raster++) + { + var any = false; + for (var k = 0; k < 16; k++) + { + var v = source[(raster * 16) + k]; + if (v != 0) + { + lumaCoef[(raster * 16) + k] += v; + any = true; + } + } + + if (any) + { + lumaHas[raster] = true; + } + } + + for (var block = 0; block < 16; block++) + { + var any = false; + for (var k = 0; k < 16; k++) + { + var v = source[256 + (block * 16) + k]; + if (v != 0) + { + chromaCoef[(block * 16) + k] += v; + any = true; + } + } + + if (any) + { + chromaHas[block] = true; + } + } + } + + /// + /// motion_prediction_flag_l0 and _l1 of an ordinary inter macroblock of a refinement slice (§G.7.3.6.1), for the + /// partitions (8×8 blocks of each), read or inferred. + /// + private void ReadMotionPredictionFlags(int count, bool subPartitions) + { + Array.Clear(svcMotionPred); + var s = svcSlice!; + for (var list = 0; list < 2; list++) + { + for (var part = 0; part < count; part++) + { + if ((partPred[part] & (1 << list)) == 0 || (subPartitions && subDirect[(mb * 4) + part])) + { + continue; + } + + var flag = s.AdaptiveMotionPrediction ? rd.ReadFlag() : s.DefaultMotionPrediction; + if (!flag) + { + continue; + } + + if (subPartitions) + { + svcMotionPred[(list * 4) + part] = true; + } + else + { + for (var b8 = 0; b8 < 4; b8++) + { + if (shape == Shape16x16 || (shape == Shape16x8 && (b8 >> 1) == part) || (shape == Shape8x16 && (b8 & 1) == part)) + { + svcMotionPred[(list * 4) + b8] = true; + } + } + } + } + } + } + + /// Whether the motion of the 8×8 block is predicted from the layer below. + private bool MotionFromBase(int list, int b8) => svcOwnMb && svcMotionPred[(list * 4) + b8]; + + /// The reference index of the layer below for an 8×8 block (0 where it has none). + private int BaseRefIdx(int list, int b8) => Math.Max(0, (int)baseRefIdx[(((list * mbCount) + mb) * 4) + b8]); + + /// The motion vector of the layer below for a 4×4 block (raster index). + private (int X, int Y) BaseMv(int list, int blk) + { + if (baseRefIdx[(((list * mbCount) + mb) * 4) + (((blk >> 3) * 2) + ((blk & 3) >> 1))] < 0) + { + return (0, 0); + } + + var i = ((((list * mbCount) + mb) * 16) + blk) * 2; + return (baseMv[i], baseMv[i + 1]); + } + + /// residual_prediction_flag of an ordinary inter macroblock of a refinement slice, read or inferred. + private bool ReadResidualPredictionFlag() + { + var s = svcSlice!; + return s.AdaptiveResidualPrediction ? rd.ReadFlag() : s.DefaultResidualPrediction; + } + + /// A slice with slice_skip_flag: every macroblock as base_mode_flag 1 with the residual of the layer below. + private void DecodeSkippedSlice(int addr, int total) + { + var count = svcSlice!.NumMbsInSlice; + for (var i = 0; i < count && addr < total; i++) + { + BeginMacroblock(addr); + addr = NextAddress(addr); + DecodeBaseModeMacroblock(readSyntax: false); + RecordLayer(); + } + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs new file mode 100644 index 0000000..f11cf98 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -0,0 +1,1563 @@ +namespace Febe.Core.Codecs.H264; + +/// What an access unit offers to start decoding from (see ). +public enum H264AccessPoint +{ + /// A P or B picture, or no picture: decoding cannot start here. + None, + + /// A picture of I slices that is not IDR: the pictures after it may still refer to earlier ones. + IntraPicture, + + /// An IDR picture: nothing after it refers to anything before. + Idr, +} + +/// +/// An H.264 (ITU-T H.264 | ISO/IEC 14496-10) decoder written from the standard: Baseline, Extended, Main and the High +/// profiles — 4:2:0, 4:2:2, 4:4:4 (also with the colour planes coded separately) and monochrome, 8 to 14 bits per sample, +/// lossless macroblocks (qpprime_y_zero_transform_bypass_flag) — CAVLC and CABAC, I, P and B slices, 8×8 transform and +/// scaling matrices, spatial +/// and temporal direct prediction, list modification, memory management operations and long-term references, +/// deblocking — for progressive frames and for interlaced video: field pictures, frames and fields mixed picture by +/// picture (PAFF), frames of frame and field macroblock pairs (MBAFF). Frames come out whole: the two fields of a pair are +/// interleaved. The tools of Baseline and Extended: slice groups (FMO, map types 0–6), slices in any order (ASO), SP and +/// SI slices (switching pictures), slice data partitioning (NAL units 2–4); redundant coded pictures are skipped, the +/// primary one is decoded. Written from the standard but not yet checked against a conformance stream: explicit and +/// implicit weighted prediction, gaps in frame_num, I_PCM, SI macroblocks and sp_for_switch_flag, data partitioning +/// (checked only on conformance streams split into partitions), 4:4:4, separate colour planes, lossless coding and bit +/// depths above 10. Not handled (an ): CABAC in 4:4:4 with the colour planes coded together +/// (its contexts 460–1023 are not transcribed yet), SP and SI slices outside 4:2:0 at 8 bits. +/// Multiview streams (MVC, Annex H): every view, with inter-view prediction (see H264Decoder.Mvc.cs), each frame tagged +/// with its ; false gives the base view only. Scalable streams +/// (SVC, Annex G): the base layer always, and above it the quality refinements of the base resolution (MGS, CAVLC); the +/// other enhancement layers are left out and says why (see H264Decoder.Svc.cs). +/// +public sealed partial class H264Decoder +{ + private readonly Dictionary sequences = []; + private readonly Dictionary pictures = []; + private readonly List dpb = []; + private readonly Stack pool = new(); + + private Sps? activeSps; + + /// The frame store being decoded into (a frame, or one field of it). + private Picture? cur; + + /// The structure of the picture being decoded: 0 frame, 1 top field, 2 bottom field. + private int curStructure; + + /// The picture being decoded is the second field of . + private bool curSecondField; + + /// A first field already decoded, waiting for the second field of its frame. + private Picture? openField; + + private int openStructure; + private int openRefIdc; + + private SliceHeader? picHeader; + private int picNalType; + private int picRefIdc; + private bool picMmco5; + private bool picSkipped; + private int sliceCounter; + + /// The RBSP of the NAL unit being decoded: one buffer for the whole stream. + private byte[]? rbsp; + + private int prevPocMsb; + private int prevPocLsb; + private int prevFrameNumOffset; + private int prevFrameNum; + private int prevRefFrameNum; + private bool haveReference; + private int frameNumOffset; + private int pocMsb; + private int maxLongTermFrameIdx = -1; + private int period; + private long decodeCounter; + + /// + /// Which frames to hand out, by decoding index; null hands out all of them. A picture that is not used for reference + /// and is not wanted is not reconstructed at all: only its header counts. In an MVC stream decoded with + /// the same filter applies to every view, each with its own decoding index + /// ( counts the view components of a view): when every access unit has all the + /// views, index n of each view is the n-th access unit. + /// + public Func? Wanted + { + get => root is null ? wanted : root.Wanted; + set => wanted = value; + } + + private Func? wanted; + + /// Raised for each decoded frame that accepts, in decoding order. + public event Action? FrameDecoded; + + /// Frames decoded so far (including those not handed out). + public long FramesDecoded => decodeCounter; + + /// Decodes a whole Annex B byte stream (start codes), then flushes the last picture. + public void DecodeAnnexB(ReadOnlySpan stream) + { + DecodeUnitsAnnexB(stream); + Flush(); + } + + /// + /// Reads the SPS and PPS of an avcC box (AVCDecoderConfigurationRecord); returns the size of the NAL length + /// fields of the samples. + /// + public int ConfigureAvcC(ReadOnlySpan avcC) + { + if (avcC.Length < 7 || avcC[0] != 1) + { + throw new H264Exception("Configurazione avcC non valida."); + } + + var lengthSize = (avcC[4] & 3) + 1; + var offset = 5; + for (var pass = 0; pass < 2; pass++) + { + if (offset >= avcC.Length) + { + break; + } + + var count = pass == 0 ? avcC[offset] & 0x1F : avcC[offset]; + offset++; + for (var i = 0; i < count && offset + 2 <= avcC.Length; i++) + { + var size = (avcC[offset] << 8) | avcC[offset + 1]; + offset += 2; + if (size == 0 || offset + size > avcC.Length) + { + throw new H264Exception("Configurazione avcC troncata."); + } + + Decode(NalUnits.Unescape(avcC.Slice(offset, size), ref rbsp)); + offset += size; + } + } + + return lengthSize; + } + + /// + /// Decodes one access unit stored with length prefixes (an MP4 or Matroska sample) and finishes its picture. A + /// sample holding only the first field of a frame leaves it waiting for the second one, in the next sample. + /// + public void DecodeSample(ReadOnlySpan sample, int lengthSize) + { + var position = 0; + while (NalUnits.NextLengthPrefixed(sample, lengthSize, ref position, out var unit)) + { + Decode(NalUnits.Unescape(sample[unit], ref rbsp)); + } + + FinishAccessUnit(); + } + + /// Decodes one access unit in Annex B form and finishes its picture (as ). + public void DecodeAccessUnitAnnexB(ReadOnlySpan accessUnit) + { + DecodeUnitsAnnexB(accessUnit); + FinishAccessUnit(); + } + + /// Finishes the picture of every view of the access unit. + private void FinishAccessUnit() + { + FinishPicture(); + FinishViews(); + } + + /// + /// Whether decoding can start at this access unit: exactly at an IDR picture; only approximately at a picture whose + /// first slice is an I slice, since the pictures after it may still refer to earlier ones. + /// is the size of the NAL length fields, 0 for Annex B. + /// + public static H264AccessPoint AccessPoint(ReadOnlySpan accessUnit, int lengthSize) + { + var position = 0; + while (true) + { + Range unit; + var more = lengthSize == 0 + ? NalUnits.NextAnnexB(accessUnit, ref position, out unit) + : NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit); + if (!more) + { + return H264AccessPoint.None; + } + + var nal = accessUnit[unit]; + switch (nal[0] & 0x1F) + { + case 5: + return H264AccessPoint.Idr; + case 1: + case 2: // partition A starts like a slice + try + { + // first_mb_in_slice and slice_type: a few bytes of the header are enough. + var reader = NalUnits.Parse(nal[..Math.Min(nal.Length, 16)]).Reader(); + _ = reader.ReadUe(); + return (SliceType)(reader.ReadUe(9) % 5) is SliceType.I or SliceType.SI ? H264AccessPoint.IntraPicture : H264AccessPoint.None; + } + catch (H264Exception) + { + return H264AccessPoint.None; + } + } + } + } + + private void DecodeUnitsAnnexB(ReadOnlySpan stream) + { + var position = 0; + while (NalUnits.NextAnnexB(stream, ref position, out var unit)) + { + Decode(NalUnits.Unescape(stream[unit], ref rbsp)); + } + } + + /// Finishes the picture being decoded, if any, and hands out a first field still waiting for its pair. + public void Flush() + { + FinishPicture(); + if (openField is { } field) + { + openField = null; + HandOut(field, activeSps!); + } + + FlushViews(); + } + + /// + /// Finishes the picture being decoded; a damaged picture whose deblocking or cropping fails raises an + /// like the rest of the stream, and is dropped. + /// + private void FinishPicture() + { + try + { + if (partitionPending) + { + DecodePartitionedSlice(); + } + + CompletePicture(); + } + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException) + { + cur = null; + picHeader = null; + openField = null; + throw new H264Exception("Flusso H.264 troncato o danneggiato."); + } + } + + /// Decodes one NAL unit (with its header, without start code) and leaves the picture open: for the tests. + internal void DecodeUnit(ReadOnlySpan nal) => Decode(NalUnits.Unescape(nal, ref rbsp)); + + private void Decode(NalUnit nal) + { + try + { + // The partitions B and C of a slice follow its partition A: anything else completes it. + if (partitionPending && nal.Type is not (3 or 4)) + { + DecodePartitionedSlice(); + } + + switch (nal.Type) + { + case 1: + case 5: + if (viewDecoders.Count > 0) + { + // The base view opens a new access unit: the view components of the last one are complete. + FinishViews(); + } + + DecodeSlice(nal); + break; + case 14: + if (nal.HeaderLength == 4 && nal.IsSvc) + { + ReadSvcPrefix(nal); + } + else + { + ReadPrefix(nal); + } + + break; + case 15: + { + var subset = Sps.ParseSubset(nal.Reader()); + subsetSequences[subset.Id] = subset; + multiview |= subset.Mvc is not null; + scalable |= subset.Svc is not null; + break; + } + + case 20: + if (nal.HeaderLength == 4 && nal.IsSvc) + { + DecodeSvcSlice(nal); + } + else + { + DecodeViewSlice(nal); + } + + break; + case 2: + StorePartitionA(nal); + break; + case 3: + case 4: + StorePartition(nal); + break; + case 7: + { + var sps = Sps.Parse(nal.Reader()); + sequences[sps.Id] = sps; + break; + } + + case 8: + { + var pps = Pps.Parse(nal.Reader(), sequences, subsetSequences); + pictures[pps.Id] = pps; + break; + } + + case 11: // end of stream + Flush(); + break; + } + } + catch (Exception ex) when (ex is IndexOutOfRangeException or ArgumentException or NullReferenceException) + { + throw new H264Exception("Flusso H.264 troncato o danneggiato."); + } + } + + private void DecodeSlice(NalUnit nal) + { + var reader = nal.Reader(); + var header = ParseSliceHeader(reader, nal, out var sps, out var pps); + + // A redundant coded picture (§7.4.3) repeats the primary one, which is decoded: it is skipped. + if (header.RedundantPicCnt > 0) + { + return; + } + + DecodeParsedSlice(nal, reader, header, sps, pps); + } + + private SliceHeader ParseSliceHeader(RbspReader reader, NalUnit nal, out Sps sps, out Pps pps) + { + return SliceHeader.Parse(reader, nal, sequences, pictures, out sps, out pps); + } + + /// A slice whose header is read: the picture it belongs to, then its macroblocks. + private void DecodeParsedSlice(NalUnit nal, RbspReader reader, SliceHeader header, Sps sps, Pps pps) + { + if (cur is null || picHeader is null || StartsNewPicture(header, nal) || FirstMacroblockDone(header, sps)) + { + FinishPicture(); + StartPicture(nal, header, sps); + } + + if (picSkipped) + { + return; + } + + if (separatePlanes) + { + SelectColourPlane(header.ColourPlaneId); + } + + if (!header.IsIntra && !HasReference()) + { + // A P or B slice without any picture to predict from: decoding started away from a random access point + // (a missing index, a damaged stream). Predicting from nothing would give a corrupt frame. + throw new H264Exception("Slice P o B senza immagini di riferimento."); + } + + DecodeSliceData(reader, nal, header, sps, pps); + } + + /// The first slice of a new primary picture (§7.4.1.2.4), compared with the first slice of the current one. + private bool StartsNewPicture(SliceHeader h, NalUnit nal) + { + var p = picHeader!; + if (h.FrameNum != p.FrameNum || h.PpsId != p.PpsId || h.FieldPic != p.FieldPic || h.BottomField != p.BottomField + || (nal.RefIdc == 0) != (picRefIdc == 0) || (nal.Type == 5) != (picNalType == 5) || (nal.Type == 5 && h.IdrPicId != p.IdrPicId)) + { + return true; + } + + return activeSps!.PocType switch + { + 0 => h.PocLsb != p.PocLsb || h.DeltaPocBottom != p.DeltaPocBottom, + 1 => h.DeltaPoc0 != p.DeltaPoc0 || h.DeltaPoc1 != p.DeltaPoc1, + _ => false, + }; + } + + /// A slice starting on a macroblock already decoded: the previous picture lost its end, this is a new one. + private bool FirstMacroblockDone(SliceHeader h, Sps sps) + { + if (!ReferenceEquals(sps, activeSps) || mbSlice.Length != sps.WidthInMbs * sps.HeightInMbs) + { + return false; + } + + // Colour planes coded separately: the macroblocks of the plane of the slice. + var slices = separatePlanes ? planeStates[h.ColourPlaneId].Slice : mbSlice; + + var w = sps.WidthInMbs; + int index; + if (h.FieldPic) + { + index = (((2 * (h.FirstMb / w)) + (h.BottomField ? 1 : 0)) * w) + (h.FirstMb % w); + } + else if (sps.MbAdaptiveFrameField) + { + index = (2 * (h.FirstMb / w) * w) + (h.FirstMb % w); + } + else + { + index = h.FirstMb; + } + + return (uint)index < (uint)slices.Length && slices[index] >= 0; + } + + /// Whether a picture other than the one being decoded can be predicted from. + private bool HasReference() + { + if (root is not null && HasInterViewReference()) + { + return true; + } + + foreach (var p in dpb) + { + if (!ReferenceEquals(p, cur)) + { + if (p.IsReference) + { + return true; + } + } + else if (curStructure != 0 && ((p.ShortMask | p.LongMask) & (3 - curStructure)) != 0) + { + return true; // the first field of the frame + } + } + + return false; + } + + private void StartPicture(NalUnit nal, SliceHeader header, Sps sps) + { + if (activeSps is null || !ReferenceEquals(activeSps, sps)) + { + if (activeSps is null || !SameLayout(activeSps, sps)) + { + if (openField is { } waiting && activeSps is not null) + { + openField = null; + HandOut(waiting, activeSps); + } + + dpb.Clear(); + pool.Clear(); + AllocateMacroblockState(sps.WidthInMbs, sps.HeightInMbs, sps.SeparateColourPlane ? 3 : 1); + } + + activeSps = sps; + ConfigureFormat(sps); + } + + var idr = nal.Type == 5; + var structure = header.Structure; + + // The second field of a frame (§3.30, §3.31): the field after a first field of the opposite parity, with the same + // frame_num, both reference fields or both not, and not an IDR picture (which would release the first one). + curSecondField = false; + if (openField is { } first) + { + openField = null; + if (structure != 0 && structure != openStructure && header.FrameNum == first.FrameNum && !idr + && (nal.RefIdc != 0) == (openRefIdc != 0)) + { + cur = first; + curSecondField = true; + } + else + { + HandOut(first, sps); + } + } + + if (!curSecondField) + { + if (idr) + { + period++; + } + else if (haveReference && header.FrameNum != prevRefFrameNum && header.FrameNum != (prevRefFrameNum + 1) % sps.MaxFrameNum) + { + FillFrameNumGap(header.FrameNum, sps); + } + + cur = NewPicture(sps); + cur.FrameNum = header.FrameNum; + cur.Period = period; + cur.DecodeIndex = decodeCounter; + cur.CodedAsFields = structure != 0; + cur.Decoded = 0; + cur.Skipped = false; + } + + var picture = cur!; + NoteViewComponent(picture); + picDqId = 0; + picSvcStopped = false; + + curStructure = structure; + picHeader = header; + picNalType = nal.Type; + picRefIdc = nal.RefIdc; + picMmco5 = header.Mmco.Exists(m => m.Op == 5); + ComputePoc(picture, header, nal, sps, idr, structure); + picture.Decoded |= structure == 0 ? 3 : structure; + sliceCounter = 0; + sliceFilters.Clear(); + sliceSwitching.Clear(); + anySwitching = false; + foreach (var state in planeStates) + { + Array.Fill(state.Slice, -1); + } + + // A picture nobody refers to and nobody wants: its header has set the state above, its slices are not decoded. + picSkipped = nal.RefIdc == 0 && !NeededByOtherViews && Wanted is { } wanted && !wanted(picture.DecodeIndex); + if (picSkipped) + { + picture.Skipped = true; + } + } + + private Picture NewPicture(Sps sps) + { + while (pool.Count > 0) + { + var p = pool.Pop(); + if (p.Fits(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps)) && !p.InDpb && !ReferenceEquals(p, openField)) + { + p.ShortMask = p.LongMask = 0; + p.NonExisting = false; + p.ClearReferences(); + return p; + } + } + + return new Picture(sps.WidthInMbs, sps.HeightInMbs, sps.ChromaFormatIdc, BytesPerSample, PlaneCount(sps)); + } + + private int BytesPerSample => wide ? 2 : 1; + + private static int PlaneCount(Sps sps) => sps.SeparateColourPlane ? 3 : 1; + + /// Two sequences whose pictures and macroblock data have the same shape: size, chroma format, sample size. + private static bool SameLayout(Sps a, Sps b) => + a.WidthInMbs == b.WidthInMbs && a.HeightInMbs == b.HeightInMbs && a.ChromaFormatIdc == b.ChromaFormatIdc + && a.SeparateColourPlane == b.SeparateColourPlane && SampleBytes(a) == SampleBytes(b); + + /// Bytes of each stored sample of a sequence: 2 when luma, or chroma if present, has more than 8 bits. + private static int SampleBytes(Sps s) => + s.BitDepthLuma > 8 || (s.ChromaFormatIdc != 0 && !s.SeparateColourPlane && s.BitDepthChroma > 8) ? 2 : 1; + + /// Picture order count (§8.2.1) of the picture starting now, into the fields of it codes. + private void ComputePoc(Picture p, SliceHeader h, NalUnit nal, Sps sps, bool idr, int structure) + { + int top, bottom; + switch (sps.PocType) + { + case 0: + { + if (idr) + { + prevPocMsb = 0; + prevPocLsb = 0; + } + + var max = 1 << sps.Log2MaxPocLsb; + if (h.PocLsb < prevPocLsb && prevPocLsb - h.PocLsb >= max / 2) + { + pocMsb = prevPocMsb + max; + } + else if (h.PocLsb > prevPocLsb && h.PocLsb - prevPocLsb > max / 2) + { + pocMsb = prevPocMsb - max; + } + else + { + pocMsb = prevPocMsb; + } + + top = bottom = pocMsb + h.PocLsb; + if (structure == 0) + { + bottom = top + h.DeltaPocBottom; + } + + break; + } + + case 1: + { + UpdateFrameNumOffset(h, sps, idr); + var cycle = sps.OffsetForRefFrame.Length; + var absFrameNum = cycle != 0 ? frameNumOffset + h.FrameNum : 0; + if (nal.RefIdc == 0 && absFrameNum > 0) + { + absFrameNum--; + } + + var expected = 0; + if (absFrameNum > 0) + { + var delta = 0; + foreach (var o in sps.OffsetForRefFrame) + { + delta += o; + } + + var cycleCount = (absFrameNum - 1) / cycle; + var inCycle = (absFrameNum - 1) % cycle; + expected = cycleCount * delta; + for (var i = 0; i <= inCycle; i++) + { + expected += sps.OffsetForRefFrame[i]; + } + } + + if (nal.RefIdc == 0) + { + expected += sps.OffsetForNonRefPic; + } + + if (structure == 0) + { + top = expected + h.DeltaPoc0; + bottom = top + sps.OffsetForTopToBottomField + h.DeltaPoc1; + } + else + { + top = expected + h.DeltaPoc0; + bottom = expected + sps.OffsetForTopToBottomField + h.DeltaPoc0; + } + + break; + } + + default: + { + UpdateFrameNumOffset(h, sps, idr); + top = bottom = idr ? 0 : nal.RefIdc == 0 ? (2 * (frameNumOffset + h.FrameNum)) - 1 : 2 * (frameNumOffset + h.FrameNum); + break; + } + } + + if (structure != 2) + { + p.TopPoc = top; + } + + if (structure != 1) + { + p.BottomPoc = bottom; + } + } + + private void UpdateFrameNumOffset(SliceHeader h, Sps sps, bool idr) + { + if (idr) + { + frameNumOffset = 0; + } + else if (prevFrameNum > h.FrameNum) + { + frameNumOffset = prevFrameNumOffset + sps.MaxFrameNum; + } + else + { + frameNumOffset = prevFrameNumOffset; + } + } + + /// + /// Frames inferred for a gap in frame_num (§8.2.5.2): only their marking matters, and their frame number offset + /// (§8.2.1), which carries the wraps of frame_num to the pictures after the gap. Of a gap longer than the buffer only + /// the last frames can stay references: the earlier ones are counted, never allocated. + /// + private void FillFrameNumGap(int frameNum, Sps sps) + { + var max = sps.MaxFrameNum; + var missing = ((frameNum - prevRefFrameNum - 1) % max + max) % max; + var keep = Math.Max(1, sps.MaxNumRefFrames); + if (missing > keep) + { + foreach (var p in dpb) + { + p.ShortMask = 0; + } + } + + var skipped = missing - keep; + var i = 0; + for (var n = (prevRefFrameNum + 1) % max; n != frameNum; n = (n + 1) % max, i++) + { + if (sps.PocType != 0) + { + // UpdateFrameNumOffset for the inferred frame n (never an IDR picture). + frameNumOffset = prevFrameNum > n ? prevFrameNumOffset + max : prevFrameNumOffset; + prevFrameNumOffset = frameNumOffset; + } + + prevRefFrameNum = n; + prevFrameNum = n; + if (i < skipped) + { + continue; + } + + var gap = NewPicture(sps); + gap.FrameNum = n; + gap.NonExisting = true; + gap.Period = period; + gap.TopPoc = gap.BottomPoc = 0; + gap.Decoded = 3; + gap.CodedAsFields = false; + gap.MarkAsGap(); + SlidingWindow(sps, n, null); + gap.ShortMask = 3; + AddToDpb(gap); + } + + PruneDpb(); + } + + private void CompletePicture() + { + if (cur is null || picHeader is null || activeSps is null) + { + return; + } + + var sps = activeSps; + var picture = cur; + var structure = curStructure; + var skipped = picSkipped; + picSkipped = false; + if (!skipped) + { + Deblock(picture); + } + + if (picRefIdc != 0) + { + MarkReferences(picture, sps); + } + + // State for the next picture. + if (picMmco5) + { + // After a memory_management_control_operation 5 the picture counts as frame_num 0 with its order count + // brought to 0 (tempPicOrderCnt of §8.2.1). + var temp = structure == 1 ? picture.TopPoc : structure == 2 ? picture.BottomPoc : Math.Min(picture.TopPoc, picture.BottomPoc); + if (structure != 2) + { + picture.TopPoc -= temp; + } + + if (structure != 1) + { + picture.BottomPoc -= temp; + } + + prevPocMsb = 0; + prevPocLsb = structure == 2 ? 0 : picture.TopPoc; + prevFrameNum = 0; + prevFrameNumOffset = 0; + picture.FrameNum = 0; + } + else + { + if (picRefIdc != 0) + { + prevPocMsb = pocMsb; + prevPocLsb = picHeader.PocLsb; + } + + prevFrameNum = picture.FrameNum; + prevFrameNumOffset = frameNumOffset; + } + + if (picRefIdc != 0) + { + prevRefFrameNum = picture.FrameNum; + haveReference = true; + } + + cur = null; + picHeader = null; + if (structure != 0 && !curSecondField) + { + // A first field: the frame comes out with its second field. + openField = picture; + openStructure = structure; + openRefIdc = picRefIdc; + } + else + { + HandOut(picture, sps); + } + + curSecondField = false; + PruneDpb(); + } + + /// Hands out a finished frame (or a field left without its pair) and counts it. + private void HandOut(Picture picture, Sps sps) + { + if (!picture.Skipped && (Wanted?.Invoke(picture.DecodeIndex) ?? true)) + { + FrameDecoded?.Invoke(Crop(picture, sps, viewId)); + } + + decodeCounter++; + if (!picture.IsReference && !picture.InDpb) + { + pool.Push(picture); + } + } + + /// + /// The frame of a picture, cropped (§7.4.2.1.1, CropUnitX and CropUnitY). A monochrome frame gets chroma planes of + /// 4:2:0 size at the middle value, the rows of a field without its pair the middle value too, as the reference + /// decoder writes them; colour planes coded separately come out as 4:4:4 with the luma bit depth. + /// + private static H264Frame Crop(Picture p, Sps sps, int viewId) + { + var bps = p.BytesPerSample; + var format = sps.ChromaFormatIdc; + var bitDepthY = sps.BitDepthLuma; + var bitDepthC = format == 0 || sps.SeparateColourPlane ? bitDepthY : sps.BitDepthChroma; + int unitX = sps.CropUnitX, unitY = sps.CropUnitY; + var left = sps.CropLeft * unitX; + var top = sps.CropTop * unitY; + var width = Math.Max(2, p.Width - left - (sps.CropRight * unitX)); + var height = Math.Max(2, p.Height - top - (sps.CropBottom * unitY)); + var y = CopyRect(p.Y, p.Width, left, top, width, height, bps); + + byte[] cb, cr; + int ch, chromaTop; + if (format == 0) + { + int cw = (width + 1) / 2; + ch = (height + 1) / 2; + chromaTop = 0; + cb = new byte[cw * ch * bps]; + FillMiddle(cb, bps, bitDepthC); + cr = (byte[])cb.Clone(); + } + else + { + int subW = sps.SubWidthC, subH = sps.SubHeightC; + var cw = (width + subW - 1) / subW; + ch = (height + subH - 1) / subH; + chromaTop = top / subH; + cb = CopyRect(p.Cb, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps); + cr = CopyRect(p.Cr, p.ChromaWidth, left / subW, chromaTop, cw, ch, bps); + } + + if (p.Decoded != 3) + { + // A field without its pair: the rows of the missing field are grey (the middle value), since the stream has none + // for them and the decoder does not invent any; H.264 leaves the output of an unpaired field open. + var missing = p.Decoded == 1 ? 1 : 0; + var rowY = width * bps; + for (var r = 0; r < height; r++) + { + if (((top + r) & 1) == missing) + { + FillMiddle(y.AsSpan(r * rowY, rowY), bps, bitDepthY); + } + } + + if (format != 0) + { + var rowC = cb.Length / ch; + for (var r = 0; r < ch; r++) + { + if (((chromaTop + r) & 1) == missing) + { + FillMiddle(cb.AsSpan(r * rowC, rowC), bps, bitDepthC); + FillMiddle(cr.AsSpan(r * rowC, rowC), bps, bitDepthC); + } + } + } + } + + return new H264Frame(width, height, y, cb, cr, p.Poc, p.Period, p.DecodeIndex, sps.MatrixCoefficients, sps.FullRange, format, bitDepthY, bitDepthC, viewId); + } + + /// A × rectangle of a plane samples wide. + private static byte[] CopyRect(byte[] plane, int stride, int left, int top, int width, int height, int bps) + { + var result = new byte[width * height * bps]; + for (var r = 0; r < height; r++) + { + Array.Copy(plane, (((top + r) * stride) + left) * bps, result, r * width * bps, width * bps); + } + + return result; + } + + /// Samples at the middle value 2^(bitDepth − 1). + private static void FillMiddle(Span samples, int bps, int bitDepth) + { + if (bps == 1) + { + samples.Fill((byte)(1 << (bitDepth - 1))); + } + else + { + System.Runtime.InteropServices.MemoryMarshal.Cast(samples).Fill((ushort)(1 << (bitDepth - 1))); + } + } + + private void AddToDpb(Picture p) + { + if (!p.InDpb) + { + p.InDpb = true; + dpb.Add(p); + } + } + + /// The bit of a field in the masks of : 1 top, 2 bottom, 3 the frame. + private static int FieldBit(int structure) => structure == 0 ? 3 : structure; + + /// Decoded reference picture marking (§8.2.5) of the picture (frame or field) just decoded. + private void MarkReferences(Picture picture, Sps sps) + { + var h = picHeader!; + var bit = FieldBit(curStructure); + if (picNalType == 5) + { + foreach (var p in dpb) + { + if (!ReferenceEquals(p, picture)) + { + p.ShortMask = p.LongMask = 0; + } + } + + if (h.LongTermReference) + { + picture.LongMask |= bit; + picture.LongTermFrameIdx = 0; + maxLongTermFrameIdx = 0; + } + else + { + picture.ShortMask |= bit; + maxLongTermFrameIdx = -1; + } + + AddToDpb(picture); + return; + } + + var becameLongTerm = false; + if (h.AdaptiveMarking) + { + becameLongTerm = ApplyMmco(picture, h, sps, bit); + if (picMmco5) + { + period++; + picture.Period = period; + } + } + else if (!(curSecondField && (picture.ShortMask & (3 - bit)) != 0)) + { + // The second field of a pair whose first field is a short-term reference joins it without the sliding window. + SlidingWindow(sps, picture.FrameNum, picture); + } + + if (!becameLongTerm) + { + picture.ShortMask |= bit; + } + + AddToDpb(picture); + LimitReferences(picture, sps); + } + + /// The memory management control operations of the picture (§8.2.5.4); true when it became long-term. + private bool ApplyMmco(Picture picture, SliceHeader h, Sps sps, int bit) + { + var field = curStructure != 0; + var parity = curStructure == 2 ? 1 : 0; + var currPicNum = field ? (2 * h.FrameNum) + 1 : h.FrameNum; + var becameLongTerm = false; + UpdateFrameNumWrap(h.FrameNum, sps); + foreach (var (op, a, b) in h.Mmco) + { + switch (op) + { + case 1: + { + var picNumX = currPicNum - (a + 1); + if (FindShortTerm(picNumX, field, parity, out var p, out var q)) + { + p.ShortMask &= ~q; + } + + break; + } + + case 2: + if (FindLongTerm(a, field, parity, out var lp, out var lq)) + { + lp.LongMask &= ~lq; + } + + break; + case 3: + { + var picNumX = currPicNum - (a + 1); + if (!FindShortTerm(picNumX, field, parity, out var p, out var q)) + { + break; + } + + // LongTermFrameIdx b goes to this picture: any other frame or field holding it is released, unless + // it is the other field of the same frame. + foreach (var other in dpb) + { + if (other.LongMask != 0 && other.LongTermFrameIdx == b && !ReferenceEquals(other, p)) + { + other.LongMask = 0; + } + } + + if (p.LongMask != 0 && p.LongTermFrameIdx != b) + { + p.LongMask = 0; + } + + p.ShortMask &= ~q; + p.LongMask |= q; + p.LongTermFrameIdx = b; + break; + } + + case 4: + maxLongTermFrameIdx = a - 1; + foreach (var p in dpb) + { + if (p.LongMask != 0 && p.LongTermFrameIdx > maxLongTermFrameIdx) + { + p.LongMask = 0; + } + } + + break; + case 5: + foreach (var p in dpb) + { + if (!ReferenceEquals(p, picture)) + { + p.ShortMask = p.LongMask = 0; + } + } + + // The first field of the frame, too: after this operation nothing before the picture is a reference. + picture.ShortMask = picture.LongMask = 0; + maxLongTermFrameIdx = -1; + break; + case 6: + foreach (var p in dpb) + { + if (p.LongMask != 0 && p.LongTermFrameIdx == b && !ReferenceEquals(p, picture)) + { + p.LongMask = 0; + } + } + + if (picture.LongMask != 0 && picture.LongTermFrameIdx != b) + { + picture.LongMask = 0; + } + + picture.LongMask |= bit; + picture.LongTermFrameIdx = b; + becameLongTerm = true; + break; + } + } + + return becameLongTerm; + } + + /// The short-term frame (or field) whose PicNum is (§8.2.4.1); q is its mask bit. + private bool FindShortTerm(int picNum, bool field, int parity, out Picture p, out int q) + { + foreach (var candidate in dpb) + { + if (!field) + { + if (candidate.ShortMask == 3 && candidate.FrameNumWrap == picNum) + { + (p, q) = (candidate, 3); + return true; + } + + continue; + } + + for (var f = 0; f < 2; f++) + { + if ((candidate.ShortMask & (1 << f)) != 0 && (2 * candidate.FrameNumWrap) + (f == parity ? 1 : 0) == picNum) + { + (p, q) = (candidate, 1 << f); + return true; + } + } + } + + (p, q) = (null!, 0); + return false; + } + + /// The long-term frame (or field) whose LongTermPicNum is . + private bool FindLongTerm(int longTermPicNum, bool field, int parity, out Picture p, out int q) + { + foreach (var candidate in dpb) + { + if (!field) + { + if (candidate.LongMask == 3 && candidate.LongTermFrameIdx == longTermPicNum) + { + (p, q) = (candidate, 3); + return true; + } + + continue; + } + + for (var f = 0; f < 2; f++) + { + if ((candidate.LongMask & (1 << f)) != 0 && (2 * candidate.LongTermFrameIdx) + (f == parity ? 1 : 0) == longTermPicNum) + { + (p, q) = (candidate, 1 << f); + return true; + } + } + } + + (p, q) = (null!, 0); + return false; + } + + /// + /// A stream may never keep more than Max(max_num_ref_frames, 1) reference frames (§8.2.5.4 and §7.4.2.1.1); a damaged + /// one whose marking operations never release any would make the buffer grow with every picture. Here the oldest + /// references beyond the limit are released, as the sliding window would. + /// + private void LimitReferences(Picture current, Sps sps) + { + var limit = Math.Max(1, sps.MaxNumRefFrames); + while (true) + { + var count = 0; + Picture? oldestShort = null, oldestLong = null; + foreach (var p in dpb) + { + if (!p.IsReference) + { + continue; + } + + count++; + if (ReferenceEquals(p, current)) + { + continue; + } + + if (p.ShortMask != 0 && (oldestShort is null || p.FrameNumWrap < oldestShort.FrameNumWrap)) + { + oldestShort = p; + } + else if (p.ShortMask == 0 && (oldestLong is null || p.LongTermFrameIdx < oldestLong.LongTermFrameIdx)) + { + oldestLong = p; + } + } + + if (count <= limit || (oldestShort ?? oldestLong) is not { } victim) + { + return; + } + + victim.ShortMask = victim.LongMask = 0; + } + } + + /// + /// Sliding window marking (§8.2.5.3) before a new short-term picture is added: frames, field pairs and single fields + /// count as one each; the frame store of the current picture () is not removed. + /// + private void SlidingWindow(Sps sps, int frameNum, Picture? current) + { + UpdateFrameNumWrap(frameNum, sps); + var limit = Math.Max(1, sps.MaxNumRefFrames); + while (true) + { + int shortCount = 0, longCount = 0; + Picture? oldest = null; + foreach (var p in dpb) + { + if (p.ShortMask != 0) + { + shortCount++; + if (!ReferenceEquals(p, current) && (oldest is null || p.FrameNumWrap < oldest.FrameNumWrap)) + { + oldest = p; + } + } + else if (p.LongMask != 0) + { + longCount++; + } + } + + if (shortCount + longCount < limit || oldest is null) + { + return; + } + + oldest.ShortMask = 0; + } + } + + private void UpdateFrameNumWrap(int frameNum, Sps sps) + { + foreach (var p in dpb) + { + if (p.ShortMask != 0) + { + p.FrameNumWrap = p.FrameNum > frameNum ? p.FrameNum - sps.MaxFrameNum : p.FrameNum; + } + } + } + + /// Drops the pictures no longer used for reference from the buffer (they are already handed out). + private void PruneDpb() + { + for (var i = dpb.Count - 1; i >= 0; i--) + { + var p = dpb[i]; + if (!p.IsReference && !ReferenceEquals(p, cur) && !ReferenceEquals(p, openField)) + { + dpb.RemoveAt(i); + p.InDpb = false; + pool.Push(p); + } + } + } + + /// Reference picture lists of the slice (§8.2.4): initialisation, then modification. + private void BuildReferenceLists(SliceHeader h, Sps sps) + { + UpdateFrameNumWrap(h.FrameNum, sps); + if (curStructure == 0) + { + BuildFrameLists(h, sps); + } + else + { + BuildFieldLists(h, sps); + } + } + + private void BuildFrameLists(SliceHeader h, Sps sps) + { + var picture = cur!; + var shortTerm = new List(); + var longTerm = new List(); + foreach (var p in dpb) + { + if (ReferenceEquals(p, picture)) + { + continue; + } + + if (p.ShortTerm) + { + shortTerm.Add(p); + } + else if (p.LongTerm) + { + longTerm.Add(p); + } + } + + longTerm.Sort((a, b) => a.LongTermPicNum.CompareTo(b.LongTermPicNum)); + List init0 = [], init1 = []; + if (h.IsP) + { + shortTerm.Sort((a, b) => b.PicNum.CompareTo(a.PicNum)); + foreach (var p in shortTerm) + { + init0.Add(new RefEntry(p, -1)); + } + + foreach (var p in longTerm) + { + init0.Add(new RefEntry(p, -1)); + } + } + else + { + var poc = picture.Poc; + var before = shortTerm.FindAll(p => p.Poc < poc); + var after = shortTerm.FindAll(p => p.Poc > poc); + before.Sort((a, b) => b.Poc.CompareTo(a.Poc)); + after.Sort((a, b) => a.Poc.CompareTo(b.Poc)); + foreach (var p in (List)[.. before, .. after, .. longTerm]) + { + init0.Add(new RefEntry(p, -1)); + } + + foreach (var p in (List)[.. after, .. before, .. longTerm]) + { + init1.Add(new RefEntry(p, -1)); + } + + SwapIfSame(init0, init1); + } + + AppendInterView(init0, 0); + refList[0] = Modify(init0, 0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps); + if (h.IsB) + { + AppendInterView(init1, 1); + } + + refList[1] = h.IsB ? Modify(init1, 1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : []; + } + + /// Lists of a field picture (§8.2.4.2.2, §8.2.4.2.4 and §8.2.4.2.5): frames ordered, then their fields alternated. + private void BuildFieldLists(SliceHeader h, Sps sps) + { + var parity = curStructure == 2 ? 1 : 0; + var picture = cur!; + var shortTerm = new List(); + var longTerm = new List(); + foreach (var p in dpb) + { + if (p.ShortMask != 0) + { + shortTerm.Add(p); + } + else if (p.LongMask != 0) + { + longTerm.Add(p); + } + } + + longTerm.Sort((a, b) => a.LongTermFrameIdx.CompareTo(b.LongTermFrameIdx)); + List init0 = [], init1 = []; + if (h.IsP) + { + shortTerm.Sort((a, b) => b.FrameNumWrap.CompareTo(a.FrameNumWrap)); + Alternate(shortTerm, parity, longTerm: false, init0); + Alternate(longTerm, parity, longTerm: true, init0); + } + else + { + var poc = picture.PocOf(parity); + var before = shortTerm.FindAll(p => ShortTermPoc(p) <= poc); + var after = shortTerm.FindAll(p => ShortTermPoc(p) > poc); + before.Sort((a, b) => ShortTermPoc(b).CompareTo(ShortTermPoc(a))); + after.Sort((a, b) => ShortTermPoc(a).CompareTo(ShortTermPoc(b))); + Alternate([.. before, .. after], parity, longTerm: false, init0); + Alternate(longTerm, parity, longTerm: true, init0); + Alternate([.. after, .. before], parity, longTerm: false, init1); + Alternate(longTerm, parity, longTerm: true, init1); + SwapIfSame(init0, init1); + } + + AppendInterView(init0, 0); + refList[0] = Modify(init0, 0, h.NumRefIdxActiveL0, h.Modifications[0], h, sps); + if (h.IsB) + { + AppendInterView(init1, 1); + } + + refList[1] = h.IsB ? Modify(init1, 1, h.NumRefIdxActiveL1, h.Modifications[1], h, sps) : []; + } + + /// PicOrderCnt of a frame entry for the field lists: the smaller of its fields marked short-term. + private static int ShortTermPoc(Picture p) => p.ShortMask switch + { + 1 => p.TopPoc, + 2 => p.BottomPoc, + _ => Math.Min(p.TopPoc, p.BottomPoc), + }; + + /// + /// §8.2.4.2.5: fields taken from the ordered frames alternately, starting with the parity of the current field; the + /// fields not marked (short-term or long-term, as the list) are skipped, and when one parity runs out the rest of + /// the other follows in order. + /// + private static void Alternate(List frames, int parity, bool longTerm, List output) + { + int same = 0, opposite = 0, n = frames.Count; + int sameBit = 1 << parity, oppositeBit = 1 << (1 - parity); + while (same < n || opposite < n) + { + while (same < n && ((longTerm ? frames[same].LongMask : frames[same].ShortMask) & sameBit) == 0) + { + same++; + } + + while (opposite < n && ((longTerm ? frames[opposite].LongMask : frames[opposite].ShortMask) & oppositeBit) == 0) + { + opposite++; + } + + if (same < n) + { + output.Add(new RefEntry(frames[same++], parity)); + } + + if (opposite < n) + { + output.Add(new RefEntry(frames[opposite++], 1 - parity)); + } + } + } + + /// When list 1 has more than one entry and equals list 0, its first two entries are switched (§8.2.4.2.3). + private static void SwapIfSame(List init0, List init1) + { + if (init1.Count > 1 && init0.Count == init1.Count) + { + for (var i = 0; i < init0.Count; i++) + { + if (!ReferenceEquals(init0[i].Pic, init1[i].Pic) || init0[i].Parity != init1[i].Parity) + { + return; + } + } + + (init1[0], init1[1]) = (init1[1], init1[0]); + } + } + + /// + /// The modification of list (§8.2.4.3), for frames or fields; in a non-base view also + /// with the inter-view references (§H.8.2.2.3). + /// + private RefEntry[] Modify(List initial, int listIndex, int count, List<(int Idc, int Value)> modifications, SliceHeader h, Sps sps) + { + var list = new RefEntry[count + 1]; + for (var i = 0; i < count && i < initial.Count; i++) + { + list[i] = initial[i]; + } + + var field = curStructure != 0; + var parity = curStructure == 2 ? 1 : 0; + var maxPicNum = field ? 2 * sps.MaxFrameNum : sps.MaxFrameNum; + var currPicNum = field ? (2 * h.FrameNum) + 1 : h.FrameNum; + var pred = currPicNum; + var viewPred = -1; + var refIdx = 0; + foreach (var (idc, value) in modifications) + { + if (refIdx >= count) + { + break; + } + + RefEntry found = default; + if (idc is 0 or 1) + { + var abs = value + 1; + int noWrap; + if (idc == 0) + { + noWrap = pred - abs < 0 ? pred - abs + maxPicNum : pred - abs; + } + else + { + noWrap = pred + abs >= maxPicNum ? pred + abs - maxPicNum : pred + abs; + } + + pred = noWrap; + var picNum = noWrap > currPicNum ? noWrap - maxPicNum : noWrap; + if (FindShortTerm(picNum, field, parity, out var p, out var q) && !(ReferenceEquals(p, cur) && q == FieldBit(curStructure))) + { + found = new RefEntry(p, field ? q - 1 : -1); + } + } + else if (idc is 4 or 5) + { + found = ModifiedInterView(listIndex, idc, value, ref viewPred); + } + else if (FindLongTerm(value, field, parity, out var p, out var q) && !(ReferenceEquals(p, cur) && q == FieldBit(curStructure))) + { + found = new RefEntry(p, field ? q - 1 : -1); + } + + for (var c = count; c > refIdx; c--) + { + list[c] = list[c - 1]; + } + + list[refIdx++] = found; + var n = refIdx; + for (var c = refIdx; c <= count; c++) + { + if (found.Pic is null || !ReferenceEquals(list[c].Pic, found.Pic) || list[c].Parity != found.Parity) + { + list[n++] = list[c]; + } + } + } + + Array.Resize(ref list, count); + return list; + } +} diff --git a/src/Febe.Core/Codecs/H264/H264StreamInfo.cs b/src/Febe.Core/Codecs/H264/H264StreamInfo.cs new file mode 100644 index 0000000..bc69cf0 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264StreamInfo.cs @@ -0,0 +1,92 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.H264; + +/// +/// What the sequence parameter set of an H.264 stream says without decoding it: the size of the pictures shown, after +/// the cropping of §7.4.2.1.1. Used by the container readers whose headers do not carry the size (FLV without +/// metadata, MPEG program streams). +/// +public static class H264StreamInfo +{ + /// The picture size of an SPS NAL unit (header byte included); false when it is not an SPS or is damaged. + public static bool TryPictureSize(ReadOnlySpan nal, out int width, out int height) + { + width = height = 0; + if (nal.Length < 4 || (nal[0] & 0x9F) != 7 || nal[1] is not (44 or 66 or 77 or 83 or 86 or 88 or 100 or 110 or 118 or 122 + or 128 or 134 or 135 or 138 or 139 or 144 or 244)) + { + return false; // forbidden_zero_bit set, not nal_unit_type 7, or a profile_idc no profile of Annex A has + } + + try + { + var sps = Sps.Parse(NalUnits.Parse(nal).Reader()); + var w = (sps.WidthInMbs * 16) - (sps.CropUnitX * (sps.CropLeft + sps.CropRight)); + var h = (sps.HeightInMbs * 16) - (sps.CropUnitY * (sps.CropTop + sps.CropBottom)); + if (w <= 0 || h <= 0) + { + return false; + } + + (width, height) = (w, h); + return true; + } + catch (Exception ex) when (ex is H264Exception or IndexOutOfRangeException or ArgumentException or OverflowException) + { + return false; + } + } + + /// + /// The picture size of the first SPS of an AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3.1), as FLV and MP4 + /// carry it. + /// + public static bool TryPictureSizeFromConfiguration(ReadOnlySpan avcC, out int width, out int height) + { + width = height = 0; + if (avcC.Length < 8 || avcC[0] != 1 || (avcC[5] & 0x1F) == 0) + { + return false; + } + + var length = BinaryPrimitives.ReadUInt16BigEndian(avcC[6..]); + return 8 + length <= avcC.Length && TryPictureSize(avcC.Slice(8, length), out width, out height); + } + + /// + /// The picture size of the first whole SPS of an Annex B byte stream; an SPS that the end of + /// cuts counts only when says nothing follows. + /// + public static bool TryPictureSizeFromAnnexB(ReadOnlySpan stream, bool complete, out int width, out int height) + { + width = height = 0; + ReadOnlySpan startCode = [0, 0, 1]; + var found = stream.IndexOf(startCode); + while (found >= 0) + { + var start = found + 3; + var next = stream[start..].IndexOf(startCode); + if (next < 0 && !complete) + { + return false; // the last unit may be cut short + } + + var end = next < 0 ? stream.Length : start + next; + var nal = stream[start..end]; + while (nal.Length > 0 && nal[^1] == 0) + { + nal = nal[..^1]; // the zero byte of a four-byte start code belongs to the next unit + } + + if (nal.Length > 0 && (nal[0] & 0x1F) == 7 && TryPictureSize(nal, out width, out height)) + { + return true; + } + + found = next < 0 ? -1 : end; + } + + return false; + } +} diff --git a/src/Febe.Core/Codecs/H264/H264Tables.cs b/src/Febe.Core/Codecs/H264/H264Tables.cs new file mode 100644 index 0000000..0a92440 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/H264Tables.cs @@ -0,0 +1,178 @@ +namespace Febe.Core.Codecs.H264; + +/// Fixed tables of ITU-T H.264 other than the variable-length codes and the CABAC contexts. +internal static class H264Tables +{ + /// Zig-zag scan of 4×4 frame blocks: scan index → raster position (row * 4 + column). + internal static readonly byte[] ZigZag4x4 = BuildZigZag(4); + + /// Zig-zag scan of 8×8 frame blocks: scan index → raster position (row * 8 + column). + internal static readonly byte[] ZigZag8x8 = BuildZigZag(8); + + /// Field scan of 4×4 blocks (table 8-13): scan index → raster position (row * 4 + column). + internal static readonly byte[] FieldScan4x4 = [0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15]; + + /// Field scan of 8×8 blocks (table 8-14): scan index → raster position (row * 8 + column). + internal static readonly byte[] FieldScan8x8 = + [ + 0, 8, 16, 1, 9, 24, 32, 17, 2, 25, 40, 48, 56, 33, 10, 3, 18, 41, 49, 57, 26, 11, 4, 19, 34, 42, 50, 58, 27, 12, 5, 20, + 35, 43, 51, 59, 28, 13, 6, 21, 36, 44, 52, 60, 29, 14, 22, 37, 45, 53, 61, 30, 7, 15, 38, 46, 54, 62, 23, 31, 39, 47, 55, 63, + ]; + + /// luma4x4BlkIdx → raster index of the 4×4 block in the macroblock ((y / 4) * 4 + x / 4). + internal static readonly byte[] BlockToRaster = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15]; + + /// Raster index of a 4×4 block → luma4x4BlkIdx. + internal static readonly byte[] RasterToBlock = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15]; + + /// coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum (table 9-4, 4:2:0 and 4:2:2). + internal static readonly byte[] CbpIntra = + [ + 47, 31, 15, 0, 23, 27, 29, 30, 7, 11, 13, 14, 39, 43, 45, 46, 16, 3, 5, 10, 12, 19, 21, 26, 28, 35, 37, 42, 44, 1, 2, 4, + 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, + ]; + + /// coded_block_pattern of inter macroblocks from codeNum (table 9-4). + internal static readonly byte[] CbpInter = + [ + 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, 36, 40, 39, 43, 45, 46, + 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41, + ]; + + /// coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3). + internal static readonly byte[] CbpIntraNoChroma = [15, 0, 7, 11, 13, 14, 3, 5, 10, 12, 1, 2, 4, 8, 6, 9]; + + /// coded_block_pattern of inter macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3). + internal static readonly byte[] CbpInterNoChroma = [0, 1, 2, 4, 8, 3, 5, 10, 12, 15, 7, 11, 13, 14, 6, 9]; + + /// normAdjust4x4 values v[m][0..2] (equation 8-315). + internal static readonly byte[,] NormAdjust4x4 = + { + { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 }, + }; + + /// normAdjust8x8 values v[m][0..5] (equation 8-318). + internal static readonly byte[,] NormAdjust8x8 = + { + { 20, 18, 32, 19, 25, 24 }, { 22, 19, 35, 21, 28, 26 }, { 26, 23, 42, 24, 33, 31 }, + { 28, 25, 45, 26, 35, 33 }, { 32, 28, 51, 30, 40, 38 }, { 36, 32, 58, 34, 46, 43 }, + }; + + /// Default_4x4_Intra in zig-zag order (table 7-3). + internal static readonly byte[] Default4x4Intra = [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42]; + + /// Default_4x4_Inter in zig-zag order (table 7-3). + internal static readonly byte[] Default4x4Inter = [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34]; + + /// Default_8x8_Intra in zig-zag order (table 7-4). + internal static readonly byte[] Default8x8Intra = + [ + 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, + 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42, + ]; + + /// Default_8x8_Inter in zig-zag order (table 7-4). + internal static readonly byte[] Default8x8Inter = + [ + 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 24, 24, 24, 24, + 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35, + ]; + + /// QPc from qPI (table 8-15), for qPI 0..51. + internal static readonly byte[] ChromaQp = + [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39, + ]; + + /// α′ of the deblocking filter (table 8-16), by indexA. + internal static readonly byte[] Alpha = + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28, + 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255, + ]; + + /// β′ of the deblocking filter (table 8-16), by indexB. + internal static readonly byte[] Beta = + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8, + 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, + ]; + + /// tC0′ of the deblocking filter (table 8-17), [indexA * 3 + bS − 1]. + internal static readonly byte[] Tc0 = + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, + 1, 1, 2, 1, 2, 3, 1, 2, 3, 2, 2, 3, 2, 2, 4, 2, 3, 4, 2, 3, 4, 3, 3, 5, 3, 4, 6, 3, 4, 6, 4, 5, 7, 4, 5, 8, 4, 6, 9, + 5, 7, 10, 6, 8, 11, 6, 8, 13, 7, 10, 14, 8, 11, 16, 9, 12, 18, 10, 13, 20, 11, 15, 23, 13, 17, 25, + ]; + + /// ctxIdxInc of significant_coeff_flag for 8×8 frame blocks (table 9-43), by levelListIdx. + internal static readonly byte[] SignificantContext8x8 = + [ + 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7, + 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12, + ]; + + /// ctxIdxInc of significant_coeff_flag for 8×8 field blocks (table 9-43), by levelListIdx. + internal static readonly byte[] SignificantContext8x8Field = + [ + 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 4, 5, 6, 9, 10, 10, 8, 11, 12, 11, 9, 9, 10, 10, 8, 11, 12, 11, + 9, 9, 10, 10, 8, 11, 12, 11, 9, 9, 10, 10, 8, 13, 13, 9, 9, 10, 10, 8, 13, 13, 9, 9, 10, 10, 14, 14, 14, 14, 14, + ]; + + /// ctxIdxInc of last_significant_coeff_flag for 8×8 blocks (table 9-43), by levelListIdx. + internal static readonly byte[] LastContext8x8 = + [ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, + ]; + + private static byte[] BuildZigZag(int size) + { + var scan = new byte[size * size]; + int x = 0, y = 0; + for (var i = 0; i < scan.Length; i++) + { + scan[i] = (byte)((y * size) + x); + if (((x + y) & 1) == 0) + { + // Moving up and to the right. + if (x == size - 1) + { + y++; + } + else if (y == 0) + { + x++; + } + else + { + x++; + y--; + } + } + else + { + // Moving down and to the left. + if (y == size - 1) + { + x++; + } + else if (x == 0) + { + y++; + } + else + { + x--; + y++; + } + } + } + + return scan; + } +} diff --git a/src/Febe.Core/Codecs/H264/InterPrediction.cs b/src/Febe.Core/Codecs/H264/InterPrediction.cs new file mode 100644 index 0000000..c040f99 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/InterPrediction.cs @@ -0,0 +1,240 @@ +using static Febe.Core.Codecs.H264.Samples; + +namespace Febe.Core.Codecs.H264; + +/// +/// Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3), at any bit depth (max is +/// 2^BitDepth − 1). The luma interpolation serves also the Cb and Cr planes of 4:4:4. +/// +internal static class InterPrediction +{ + /// + /// Luma prediction of a × block whose top-left corner, in quarter + /// samples, is (, ), from the × + /// picture whose row y starts at + y × (a frame, or one field of a + /// frame store). Samples outside the picture repeat the edge. + /// + internal static void Luma(ReadOnlySpan plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span dst, int max) + where T : unmanaged + { + int xInt = qx >> 2, yInt = qy >> 2, xFrac = qx & 3, yFrac = qy & 3; + + // Window with two samples before and three after in each direction. + var ww = w + 5; + var wh = h + 5; + Span win = stackalloc int[21 * 21]; + var inside = xInt - 2 >= 0 && yInt - 2 >= 0 && xInt + w + 3 <= pw && yInt + h + 3 <= ph; + for (var r = 0; r < wh; r++) + { + var sy = yInt - 2 + r; + if (!inside) + { + sy = sy < 0 ? 0 : sy >= ph ? ph - 1 : sy; + } + + var rowBase = origin + (sy * stride); + var target = win.Slice(r * ww, ww); + if (inside) + { + var source = plane.Slice(rowBase + xInt - 2, ww); + for (var c = 0; c < ww; c++) + { + target[c] = Get(source[c]); + } + + continue; + } + + for (var c = 0; c < ww; c++) + { + var sx = xInt - 2 + c; + sx = sx < 0 ? 0 : sx >= pw ? pw - 1 : sx; + target[c] = Get(plane[rowBase + sx]); + } + } + + if (xFrac == 0 && yFrac == 0) + { + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + dst[(y * w) + x] = Make(win[((y + 2) * ww) + x + 2]); + } + } + + return; + } + + // Horizontal half samples b (rows 0..h, the extra row is s), vertical half samples h (columns 0..w, the extra + // column is m), centre half samples j. + Span bh = stackalloc int[17 * 16]; + Span vh = stackalloc int[16 * 17]; + Span jc = stackalloc int[16 * 16]; + if (xFrac != 0) + { + for (var y = 0; y <= h && y + 2 < wh; y++) + { + for (var x = 0; x < w; x++) + { + var b = ((y + 2) * ww) + x; + var v = win[b] - (5 * win[b + 1]) + (20 * win[b + 2]) + (20 * win[b + 3]) - (5 * win[b + 4]) + win[b + 5]; + bh[(y * w) + x] = Clip((v + 16) >> 5, max); + } + } + } + + if (yFrac != 0) + { + for (var y = 0; y < h; y++) + { + for (var x = 0; x <= w && x + 2 < ww; x++) + { + var b = (y * ww) + x + 2; + var v = win[b] - (5 * win[b + ww]) + (20 * win[b + (2 * ww)]) + (20 * win[b + (3 * ww)]) - (5 * win[b + (4 * ww)]) + win[b + (5 * ww)]; + vh[(y * (w + 1)) + x] = Clip((v + 16) >> 5, max); + } + } + } + + var needJ = (xFrac == 2 && yFrac != 0) || (yFrac == 2 && xFrac != 0); + if (needJ) + { + // Unrounded horizontal half samples of every window row, then the vertical filter over them. + Span b1 = stackalloc int[21 * 16]; + for (var r = 0; r < wh; r++) + { + for (var x = 0; x < w; x++) + { + var b = (r * ww) + x; + b1[(r * w) + x] = win[b] - (5 * win[b + 1]) + (20 * win[b + 2]) + (20 * win[b + 3]) - (5 * win[b + 4]) + win[b + 5]; + } + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var b = (y * w) + x; + var v = b1[b] - (5 * b1[b + w]) + (20 * b1[b + (2 * w)]) + (20 * b1[b + (3 * w)]) - (5 * b1[b + (4 * w)]) + b1[b + (5 * w)]; + jc[b] = Clip((v + 512) >> 10, max); + } + } + } + + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var g = win[((y + 2) * ww) + x + 2]; + int value; + switch ((xFrac << 2) | yFrac) + { + case 0x1: // d + value = (g + vh[(y * (w + 1)) + x] + 1) >> 1; + break; + case 0x2: // h + value = vh[(y * (w + 1)) + x]; + break; + case 0x3: // n + value = (win[((y + 3) * ww) + x + 2] + vh[(y * (w + 1)) + x] + 1) >> 1; + break; + case 0x4: // a + value = (g + bh[(y * w) + x] + 1) >> 1; + break; + case 0x5: // e + value = (bh[(y * w) + x] + vh[(y * (w + 1)) + x] + 1) >> 1; + break; + case 0x6: // i + value = (vh[(y * (w + 1)) + x] + jc[(y * w) + x] + 1) >> 1; + break; + case 0x7: // p + value = (vh[(y * (w + 1)) + x] + bh[((y + 1) * w) + x] + 1) >> 1; + break; + case 0x8: // b + value = bh[(y * w) + x]; + break; + case 0x9: // f + value = (bh[(y * w) + x] + jc[(y * w) + x] + 1) >> 1; + break; + case 0xA: // j + value = jc[(y * w) + x]; + break; + case 0xB: // q + value = (jc[(y * w) + x] + bh[((y + 1) * w) + x] + 1) >> 1; + break; + case 0xC: // c + value = (win[((y + 2) * ww) + x + 3] + bh[(y * w) + x] + 1) >> 1; + break; + case 0xD: // g + value = (bh[(y * w) + x] + vh[(y * (w + 1)) + x + 1] + 1) >> 1; + break; + case 0xE: // k + value = (jc[(y * w) + x] + vh[(y * (w + 1)) + x + 1] + 1) >> 1; + break; + default: // 0xF, r + value = (vh[(y * (w + 1)) + x + 1] + bh[((y + 1) * w) + x] + 1) >> 1; + break; + } + + dst[(y * w) + x] = Make(value); + } + } + } + + /// + /// Chroma prediction (4:2:0 and 4:2:2) of a × block whose corner, in eighths + /// of a chroma sample, is (, ), from a plane view as for . + /// + internal static void Chroma(ReadOnlySpan plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span dst) + where T : unmanaged + { + int xInt = ex >> 3, yInt = ey >> 3, xFrac = ex & 7, yFrac = ey & 7; + int wA = (8 - xFrac) * (8 - yFrac), wB = xFrac * (8 - yFrac), wC = (8 - xFrac) * yFrac, wD = xFrac * yFrac; + for (var y = 0; y < h; y++) + { + var y0 = origin + (Math.Clamp(yInt + y, 0, ph - 1) * stride); + var y1 = origin + (Math.Clamp(yInt + y + 1, 0, ph - 1) * stride); + for (var x = 0; x < w; x++) + { + var x0 = Math.Clamp(xInt + x, 0, pw - 1); + var x1 = Math.Clamp(xInt + x + 1, 0, pw - 1); + dst[(y * w) + x] = Make(((wA * Get(plane[y0 + x0])) + (wB * Get(plane[y0 + x1])) + (wC * Get(plane[y1 + x0])) + (wD * Get(plane[y1 + x1])) + 32) >> 6); + } + } + } + + /// Default bi-prediction average (equation 8-273), into . + internal static void Average(Span a, ReadOnlySpan b) + where T : unmanaged + { + for (var i = 0; i < a.Length; i++) + { + a[i] = Make((Get(a[i]) + Get(b[i]) + 1) >> 1); + } + } + + /// Weighted prediction from one list (equation 8-270); is already scaled to the bit depth. + internal static void WeightOne(Span a, int logWd, int weight, int offset, int max) + where T : unmanaged + { + for (var i = 0; i < a.Length; i++) + { + var s = Get(a[i]); + var v = logWd >= 1 ? ((s * weight) + (1 << (logWd - 1))) >> logWd : s * weight; + a[i] = Make(Clip(v + offset, max)); + } + } + + /// Weighted bi-prediction (equation 8-272), into ; the offsets are already scaled to the bit depth. + internal static void WeightTwo(Span a, ReadOnlySpan b, int logWd, int w0, int w1, int o0, int o1, int max) + where T : unmanaged + { + var offset = (o0 + o1 + 1) >> 1; + for (var i = 0; i < a.Length; i++) + { + var v = (((Get(a[i]) * w0) + (Get(b[i]) * w1) + (1 << logWd)) >> (logWd + 1)) + offset; + a[i] = Make(Clip(v, max)); + } + } +} diff --git a/src/Febe.Core/Codecs/H264/IntraPrediction.cs b/src/Febe.Core/Codecs/H264/IntraPrediction.cs new file mode 100644 index 0000000..e03ec3e --- /dev/null +++ b/src/Febe.Core/Codecs/H264/IntraPrediction.cs @@ -0,0 +1,519 @@ +using static Febe.Core.Codecs.H264.Samples; + +namespace Febe.Core.Codecs.H264; + +/// +/// Intra prediction (§8.3) written into the plane: luma 4×4, 8×8 and 16×16 blocks (also the Cb and Cr planes of 4:4:4, +/// predicted like luma, and the colour planes coded separately) and the chroma of 4:2:0 and 4:2:2, at any bit depth: a +/// missing neighbour counts as 1 << (BitDepth − 1). +/// +internal static class IntraPrediction +{ + /// Intra_4x4 (§8.3.1.2) of the block at . + internal static void Predict4x4(Span p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft, int bitDepth) + where T : unmanaged + { + var mid = 1 << (bitDepth - 1); + Span t = stackalloc int[8]; + Span l = stackalloc int[4]; + for (var i = 0; i < 4; i++) + { + t[i] = top ? Get(p[o - stride + i]) : mid; + l[i] = left ? Get(p[o + (i * stride) - 1]) : mid; + } + + for (var i = 4; i < 8; i++) + { + t[i] = topRight ? Get(p[o - stride + i]) : t[3]; + } + + var tl = topLeft ? Get(p[o - stride - 1]) : mid; + switch (mode) + { + case 0: // Vertical + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 4; x++) + { + p[o + (y * stride) + x] = Make(t[x]); + } + } + + break; + case 1: // Horizontal + for (var y = 0; y < 4; y++) + { + p.Slice(o + (y * stride), 4).Fill(Make(l[y])); + } + + break; + case 2: // DC + { + int dc; + if (top && left) + { + dc = (t[0] + t[1] + t[2] + t[3] + l[0] + l[1] + l[2] + l[3] + 4) >> 3; + } + else if (left) + { + dc = (l[0] + l[1] + l[2] + l[3] + 2) >> 2; + } + else if (top) + { + dc = (t[0] + t[1] + t[2] + t[3] + 2) >> 2; + } + else + { + dc = mid; + } + + Fill(p, o, stride, 4, 4, dc); + break; + } + + case 3: // Diagonal_Down_Left + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 4; x++) + { + p[o + (y * stride) + x] = Make(x == 3 && y == 3 + ? (t[6] + (3 * t[7]) + 2) >> 2 + : (t[x + y] + (2 * t[x + y + 1]) + t[x + y + 2] + 2) >> 2); + } + } + + break; + default: + { + // Modes 4–8 use the edge as one array: e[0..3] = left from bottom to top, e[4] = top-left, + // e[5..12] = top. Index of p[-1, y] is 3 − y, of p[x, −1] is 5 + x. + Span e = stackalloc int[13]; + for (var i = 0; i < 4; i++) + { + e[3 - i] = l[i]; + } + + e[4] = tl; + for (var i = 0; i < 8; i++) + { + e[5 + i] = t[i]; + } + + for (var y = 0; y < 4; y++) + { + for (var x = 0; x < 4; x++) + { + p[o + (y * stride) + x] = Make(Directional(e, 4, mode, x, y, 4)); + } + } + + break; + } + } + } + + /// + /// Modes 4–8 of Intra_4x4 and Intra_8x8 on an edge array where p[−1, y] is at c − 1 − y, p[−1, −1] at + /// c and p[x, −1] at c + 1 + x ( = block size). + /// + private static int Directional(ReadOnlySpan e, int c, int mode, int x, int y, int n) + { + switch (mode) + { + case 4: // Diagonal_Down_Right + if (x > y) + { + return (T(e, c, x - y - 2) + (2 * T(e, c, x - y - 1)) + T(e, c, x - y) + 2) >> 2; + } + + if (x < y) + { + return (L(e, c, y - x - 2) + (2 * L(e, c, y - x - 1)) + L(e, c, y - x) + 2) >> 2; + } + + return (T(e, c, 0) + (2 * T(e, c, -1)) + L(e, c, 0) + 2) >> 2; + case 5: // Vertical_Right + { + var z = (2 * x) - y; + if (z >= 0 && (z & 1) == 0) + { + return (T(e, c, x - (y >> 1) - 1) + T(e, c, x - (y >> 1)) + 1) >> 1; + } + + if (z >= 0) + { + return (T(e, c, x - (y >> 1) - 2) + (2 * T(e, c, x - (y >> 1) - 1)) + T(e, c, x - (y >> 1)) + 2) >> 2; + } + + if (z == -1) + { + return (L(e, c, 0) + (2 * L(e, c, -1)) + T(e, c, 0) + 2) >> 2; + } + + return (L(e, c, y - (2 * x) - 1) + (2 * L(e, c, y - (2 * x) - 2)) + L(e, c, y - (2 * x) - 3) + 2) >> 2; + } + + case 6: // Horizontal_Down + { + var z = (2 * y) - x; + if (z >= 0 && (z & 1) == 0) + { + return (L(e, c, y - (x >> 1) - 1) + L(e, c, y - (x >> 1)) + 1) >> 1; + } + + if (z >= 0) + { + return (L(e, c, y - (x >> 1) - 2) + (2 * L(e, c, y - (x >> 1) - 1)) + L(e, c, y - (x >> 1)) + 2) >> 2; + } + + if (z == -1) + { + return (L(e, c, 0) + (2 * L(e, c, -1)) + T(e, c, 0) + 2) >> 2; + } + + return (T(e, c, x - (2 * y) - 1) + (2 * T(e, c, x - (2 * y) - 2)) + T(e, c, x - (2 * y) - 3) + 2) >> 2; + } + + case 7: // Vertical_Left + if ((y & 1) == 0) + { + return (T(e, c, x + (y >> 1)) + T(e, c, x + (y >> 1) + 1) + 1) >> 1; + } + + return (T(e, c, x + (y >> 1)) + (2 * T(e, c, x + (y >> 1) + 1)) + T(e, c, x + (y >> 1) + 2) + 2) >> 2; + default: // 8, Horizontal_Up + { + var z = x + (2 * y); + var last = (2 * n) - 3; + if (z < last && (z & 1) == 0) + { + return (L(e, c, y + (x >> 1)) + L(e, c, y + (x >> 1) + 1) + 1) >> 1; + } + + if (z < last) + { + return (L(e, c, y + (x >> 1)) + (2 * L(e, c, y + (x >> 1) + 1)) + L(e, c, y + (x >> 1) + 2) + 2) >> 2; + } + + if (z == last) + { + return (L(e, c, n - 2) + (3 * L(e, c, n - 1)) + 2) >> 2; + } + + return L(e, c, n - 1); + } + } + } + + /// p[i, −1] of the edge array, i ≥ −1. + private static int T(ReadOnlySpan e, int c, int i) => e[c + 1 + i]; + + /// p[−1, i] of the edge array, i ≥ −1. + private static int L(ReadOnlySpan e, int c, int i) => e[c - 1 - i]; + + /// Intra_8x8 with the reference sample filtering of §8.3.2.2.1. + internal static void Predict8x8(Span p, int o, int stride, int mode, bool left, bool top, bool topRight, bool topLeft, int bitDepth) + where T : unmanaged + { + var mid = 1 << (bitDepth - 1); + Span t = stackalloc int[16]; + Span l = stackalloc int[8]; + for (var i = 0; i < 8; i++) + { + t[i] = top ? Get(p[o - stride + i]) : mid; + l[i] = left ? Get(p[o + (i * stride) - 1]) : mid; + } + + for (var i = 8; i < 16; i++) + { + t[i] = topRight ? Get(p[o - stride + i]) : t[7]; + } + + var tl = topLeft ? Get(p[o - stride - 1]) : mid; + + // Filtered references p′. + Span ft = stackalloc int[16]; + Span fl = stackalloc int[8]; + var ftl = tl; + if (top) + { + ft[0] = topLeft ? (tl + (2 * t[0]) + t[1] + 2) >> 2 : ((3 * t[0]) + t[1] + 2) >> 2; + for (var x = 1; x < 15; x++) + { + ft[x] = (t[x - 1] + (2 * t[x]) + t[x + 1] + 2) >> 2; + } + + ft[15] = (t[14] + (3 * t[15]) + 2) >> 2; + } + + if (topLeft) + { + if (top && left) + { + ftl = (t[0] + (2 * tl) + l[0] + 2) >> 2; + } + else if (top) + { + ftl = ((3 * tl) + t[0] + 2) >> 2; + } + else if (left) + { + ftl = ((3 * tl) + l[0] + 2) >> 2; + } + } + + if (left) + { + fl[0] = topLeft ? (tl + (2 * l[0]) + l[1] + 2) >> 2 : ((3 * l[0]) + l[1] + 2) >> 2; + for (var y = 1; y < 7; y++) + { + fl[y] = (l[y - 1] + (2 * l[y]) + l[y + 1] + 2) >> 2; + } + + fl[7] = (l[6] + (3 * l[7]) + 2) >> 2; + } + + switch (mode) + { + case 0: + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + p[o + (y * stride) + x] = Make(ft[x]); + } + } + + break; + case 1: + for (var y = 0; y < 8; y++) + { + p.Slice(o + (y * stride), 8).Fill(Make(fl[y])); + } + + break; + case 2: + { + int sumT = 0, sumL = 0; + for (var i = 0; i < 8; i++) + { + sumT += ft[i]; + sumL += fl[i]; + } + + var dc = top && left ? (sumT + sumL + 8) >> 4 : left ? (sumL + 4) >> 3 : top ? (sumT + 4) >> 3 : mid; + Fill(p, o, stride, 8, 8, dc); + break; + } + + case 3: + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + p[o + (y * stride) + x] = Make(x == 7 && y == 7 + ? (ft[14] + (3 * ft[15]) + 2) >> 2 + : (ft[x + y] + (2 * ft[x + y + 1]) + ft[x + y + 2] + 2) >> 2); + } + } + + break; + default: + { + Span e = stackalloc int[25]; + for (var i = 0; i < 8; i++) + { + e[7 - i] = fl[i]; + } + + e[8] = ftl; + for (var i = 0; i < 16; i++) + { + e[9 + i] = ft[i]; + } + + for (var y = 0; y < 8; y++) + { + for (var x = 0; x < 8; x++) + { + p[o + (y * stride) + x] = Make(Directional(e, 8, mode, x, y, 8)); + } + } + + break; + } + } + } + + /// Intra_16x16 (§8.3.3). + internal static void Predict16x16(Span p, int o, int stride, int mode, bool left, bool top, bool topLeft, int bitDepth) + where T : unmanaged + { + switch (mode) + { + case 0: + for (var y = 0; y < 16; y++) + { + p.Slice(o - stride, 16).CopyTo(p.Slice(o + (y * stride), 16)); + } + + break; + case 1: + for (var y = 0; y < 16; y++) + { + p.Slice(o + (y * stride), 16).Fill(p[o + (y * stride) - 1]); + } + + break; + case 2: + { + int sumT = 0, sumL = 0; + for (var i = 0; i < 16; i++) + { + if (top) + { + sumT += Get(p[o - stride + i]); + } + + if (left) + { + sumL += Get(p[o + (i * stride) - 1]); + } + } + + var dc = top && left ? (sumT + sumL + 16) >> 5 : left ? (sumL + 8) >> 4 : top ? (sumT + 8) >> 4 : 1 << (bitDepth - 1); + Fill(p, o, stride, 16, 16, dc); + break; + } + + default: + Plane(p, o, stride, 16, 16, topLeft, (1 << bitDepth) - 1); + break; + } + } + + /// + /// Chroma prediction of one component of 4:2:0 (8×8) or 4:2:2 (8×16) (§8.3.4): 0 DC, 1 horizontal, 2 vertical, 3 + /// plane. Bit g of says whether the left samples of rows 4g to 4g + 3 are available: they + /// may differ (an MBAFF frame with constrained intra prediction, where they come from two macroblocks), and the DC + /// prediction of each 4×4 block uses its own. + /// + internal static void PredictChroma(Span p, int o, int stride, int mode, int height, int leftRows, bool top, bool topLeft, int bitDepth) + where T : unmanaged + { + var mid = 1 << (bitDepth - 1); + switch (mode) + { + case 0: + for (var by = 0; by < height / 4; by++) + { + var left = ((leftRows >> by) & 1) != 0; + for (var bx = 0; bx < 2; bx++) + { + var b = o + (by * 4 * stride) + (bx * 4); + int sumT = 0, sumL = 0; + for (var i = 0; i < 4; i++) + { + if (top) + { + sumT += Get(p[o - stride + (bx * 4) + i]); + } + + if (left) + { + sumL += Get(p[o + (((by * 4) + i) * stride) - 1]); + } + } + + // §8.3.4.1–8.3.4.3: the blocks at (0, 0) and those off the first row and column use both edges, + // the others of the first row prefer the top one, those of the first column the left one. + int dc; + if ((bx == 0 && by == 0) || (bx > 0 && by > 0)) + { + dc = top && left ? (sumT + sumL + 4) >> 3 : left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : mid; + } + else if (bx > 0) + { + dc = top ? (sumT + 2) >> 2 : left ? (sumL + 2) >> 2 : mid; + } + else + { + dc = left ? (sumL + 2) >> 2 : top ? (sumT + 2) >> 2 : mid; + } + + Fill(p, b, stride, 4, 4, dc); + } + } + + break; + case 1: + for (var y = 0; y < height; y++) + { + p.Slice(o + (y * stride), 8).Fill(p[o + (y * stride) - 1]); + } + + break; + case 2: + for (var y = 0; y < height; y++) + { + p.Slice(o - stride, 8).CopyTo(p.Slice(o + (y * stride), 8)); + } + + break; + default: + Plane(p, o, stride, 8, height, topLeft, (1 << bitDepth) - 1); + break; + } + } + + /// + /// Plane prediction of a 16×16 luma block or of an 8×8 or 8×16 chroma one (equations 8-125 to 8-131 and 8-138 to + /// 8-145): the gradient of a 16-sample side is weighed by 5, of an 8-sample side by 34. + /// + private static void Plane(Span p, int o, int stride, int w, int h, bool topLeft, int max) + where T : unmanaged + { + _ = topLeft; // the plane mode is only used when all three neighbours are available + var hw = w / 2; + var hh = h / 2; + int sumH = 0, sumV = 0; + for (var i = 0; i < hw; i++) + { + var right = Get(p[o - stride + hw + i]); + var leftIndex = hw - 2 - i; + var leftSample = Get(leftIndex >= 0 ? p[o - stride + leftIndex] : p[o - stride - 1]); + sumH += (i + 1) * (right - leftSample); + } + + for (var i = 0; i < hh; i++) + { + var below = Get(p[o + ((hh + i) * stride) - 1]); + var aboveIndex = hh - 2 - i; + var aboveSample = Get(aboveIndex >= 0 ? p[o + (aboveIndex * stride) - 1] : p[o - stride - 1]); + sumV += (i + 1) * (below - aboveSample); + } + + var a = 16 * (Get(p[o + ((h - 1) * stride) - 1]) + Get(p[o - stride + w - 1])); + var b = (((w == 16 ? 5 : 34) * sumH) + 32) >> 6; + var c = (((h == 16 ? 5 : 34) * sumV) + 32) >> 6; + for (var y = 0; y < h; y++) + { + var row = p.Slice(o + (y * stride), w); + var v = a + (c * (y - (hh - 1))) - (b * (hw - 1)) + 16; + for (var x = 0; x < w; x++, v += b) + { + row[x] = Make(Clip(v >> 5, max)); + } + } + } + + private static void Fill(Span p, int o, int stride, int w, int h, int value) + where T : unmanaged + { + var sample = Make(value); + for (var y = 0; y < h; y++) + { + p.Slice(o + (y * stride), w).Fill(sample); + } + } +} diff --git a/src/Febe.Core/Codecs/H264/ParameterSets.cs b/src/Febe.Core/Codecs/H264/ParameterSets.cs new file mode 100644 index 0000000..704ab56 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/ParameterSets.cs @@ -0,0 +1,728 @@ +namespace Febe.Core.Codecs.H264; + +/// A sequence parameter set (§7.3.2.1.1), with the fields Febe uses. +internal sealed class Sps +{ + /// MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits. + internal const int MaxFrameMbs = 139_264; + + /// MaxDpbMbs of level 6.2 (table A-1): the largest decoded picture buffer of any level, in macroblocks. + internal const int MaxDpbMbs = 696_320; + + internal int ProfileIdc; + internal int LevelIdc; + internal int Id; + internal int ChromaFormatIdc = 1; + + /// separate_colour_plane_flag: the three colour planes of 4:4:4 are coded as three monochrome pictures. + internal bool SeparateColourPlane; + + internal int BitDepthLuma = 8; + internal int BitDepthChroma = 8; + + /// qpprime_y_zero_transform_bypass_flag: macroblocks with QP′Y 0 are lossless (§8.5.15). + internal bool TransformBypass; + + /// ChromaArrayType (§7.4.2.1.1): chroma_format_idc, or 0 when the colour planes are separate. + internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc; + + /// SubWidthC (Table 6-1): 2 for 4:2:0 and 4:2:2, 1 for 4:4:4. + internal int SubWidthC => ChromaFormatIdc == 3 ? 1 : 2; + + /// SubHeightC (Table 6-1): 2 for 4:2:0, 1 for 4:2:2 and 4:4:4. + internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1; + + /// QpBdOffsetY = 6 × bit_depth_luma_minus8. + internal int QpBdOffsetY => 6 * (BitDepthLuma - 8); + + /// QpBdOffsetC = 6 × bit_depth_chroma_minus8. + internal int QpBdOffsetC => 6 * (BitDepthChroma - 8); + + /// Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A. + internal byte[][] ScalingLists = ScalingMatrix.Flat(); + + /// seq_scaling_matrix_present_flag: chooses fall-back rule B (instead of A) for the PPS lists. + internal bool ScalingMatrixPresent; + + internal int Log2MaxFrameNum; + internal int PocType; + internal int Log2MaxPocLsb; + internal bool DeltaPicOrderAlwaysZero; + internal int OffsetForNonRefPic; + internal int OffsetForTopToBottomField; + internal int[] OffsetForRefFrame = []; + internal int MaxNumRefFrames; + internal bool GapsInFrameNumAllowed; + internal int WidthInMbs; + internal int HeightInMapUnits; + internal bool FrameMbsOnly; + internal bool MbAdaptiveFrameField; + internal bool Direct8x8Inference; + internal int CropLeft, CropRight, CropTop, CropBottom; + + /// VUI colour description: matrix_coefficients (2 = unspecified) and video_full_range_flag. + internal int MatrixCoefficients = 2; + + internal bool FullRange; + + internal int MaxFrameNum => 1 << Log2MaxFrameNum; + + /// CropUnitX of §7.4.2.1.1: 1 without chroma (or in 4:4:4), else SubWidthC. + internal int CropUnitX => ChromaArrayType == 0 ? 1 : SubWidthC; + + /// CropUnitY of §7.4.2.1.1, doubled when the frames may be coded as fields. + internal int CropUnitY => (ChromaArrayType == 0 ? 1 : SubHeightC) * (FrameMbsOnly ? 1 : 2); + + internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits; + + /// The multiview extension of a subset SPS (profiles 118, 128 and 134), null otherwise. + internal MvcExtension? Mvc; + + /// The scalable extension of a subset SPS (profiles 83 and 86), null otherwise. + internal SvcExtension? Svc; + + /// + /// A subset sequence parameter set (NAL unit 15, §7.3.2.1.3): seq_parameter_set_data() with its whole VUI, then the + /// extension of its profile — scalable (§G.7.3.2.1.4) or multiview (§H.7.3.2.1.4); what follows the parts the decoder + /// uses is not read. + /// + internal static Sps ParseSubset(RbspReader r) + { + var s = Parse(r, wholeVui: true); + if (s.ProfileIdc is 83 or 86) + { + s.Svc = SvcExtension.Parse(r, s.ChromaArrayType); + } + else if (s.ProfileIdc is 118 or 128 or 134) + { + r.Skip(1); // bit_equal_to_one + s.Mvc = MvcExtension.Parse(r); + } + + return s; + } + + internal static Sps Parse(RbspReader r) => Parse(r, wholeVui: false); + + private static Sps Parse(RbspReader r, bool wholeVui) + { + var s = new Sps { ProfileIdc = (int)r.Read(8) }; + r.Skip(8); // constraint flags and reserved bits + s.LevelIdc = (int)r.Read(8); + s.Id = r.ReadUe(31); + if (s.ProfileIdc is 100 or 110 or 122 or 244 or 44 or 83 or 86 or 118 or 128 or 138 or 139 or 134 or 135) + { + s.ChromaFormatIdc = r.ReadUe(3); + if (s.ChromaFormatIdc == 3) + { + s.SeparateColourPlane = r.ReadFlag(); + } + + s.BitDepthLuma = r.ReadUe(6) + 8; + s.BitDepthChroma = r.ReadUe(6) + 8; + s.TransformBypass = r.ReadFlag(); + if (r.ReadFlag()) + { + s.ScalingMatrixPresent = true; + s.ScalingLists = ScalingMatrix.ParseLists(r, s.ChromaFormatIdc == 3 ? 12 : 8, null); + } + } + + s.Log2MaxFrameNum = r.ReadUe(12) + 4; + s.PocType = r.ReadUe(2); + if (s.PocType == 0) + { + s.Log2MaxPocLsb = r.ReadUe(12) + 4; + } + else if (s.PocType == 1) + { + s.DeltaPicOrderAlwaysZero = r.ReadFlag(); + s.OffsetForNonRefPic = r.ReadSe(); + s.OffsetForTopToBottomField = r.ReadSe(); + var cycle = r.ReadUe(255); + s.OffsetForRefFrame = new int[cycle]; + for (var i = 0; i < cycle; i++) + { + s.OffsetForRefFrame[i] = r.ReadSe(); + } + } + + s.MaxNumRefFrames = r.ReadUe(16); + s.GapsInFrameNumAllowed = r.ReadFlag(); + s.WidthInMbs = r.ReadUe(1023) + 1; + s.HeightInMapUnits = r.ReadUe(1023) + 1; + s.FrameMbsOnly = r.ReadFlag(); + if (!s.FrameMbsOnly) + { + s.MbAdaptiveFrameField = r.ReadFlag(); + } + + // The largest frame of any level (MaxFS of level 6.2, table A-1): a damaged SPS never makes the decoder + // allocate pictures larger than a real stream can have. + if ((long)s.WidthInMbs * s.HeightInMbs > MaxFrameMbs) + { + throw new H264Exception("Immagine più grande di ogni livello H.264."); + } + + // The reference frames must fit in the largest buffer of any level (MaxDpbMbs of level 6.2, table A-1; A.3.1 + // and A.3.2 bound max_num_ref_frames by it): sixteen frames of the largest size would be 1.4 GB. + if ((long)s.MaxNumRefFrames * s.WidthInMbs * s.HeightInMbs > MaxDpbMbs) + { + throw new H264Exception("Troppe immagini di riferimento per ogni livello H.264."); + } + + s.Direct8x8Inference = r.ReadFlag(); + if (r.ReadFlag()) + { + s.CropLeft = r.ReadUe(8192); + s.CropRight = r.ReadUe(8192); + s.CropTop = r.ReadUe(8192); + s.CropBottom = r.ReadUe(8192); + + // §7.4.2.1.1: the cropped frame keeps at least one sample. + if (s.CropUnitX * (s.CropLeft + s.CropRight) >= s.WidthInMbs * 16 || s.CropUnitY * (s.CropTop + s.CropBottom) >= s.HeightInMbs * 16) + { + throw new H264Exception("Ritaglio dell'immagine non valido."); + } + } + + if (r.ReadFlag()) + { + ParseVuiColour(r, s); + if (wholeVui) + { + SkipVuiRest(r); + } + } + + return s; + } + + /// The VUI after the colour description (§E.1.1), read only to reach what follows it in a subset SPS. + private static void SkipVuiRest(RbspReader r) + { + if (r.ReadFlag()) + { + _ = r.ReadUe(); // chroma_sample_loc_type_top_field + _ = r.ReadUe(); // chroma_sample_loc_type_bottom_field + } + + if (r.ReadFlag()) + { + r.Skip(65); // num_units_in_tick, time_scale, fixed_frame_rate_flag + } + + var nalHrd = r.ReadFlag(); + if (nalHrd) + { + SkipHrd(r); + } + + var vclHrd = r.ReadFlag(); + if (vclHrd) + { + SkipHrd(r); + } + + if (nalHrd || vclHrd) + { + r.Skip(1); // low_delay_hrd_flag + } + + r.Skip(1); // pic_struct_present_flag + if (r.ReadFlag()) + { + r.Skip(1); // motion_vectors_over_pic_boundaries_flag + for (var i = 0; i < 6; i++) + { + _ = r.ReadUe(); + } + } + } + + /// hrd_parameters() (§E.1.2), skipped. + private static void SkipHrd(RbspReader r) + { + var count = r.ReadUe(31) + 1; + r.Skip(8); // bit_rate_scale, cpb_size_scale + for (var i = 0; i < count; i++) + { + _ = r.ReadUe(); + _ = r.ReadUe(); + r.Skip(1); + } + + r.Skip(20); + } + + /// The start of the VUI (§E.1.1), up to the colour description; the rest is not needed. + private static void ParseVuiColour(RbspReader r, Sps s) + { + if (r.ReadFlag()) + { + var aspect = r.Read(8); + if (aspect == 255) + { + r.Skip(32); // sar_width, sar_height + } + } + + if (r.ReadFlag()) + { + r.Skip(1); // overscan_appropriate_flag + } + + if (r.ReadFlag()) + { + r.Skip(3); // video_format + s.FullRange = r.ReadFlag(); + if (r.ReadFlag()) + { + r.Skip(16); // colour_primaries, transfer_characteristics + s.MatrixCoefficients = (int)r.Read(8); + } + } + } +} + +/// +/// seq_parameter_set_mvc_extension() (§H.7.3.2.1.4) up to the dependencies between views: the views in view order, and +/// for each the views its anchor and non-anchor view components may refer to, per list. +/// +internal sealed class MvcExtension +{ + /// view_id of each view, by view order index (VOIdx). + internal int[] ViewIds = []; + + /// anchor_ref_lX[VOIdx][j] by list X: the view_id of each inter-view reference of an anchor view component. + internal int[][][] AnchorRefs = [[], []]; + + /// non_anchor_ref_lX[VOIdx][j] by list X. + internal int[][][] NonAnchorRefs = [[], []]; + + /// The view order index of a view, −1 when the sequence does not have it. + internal int OrderOf(int viewId) => Array.IndexOf(ViewIds, viewId); + + internal static MvcExtension Parse(RbspReader r) + { + var views = r.ReadUe(1023) + 1; + var m = new MvcExtension { ViewIds = new int[views] }; + for (var i = 0; i < views; i++) + { + m.ViewIds[i] = r.ReadUe(1023); + } + + for (var list = 0; list < 2; list++) + { + m.AnchorRefs[list] = new int[views][]; + m.NonAnchorRefs[list] = new int[views][]; + m.AnchorRefs[list][0] = []; + m.NonAnchorRefs[list][0] = []; + } + + for (var pass = 0; pass < 2; pass++) + { + var refs = pass == 0 ? m.AnchorRefs : m.NonAnchorRefs; + for (var i = 1; i < views; i++) + { + for (var list = 0; list < 2; list++) + { + var count = r.ReadUe(15); + var ids = new int[count]; + for (var j = 0; j < count; j++) + { + ids[j] = r.ReadUe(1023); + } + + refs[list][i] = ids; + } + } + } + + return m; + } +} + +/// seq_parameter_set_svc_extension() (§G.7.3.2.1.4). +internal sealed class SvcExtension +{ + internal bool InterLayerDeblockingFilterControlPresent; + internal int ExtendedSpatialScalabilityIdc; + internal bool ChromaPhaseXPlus1; + internal int ChromaPhaseYPlus1 = 1; + internal bool SeqRefLayerChromaPhaseXPlus1; + internal int SeqRefLayerChromaPhaseYPlus1 = 1; + internal int SeqScaledRefLayerLeft; + internal int SeqScaledRefLayerTop; + internal int SeqScaledRefLayerRight; + internal int SeqScaledRefLayerBottom; + internal bool SeqTcoeffLevelPrediction; + internal bool AdaptiveTcoeffLevelPrediction; + internal bool SliceHeaderRestriction; + + internal static SvcExtension Parse(RbspReader r, int chromaArrayType) + { + var e = new SvcExtension + { + InterLayerDeblockingFilterControlPresent = r.ReadFlag(), + ExtendedSpatialScalabilityIdc = (int)r.Read(2), + }; + if (chromaArrayType is 1 or 2) + { + e.ChromaPhaseXPlus1 = r.ReadFlag(); + } + + if (chromaArrayType == 1) + { + e.ChromaPhaseYPlus1 = (int)r.Read(2); + } + + if (e.ExtendedSpatialScalabilityIdc == 1) + { + if (chromaArrayType > 0) + { + e.SeqRefLayerChromaPhaseXPlus1 = r.ReadFlag(); + e.SeqRefLayerChromaPhaseYPlus1 = (int)r.Read(2); + } + + e.SeqScaledRefLayerLeft = r.ReadSe(); + e.SeqScaledRefLayerTop = r.ReadSe(); + e.SeqScaledRefLayerRight = r.ReadSe(); + e.SeqScaledRefLayerBottom = r.ReadSe(); + } + + e.SeqTcoeffLevelPrediction = r.ReadFlag(); + if (e.SeqTcoeffLevelPrediction) + { + e.AdaptiveTcoeffLevelPrediction = r.ReadFlag(); + } + + e.SliceHeaderRestriction = r.ReadFlag(); + return e; + } +} + +/// A picture parameter set (§7.3.2.2). +internal sealed class Pps +{ + internal int Id; + internal int SpsId; + internal bool Cabac; + internal bool BottomFieldPicOrderInFramePresent; + internal int NumRefIdxL0DefaultActive; + internal int NumRefIdxL1DefaultActive; + internal bool WeightedPred; + internal int WeightedBipredIdc; + internal int PicInitQp; + + /// 26 + pic_init_qs_minus26: the starting QS of SP and SI slices. + internal int PicInitQs; + + /// num_slice_groups_minus1 + 1: more than one is FMO (§8.2.2). + internal int NumSliceGroups = 1; + + internal int SliceGroupMapType; + + /// run_length_minus1 + 1 of each slice group (map type 0). + internal int[] RunLength = []; + + /// top_left and bottom_right of the rectangles of the slice groups but the last (map type 2). + internal int[] TopLeft = []; + + internal int[] BottomRight = []; + + internal bool SliceGroupChangeDirection; + + /// slice_group_change_rate_minus1 + 1 (map types 3–5). + internal int SliceGroupChangeRate; + + /// slice_group_id of each map unit (map type 6). + internal byte[] SliceGroupIds = []; + + internal int ChromaQpIndexOffset; + internal int SecondChromaQpIndexOffset; + internal bool DeblockingFilterControlPresent; + internal bool ConstrainedIntraPred; + internal bool RedundantPicCntPresent; + internal bool Transform8x8Mode; + + /// The scaling lists of the picture, null when the PPS has none (those of the SPS apply). + internal byte[][]? ScalingLists; + + /// The RBSP after the NAL unit header. + /// The SPSs read so far. + /// The subset SPSs read so far: a PPS of the enhancement layers or views may refer to one. + internal static Pps Parse(RbspReader r, IReadOnlyDictionary sequences, IReadOnlyDictionary? subsetSequences = null) + { + var p = new Pps { Id = r.ReadUe(255), SpsId = r.ReadUe(31) }; + p.Cabac = r.ReadFlag(); + p.BottomFieldPicOrderInFramePresent = r.ReadFlag(); + p.NumSliceGroups = r.ReadUe(7) + 1; + if (p.NumSliceGroups > 1) + { + ParseSliceGroups(r, p); + } + + p.NumRefIdxL0DefaultActive = r.ReadUe(31) + 1; + p.NumRefIdxL1DefaultActive = r.ReadUe(31) + 1; + p.WeightedPred = r.ReadFlag(); + p.WeightedBipredIdc = (int)r.Read(2); + p.PicInitQp = 26 + r.ReadSe(); + p.PicInitQs = 26 + r.ReadSe(); + if (p.PicInitQs is < 0 or > 51) + { + throw new H264Exception("QS iniziale del PPS non valido."); + } + + p.ChromaQpIndexOffset = r.ReadSe(); + p.DeblockingFilterControlPresent = r.ReadFlag(); + p.ConstrainedIntraPred = r.ReadFlag(); + p.RedundantPicCntPresent = r.ReadFlag(); + p.SecondChromaQpIndexOffset = p.ChromaQpIndexOffset; + if (r.MoreRbspData) + { + p.Transform8x8Mode = r.ReadFlag(); + if (r.ReadFlag()) + { + if (!sequences.TryGetValue(p.SpsId, out var sps)) + { + subsetSequences?.TryGetValue(p.SpsId, out sps); + } + + var chroma444 = sps is { ChromaFormatIdc: 3 }; + var count = 6 + ((chroma444 ? 6 : 2) * (p.Transform8x8Mode ? 1 : 0)); + p.ScalingLists = ScalingMatrix.ParseLists(r, count, sps is { ScalingMatrixPresent: true } ? sps.ScalingLists : null); + } + + p.SecondChromaQpIndexOffset = r.ReadSe(); + } + + return p; + } + + /// The slice group map of §7.3.2.2 (num_slice_groups_minus1 above 0), checked against the picture later. + private static void ParseSliceGroups(RbspReader r, Pps p) + { + p.SliceGroupMapType = r.ReadUe(6); + var groups = p.NumSliceGroups; + switch (p.SliceGroupMapType) + { + case 0: + p.RunLength = new int[groups]; + for (var i = 0; i < groups; i++) + { + p.RunLength[i] = r.ReadUe(Sps.MaxFrameMbs - 1) + 1; + } + + break; + case 2: + p.TopLeft = new int[groups - 1]; + p.BottomRight = new int[groups - 1]; + for (var i = 0; i < groups - 1; i++) + { + p.TopLeft[i] = r.ReadUe(Sps.MaxFrameMbs - 1); + p.BottomRight[i] = r.ReadUe(Sps.MaxFrameMbs - 1); + } + + break; + case 3: + case 4: + case 5: + p.SliceGroupChangeDirection = r.ReadFlag(); + p.SliceGroupChangeRate = r.ReadUe(Sps.MaxFrameMbs - 1) + 1; + break; + case 6: + { + var size = r.ReadUe(Sps.MaxFrameMbs - 1) + 1; + var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1)); + p.SliceGroupIds = new byte[size]; + for (var i = 0; i < size; i++) + { + var id = (int)r.Read(bits); + if (id >= groups || r.BitsLeft < 0) + { + throw new H264Exception("slice_group_id non valido."); + } + + p.SliceGroupIds[i] = (byte)id; + } + + break; + } + } + } +} + +/// Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9). +internal static class ScalingMatrix +{ + /// Twelve flat lists (Flat_4x4_16 and Flat_8x8_16). + internal static byte[][] Flat() + { + var lists = new byte[12][]; + for (var i = 0; i < 12; i++) + { + lists[i] = new byte[i < 6 ? 16 : 64]; + Array.Fill(lists[i], (byte)16); + } + + return lists; + } + + /// + /// Parses lists and applies the fall-back rules: rule A (from the defaults) for the SPS, + /// rule B (from the lists of the SPS, ) for the PPS. Lists that are not + /// transmitted at all (8×8 without transform_8x8_mode) keep the SPS ones, or flat. + /// + internal static byte[][] ParseLists(RbspReader r, int count, byte[][]? sequenceLists) + { + var lists = new byte[12][]; + for (var i = 0; i < 12; i++) + { + var size = i < 6 ? 16 : 64; + var present = i < count && r.ReadFlag(); + if (present) + { + var list = new byte[size]; + if (ParseList(r, list)) + { + lists[i] = Default(i); + } + else + { + lists[i] = list; + } + } + else if (i < count) + { + lists[i] = FallBack(i, lists, sequenceLists); + } + else + { + lists[i] = sequenceLists?[i] ?? FallBack(i, lists, null); + } + } + + return lists; + } + + /// Reads one list; true when it says «use the default matrix». + private static bool ParseList(RbspReader r, byte[] list) + { + var last = 8; + var next = 8; + for (var j = 0; j < list.Length; j++) + { + if (next != 0) + { + var delta = r.ReadSe(); + if (delta is < -128 or > 127) + { + throw new H264Exception("Matrice di quantizzazione non valida."); + } + + next = (last + delta + 256) % 256; + if (j == 0 && next == 0) + { + return true; + } + } + + list[j] = (byte)(next == 0 ? last : next); + last = list[j]; + } + + return false; + } + + private static byte[] Default(int i) => i switch + { + < 3 => H264Tables.Default4x4Intra, + < 6 => H264Tables.Default4x4Inter, + _ => (i & 1) == 0 ? H264Tables.Default8x8Intra : H264Tables.Default8x8Inter, + }; + + /// Fall-back rule A ( null) or B. + private static byte[] FallBack(int i, byte[][] lists, byte[][]? sequenceLists) => i switch + { + 0 or 3 => sequenceLists?[i] ?? Default(i), + 1 or 2 or 4 or 5 => lists[i - 1], + 6 or 7 => sequenceLists?[i] ?? Default(i), + _ => lists[i - 2], + }; + + /// + /// LevelScale4x4[m][i] for the six 4×4 lists (raster positions): result[list][m * 16 + pos]. + /// + internal static int[][] LevelScale4x4(byte[][] lists) + { + var result = new int[6][]; + for (var l = 0; l < 6; l++) + { + var scale = new int[6 * 16]; + for (var k = 0; k < 16; k++) + { + var pos = H264Tables.ZigZag4x4[k]; + int row = pos >> 2, col = pos & 3; + var cls = (row & 1) == 0 && (col & 1) == 0 ? 0 : (row & 1) == 1 && (col & 1) == 1 ? 1 : 2; + for (var m = 0; m < 6; m++) + { + scale[(m * 16) + pos] = lists[l][k] * H264Tables.NormAdjust4x4[m, cls]; + } + } + + result[l] = scale; + } + + return result; + } + + /// LevelScale8x8 for the 8×8 lists 6–11 (raster positions): result[list − 6][m * 64 + pos]. + internal static int[][] LevelScale8x8(byte[][] lists) + { + var result = new int[6][]; + for (var l = 0; l < 6; l++) + { + var scale = new int[6 * 64]; + for (var k = 0; k < 64; k++) + { + var pos = H264Tables.ZigZag8x8[k]; + int i = pos >> 3, j = pos & 7; + int cls; + if ((i & 3) == 0 && (j & 3) == 0) + { + cls = 0; + } + else if ((i & 1) == 1 && (j & 1) == 1) + { + cls = 1; + } + else if ((i & 3) == 2 && (j & 3) == 2) + { + cls = 2; + } + else if (((i & 3) == 0 && (j & 1) == 1) || ((i & 1) == 1 && (j & 3) == 0)) + { + cls = 3; + } + else if (((i & 3) == 0 && (j & 3) == 2) || ((i & 3) == 2 && (j & 3) == 0)) + { + cls = 4; + } + else + { + cls = 5; + } + + for (var m = 0; m < 6; m++) + { + scale[(m * 64) + pos] = lists[6 + l][k] * H264Tables.NormAdjust8x8[m, cls]; + } + } + + result[l] = scale; + } + + return result; + } +} diff --git a/src/Febe.Core/Codecs/H264/Picture.cs b/src/Febe.Core/Codecs/H264/Picture.cs new file mode 100644 index 0000000..148c5d4 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/Picture.cs @@ -0,0 +1,257 @@ +namespace Febe.Core.Codecs.H264; + +/// +/// A frame store of the decoded picture buffer: a decoded frame, or the two fields of a complementary field pair (its +/// even rows are the top field, its odd rows the bottom one), with what later pictures need from it: samples (the full +/// macroblock area, one or two bytes per sample), motion vectors and references of every block (for direct prediction +/// and the deblocking of the pictures that follow), and its marking. +/// +/// +/// The data of the macroblocks is kept on the grid of the frame, whatever the coding: a frame macroblock at its row; a +/// macroblock pair of an MBAFF frame at rows 2k (top) and 2k + 1 (bottom), field pairs included; the macroblock of row +/// k of a field picture at row 2k + parity. Field macroblocks () keep their motion vectors in +/// field units and refer to fields (). When the three colour planes of 4:4:4 are coded separately +/// (separate_colour_plane_flag) each has macroblocks of its own: the motion data is kept per plane, and +/// chooses the one the properties show. +/// +internal sealed class Picture +{ + private readonly MotionPlane[] motion; + private MotionPlane selected; + + /// Width in macroblocks. + /// Height in macroblocks. + /// chroma_format_idc: 0 monochrome (no chroma planes), 1 4:2:0, 2 4:2:2, 3 4:4:4. + /// 1 up to 8 bits, 2 above. + /// 3 when the colour planes are coded separately, else 1. + internal Picture(int widthInMbs, int heightInMbs, int chromaFormat = 1, int bytesPerSample = 1, int colourPlanes = 1) + { + WidthInMbs = widthInMbs; + HeightInMbs = heightInMbs; + Width = widthInMbs * 16; + Height = heightInMbs * 16; + ChromaFormat = chromaFormat; + BytesPerSample = bytesPerSample; + ChromaWidth = chromaFormat == 0 ? 0 : chromaFormat == 3 ? Width : Width / 2; + ChromaHeight = chromaFormat == 0 ? 0 : chromaFormat == 1 ? Height / 2 : Height; + var mbs = widthInMbs * heightInMbs; + Y = new byte[Width * Height * bytesPerSample]; + Cb = new byte[ChromaWidth * ChromaHeight * bytesPerSample]; + Cr = new byte[ChromaWidth * ChromaHeight * bytesPerSample]; + motion = new MotionPlane[colourPlanes]; + for (var i = 0; i < colourPlanes; i++) + { + motion[i] = new MotionPlane(mbs); + } + + selected = motion[0]; + } + + internal int WidthInMbs { get; } + + internal int HeightInMbs { get; } + + internal int Width { get; } + + internal int Height { get; } + + /// chroma_format_idc of the samples (3 also for separate colour planes). + internal int ChromaFormat { get; } + + internal int BytesPerSample { get; } + + /// Width of the Cb and Cr planes in samples (0 for monochrome). + internal int ChromaWidth { get; } + + /// Height of the Cb and Cr planes in samples (0 for monochrome). + internal int ChromaHeight { get; } + + internal byte[] Y { get; } + + internal byte[] Cb { get; } + + internal byte[] Cr { get; } + + /// Motion vectors: [((list * mbs + mb) * 16 + raster 4×4 block) * 2 + component], quarter samples. + internal short[] Mv => selected.Mv; + + /// Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used. + internal sbyte[] RefIdx => selected.RefIdx; + + /// The frame store each 8×8 block refers to, by list (same index as ). + internal Picture?[] RefPic => selected.RefPic; + + /// The field of referred to: 0 top, 1 bottom, −1 the frame (same index as ). + internal sbyte[] RefPar => selected.RefPar; + + internal bool[] MbIntra => selected.MbIntra; + + /// Field macroblocks: those of field pictures and the field pairs of MBAFF frames. + internal bool[] MbField => selected.MbField; + + /// The plane of colour component (0 Y, 1 Cb, 2 Cr). + internal byte[] Plane(int k) => k == 0 ? Y : k == 1 ? Cb : Cr; + + /// Shows the motion data of colour plane (only one exists unless the planes are separate). + internal void SelectPlane(int k) => selected = motion[Math.Min(k, motion.Length - 1)]; + + /// A store taken from the pool: no block refers to any picture yet. + internal void ClearReferences() + { + foreach (var m in motion) + { + Array.Clear(m.RefPic); + } + } + + /// A frame inferred for a gap in frame_num: all its macroblocks count as intra frame macroblocks. + internal void MarkAsGap() + { + foreach (var m in motion) + { + Array.Fill(m.MbIntra, true); + Array.Clear(m.MbField); + } + } + + internal int MbCount => WidthInMbs * HeightInMbs; + + /// TopFieldOrderCnt and BottomFieldOrderCnt (§8.2.1) of the fields decoded so far. + internal int TopPoc; + + internal int BottomPoc; + + /// The fields decoded so far: 1 top, 2 bottom, 3 both (a frame or a field pair). + internal int Decoded; + + /// Coded as two field pictures (else as a frame, progressive or MBAFF). + internal bool CodedAsFields; + + internal int FrameNum; + internal int FrameNumWrap; + internal int LongTermFrameIdx; + + /// Fields used for short-term reference: 1 top, 2 bottom, 3 both (the frame). + internal int ShortMask; + + /// Fields used for long-term reference, as . + internal int LongMask; + + /// A frame inferred for a gap in frame_num (§8.2.5.2): never output, its samples are not meaningful. + internal bool NonExisting; + + /// Some field of the frame was not reconstructed (nobody refers to it, nobody wants it): it is not handed out. + internal bool Skipped; + + /// In the decoded picture buffer. + internal bool InDpb; + + /// Decoding order of the frame in the stream. + internal long DecodeIndex; + + /// Counts IDR pictures (and memory_management_control_operation 5): output order restarts with each. + internal int Period; + + internal bool IsReference => (ShortMask | LongMask) != 0; + + /// A short-term reference frame: both fields marked (§8.2.4.1, frames and complementary pairs). + internal bool ShortTerm => ShortMask == 3; + + /// A long-term reference frame. + internal bool LongTerm => LongMask == 3; + + internal int PicNum => FrameNumWrap; + + internal int LongTermPicNum => LongTermFrameIdx; + + /// PicOrderCnt of the frame (§8.2.1): the smaller of the fields decoded. + internal int Poc => Decoded switch + { + 1 => TopPoc, + 2 => BottomPoc, + _ => Math.Min(TopPoc, BottomPoc), + }; + + /// PicOrderCnt of a field (0 top, 1 bottom) or of the frame (−1). + internal int PocOf(int parity) => parity < 0 ? Poc : parity == 0 ? TopPoc : BottomPoc; + + /// Whether the field (0 top, 1 bottom) or the frame (−1) is a long-term reference. + internal bool IsLongTerm(int parity) => parity < 0 ? LongMask == 3 : (LongMask & (1 << parity)) != 0; + + internal bool Fits(int widthInMbs, int heightInMbs, int chromaFormat, int bytesPerSample, int colourPlanes) => + WidthInMbs == widthInMbs && HeightInMbs == heightInMbs && ChromaFormat == chromaFormat && BytesPerSample == bytesPerSample + && motion.Length == colourPlanes; + + /// The motion data of the macroblocks of one colour plane. + private sealed class MotionPlane(int mbs) + { + internal readonly short[] Mv = new short[2 * mbs * 16 * 2]; + internal readonly sbyte[] RefIdx = new sbyte[2 * mbs * 4]; + internal readonly Picture?[] RefPic = new Picture?[2 * mbs * 4]; + internal readonly sbyte[] RefPar = new sbyte[2 * mbs * 4]; + internal readonly bool[] MbIntra = new bool[mbs]; + internal readonly bool[] MbField = new bool[mbs]; + } +} + +/// +/// A reference picture of a list: a frame ( −1) or one field of a frame store; for a non-base view of +/// MVC also the view component of another view in the same access unit (), which is marked +/// "used for inter-view reference" only: neither a short-term nor a long-term reference of the current view. +/// +internal readonly record struct RefEntry(Picture? Pic, int Parity, bool InterView = false) +{ + internal int Poc => Pic!.PocOf(Parity); + + internal bool IsLongTerm => !InterView && Pic!.IsLongTerm(Parity); +} + +/// +/// A decoded frame, cropped, in planar YUV. Up to 8 bits each sample is a byte; above, two bytes, little-endian (the +/// layout of the official reconstruction files of the ITU-T H.264.1 series). A monochrome frame (4:0:0) comes with Cb and +/// Cr planes of 4:2:0 size at the middle value 2^(BitDepthChroma − 1), as the official reconstructions of the monochrome +/// conformance streams hold them. H.264 itself specifies neither layout. +/// +/// Luma width after cropping. +/// Luma height after cropping. +/// Luma, × samples. +/// Blue-difference chroma, × samples. +/// Red-difference chroma, same size as . +/// Picture order count: frames are shown by increasing value within a . +/// Increases at each IDR picture. +/// Position of the frame in decoding order (0 for the first). +/// matrix_coefficients of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified). +/// video_full_range_flag of the VUI. +/// chroma_format_idc: 0 monochrome, 1 4:2:0, 2 4:2:2, 3 4:4:4. +/// Bits of each luma sample, 8 to 14. +/// Bits of each chroma sample, 8 to 14. +/// view_id of the view of an MVC stream the frame belongs to (that of the base view, usually 0, otherwise). +public sealed record H264Frame( + int Width, int Height, byte[] Y, byte[] Cb, byte[] Cr, int Poc, int Period, long DecodeIndex, int MatrixCoefficients, bool FullRange, + int ChromaFormat = 1, int BitDepthLuma = 8, int BitDepthChroma = 8, int ViewId = 0) +{ + /// Width of and in samples. + public int ChromaWidth => ChromaFormat == 3 ? Width : (Width + 1) / 2; + + /// Height of and in samples. + public int ChromaHeight => ChromaFormat is 2 or 3 ? Height : (Height + 1) / 2; + + /// Bytes of every sample of the three planes: 2 when either bit depth is above 8, else 1. + public int BytesPerSample => BitDepthLuma > 8 || BitDepthChroma > 8 ? 2 : 1; + + /// Luma sample (row × Width + column), whatever the bit depth. + public int LumaAt(int index) => BytesPerSample == 2 ? Y[2 * index] | (Y[(2 * index) + 1] << 8) : Y[index]; + + /// Sample of a chroma plane (row × ChromaWidth + column), whatever the bit depth. + public int ChromaAt(byte[] plane, int index) => BytesPerSample == 2 ? plane[2 * index] | (plane[(2 * index) + 1] << 8) : plane[index]; + + /// The frame as one planar buffer (Y, then Cb, then Cr), as the official reconstruction files lay it out. + public byte[] ToPlanar() + { + var buffer = new byte[Y.Length + Cb.Length + Cr.Length]; + Y.CopyTo(buffer, 0); + Cb.CopyTo(buffer, Y.Length); + Cr.CopyTo(buffer, Y.Length + Cb.Length); + return buffer; + } +} diff --git a/src/Febe.Core/Codecs/H264/RbspReader.cs b/src/Febe.Core/Codecs/H264/RbspReader.cs new file mode 100644 index 0000000..5161ea3 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/RbspReader.cs @@ -0,0 +1,298 @@ +using System.Buffers.Binary; + +namespace Febe.Core.Codecs.H264; + +/// A malformed or unsupported H.264 stream. +public sealed class H264Exception(string message) : Exception(message); + +/// +/// Reads the bits of a raw byte sequence payload (RBSP): a NAL unit with its emulation prevention bytes removed +/// (ITU-T H.264 §7.4.1). The buffer carries sixteen zero bytes past the end, so reads never need a bounds check; reading +/// past the payload gives zeros and is detected by the callers through . +/// +internal sealed class RbspReader +{ + private readonly byte[] data; + private readonly int length; + private readonly int stopBit; + private int position; + + /// The payload, followed by at least sixteen bytes of padding. + /// Bytes of payload. + /// First byte to read (after the NAL unit header). + internal RbspReader(byte[] data, int length, int startByte) + { + this.data = data; + this.length = length; + position = startByte * 8; + + // The rbsp_stop_one_bit is the last bit set in the payload (trailing cabac_zero_words are all zero). + var last = length - 1; + while (last >= startByte && data[last] == 0) + { + last--; + } + + stopBit = last < startByte ? startByte * 8 : (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(data[last]); + } + + internal byte[] Data => data; + + internal int Position + { + get => position; + set => position = value; + } + + internal int BitsLeft => (length * 8) - position; + + internal bool ByteAligned => (position & 7) == 0; + + /// more_rbsp_data(): true while bits remain before the stop bit. + internal bool MoreRbspData => position < stopBit; + + internal uint Peek(int count) + { + var index = position >> 3; + var word = BinaryPrimitives.ReadUInt64BigEndian(data.AsSpan(index, 8)); + return (uint)((word << (position & 7)) >> (64 - count)); + } + + internal uint Read(int count) + { + if (count == 0) + { + return 0; + } + + var value = Peek(count); + position += count; + return value; + } + + internal void Skip(int count) => position += count; + + internal int ReadBit() + { + var bit = (data[position >> 3] >> (7 - (position & 7))) & 1; + position++; + return bit; + } + + internal bool ReadFlag() => ReadBit() != 0; + + /// ue(v): Exp-Golomb code (§9.1). + internal uint ReadUe() + { + var zeros = 0; + while (ReadBit() == 0) + { + if (++zeros > 31 || position > (length * 8) + 32) + { + throw new H264Exception("Codice Exp-Golomb non valido."); + } + } + + if (zeros == 0) + { + return 0; + } + + return (uint)(((1UL << zeros) - 1) + Read(zeros)); + } + + /// se(v): signed Exp-Golomb code (§9.1.1). + internal int ReadSe() + { + var code = ReadUe(); + var magnitude = (int)((code + 1) >> 1); + return (code & 1) != 0 ? magnitude : -magnitude; + } + + /// A ue(v) value that must not exceed . + internal int ReadUe(int max) + { + var value = ReadUe(); + if (value > (uint)max) + { + throw new H264Exception("Valore fuori dall'intervallo ammesso."); + } + + return (int)value; + } +} + +/// +/// One NAL unit, with its RBSP. The units of the scalable and multiview extensions (prefix 14, slice extension 20 and +/// 21) carry three more header bytes (nal_unit_header_svc_extension or nal_unit_header_mvc_extension, §7.3.1), kept as +/// they are in [1..3]: the emulation prevention bytes are removed only after them. +/// +internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int Length) +{ + /// Bytes of the NAL unit header: 4 for the extension units, else 1. + internal int HeaderLength => HasExtensionHeader(Type) && Length >= 4 ? 4 : 1; + + /// svc_extension_flag of an extension unit: 1 for SVC (Annex G), 0 for MVC (Annex H). + internal bool IsSvc => (Rbsp[1] & 0x80) != 0; + + /// A reader positioned after the header. + internal RbspReader Reader() => new(Rbsp, Length, HeaderLength); + + /// NAL unit types whose header has the three extension bytes. + internal static bool HasExtensionHeader(int type) => type is 14 or 20 or 21; +} + +/// +/// Splitting of byte streams (Annex B) and length-prefixed samples (ISO/IEC 14496-15) into NAL units, one at a time, and +/// removal of their emulation prevention bytes into a buffer the caller keeps: decoding a sample allocates nothing. +/// +internal static class NalUnits +{ + /// Bytes of zero padding a buffer keeps past the payload (see ). + internal const int Padding = 16; + + /// Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer. + internal static NalUnit Parse(ReadOnlySpan nal) + { + byte[]? buffer = null; + return Unescape(nal, ref buffer); + } + + /// + /// Removes the emulation prevention bytes of one NAL unit into , grown when needed; the + /// unit is valid until the buffer is used again. + /// + internal static NalUnit Unescape(ReadOnlySpan nal, ref byte[]? buffer) + { + if (nal.Length < 1) + { + throw new H264Exception("Unità NAL vuota."); + } + + if (buffer is null || buffer.Length < nal.Length + Padding) + { + buffer = new byte[Math.Max(nal.Length + Padding, (buffer?.Length ?? 0) * 2)]; + } + + // Copied run by run between the 0x000003 patterns (a vectorised search), as the byte-by-byte rule of §7.4.1, + // after the header: the three extension bytes of the units 14, 20 and 21 are not part of the RBSP. + ReadOnlySpan pattern = [0, 0, 3]; + var target = buffer.AsSpan(); + var head = NalUnit.HasExtensionHeader(nal[0] & 0x1F) ? Math.Min(4, nal.Length) : 0; + nal[..head].CopyTo(target); + var count = head; + var rest = nal[head..]; + while (true) + { + var i = rest.IndexOf(pattern); + if (i < 0) + { + rest.CopyTo(target[count..]); + count += rest.Length; + break; + } + + rest[..(i + 2)].CopyTo(target[count..]); + count += i + 2; + rest = rest[(i + 3)..]; + } + + target.Slice(count, Padding).Clear(); + return new NalUnit(nal[0] & 0x1F, (nal[0] >> 5) & 3, buffer, count); + } + + /// + /// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from , + /// which moves past it; false when there is none left. + /// + internal static bool NextAnnexB(ReadOnlySpan stream, ref int position, out Range unit) + { + ReadOnlySpan startCode = [0, 0, 1]; + while (position < stream.Length) + { + var found = stream[position..].IndexOf(startCode); + if (found < 0) + { + break; + } + + var start = position + found + 3; + var next = start < stream.Length ? stream[start..].IndexOf(startCode) : -1; + var end = next < 0 ? stream.Length : start + next; + position = end; + + // Zero bytes before the next start code belong to it (four-byte start codes, trailing_zero_8bits). + var trimmed = end; + while (trimmed > start && stream[trimmed - 1] == 0) + { + trimmed--; + } + + if (trimmed > start) + { + unit = start..trimmed; + return true; + } + } + + position = stream.Length; + unit = default; + return false; + } + + /// + /// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from + /// ; false at the end or at a damaged length (what was read stands). + /// + internal static bool NextLengthPrefixed(ReadOnlySpan sample, int lengthSize, ref int position, out Range unit) + { + unit = default; + if (position + lengthSize > sample.Length) + { + return false; + } + + var size = 0; + for (var k = 0; k < lengthSize; k++) + { + size = (size << 8) | sample[position + k]; + } + + position += lengthSize; + if (size <= 0 || size > sample.Length - position) + { + position = sample.Length; + return false; + } + + unit = position..(position + size); + position += size; + return true; + } + + /// The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests). + internal static List SplitAnnexB(ReadOnlySpan stream) + { + var units = new List(); + var position = 0; + while (NextAnnexB(stream, ref position, out var unit)) + { + units.Add(Parse(stream[unit])); + } + + return units; + } + + /// The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests). + internal static List SplitLengthPrefixed(ReadOnlySpan sample, int lengthSize) + { + var units = new List(); + var position = 0; + while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit)) + { + units.Add(Parse(sample[unit])); + } + + return units; + } +} diff --git a/src/Febe.Core/Codecs/H264/Samples.cs b/src/Febe.Core/Codecs/H264/Samples.cs new file mode 100644 index 0000000..eadfbbd --- /dev/null +++ b/src/Febe.Core/Codecs/H264/Samples.cs @@ -0,0 +1,43 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Febe.Core.Codecs.H264; + +/// +/// The two sample types of the decoder: for 8-bit video, above 8 bits (up to 14, +/// High 4:4:4). The planes of a picture are byte arrays of one or two bytes per sample (little-endian, as the official +/// reconstructions store them); the prediction, transform and filter code is generic over the sample type, and the JIT +/// compiles it once for each, so 8-bit video pays nothing for the wider one. +/// +internal static class Samples +{ + /// The value of a sample. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int Get(T sample) + where T : unmanaged => + typeof(T) == typeof(byte) ? Unsafe.As(ref sample) : Unsafe.As(ref sample); + + /// A sample of value , already within the range of the bit depth. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static T Make(int value) + where T : unmanaged + { + if (typeof(T) == typeof(byte)) + { + var b = (byte)value; + return Unsafe.As(ref b); + } + + var u = (ushort)value; + return Unsafe.As(ref u); + } + + /// A plane stored as bytes, seen as samples of type . + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Span Plane(byte[] plane) + where T : unmanaged => MemoryMarshal.Cast(plane.AsSpan()); + + /// Clip1 of §5.7: within 0... + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int Clip(int value, int max) => value < 0 ? 0 : value > max ? max : value; +} diff --git a/src/Febe.Core/Codecs/H264/SliceHeader.cs b/src/Febe.Core/Codecs/H264/SliceHeader.cs new file mode 100644 index 0000000..f5ec2c5 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/SliceHeader.cs @@ -0,0 +1,687 @@ +namespace Febe.Core.Codecs.H264; + +/// Slice types (slice_type modulo 5). +internal enum SliceType +{ + P = 0, + B = 1, + I = 2, + SP = 3, + SI = 4, +} + +/// nal_unit_header_svc_extension() (§G.7.3.1.1): where the NAL unit sits among the layers of an SVC stream. +internal readonly record struct SvcNalHeader( + bool Idr, int PriorityId, bool NoInterLayerPred, int DependencyId, int QualityId, int TemporalId, bool UseRefBasePic, + bool Discardable, bool Output) +{ + /// DQId = (dependency_id << 4) + quality_id. + internal int DqId => (DependencyId << 4) + QualityId; + + /// The extension header of a NAL unit 14 or 20 with svc_extension_flag 1. + internal static SvcNalHeader Of(NalUnit nal) + { + int b1 = nal.Rbsp[1], b2 = nal.Rbsp[2], b3 = nal.Rbsp[3]; + return new SvcNalHeader( + (b1 & 0x40) != 0, b1 & 0x3F, (b2 & 0x80) != 0, (b2 >> 4) & 7, b2 & 15, b3 >> 5, (b3 & 0x10) != 0, (b3 & 8) != 0, (b3 & 4) != 0); + } +} + +/// The fields of slice_header_in_scalable_extension() that a slice of AVC does not have. +internal sealed class SvcSliceFields +{ + internal SvcNalHeader Header; + internal bool BasePredWeightTable; + internal bool StoreRefBasePic; + internal bool BaseMarking; + internal int RefLayerDqId; + internal int DisableInterLayerDeblocking; + internal int InterLayerAlphaOffset; + internal int InterLayerBetaOffset; + internal bool ConstrainedIntraResampling; + internal bool ScaledRefLayerOffsets; + internal bool SliceSkip; + internal int NumMbsInSlice; + internal bool AdaptiveBaseMode; + internal bool DefaultBaseMode; + internal bool AdaptiveMotionPrediction; + internal bool DefaultMotionPrediction; + internal bool AdaptiveResidualPrediction; + internal bool DefaultResidualPrediction; + internal bool TcoeffLevelPrediction; + internal int ScanIdxStart; + internal int ScanIdxEnd = 15; +} + +/// A slice header (§7.3.3), with the reference list modifications, weights and marking it carries. +internal sealed class SliceHeader +{ + internal int FirstMb; + internal SliceType Type; + internal int PpsId; + + /// colour_plane_id: the colour plane (0 Y, 1 Cb, 2 Cr) of a slice when the planes are coded separately. + internal int ColourPlaneId; + + internal int FrameNum; + internal bool FieldPic; + internal bool BottomField; + internal int IdrPicId; + internal int PocLsb; + internal int DeltaPocBottom; + internal int DeltaPoc0; + internal int DeltaPoc1; + + /// redundant_pic_cnt: 0 for the primary coded picture, above 0 for a redundant one. + internal int RedundantPicCnt; + + internal bool DirectSpatialMvPred; + internal int NumRefIdxActiveL0; + internal int NumRefIdxActiveL1; + + /// ref_pic_list_modification: (modification_of_pic_nums_idc, value) per list. + internal List<(int Idc, int Value)>[] Modifications = [[], []]; + + internal int LumaLog2WeightDenom; + internal int ChromaLog2WeightDenom; + + /// Explicit weights [list][refIdx * 3 + component] and offsets; null when there is no pred_weight_table. + internal int[][]? Weights; + + internal int[][]? Offsets; + + internal bool NoOutputOfPriorPics; + internal bool LongTermReference; + internal bool AdaptiveMarking; + + /// memory_management_control_operation entries: (operation, value 1, value 2). + internal List<(int Op, int A, int B)> Mmco = []; + + internal int CabacInitIdc; + internal int QpDelta; + internal int DisableDeblocking; + internal int AlphaOffset; + internal int BetaOffset; + + /// sp_for_switch_flag of an SP slice: its P macroblocks decode as those of a switching picture (§8.6.1). + internal bool SpForSwitch; + + /// QS_Y of an SP or SI slice: pic_init_qs_minus26 + 26 + slice_qs_delta. + internal int Qs; + + /// slice_group_change_cycle (map types 3–5 of FMO). + internal int SliceGroupChangeCycle; + + /// The scalable part of slice_header_in_scalable_extension() (§G.7.3.3.4), for a slice of NAL unit 20 of SVC. + internal SvcSliceFields? Svc; + + internal bool IsIntra => Type is SliceType.I or SliceType.SI; + + /// A P or SP slice: both are parsed and predicted alike (an SP slice differs in the reconstruction). + internal bool IsP => Type is SliceType.P or SliceType.SP; + + /// An SP or SI slice: switching pictures (§8.6). + internal bool IsSwitching => Type is SliceType.SP or SliceType.SI; + + internal bool IsB => Type == SliceType.B; + + /// 0 frame, 1 top field, 2 bottom field. + internal int Structure => !FieldPic ? 0 : BottomField ? 2 : 1; + + /// + /// slice_header() of a NAL unit 1, 5 or () of a non-base view: there the list + /// modifications may also insert inter-view references (modification_of_pic_nums_idc 4 and 5, §H.7.3.3.1.1), and + /// stands for the view component, with type 5 when it is IDR. + /// + internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary sequences, IReadOnlyDictionary pictures, out Sps sps, out Pps pps, bool multiview = false) + { + var h = new SliceHeader { FirstMb = (int)r.ReadUe() }; + var type = r.ReadUe(9); + h.Type = (SliceType)(type % 5); + h.PpsId = r.ReadUe(255); + if (!pictures.TryGetValue(h.PpsId, out pps!) || !sequences.TryGetValue(pps.SpsId, out sps!)) + { + throw new H264Exception("Slice senza i suoi insiemi di parametri."); + } + + if (sps.SeparateColourPlane) + { + h.ColourPlaneId = (int)r.Read(2); + if (h.ColourPlaneId > 2) + { + throw new H264Exception("colour_plane_id non valido."); + } + } + + h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum); + if (!sps.FrameMbsOnly) + { + h.FieldPic = r.ReadFlag(); + if (h.FieldPic) + { + h.BottomField = r.ReadFlag(); + } + } + + if (nal.Type == 5) + { + h.IdrPicId = (int)r.ReadUe(); + } + + if (sps.PocType == 0) + { + h.PocLsb = (int)r.Read(sps.Log2MaxPocLsb); + if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic) + { + h.DeltaPocBottom = r.ReadSe(); + } + } + else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero) + { + h.DeltaPoc0 = r.ReadSe(); + if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic) + { + h.DeltaPoc1 = r.ReadSe(); + } + } + + if (pps.RedundantPicCntPresent) + { + h.RedundantPicCnt = r.ReadUe(127); + } + + if (h.IsB) + { + h.DirectSpatialMvPred = r.ReadFlag(); + } + + h.NumRefIdxActiveL0 = pps.NumRefIdxL0DefaultActive; + h.NumRefIdxActiveL1 = pps.NumRefIdxL1DefaultActive; + if (!h.IsIntra) + { + if (r.ReadFlag()) + { + h.NumRefIdxActiveL0 = r.ReadUe(31) + 1; + if (h.IsB) + { + h.NumRefIdxActiveL1 = r.ReadUe(31) + 1; + } + } + + ParseModifications(r, h.Modifications[0], multiview); + if (h.IsB) + { + ParseModifications(r, h.Modifications[1], multiview); + } + } + + if (!h.IsB) + { + h.NumRefIdxActiveL1 = 0; + } + + if (h.IsIntra) + { + h.NumRefIdxActiveL0 = 0; + } + + if ((pps.WeightedPred && h.IsP) || (pps.WeightedBipredIdc == 1 && h.IsB)) + { + ParseWeights(r, h, sps); + } + + if (nal.RefIdc != 0) + { + if (nal.Type == 5) + { + h.NoOutputOfPriorPics = r.ReadFlag(); + h.LongTermReference = r.ReadFlag(); + } + else if ((h.AdaptiveMarking = r.ReadFlag())) + { + for (var guard = 0; guard < 100; guard++) + { + var op = r.ReadUe(6); + if (op == 0) + { + break; + } + + int a = 0, b = 0; + if (op is 1 or 3) + { + a = (int)r.ReadUe(); // difference_of_pic_nums_minus1 + } + + if (op == 2) + { + a = (int)r.ReadUe(); // long_term_pic_num + } + + if (op is 3 or 6) + { + b = (int)r.ReadUe(); // long_term_frame_idx + } + + if (op == 4) + { + a = (int)r.ReadUe(); // max_long_term_frame_idx_plus1 + } + + h.Mmco.Add((op, a, b)); + } + } + } + + if (pps.Cabac && !h.IsIntra) + { + h.CabacInitIdc = r.ReadUe(2); + } + + h.QpDelta = r.ReadSe(); + if (h.Type is SliceType.SP or SliceType.SI) + { + if (h.Type == SliceType.SP) + { + h.SpForSwitch = r.ReadFlag(); + } + + h.Qs = pps.PicInitQs + r.ReadSe(); + if (h.Qs is < 0 or > 51) + { + throw new H264Exception("QS della slice non valido."); + } + } + + if (pps.DeblockingFilterControlPresent) + { + h.DisableDeblocking = r.ReadUe(2); + if (h.DisableDeblocking != 1) + { + h.AlphaOffset = r.ReadSe() * 2; + h.BetaOffset = r.ReadSe() * 2; + } + } + + if (pps.NumSliceGroups > 1 && pps.SliceGroupMapType is >= 3 and <= 5) + { + // Ceil(Log2(PicSizeInMapUnits ÷ SliceGroupChangeRate + 1)) bits (§7.4.3). + var size = sps.WidthInMbs * sps.HeightInMapUnits; + var units = (size + pps.SliceGroupChangeRate - 1) / pps.SliceGroupChangeRate; + var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)units); + h.SliceGroupChangeCycle = (int)r.Read(bits); + } + + return h; + } + + /// ref_pic_list_modification() (§7.3.3.1), or ref_pic_list_mvc_modification() (§H.7.3.3.1.1). + internal static void ParseModifications(RbspReader r, List<(int, int)> list, bool multiview = false) + { + if (!r.ReadFlag()) + { + return; + } + + for (var guard = 0; guard < 100; guard++) + { + var idc = r.ReadUe(5); + if (idc == 3) + { + return; + } + + if (idc > 2 && !(multiview && idc is 4 or 5)) + { + throw new H264Exception("Modifica della lista di riferimento non gestita."); + } + + list.Add((idc, (int)r.ReadUe())); + } + + throw new H264Exception("Modifiche della lista di riferimento senza fine."); + } + + /// + /// slice_header_in_scalable_extension() (§G.7.3.3.4) of a slice of NAL unit 20 with the SVC header + /// ; is the header of the layer with quality_id 0 of the same + /// dependency, from which a slice with quality_id above 0 takes its lists, weights and marking (§G.7.4.3.4). + /// + internal static SliceHeader ParseScalable(RbspReader r, NalUnit nal, SvcNalHeader ext, IReadOnlyDictionary subsetSequences, IReadOnlyDictionary pictures, SliceHeader? baseHeader, out Sps sps, out Pps pps) + { + var h = new SliceHeader { FirstMb = (int)r.ReadUe() }; + var type = r.ReadUe(9); + h.Type = (SliceType)(type % 5); + if (h.Type is SliceType.SP or SliceType.SI) + { + throw new H264Exception("Tipo di slice non valido in SVC."); + } + + h.PpsId = r.ReadUe(255); + if (!pictures.TryGetValue(h.PpsId, out pps!) || !subsetSequences.TryGetValue(pps.SpsId, out sps!) || sps.Svc is null) + { + throw new H264Exception("Slice SVC senza i suoi insiemi di parametri."); + } + + var svc = new SvcSliceFields { Header = ext }; + h.Svc = svc; + if (sps.SeparateColourPlane) + { + h.ColourPlaneId = (int)r.Read(2); + } + + h.FrameNum = (int)r.Read(sps.Log2MaxFrameNum); + if (!sps.FrameMbsOnly) + { + h.FieldPic = r.ReadFlag(); + if (h.FieldPic) + { + h.BottomField = r.ReadFlag(); + } + } + + if (ext.Idr) + { + h.IdrPicId = (int)r.ReadUe(); + } + + if (sps.PocType == 0) + { + h.PocLsb = (int)r.Read(sps.Log2MaxPocLsb); + if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic) + { + h.DeltaPocBottom = r.ReadSe(); + } + } + else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero) + { + h.DeltaPoc0 = r.ReadSe(); + if (pps.BottomFieldPicOrderInFramePresent && !h.FieldPic) + { + h.DeltaPoc1 = r.ReadSe(); + } + } + + if (pps.RedundantPicCntPresent) + { + h.RedundantPicCnt = r.ReadUe(127); + } + + if (ext.QualityId == 0) + { + if (h.IsB) + { + h.DirectSpatialMvPred = r.ReadFlag(); + } + + h.NumRefIdxActiveL0 = h.IsIntra ? 0 : pps.NumRefIdxL0DefaultActive; + h.NumRefIdxActiveL1 = h.IsB ? pps.NumRefIdxL1DefaultActive : 0; + if (!h.IsIntra) + { + if (r.ReadFlag()) + { + h.NumRefIdxActiveL0 = r.ReadUe(31) + 1; + if (h.IsB) + { + h.NumRefIdxActiveL1 = r.ReadUe(31) + 1; + } + } + + ParseModifications(r, h.Modifications[0]); + if (h.IsB) + { + ParseModifications(r, h.Modifications[1]); + } + } + + if ((pps.WeightedPred && h.IsP) || (pps.WeightedBipredIdc == 1 && h.IsB)) + { + var fromBase = !ext.NoInterLayerPred && r.ReadFlag(); // base_pred_weight_table_flag + svc.BasePredWeightTable = fromBase; + if (!fromBase) + { + ParseWeights(r, h, sps); + } + } + + if (nal.RefIdc != 0) + { + ParseMarking(r, h, ext.Idr); + if (!sps.Svc.SliceHeaderRestriction) + { + svc.StoreRefBasePic = r.ReadFlag(); + if ((ext.UseRefBasePic || svc.StoreRefBasePic) && !ext.Idr) + { + svc.BaseMarking = true; + SkipBaseMarking(r); + } + } + } + } + else + { + // A quality refinement: the lists, the weights and the marking of the layer below (§G.7.4.3.4). + if (baseHeader is null) + { + throw new H264Exception("Strato di qualità senza il suo strato di base."); + } + + h.DirectSpatialMvPred = baseHeader.DirectSpatialMvPred; + h.NumRefIdxActiveL0 = h.IsIntra ? 0 : baseHeader.NumRefIdxActiveL0; + h.NumRefIdxActiveL1 = h.IsB ? baseHeader.NumRefIdxActiveL1 : 0; + h.Modifications = baseHeader.Modifications; + h.LumaLog2WeightDenom = baseHeader.LumaLog2WeightDenom; + h.ChromaLog2WeightDenom = baseHeader.ChromaLog2WeightDenom; + h.Weights = baseHeader.Weights; + h.Offsets = baseHeader.Offsets; + } + + if (pps.Cabac && !h.IsIntra) + { + h.CabacInitIdc = r.ReadUe(2); + } + + h.QpDelta = r.ReadSe(); + if (pps.DeblockingFilterControlPresent) + { + h.DisableDeblocking = r.ReadUe(6); + if (h.DisableDeblocking != 1) + { + h.AlphaOffset = r.ReadSe() * 2; + h.BetaOffset = r.ReadSe() * 2; + } + } + + if (pps.NumSliceGroups > 1 && pps.SliceGroupMapType is >= 3 and <= 5) + { + var size = sps.WidthInMbs * sps.HeightInMapUnits; + var units = (size + pps.SliceGroupChangeRate - 1) / pps.SliceGroupChangeRate; + var bits = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)units); + h.SliceGroupChangeCycle = (int)r.Read(bits); + } + + var dqId = (ext.DependencyId << 4) + ext.QualityId; + svc.RefLayerDqId = ext.QualityId > 0 ? dqId - 1 : -1; + if (!ext.NoInterLayerPred && ext.QualityId == 0) + { + svc.RefLayerDqId = r.ReadUe(127); + if (sps.Svc.InterLayerDeblockingFilterControlPresent) + { + svc.DisableInterLayerDeblocking = r.ReadUe(6); + if (svc.DisableInterLayerDeblocking != 1) + { + svc.InterLayerAlphaOffset = r.ReadSe() * 2; + svc.InterLayerBetaOffset = r.ReadSe() * 2; + } + } + + svc.ConstrainedIntraResampling = r.ReadFlag(); + if (sps.Svc.ExtendedSpatialScalabilityIdc == 2) + { + if (sps.ChromaArrayType > 0) + { + r.Skip(3); // ref_layer_chroma_phase_x_plus1_flag, ref_layer_chroma_phase_y_plus1 + } + + svc.ScaledRefLayerOffsets = true; + for (var i = 0; i < 4; i++) + { + _ = r.ReadSe(); + } + } + } + + if (!ext.NoInterLayerPred) + { + svc.SliceSkip = r.ReadFlag(); + if (svc.SliceSkip) + { + svc.NumMbsInSlice = (int)r.ReadUe() + 1; + } + else + { + svc.AdaptiveBaseMode = r.ReadFlag(); + if (!svc.AdaptiveBaseMode) + { + svc.DefaultBaseMode = r.ReadFlag(); + } + + if (!svc.DefaultBaseMode) + { + svc.AdaptiveMotionPrediction = r.ReadFlag(); + if (!svc.AdaptiveMotionPrediction) + { + svc.DefaultMotionPrediction = r.ReadFlag(); + } + } + + svc.AdaptiveResidualPrediction = r.ReadFlag(); + if (!svc.AdaptiveResidualPrediction) + { + svc.DefaultResidualPrediction = r.ReadFlag(); + } + } + + if (sps.Svc.AdaptiveTcoeffLevelPrediction) + { + svc.TcoeffLevelPrediction = r.ReadFlag(); + } + else + { + svc.TcoeffLevelPrediction = sps.Svc.SeqTcoeffLevelPrediction; + } + } + + svc.ScanIdxEnd = 15; + if (!sps.Svc.SliceHeaderRestriction && !svc.SliceSkip) + { + svc.ScanIdxStart = (int)r.Read(4); + svc.ScanIdxEnd = (int)r.Read(4); + } + + return h; + } + + /// dec_ref_pic_marking() (§7.3.3.3) of an IDR picture or not. + private static void ParseMarking(RbspReader r, SliceHeader h, bool idr) + { + if (idr) + { + h.NoOutputOfPriorPics = r.ReadFlag(); + h.LongTermReference = r.ReadFlag(); + return; + } + + if (!(h.AdaptiveMarking = r.ReadFlag())) + { + return; + } + + for (var guard = 0; guard < 100; guard++) + { + var op = r.ReadUe(6); + if (op == 0) + { + return; + } + + int a = 0, b = 0; + if (op is 1 or 2 or 3 or 4) + { + a = (int)r.ReadUe(); + } + + if (op is 3 or 6) + { + b = (int)r.ReadUe(); + } + + h.Mmco.Add((op, a, b)); + } + } + + /// dec_ref_base_pic_marking() (§G.7.3.3.5), skipped: base representations are not kept. + internal static void SkipBaseMarking(RbspReader r) + { + if (!r.ReadFlag()) + { + return; + } + + for (var guard = 0; guard < 100; guard++) + { + var op = r.ReadUe(3); + if (op == 0) + { + return; + } + + _ = r.ReadUe(); + } + } + + private static void ParseWeights(RbspReader r, SliceHeader h, Sps sps) + { + h.LumaLog2WeightDenom = r.ReadUe(7); + // No chroma weights without chroma: monochrome, or each colour plane coded separately (ChromaArrayType 0). + var chroma = sps.ChromaArrayType != 0; + if (chroma) + { + h.ChromaLog2WeightDenom = r.ReadUe(7); + } + + h.Weights = new int[2][]; + h.Offsets = new int[2][]; + for (var list = 0; list < (h.IsB ? 2 : 1); list++) + { + var count = list == 0 ? h.NumRefIdxActiveL0 : h.NumRefIdxActiveL1; + var weights = new int[count * 3]; + var offsets = new int[count * 3]; + for (var i = 0; i < count; i++) + { + weights[i * 3] = 1 << h.LumaLog2WeightDenom; + weights[(i * 3) + 1] = weights[(i * 3) + 2] = 1 << h.ChromaLog2WeightDenom; + if (r.ReadFlag()) + { + weights[i * 3] = r.ReadSe(); + offsets[i * 3] = r.ReadSe(); + } + + if (chroma && r.ReadFlag()) + { + for (var c = 1; c <= 2; c++) + { + weights[(i * 3) + c] = r.ReadSe(); + offsets[(i * 3) + c] = r.ReadSe(); + } + } + } + + h.Weights[list] = weights; + h.Offsets[list] = offsets; + } + + h.Weights[1] ??= []; + h.Offsets[1] ??= []; + } +} diff --git a/src/Febe.Core/Codecs/H264/SwitchingTransform.cs b/src/Febe.Core/Codecs/H264/SwitchingTransform.cs new file mode 100644 index 0000000..7c92469 --- /dev/null +++ b/src/Febe.Core/Codecs/H264/SwitchingTransform.cs @@ -0,0 +1,161 @@ +namespace Febe.Core.Codecs.H264; + +/// +/// The reconstruction of the P macroblocks of SP slices and of the SI macroblocks (§8.6): the prediction is transformed +/// and quantised with QS together with the received levels, so that a switching picture rebuilds exactly the same +/// samples whichever stream it was reached from. The block is then decoded with QS as usual, and the result replaces the +/// prediction instead of being added to it. +/// +internal static class SwitchingTransform +{ + /// Quantisation factors (the inverse of normAdjust4x4) by QS % 6 and class of position (0 even-even, 1 odd-odd, 2 others). + private static readonly int[,] Quant = + { + { 13107, 5243, 8066 }, { 11916, 4660, 7490 }, { 10082, 4194, 6554 }, { 9362, 3647, 5825 }, { 8192, 3355, 5243 }, { 7282, 2893, 4559 }, + }; + + /// Aij of §8.6.1 by class of position. + private static readonly int[] Norm = [16, 25, 20]; + + /// The class of each raster position of a 4×4 block (0 even row and column, 1 both odd, 2 the others). + private static readonly byte[] Class = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1]; + + /// + /// A luma 4×4 block: the prediction at is replaced by the reconstruction from it and the levels + /// (raster order, not scaled). is set for SI macroblocks and for SP slices with + /// sp_for_switch_flag: the levels are then added to the quantised prediction (§8.6.2) instead of the scaled ones to the + /// transformed prediction (§8.6.1). + /// + internal static void Luma4x4(byte[] plane, int o, int stride, ReadOnlySpan levels, int qp, int qs, bool levelInQs) + { + Span c = stackalloc int[16]; + Forward(plane, o, stride, c); + int qpMod = qp % 6, qpDiv = qp / 6, qsMod = qs % 6, qsDiv = qs / 6; + for (var pos = 0; pos < 16; pos++) + { + var cls = Class[pos]; + var level = Requantise(c[pos], levels[pos], cls, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: false); + c[pos] = (level * H264Tables.NormAdjust4x4[qsMod, cls]) << qsDiv; + } + + Store4x4(c, plane, o, stride); + } + + /// + /// One chroma component (four 4×4 blocks): holds the AC levels of the four blocks (block × 16 + /// + raster position; position 0 is ignored), the four DC levels in the order they are parsed. + /// + internal static void Chroma(byte[] plane, int o, int stride, ReadOnlySpan ac, ReadOnlySpan dc, int qpc, int qsc, bool levelInQs) + { + Span c = stackalloc int[64]; + for (var b = 0; b < 4; b++) + { + Forward(plane, BlockOffset(o, stride, b), stride, c.Slice(b * 16, 16)); + } + + int qpMod = qpc % 6, qpDiv = qpc / 6, qsMod = qsc % 6, qsDiv = qsc / 6; + + // The DC terms of the prediction through the 2×2 transform, combined with the levels, back through it (§8.6.1). + int p0 = c[0], p1 = c[16], p2 = c[32], p3 = c[48]; + Span q = [p0 + p1 + p2 + p3, p0 - p1 + p2 - p3, p0 + p1 - p2 - p3, p0 - p1 - p2 + p3]; + for (var k = 0; k < 4; k++) + { + q[k] = Requantise(q[k], dc[k], 0, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: true); + } + + int f0 = q[0] + q[1] + q[2] + q[3], f1 = q[0] - q[1] + q[2] - q[3], f2 = q[0] + q[1] - q[2] - q[3], f3 = q[0] - q[1] - q[2] + q[3]; + var scaleDc = 16 * H264Tables.NormAdjust4x4[qsMod, 0]; + c[0] = ((f0 * scaleDc) << qsDiv) >> 5; + c[16] = ((f1 * scaleDc) << qsDiv) >> 5; + c[32] = ((f2 * scaleDc) << qsDiv) >> 5; + c[48] = ((f3 * scaleDc) << qsDiv) >> 5; + + for (var b = 0; b < 4; b++) + { + var block = c.Slice(b * 16, 16); + for (var pos = 1; pos < 16; pos++) + { + var cls = Class[pos]; + var level = Requantise(block[pos], ac[(b * 16) + pos], cls, qpMod, qpDiv, qsMod, qsDiv, levelInQs, dc: false); + block[pos] = (level * H264Tables.NormAdjust4x4[qsMod, cls]) << qsDiv; + } + + Store4x4(block, plane, BlockOffset(o, stride, b), stride); + } + } + + /// + /// The level in QS of one coefficient from the transformed prediction and the received + /// level: equations 8-401 to 8-404 of §8.6.1 (with QP), or 8-410 to 8-411 of §8.6.2 (in QS). The DC terms of + /// chroma carry one bit more of scaling. + /// + private static int Requantise(int predicted, int level, int cls, int qpMod, int qpDiv, int qsMod, int qsDiv, bool levelInQs, bool dc) + { + var extra = dc ? 1 : 0; + var shift = 15 + qsDiv + extra; + var round = 1L << (shift - 1); + var quant = Quant[qsMod, cls]; + if (levelInQs) + { + var magnitude = (int)(((Math.Abs((long)predicted) * quant) + round) >> shift); + return level + (predicted < 0 ? -magnitude : magnitude); + } + + var sum = predicted + ((((long)level * H264Tables.NormAdjust4x4[qpMod, cls] * Norm[cls]) << qpDiv) >> (6 - extra)); + var result = (int)Math.Min(((Math.Abs(sum) * quant) + round) >> shift, int.MaxValue / 64); + return sum < 0 ? -result : result; + } + + private static int BlockOffset(int o, int stride, int b) => o + ((b >> 1) * 4 * stride) + ((b & 1) * 4); + + /// The forward 4×4 core transform of the samples at (§8.6.1, cp), raster order. + private static void Forward(byte[] plane, int o, int stride, Span c) + { + for (var i = 0; i < 4; i++) + { + var row = o + (i * stride); + int x0 = plane[row], x1 = plane[row + 1], x2 = plane[row + 2], x3 = plane[row + 3]; + int a = x0 + x3, b = x1 + x2, d = x1 - x2, e = x0 - x3; + c[i * 4] = a + b; + c[(i * 4) + 1] = (2 * e) + d; + c[(i * 4) + 2] = a - b; + c[(i * 4) + 3] = e - (2 * d); + } + + for (var j = 0; j < 4; j++) + { + int x0 = c[j], x1 = c[4 + j], x2 = c[8 + j], x3 = c[12 + j]; + int a = x0 + x3, b = x1 + x2, d = x1 - x2, e = x0 - x3; + c[j] = a + b; + c[4 + j] = (2 * e) + d; + c[8 + j] = a - b; + c[12 + j] = e - (2 * d); + } + } + + /// The inverse 4×4 transform of scaled coefficients (§8.5.12), stored at in place of the prediction. + private static void Store4x4(Span d, byte[] plane, int o, int stride) + { + for (var i = 0; i < 4; i++) + { + var r = d.Slice(i * 4, 4); + int e0 = r[0] + r[2], e1 = r[0] - r[2], e2 = (r[1] >> 1) - r[3], e3 = r[1] + (r[3] >> 1); + r[0] = e0 + e3; + r[1] = e1 + e2; + r[2] = e1 - e2; + r[3] = e0 - e3; + } + + for (var j = 0; j < 4; j++) + { + int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j]; + int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1); + plane[o + j] = Clip((g0 + g3 + 32) >> 6); + plane[o + stride + j] = Clip((g1 + g2 + 32) >> 6); + plane[o + (2 * stride) + j] = Clip((g1 - g2 + 32) >> 6); + plane[o + (3 * stride) + j] = Clip((g0 - g3 + 32) >> 6); + } + } + + private static byte Clip(int v) => (byte)(v < 0 ? 0 : v > 255 ? 255 : v); +} diff --git a/src/Febe.Core/Codecs/H264/Transform.cs b/src/Febe.Core/Codecs/H264/Transform.cs new file mode 100644 index 0000000..f02dc5f --- /dev/null +++ b/src/Febe.Core/Codecs/H264/Transform.cs @@ -0,0 +1,178 @@ +using static Febe.Core.Codecs.H264.Samples; + +namespace Febe.Core.Codecs.H264; + +/// +/// Inverse transforms of §8.5.12 and §8.5.13, adding the residual to the prediction already in the plane, and the +/// transform bypass of lossless macroblocks (§8.5.15), at any bit depth (max is 2^BitDepth − 1). +/// +internal static class Transform +{ + /// Inverse 4×4 transform of scaled coefficients (raster order), added to the 4×4 block at . + internal static void Add4x4(Span d, Span plane, int o, int stride, int max) + where T : unmanaged + { + for (var i = 0; i < 4; i++) + { + var r = d.Slice(i * 4, 4); + int e0 = r[0] + r[2], e1 = r[0] - r[2], e2 = (r[1] >> 1) - r[3], e3 = r[1] + (r[3] >> 1); + r[0] = e0 + e3; + r[1] = e1 + e2; + r[2] = e1 - e2; + r[3] = e0 - e3; + } + + for (var j = 0; j < 4; j++) + { + int f0 = d[j], f1 = d[4 + j], f2 = d[8 + j], f3 = d[12 + j]; + int g0 = f0 + f2, g1 = f0 - f2, g2 = (f1 >> 1) - f3, g3 = f1 + (f3 >> 1); + AddSample(plane, o + j, g0 + g3, max); + AddSample(plane, o + stride + j, g1 + g2, max); + AddSample(plane, o + (2 * stride) + j, g1 - g2, max); + AddSample(plane, o + (3 * stride) + j, g0 - g3, max); + } + } + + /// Inverse 8×8 transform (§8.5.13), added to the 8×8 block at . + internal static void Add8x8(Span d, Span plane, int o, int stride, int max) + where T : unmanaged + { + Span tmp = stackalloc int[8]; + for (var i = 0; i < 8; i++) + { + var row = d.Slice(i * 8, 8); + Butterfly8(row, row); + } + + Span column = stackalloc int[8]; + for (var j = 0; j < 8; j++) + { + for (var i = 0; i < 8; i++) + { + column[i] = d[(i * 8) + j]; + } + + Butterfly8(column, tmp); + for (var i = 0; i < 8; i++) + { + AddSample(plane, o + (i * stride) + j, tmp[i], max); + } + } + } + + /// + /// The residual of a lossless block (TransformBypassModeFlag, §8.5.15): holds the + /// × coefficients in raster order, which are the residual itself; under an + /// intra prediction that is horizontal ( 1) or vertical (2) each sample adds those before it + /// along the direction of the prediction. The result is added to the prediction in the plane. + /// + internal static void AddBypass(Span r, int w, int h, int dpcm, Span plane, int o, int stride, int max) + where T : unmanaged + { + if (dpcm == 1) + { + for (var y = 0; y < h; y++) + { + for (var x = 1; x < w; x++) + { + r[(y * w) + x] += r[(y * w) + x - 1]; + } + } + } + else if (dpcm == 2) + { + for (var y = 1; y < h; y++) + { + for (var x = 0; x < w; x++) + { + r[(y * w) + x] += r[((y - 1) * w) + x]; + } + } + } + + for (var y = 0; y < h; y++) + { + var row = plane.Slice(o + (y * stride), w); + for (var x = 0; x < w; x++) + { + row[x] = Make(Clip(Get(row[x]) + r[(y * w) + x], max)); + } + } + } + + private static void Butterfly8(ReadOnlySpan d, Span output) + { + int a0 = d[0] + d[4], a4 = d[0] - d[4], a2 = (d[2] >> 1) - d[6], a6 = d[2] + (d[6] >> 1); + int b0 = a0 + a6, b2 = a4 + a2, b4 = a4 - a2, b6 = a0 - a6; + var a1 = -d[3] + d[5] - d[7] - (d[7] >> 1); + var a3 = d[1] + d[7] - d[3] - (d[3] >> 1); + var a5 = -d[1] + d[7] + d[5] + (d[5] >> 1); + var a7 = d[3] + d[5] + d[1] + (d[1] >> 1); + int b1 = a1 + (a7 >> 2), b7 = a7 - (a1 >> 2), b3 = a3 + (a5 >> 2), b5 = (a3 >> 2) - a5; + output[0] = b0 + b7; + output[1] = b2 + b5; + output[2] = b4 + b3; + output[3] = b6 + b1; + output[4] = b6 - b1; + output[5] = b4 - b3; + output[6] = b2 - b5; + output[7] = b0 - b7; + } + + /// Inverse 4×4 Hadamard transform of the Intra_16x16 DC coefficients (§8.5.10), in place, raster order. + internal static void Hadamard4x4(Span c) + { + for (var i = 0; i < 4; i++) + { + var r = c.Slice(i * 4, 4); + int e0 = r[0] + r[1], e1 = r[0] - r[1], e2 = r[2] + r[3], e3 = r[2] - r[3]; + r[0] = e0 + e2; + r[1] = e0 - e2; + r[2] = e1 - e3; + r[3] = e1 + e3; + } + + // The matrix is [1 1 1 1; 1 1 -1 -1; 1 -1 -1 1; 1 -1 1 -1]: rows above, then columns. + for (var j = 0; j < 4; j++) + { + int f0 = c[j], f1 = c[4 + j], f2 = c[8 + j], f3 = c[12 + j]; + int e0 = f0 + f1, e1 = f0 - f1, e2 = f2 + f3, e3 = f2 - f3; + c[j] = e0 + e2; + c[4 + j] = e0 - e2; + c[8 + j] = e1 - e3; + c[12 + j] = e1 + e3; + } + } + + /// + /// The inverse transform of the eight chroma DC coefficients of 4:2:2 (equation 8-329): f = A · c · B, with c of four + /// rows and two columns in raster order, A the 4×4 matrix of and B = [1 1; 1 −1]; in place. + /// + internal static void ChromaDc422(Span c) + { + // c · B on each row. + for (var i = 0; i < 4; i++) + { + int a = c[2 * i], b = c[(2 * i) + 1]; + c[2 * i] = a + b; + c[(2 * i) + 1] = a - b; + } + + // A · (c · B) on each column. + for (var j = 0; j < 2; j++) + { + int f0 = c[j], f1 = c[2 + j], f2 = c[4 + j], f3 = c[6 + j]; + int e0 = f0 + f1, e1 = f0 - f1, e2 = f2 + f3, e3 = f2 - f3; + c[j] = e0 + e2; + c[2 + j] = e0 - e2; + c[4 + j] = e1 - e3; + c[6 + j] = e1 + e3; + } + } + + private static void AddSample(Span plane, int index, int residual, int max) + where T : unmanaged + { + plane[index] = Make(Clip(Get(plane[index]) + ((residual + 32) >> 6), max)); + } +} diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index 1afca4d..a5b215c 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -18,7 +18,8 @@ internal sealed record ContentFacts( /// /// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for -/// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, ffprobe as an extra for the rest). +/// photos, date from the metadata (EXIF for photos, mvhd for MP4/MOV, the in-house container readers for WebM, Matroska, AVI, +/// WMV/ASF, FLV and MPEG program streams). /// internal static class ContentAnalysis { @@ -145,8 +146,9 @@ internal static class ContentAnalysis } } - if (env.VideoProbe is { } probe && (created is null || duration is null || width is null)) + if (created is null || duration is null || width is null) { + var probe = env.VideoProbe ?? new ContainerVideoMetadataProbe(env.Clock); var extra = await probe.ProbeAsync(fullPath, ct).ConfigureAwait(false); if (extra is not null) { diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 762e1c7..1a75ac2 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -688,7 +688,7 @@ public sealed class ImportCopier(ImportEnvironment env) return null; } - var frame = await env.Frames.ExtractJpegAsync(videoPath, ct).ConfigureAwait(false); + var frame = await env.Frames.ExtractImageAsync(videoPath, ct).ConfigureAwait(false); return frame is null ? null : new MemoryStream(frame, writable: false); } diff --git a/src/Febe.Core/Import/ImportEnvironment.cs b/src/Febe.Core/Import/ImportEnvironment.cs index e1d4cc1..d8afc19 100644 --- a/src/Febe.Core/Import/ImportEnvironment.cs +++ b/src/Febe.Core/Import/ImportEnvironment.cs @@ -33,10 +33,14 @@ public sealed record ImportEnvironment /// public PerceptualHashIndex? HashIndex { get; init; } - /// ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile. - public VideoFrameExtractor? Frames { get; init; } + /// The in-house frame decoder, for thumbnails of imported videos (spec §8.4). Null: the neutral tile. + public VideoFrameDecoder? Frames { get; init; } - /// ffprobe, an optional extra for videos the hand-written reader does not cover. + /// + /// Reader of the metadata of videos the MP4 header reader does not cover (WebM/Matroska, AVI, WMV/ASF, FLV and MPEG + /// program streams: see ). Null: the in-house + /// on the clock of this environment. + /// public IVideoMetadataProbe? VideoProbe { get; init; } /// «Imposta la data del file a quella di pubblicazione» (library setting). diff --git a/src/Febe.Core/Import/LEGGIMI.md b/src/Febe.Core/Import/LEGGIMI.md index dd0861c..7914be4 100644 --- a/src/Febe.Core/Import/LEGGIMI.md +++ b/src/Febe.Core/Import/LEGGIMI.md @@ -21,8 +21,8 @@ var import = new ImportService(new ImportEnvironment Clock = clock, Thumbnails = new ThumbnailStore(data.Thumbnails), HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta - Frames = VideoFrameExtractor.TryCreate(), // miniature dei video importati, se c'è ffmpeg - VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), // facoltativo + Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 importati, decodificate in casa + VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska, AVI, WMV, FLV e MPEG (null: la stessa, predefinita) SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, DataFolder = data.Root, @@ -64,12 +64,12 @@ partenza (`DuplicateDecision.Pending`); «Fai lo stesso per gli altri» è `Deci Per ogni file, senza scrivere nulla nella sorgente: tipo dal contenuto (`MediaSniffer`: JPEG, PNG, GIF, WebP, HEIC/HEIF, AVIF, BMP, TIFF e raw, MP4, MOV anche senza `ftyp`, 3GP, WebM/Matroska, AVI, WMV, FLV, MPEG; l'audio M4A non è un -video), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account +video, e nemmeno un WMA o un FLV di solo audio quando i primi 512 kB lo dimostrano: per l'FLV almeno un tag audio intero, nessun tag video e cinque secondi di audio o la fine del file), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account probabile, tipo probabile e titolo della raccolta. - **Data**, nell'ordine: nome del file (o `_febe.jsonl` di una libreria di Febe, data esatta), metadati (EXIF - `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; ffprobe - solo come aggiunta per gli altri video), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora + `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; i lettori di + contenitori scritti in casa per WebM, Matroska, AVI, WMV/ASF, FLV e MPEG), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora dello stesso giorno, vince l'ora dei metadati. Le ore senza fuso sono quelle di Alberto (`IClock.LocalZone`). - **Cartelle** (`SourceLayout`): se la cartella scelta contiene solo cartelle di tipo (post, storie, evidenza, taggati, anni...) o solo file, è un account; altrimenti ogni sottocartella di primo livello è un'unità da associare a @@ -159,6 +159,15 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per ## Limiti noti +- WMV/ASF, FLV e MPEG (lettori `AsfReader`, `FlvReader`, `MpegPsReader` in `Codecs/Containers`, scritti dalle + specifiche): di un WMV si leggono le proprietà del file (data, durata senza il preroll; niente durata se è una + trasmissione), dei flussi (codec, dimensioni, audio, anche dentro l'estensione dell'intestazione), il titolo e + `WM/EncodingTime` quando manca la data; di un FLV `onMetaData` (durata, dimensioni, `creationdate`), le dimensioni + dall'SPS dell'H.264 o dall'intestazione dell'H.263 di Sorenson, e senza durata nei metadati quella fino alla fine dell'ultimo fotogramma (l'ultimo tag video più l'intervallo dal precedente; l'audio solo se non c'è video); di un MPEG + (MPEG-1 e MPEG-2, anche VOB) codec e dimensioni dall'intestazione di sequenza o dall'SPS dell'H.264 e la durata dal + primo all'ultimo tempo di presentazione, leggendo solo i primi 2 MB e l'ultimo MB. Un MPEG non ha data. La + miniatura viene solo dagli FLV H.264: WMV (VC-1) e MPEG-2 non si decodificano, e i campioni di un MPEG, spezzati nei + pacchetti PES, non si elencano, nemmeno se H.264. - HEIC/HEIF: si riconoscono, ma i codec di Febe (PNG, JPEG, GIF, BMP, WebP) non li decodificano: niente dimensioni, impronta e miniatura, e l'EXIF dentro HEIC non si legge. Contano solo SHA-256, nome e data di modifica. - La sola lettura si riconosce dalle opzioni di montaggio (Linux, `ro`) o dai dischi ottici (Windows): una cartella diff --git a/src/Febe.Core/Import/MediaSniffer.cs b/src/Febe.Core/Import/MediaSniffer.cs index d7fb2d3..17f620c 100644 --- a/src/Febe.Core/Import/MediaSniffer.cs +++ b/src/Febe.Core/Import/MediaSniffer.cs @@ -1,5 +1,6 @@ using System.Buffers.Binary; using System.Text; +using Febe.Core.Codecs.Containers; using Febe.Core.Domain; namespace Febe.Core.Import; @@ -17,7 +18,7 @@ public sealed record DetectedType(MediaKind Kind, string ContentType, string Ext /// /// Recognizes photos and videos from their first bytes, not from the extension (spec §9.2). Anything else is «Non -/// riconosciuto». Audio-only containers (M4A) are not videos. +/// riconosciuto». Audio-only containers (M4A, WMA, an FLV of audio alone) are not videos. /// public static class MediaSniffer { @@ -133,12 +134,13 @@ public static class MediaSniffer if (head.Length >= 16 && head.StartsWith(AsfSignature)) { - return new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV"); + // A WMA file is ASF too: only a whole header that lists audio and no video says so. + return AsfReader.IsAudioOnly(head) ? null : new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV"); } if (head.StartsWith("FLV"u8) && head[3] == 0x01) { - return new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV"); + return FlvReader.IsAudioOnly(head) ? null : new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV"); } if (head[0] == 0x00 && head[1] == 0x00 && head[2] == 0x01 && head[3] == 0xBA) diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs index 2a8bfce..c01ad97 100644 --- a/src/Febe.Core/Import/VideoMetadataProbe.cs +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -1,192 +1,57 @@ -using System.Diagnostics; -using System.Globalization; -using System.Text.Json; -using Febe.Core.Security; +using Febe.Core.Abstractions; +using Febe.Core.Codecs.Containers; namespace Febe.Core.Import; -/// Metadata of a video read by an external tool. +/// Metadata of a video read from its container. public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height); -/// -/// Reads creation time, duration and size of videos the hand-written reader does not cover (WebM, Matroska, AVI, ...). -/// Optional: the analysis works without it (spec §9.2: «oppure si usa ffprobe dove è presente»). -/// +/// Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI, WMV/ASF, FLV, MPEG program stream). public interface IVideoMetadataProbe { - /// Metadata of a video file, read-only; null when the tool cannot read it. + /// Metadata of a video file, read-only; null when it cannot be read. Task ProbeAsync(string path, CancellationToken ct = default); } /// -/// with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is -/// parsed with ; error output is never logged (it may contain paths). +/// written in house on the container readers of : no +/// external program. Only the headers are read (no sample tables), so it is quick also on long videos. /// -public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe +public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMetadataProbe { - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20); - - private FfprobeVideoMetadataProbe(string executable) => Executable = executable; - - /// Full path of ffprobe. - public string Executable { get; } - - /// Finds ffprobe on the PATH (or at ); null when it is not available. - public static FfprobeVideoMetadataProbe? TryCreate(string? explicitPath = null) - { - if (!string.IsNullOrWhiteSpace(explicitPath)) - { - return File.Exists(explicitPath) ? new FfprobeVideoMetadataProbe(Path.GetFullPath(explicitPath)) : null; - } - - var name = OperatingSystem.IsWindows() ? "ffprobe.exe" : "ffprobe"; - foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) - { - try - { - var candidate = Path.Combine(folder.Trim('"'), name); - if (File.Exists(candidate)) - { - return new FfprobeVideoMetadataProbe(candidate); - } - } - catch (ArgumentException) - { - // A malformed PATH entry: skip it. - } - } - - return null; - } + private readonly IClock _clock = clock ?? new SystemClock(); /// - /// The start of ffprobe for : its arguments, and the environment of Febe without - /// FEBE_PASSWORD and FEBE_CHIAVE_SESSIONE, removed last (spec §13.2). + /// Reads on a thread of the pool, not on the caller's: a fragmented MP4 without a declared duration is read through + /// all its fragments, and the token is checked between them. /// - internal ProcessStartInfo BuildStartInfo(string path) - { - var start = new ProcessStartInfo(Executable) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true, - }; - foreach (var argument in new[] - { - "-hide_banner", "-v", "error", "-print_format", "json", - "-show_entries", "format=duration:format_tags=creation_time:stream=codec_type,width,height:stream_tags=rotate,creation_time", - "-i", path, - }) - { - start.ArgumentList.Add(argument); - } - - return start.WithoutSecrets(); - } - - public async Task ProbeAsync(string path, CancellationToken ct = default) + public Task ProbeAsync(string path, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(path); - using var process = new Process { StartInfo = BuildStartInfo(path) }; + var now = _clock.Now; + return Task.Run(() => Probe(path, now, ct), ct); + } + + /// The metadata of ; null when the file is unreadable or of another format. + public static VideoMetadata? Probe(string path, DateTimeOffset now, CancellationToken ct = default) + { try { - if (!process.Start()) + if (ContainerReader.ReadFile(path, now, samples: false, ct) is not { } container) { return null; } + + var video = container.Video; + int? width = video is { DisplayWidth: > 0 } ? video.DisplayWidth : null; + int? height = video is { DisplayHeight: > 0 } ? video.DisplayHeight : null; + var duration = container.Duration is { } d && d > TimeSpan.Zero ? d : (TimeSpan?)null; + return new VideoMetadata(container.CreatedAt, duration, width, height); } - catch (System.ComponentModel.Win32Exception) + catch (Exception ex) when (ex is ContainerException or IOException or EndOfStreamException or UnauthorizedAccessException + or ArgumentException or IndexOutOfRangeException or OverflowException or InvalidDataException) { - return null; + return null; // a damaged or unreadable file: as if the container had nothing to say } - - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(Timeout); - string output; - try - { - var read = process.StandardOutput.ReadToEndAsync(timeout.Token); - var drain = process.StandardError.ReadToEndAsync(timeout.Token); - await Task.WhenAll(read, drain).ConfigureAwait(false); - await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); - output = read.Result; - } - catch (OperationCanceledException) - { - try - { - process.Kill(entireProcessTree: true); - } - catch (InvalidOperationException) - { - } - - ct.ThrowIfCancellationRequested(); - return null; - } - - return process.ExitCode == 0 ? Parse(output) : null; - } - - /// Parses the JSON printed by ffprobe. - internal static VideoMetadata? Parse(string json) - { - try - { - using var document = JsonDocument.Parse(json); - var root = document.RootElement; - DateTimeOffset? created = null; - TimeSpan? duration = null; - int? width = null, height = null; - if (root.TryGetProperty("format", out var format)) - { - if (format.TryGetProperty("duration", out var d) && d.ValueKind == JsonValueKind.String - && double.TryParse(d.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && seconds > 0) - { - duration = TimeSpan.FromSeconds(seconds); - } - - created = CreationTime(format); - } - - if (root.TryGetProperty("streams", out var streams) && streams.ValueKind == JsonValueKind.Array) - { - foreach (var stream in streams.EnumerateArray()) - { - if (stream.TryGetProperty("codec_type", out var type) && type.ValueKind == JsonValueKind.String && type.GetString() == "video" - && stream.TryGetProperty("width", out var w) && w.TryGetInt32(out var wv) && wv > 0 - && stream.TryGetProperty("height", out var h) && h.TryGetInt32(out var hv) && hv > 0) - { - var rotate = stream.TryGetProperty("tags", out var tags) && tags.TryGetProperty("rotate", out var r) - && int.TryParse(r.ValueKind == JsonValueKind.String ? r.GetString() : r.GetRawText(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var degrees) - ? Math.Abs(degrees) % 180 - : 0; - (width, height) = rotate == 90 ? (hv, wv) : (wv, hv); - created ??= CreationTime(stream); - break; - } - } - } - - return new VideoMetadata(created, duration, width, height); - } - catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException) - { - return null; // an unexpected shape: as if ffprobe had nothing to say - } - } - - private static DateTimeOffset? CreationTime(JsonElement element) - { - if (element.TryGetProperty("tags", out var tags) && tags.ValueKind == JsonValueKind.Object - && tags.TryGetProperty("creation_time", out var value) && value.ValueKind == JsonValueKind.String - && DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var instant) - && instant.Year >= 1995) - { - return instant.ToUniversalTime(); - } - - return null; } } diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index 484dd97..341893e 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -14,7 +14,7 @@ public sealed record RebuildOptions /// public IReadOnlyList ExtraAccountFolders { get; init; } = []; - /// Create missing thumbnails (photos; videos with ffmpeg when available). + /// Create missing thumbnails (photos; H.264 videos with the in-house frame decoder). public bool CreateThumbnails { get; init; } = true; /// Files hashed in parallel. @@ -80,7 +80,7 @@ public sealed class LibraryRebuilder( LibraryLayout layout, IClock clock, ThumbnailStore? thumbnails = null, - VideoFrameExtractor? frames = null, + VideoFrameDecoder? frames = null, PerceptualHashIndex? hashIndex = null) { private const int BatchSize = 200; @@ -466,7 +466,7 @@ public sealed class LibraryRebuilder( } else if (isVideo && createThumbnails && thumbnails is not null && !thumbnail && frames is not null) { - var frame = await frames.ExtractJpegAsync(path, ct).ConfigureAwait(false); + var frame = await frames.ExtractImageAsync(path, ct).ConfigureAwait(false); if (frame is not null) { using var stream = new MemoryStream(frame); diff --git a/src/Febe.Core/Library/ThumbnailStore.cs b/src/Febe.Core/Library/ThumbnailStore.cs index a3951f6..12cc39c 100644 --- a/src/Febe.Core/Library/ThumbnailStore.cs +++ b/src/Febe.Core/Library/ThumbnailStore.cs @@ -7,7 +7,7 @@ namespace Febe.Core.Library; /// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under /// Dati/miniature, in 256 shard folders named after the first two hex digits of the key. The key is the /// SHA-256 of the library file, so identical files share one thumbnail. Videos use the cover given by the page or a -/// frame (); without either, the interface shows the neutral tile +/// frame (); without either, the interface shows the neutral tile /// (). /// public sealed class ThumbnailStore diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs new file mode 100644 index 0000000..817c061 --- /dev/null +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -0,0 +1,664 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; + +namespace Febe.Core.Library; + +/// A decoded video frame in 8-bit RGB, rows top to bottom, three bytes per pixel (red, green, blue). +public sealed record VideoImage(int Width, int Height, byte[] Rgb) +{ + /// The image as an uncompressed 24-bit BMP file (Windows bitmap, rows bottom to top). + public byte[] ToBmp() + { + var stride = ((Width * 3) + 3) & ~3; + var size = 54 + (stride * Height); + var bmp = new byte[size]; + var span = bmp.AsSpan(); + span[0] = (byte)'B'; + span[1] = (byte)'M'; + BinaryPrimitives.WriteInt32LittleEndian(span[2..], size); + BinaryPrimitives.WriteInt32LittleEndian(span[10..], 54); + BinaryPrimitives.WriteInt32LittleEndian(span[14..], 40); + BinaryPrimitives.WriteInt32LittleEndian(span[18..], Width); + BinaryPrimitives.WriteInt32LittleEndian(span[22..], Height); + BinaryPrimitives.WriteInt16LittleEndian(span[26..], 1); + BinaryPrimitives.WriteInt16LittleEndian(span[28..], 24); + BinaryPrimitives.WriteInt32LittleEndian(span[34..], stride * Height); + BinaryPrimitives.WriteInt32LittleEndian(span[38..], 2835); // 72 dpi + BinaryPrimitives.WriteInt32LittleEndian(span[42..], 2835); + for (var y = 0; y < Height; y++) + { + var source = Rgb.AsSpan(y * Width * 3, Width * 3); + var target = span.Slice(54 + ((Height - 1 - y) * stride), Width * 3); + for (var x = 0; x < source.Length; x += 3) + { + target[x] = source[x + 2]; + target[x + 1] = source[x + 1]; + target[x + 2] = source[x]; + } + } + + return bmp; + } +} + +/// +/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole +/// video. is the largest mean difference, on a 0–255 scale, between the first sampled frame and +/// the others, measured on a coarse grid so that the noise of the compression does not count. +/// +public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference); + +/// +/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover): +/// the container readers of and the H.264 decoder written in house +/// (). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the +/// neutral tile. +/// +public sealed class VideoFrameDecoder +{ + /// Differences up to this value (0–255) count as compression noise of a still picture. + public const double StillThreshold = 3.0; + + /// + /// The longest a frame or a stillness analysis may take: what the ffmpeg extractor it replaces was given. A damaged + /// file never holds an import or a rebuild for longer. + /// + public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30); + + private const int GridSize = 32; + private const int SampledPositions = 6; + private const int MaxSequentialSamples = 2000; + private const int DefaultMaxRun = 300; + + /// How far back from a sample flagged as key the decoder looks for one it can really start from. + private const int MaxRunStartSearch = 2000; + + private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private readonly TimeSpan budget; + private readonly int maxRun; + + /// A decoder with the default budget and run length. + public VideoFrameDecoder() + : this(DefaultBudget, DefaultMaxRun) + { + } + + /// The longest one call may take (zero: no time at all). + /// + /// Samples decoded at most from a random access point to the frame asked for; a frame further away (a damaged time + /// table, a track with a single key frame) gives way to the frame of the random access point itself. + /// + internal VideoFrameDecoder(TimeSpan budget, int maxRun) + { + this.budget = budget; + this.maxRun = maxRun; + } + + /// The shared instance: it keeps no state between calls. + public static VideoFrameDecoder Instance { get; } = new(); + + /// + /// A frame of the video as a BMP image, taken one second in (or the first frame of shorter videos), rotated as the + /// video is shown, reduced to at most twice the long side of a thumbnail (a 4K frame would be a 24 MB bitmap); + /// null when the file cannot be read or decoded. + /// + public Task ExtractImageAsync(string videoPath, CancellationToken ct = default) => + ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 2 * ThumbnailStore.LongSide, ct); + + /// + /// A frame of the video at (the first frame when the video is shorter), as a BMP image whose + /// long side is at most pixels (0: full size); null when it cannot be decoded. + /// + public async Task ExtractImageAsync(string videoPath, TimeSpan at, int maxLongSide, CancellationToken ct = default) + { + var image = await DecodeFrameAsync(videoPath, at, maxLongSide, ct).ConfigureAwait(false); + return image?.ToBmp(); + } + + /// A frame of the video at in RGB; null when it cannot be decoded. + public Task DecodeFrameAsync(string videoPath, TimeSpan at, int maxLongSide = 0, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); + return Task.Run(() => WithinBudget(token => DecodeFrame(videoPath, at, maxLongSide, token), ct), ct); + } + + /// + /// Whether the video shows a still picture, from frames spread over its whole length; null when it cannot be told + /// (unreadable file, codec not decoded, or one long run without key frames in a long video). + /// + public Task AnalyseStillnessAsync(string videoPath, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); + return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct); + } + + /// Runs for at most the budget: past it the result is null, as for an unreadable file. + private T? WithinBudget(Func work, CancellationToken ct) + where T : class + { + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + if (budget <= TimeSpan.Zero) + { + limit.Cancel(); + } + else + { + limit.CancelAfter(budget); + } + + try + { + return work(limit.Token); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return null; + } + } + + private VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct) + { + try + { + ct.ThrowIfCancellationRequested(); + using var stream = ContainerReader.OpenRead(path); + if (Open(stream) is not { } video) + { + return null; + } + + var decoding = new Decoding(stream, video, maxRun); + var target = SampleAt(video, at); + + // Too far from where decoding can start: the frame there stands for it, so the work stays bounded. + var start = decoding.RunStart(target); + if (target - start > maxRun) + { + target = start; + } + + var frames = decoding.Decode([target], ct); + if (!frames.TryGetValue(target, out var frame) && target != 0) + { + frames = new Decoding(stream, video, maxRun).Decode([0], ct); + frames.TryGetValue(0, out frame); + } + + return frame is null ? null : ToImage(frame, video.Rotation, maxLongSide); + } + catch (Exception ex) when (IsUnreadable(ex)) + { + return null; + } + } + + private VideoStillness? AnalyseStillness(string path, CancellationToken ct) + { + try + { + ct.ThrowIfCancellationRequested(); + using var stream = ContainerReader.OpenRead(path); + if (Open(stream) is not { } video) + { + return null; + } + + var samples = video.Samples; + if (samples.Count == 1) + { + return new VideoStillness(true, 1, 0); + } + + // Positions spread over the presentation, from the first to the last frame. + long first = long.MaxValue, last = long.MinValue; + foreach (var s in samples) + { + first = Math.Min(first, s.PresentationTime); + last = Math.Max(last, s.PresentationTime); + } + + var decoding = new Decoding(stream, video, maxRun); + var targets = new SortedSet(); + for (var i = 0; i < SampledPositions; i++) + { + ct.ThrowIfCancellationRequested(); + var time = first + ((last - first) * i / (SampledPositions - 1)); + var index = Closest(samples, time); + + // Far from where decoding can start in a long video: the frame there stands for it, so the work stays + // bounded. + var start = decoding.RunStart(index); + if (index - start > maxRun && samples.Count > MaxSequentialSamples) + { + index = start; + } + + targets.Add(index); + } + + if (targets.Count < 2) + { + return null; + } + + var frames = decoding.Decode([.. targets], ct); + if (frames.Count < 2) + { + return null; + } + + double[]? reference = null; + var difference = 0.0; + foreach (var index in targets) + { + if (!frames.TryGetValue(index, out var frame)) + { + continue; + } + + var grid = Grid(frame); + if (reference is null) + { + reference = grid; + continue; + } + + double sum = 0; + for (var i = 0; i < grid.Length; i++) + { + sum += Math.Abs(grid[i] - reference[i]); + } + + difference = Math.Max(difference, sum / grid.Length); + } + + return new VideoStillness(difference <= StillThreshold, frames.Count, Math.Round(difference, 2)); + } + catch (Exception ex) when (IsUnreadable(ex)) + { + return null; + } + } + + private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or IOException or EndOfStreamException + or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException or InvalidOperationException + or OverflowException or InvalidDataException; + + /// The H.264 video track of a container with its samples; null for other codecs or without video. + private static VideoTrack? Open(Stream stream) + { + // The creation time does not matter here: any date is accepted (the readers add a day to «now»). + var container = ContainerReader.Read(stream, AnyDate, samples: true); + return container?.Video is { Codec: VideoCodec.H264, Samples.Count: > 0 } video + && (video.AnnexB || video.AvcConfiguration is not null) + ? video + : null; + } + + /// The sample shown at from the start; the first shown one when the video is shorter. + private static int SampleAt(VideoTrack video, TimeSpan at) + { + var samples = video.Samples; + long first = long.MaxValue, last = long.MinValue; + foreach (var s in samples) + { + first = Math.Min(first, s.PresentationTime); + last = Math.Max(last, s.PresentationTime); + } + + var wanted = first + (long)(at.TotalSeconds * video.Timescale); + return Closest(samples, wanted > last ? first : wanted); + } + + private static int Closest(IReadOnlyList samples, long time) + { + var best = 0; + var distance = long.MaxValue; + for (var i = 0; i < samples.Count; i++) + { + var d = Math.Abs(samples[i].PresentationTime - time); + if (d < distance) + { + (best, distance) = (i, d); + } + } + + return best; + } + + private static int[] KeyIndices(VideoTrack video) + { + var keys = new List(); + for (var i = 0; i < video.Samples.Count; i++) + { + if (video.Samples[i].Key) + { + keys.Add(i); + } + } + + return keys.Count > 0 && keys[0] == 0 ? [.. keys] : [0, .. keys]; + } + + /// + /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. + /// + private sealed class Decoding(Stream stream, VideoTrack video, int maxRun) + { + private readonly Dictionary found = []; + private readonly HashSet wanted = []; + private readonly int[] keys = KeyIndices(video); + private readonly Dictionary accessPoints = []; + private byte[] buffer = new byte[64 * 1024]; + + /// The sample being decoded: the picture it finishes is that sample's frame. + private int current; + + /// + /// The sample where decoding for starts. A container without an index (an AVI cut short, + /// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give + /// a corrupt picture, or none: so the samples flagged as key are looked at, from the nearest one back. The nearest + /// IDR picture is taken when it is within the run limit (the frame comes out exact); otherwise the nearest + /// picture of I slices (close, though pictures after it may refer to earlier ones); otherwise the IDR picture + /// further back, or the first sample. + /// + internal int RunStart(int index) + { + var position = Array.BinarySearch(keys, index); + position = position >= 0 ? position : Math.Max(0, ~position - 1); + var intra = -1; + for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++) + { + var candidate = keys[position]; + if (!accessPoints.TryGetValue(candidate, out var point)) + { + point = AccessPointOf(candidate); + accessPoints[candidate] = point; + } + + if (point == H264AccessPoint.Idr) + { + return index - candidate <= maxRun || intra < 0 ? candidate : intra; + } + + if (point == H264AccessPoint.IntraPicture && intra < 0) + { + intra = candidate; + } + + if (index - candidate > maxRun && intra >= 0) + { + return intra; // no IDR picture within reach: the nearest picture of I slices + } + } + + // The first sample, where every stream starts (or the end of the search): it counts as an IDR picture. + return index <= maxRun || intra < 0 ? 0 : intra; + } + + private H264AccessPoint AccessPointOf(int index) + { + try + { + var sample = ContainerReader.ReadSample(stream, video.Samples[index], ref buffer); + var lengthSize = video.AnnexB ? 0 : video.AvcConfiguration is { Length: > 4 } avcC ? (avcC[4] & 3) + 1 : 4; + return H264Decoder.AccessPoint(sample, lengthSize); + } + catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException) + { + return H264AccessPoint.None; + } + } + + internal Dictionary Decode(int[] targets, CancellationToken ct) + { + foreach (var t in targets) + { + wanted.Add(t); + } + + H264Decoder? decoder = null; + var next = 0; + var lengthSize = 4; + foreach (var target in targets) + { + var key = RunStart(target); + if (decoder is null || next > target || key >= next) + { + // Frames are matched to samples by the sample being decoded, not by the decoder's own count: a + // sample without a picture (only parameter sets, or damaged) must not shift the frames after it. + // Of an MVC stream only the base view: it is the 2D video, and the other views would add frames. + decoder = new H264Decoder { Wanted = _ => wanted.Contains(current), DecodeAllViews = false }; + decoder.FrameDecoded += frame => found.TryAdd(current, frame); + next = key; + } + + try + { + if (next == key && !video.AnnexB) + { + lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration); + } + + for (; next <= target; next++) + { + ct.ThrowIfCancellationRequested(); + current = next; + var sample = ContainerReader.ReadSample(stream, video.Samples[next], ref buffer); + if (video.AnnexB) + { + decoder.DecodeAccessUnitAnnexB(sample); + } + else + { + decoder.DecodeSample(sample, lengthSize); + } + } + } + catch (Exception ex) when (ex is H264Exception or ContainerException or EndOfStreamException or IndexOutOfRangeException + or ArgumentException or InvalidOperationException) + { + // This run is damaged (or its samples lie past the end of a truncated file): the next target starts + // again from its own key frame, and what was decoded so far stands. + decoder = null; + } + } + + return found; + } + } + + /// + /// A coarse grid of mean luma and chroma values, to compare frames without their compression noise; values on the + /// 8-bit scale whatever the bit depth, the chroma at any sampling (its own grid over its own plane). + /// + private static double[] Grid(H264Frame frame) + { + var grid = new double[GridSize * GridSize * 2]; + var counts = new int[GridSize * GridSize]; + var wide = frame.BytesPerSample == 2; + ReadOnlySpan y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Y) : default; + var lumaShift = frame.BitDepthLuma - 8; + for (var y = 0; y < frame.Height; y++) + { + var gy = y * GridSize / frame.Height; + var start = y * frame.Width; + for (var x = 0; x < frame.Width; x++) + { + var cell = (gy * GridSize) + (x * GridSize / frame.Width); + grid[cell] += wide ? y16[start + x] >> lumaShift : frame.Y[start + x]; + counts[cell]++; + } + } + + var cw = frame.ChromaWidth; + var ch = frame.ChromaHeight; + ReadOnlySpan cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cb) : default; + ReadOnlySpan cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cr) : default; + var chromaShift = frame.BitDepthChroma - 8; + var middle = 1 << (frame.BitDepthChroma - 1); + var chromaCounts = new int[GridSize * GridSize]; + for (var y = 0; y < ch; y++) + { + var gy = y * GridSize / ch; + for (var x = 0; x < cw; x++) + { + var cell = (gy * GridSize) + (x * GridSize / cw); + var i = (y * cw) + x; + int u, v; + if (wide) + { + u = Math.Abs(cb16[i] - middle) >> chromaShift; + v = Math.Abs(cr16[i] - middle) >> chromaShift; + } + 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]++; + } + } + + for (var i = 0; i < counts.Length; i++) + { + grid[i] = counts[i] > 0 ? grid[i] / counts[i] : 0; + var c = (GridSize * GridSize) + i; + grid[c] = chromaCounts[i] > 0 ? grid[c] / chromaCounts[i] : 0; + } + + return grid; + } + + /// + /// The frame in RGB: BT.709, BT.601 or BT.2020 coefficients as the stream says (unspecified: BT.709 from 720 lines + /// up), limited or full range at the bit depth of the frame (limited: black at 16 · 2^(n − 8), luma span 219 · 2^(n − 8), + /// chroma 224 · 2^(n − 8) around 2^(n − 1)), any chroma sampling (4:2:0, 4:2:2, 4:4:4; monochrome comes with grey + /// chroma), reduced by an integer factor to fit , then rotated clockwise. + /// + internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide) + { + var (kr, kb) = frame.MatrixCoefficients switch + { + 1 => (0.2126, 0.0722), + 4 => (0.30, 0.11), + 5 or 6 => (0.299, 0.114), + 7 => (0.212, 0.087), + 9 or 10 => (0.2627, 0.0593), + _ => frame.Height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114), + }; + var kg = 1 - kr - kb; + int lumaBits = frame.BitDepthLuma - 8, chromaBits = frame.BitDepthChroma - 8; + var yScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthLuma) - 1) : 255.0 / (219 << lumaBits); + var cScale = frame.FullRange ? 255.0 / ((1 << frame.BitDepthChroma) - 1) : 255.0 / (224 << chromaBits); + var yOffset = frame.FullRange ? 0 : 16 << lumaBits; + var middle = 1 << (frame.BitDepthChroma - 1); + const int Shift = 16; + const double One = 1 << Shift; + var cy = (int)Math.Round(yScale * One); + var crR = (int)Math.Round(2 * (1 - kr) * cScale * One); + var cbB = (int)Math.Round(2 * (1 - kb) * cScale * One); + var cbG = (int)Math.Round(2 * kb * (1 - kb) / kg * cScale * One); + var crG = (int)Math.Round(2 * kr * (1 - kr) / kg * cScale * One); + const int Half = 1 << (Shift - 1); + + var factor = 1; + if (maxLongSide > 0) + { + var longSide = Math.Max(frame.Width, frame.Height); + factor = Math.Max(1, (longSide + maxLongSide - 1) / maxLongSide); + } + + var width = Math.Max(1, frame.Width / factor); + var height = Math.Max(1, frame.Height / factor); + var rgb = new byte[width * height * 3]; + var cw = frame.ChromaWidth; + var shiftX = frame.ChromaFormat == 3 ? 0 : 1; + var shiftY = frame.ChromaFormat is 2 or 3 ? 0 : 1; + var wide = frame.BytesPerSample == 2; + ReadOnlySpan y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Y) : default; + ReadOnlySpan cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cb) : default; + ReadOnlySpan cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast(frame.Cr) : default; + var area = factor * factor; + for (var oy = 0; oy < height; oy++) + { + for (var ox = 0; ox < width; ox++) + { + int r = 0, g = 0, b = 0; + for (var dy = 0; dy < factor; dy++) + { + var y = (oy * factor) + dy; + var lumaRow = y * frame.Width; + var chromaRow = (y >> shiftY) * cw; + for (var dx = 0; dx < factor; dx++) + { + var x = (ox * factor) + dx; + var ci = chromaRow + (x >> shiftX); + int l, u, v; + if (wide) + { + l = (y16[lumaRow + x] - yOffset) * cy; + u = cb16[ci] - middle; + v = cr16[ci] - middle; + } + else + { + l = (frame.Y[lumaRow + x] - yOffset) * cy; + u = frame.Cb[ci] - middle; + v = frame.Cr[ci] - middle; + } + + r += Clip((l + (crR * v) + Half) >> Shift); + g += Clip((l - (cbG * u) - (crG * v) + Half) >> Shift); + b += Clip((l + (cbB * u) + Half) >> Shift); + } + } + + var o = ((oy * width) + ox) * 3; + rgb[o] = (byte)(r / area); + rgb[o + 1] = (byte)(g / area); + rgb[o + 2] = (byte)(b / area); + } + } + + return Rotate(new VideoImage(width, height, rgb), rotation); + } + + private static int Clip(int v) => v < 0 ? 0 : v > 255 ? 255 : v; + + private static VideoImage Rotate(VideoImage image, int rotation) + { + rotation = ((rotation % 360) + 360) % 360; + if (rotation is not (90 or 180 or 270)) + { + return image; + } + + var (w, h) = (image.Width, image.Height); + var (nw, nh) = rotation == 180 ? (w, h) : (h, w); + var output = new byte[image.Rgb.Length]; + for (var y = 0; y < h; y++) + { + for (var x = 0; x < w; x++) + { + var (tx, ty) = rotation switch + { + 90 => (h - 1 - y, x), + 180 => (w - 1 - x, h - 1 - y), + _ => (y, w - 1 - x), + }; + var s = ((y * w) + x) * 3; + var t = ((ty * nw) + tx) * 3; + output[t] = image.Rgb[s]; + output[t + 1] = image.Rgb[s + 1]; + output[t + 2] = image.Rgb[s + 2]; + } + } + + return new VideoImage(nw, nh, output); + } +} diff --git a/src/Febe.Core/Library/VideoFrameExtractor.cs b/src/Febe.Core/Library/VideoFrameExtractor.cs deleted file mode 100644 index a4ed64f..0000000 --- a/src/Febe.Core/Library/VideoFrameExtractor.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Diagnostics; -using Febe.Core.Security; - -namespace Febe.Core.Library; - -/// -/// Extracts a frame from a video with ffmpeg, when ffmpeg is installed (spec §8.4: thumbnails of imported videos and of -/// videos without a cover). In Docker ffmpeg is part of the image (§11); on Windows it is optional. -/// -public sealed class VideoFrameExtractor -{ - private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); - - private VideoFrameExtractor(string executable) => Executable = executable; - - /// Full path of ffmpeg. - public string Executable { get; } - - /// Finds ffmpeg on the PATH (or at ); null when it is not available. - public static VideoFrameExtractor? TryCreate(string? explicitPath = null) - { - if (!string.IsNullOrWhiteSpace(explicitPath)) - { - return File.Exists(explicitPath) ? new VideoFrameExtractor(Path.GetFullPath(explicitPath)) : null; - } - - var name = OperatingSystem.IsWindows() ? "ffmpeg.exe" : "ffmpeg"; - var path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; - foreach (var folder in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) - { - try - { - var candidate = Path.Combine(folder.Trim('"'), name); - if (File.Exists(candidate)) - { - return new VideoFrameExtractor(candidate); - } - } - catch (ArgumentException) - { - // A malformed PATH entry: skip it. - } - } - - return null; - } - - /// - /// A JPEG frame of the video, taken one second in (or the first frame of shorter videos); null when ffmpeg cannot - /// read the file. - /// - public async Task ExtractJpegAsync(string videoPath, CancellationToken ct = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(videoPath); - foreach (var seek in new[] { "1", "0" }) - { - var frame = await RunAsync(videoPath, seek, ct).ConfigureAwait(false); - if (frame is { Length: > 0 }) - { - return frame; - } - } - - return null; - } - - /// - /// The start of ffmpeg for one frame of at seconds: its - /// arguments, and the environment of Febe without FEBE_PASSWORD and FEBE_CHIAVE_SESSIONE, removed last - /// (spec §13.2). - /// - internal ProcessStartInfo BuildStartInfo(string videoPath, string seek) - { - var start = new ProcessStartInfo(Executable) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - RedirectStandardInput = false, - UseShellExecute = false, - CreateNoWindow = true, - }; - foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-ss", seek, "-i", videoPath, "-frames:v", "1", "-f", "image2pipe", "-c:v", "mjpeg", "-q:v", "3", "-" }) - { - start.ArgumentList.Add(argument); - } - - return start.WithoutSecrets(); - } - - private async Task RunAsync(string videoPath, string seek, CancellationToken ct) - { - using var process = new Process { StartInfo = BuildStartInfo(videoPath, seek) }; - try - { - if (!process.Start()) - { - return null; - } - } - catch (System.ComponentModel.Win32Exception) - { - return null; - } - - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(Timeout); - using var output = new MemoryStream(); - try - { - var copy = process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); - var drainErrors = process.StandardError.ReadToEndAsync(timeout.Token); // never logged: may contain paths - await Task.WhenAll(copy, drainErrors).ConfigureAwait(false); - await process.WaitForExitAsync(timeout.Token).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - try - { - process.Kill(entireProcessTree: true); - } - catch (InvalidOperationException) - { - } - - ct.ThrowIfCancellationRequested(); - return null; - } - - return process.ExitCode == 0 && output.Length > 0 ? output.ToArray() : null; - } -} diff --git a/src/Febe.Core/Security/ChildProcessEnvironment.cs b/src/Febe.Core/Security/ChildProcessEnvironment.cs index cb2b501..2b18ecd 100644 --- a/src/Febe.Core/Security/ChildProcessEnvironment.cs +++ b/src/Febe.Core/Security/ChildProcessEnvironment.cs @@ -3,7 +3,7 @@ using System.Diagnostics; namespace Febe.Core.Security; /// -/// What a process Febe starts (Chromium, Edge, Xvfb, ffmpeg, ffprobe, Explorer) must not inherit from Febe (issue #36, +/// What a process Febe starts (Chromium, Edge, Xvfb, Explorer) must not inherit from Febe (issue #36, /// S4, rule 10): the interface password and the key of the saved session. A child process copies the environment of its /// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site. /// diff --git a/src/Febe.Web/Import/ImportHub.cs b/src/Febe.Web/Import/ImportHub.cs index 55fe82b..ec1fab2 100644 --- a/src/Febe.Web/Import/ImportHub.cs +++ b/src/Febe.Web/Import/ImportHub.cs @@ -122,8 +122,8 @@ public sealed class ImportHub : IAsyncDisposable Clock = _clock, Thumbnails = library.Thumbnails, HashIndex = library.HashIndex, - Frames = VideoFrameExtractor.TryCreate(), - VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), + Frames = VideoFrameDecoder.Instance, + VideoProbe = new ContainerVideoMetadataProbe(_clock), SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder, DataFolder = library.Data.Root, diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index a09b4d6..69050f6 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -71,7 +71,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri | `IDiagnosticSource` (`Engine/DiagnosticSource.cs`) | `NoDiagnosticSource`: niente registrato, il rapporto ha gli elenchi vuoti (prove, avvio con un problema di configurazione) | `Febe.App`: `RecordedDiagnosticSource` sul registratore `CollectionDiagnostics` (registro in `Dati/diagnostica`, 14 giorni, e sessioni in corso); dimostrazione: `DemoDiagnosticSource`, secondo la scena | | `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione (`Febe.App`, le due vesti): `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` | | `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) | -| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) | +| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (decodificatore dei fotogrammi, cartella sorgente) | - `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già `PUT /api/settings/general`); a copia finita pubblica `LibraryChange` con motivo `import`. diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs index 7e27485..c824448 100644 --- a/src/Febe.Web/Library/DataFolderServices.cs +++ b/src/Febe.Web/Library/DataFolderServices.cs @@ -200,7 +200,7 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock var progress = new SyncProgress(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked }); try { - var rebuilder = new LibraryRebuilder(storage, library.Layout, clock, library.Thumbnails, VideoFrameExtractor.TryCreate(), library.HashIndex); + var rebuilder = new LibraryRebuilder(storage, library.Layout, clock, library.Thumbnails, VideoFrameDecoder.Instance, library.HashIndex); var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false); State = State with { Running = false, Report = report, FinishedAt = clock.Now }; changes.Publish(new LibraryChange(clock.Now, null, "rebuild")); diff --git a/tests/Febe.Tests/Febe.Tests.csproj b/tests/Febe.Tests/Febe.Tests.csproj index 8831bca..18936ce 100644 --- a/tests/Febe.Tests/Febe.Tests.csproj +++ b/tests/Febe.Tests/Febe.Tests.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/Febe.Tests/Import/ImportAnalysisTests.cs b/tests/Febe.Tests/Import/ImportAnalysisTests.cs index cd16f2d..278fa77 100644 --- a/tests/Febe.Tests/Import/ImportAnalysisTests.cs +++ b/tests/Febe.Tests/Import/ImportAnalysisTests.cs @@ -23,8 +23,8 @@ public sealed class ImportAnalysisTests bed.Write("marta.demo/travestita.png", ImportTestFiles.Photo(4, 320, 240)); bed.Write("Foto sparse/a.jpg", ImportTestFiles.Photo(5)); bed.Write("marta.demo/Thumbs.db", [1, 2, 3]); - var realVideo = Path.Combine(bed.Source, "marta.demo", "storie", "ffmpeg.mp4"); - var withFfmpeg = ImportTestFiles.TryMakeMp4WithFfmpeg(realVideo, new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero)); + bed.Write("marta.demo/storie/vero.mp4", ImportTestFiles.RealMp4(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero))); + bed.Write("marta.demo/storie/vero.webm", ImportTestFiles.RealWebm(new DateTimeOffset(2021, 4, 5, 6, 7, 8, TimeSpan.Zero))); var before = bed.Fingerprint(); var run = await bed.AnalyzeAsync(); @@ -32,16 +32,18 @@ public sealed class ImportAnalysisTests Assert.AreEqual(ImportRunState.Reviewing, run.State); Assert.IsNotNull(run.AnalyzedAt); CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "L'analisi è in sola lettura: nessun file della sorgente cambia."); - var files = (await bed.FilesAsync(run.Id)).Where(f => !f.RelativePath.EndsWith("ffmpeg.mp4", StringComparison.Ordinal)).ToList(); - Assert.HasCount(7, files, "Thumbs.db non è un contenuto e non si elenca."); - if (withFfmpeg) - { - var real = await bed.FileAsync(run.Id, "marta.demo/storie/ffmpeg.mp4"); - Assert.AreEqual("video/mp4", real.ContentType); - Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd."); - Assert.AreEqual(ImportDateSource.Metadata, real.DateSource); - Assert.AreEqual((64, 48), (real.Width, real.Height)); - } + var files = await bed.FilesAsync(run.Id); + Assert.HasCount(9, files, "Thumbs.db non è un contenuto e non si elenca."); + var real = await bed.FileAsync(run.Id, "marta.demo/storie/vero.mp4"); + Assert.AreEqual("video/mp4", real.ContentType); + Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd."); + Assert.AreEqual(ImportDateSource.Metadata, real.DateSource); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (real.Width!.Value, real.Height!.Value)); + var webm = await bed.FileAsync(run.Id, "marta.demo/storie/vero.webm"); + Assert.AreEqual("video/webm", webm.ContentType); + Assert.AreEqual(new DateTimeOffset(2021, 4, 5, 6, 7, 8, TimeSpan.Zero), webm.TakenAt, "Data di creazione dal lettore Matroska scritto in casa."); + Assert.AreEqual(ImportDateSource.Metadata, webm.DateSource); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (webm.Width!.Value, webm.Height!.Value)); Assert.IsTrue(files.All(f => f.State == ImportFileState.Analyzed)); @@ -84,15 +86,15 @@ public sealed class ImportAnalysisTests Assert.IsNull(loose.ProbableAccount, "«Foto sparse» non può essere un nome utente."); var summary = await bed.Review.GetSummaryAsync(run.Id); - Assert.AreEqual(withFfmpeg ? 8 : 7, summary.Files); - Assert.AreEqual(withFfmpeg ? 7 : 6, summary.ByOutcome[ImportOutcome.New]); + Assert.AreEqual(9, summary.Files); + Assert.AreEqual(8, summary.ByOutcome[ImportOutcome.New]); Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Unrecognized]); var marta = summary.Folders.Single(f => f.Folder == "marta.demo"); Assert.AreEqual(FolderTargetKind.NewArchiveAccount, marta.Target.Kind, "Un nome valido senza account: nuovo account, solo archivio."); Assert.AreEqual("marta.demo", marta.Target.Username); Assert.AreEqual(FolderTargetKind.None, summary.Folders.Single(f => f.Folder == "Foto sparse").Target.Kind, "Nessun nome riconosciuto: nessuna scelta fatta."); Assert.IsTrue(summary.CanMove); - StringAssert.StartsWith(summary.Headline, withFfmpeg ? "8 file, " : "7 file, "); + StringAssert.StartsWith(summary.Headline, "9 file, "); StringAssert.EndsWith(summary.Headline, "Nessun file è stato ancora copiato."); } diff --git a/tests/Febe.Tests/Import/MediaReaderTests.cs b/tests/Febe.Tests/Import/MediaReaderTests.cs index d2996b3..a291ddc 100644 --- a/tests/Febe.Tests/Import/MediaReaderTests.cs +++ b/tests/Febe.Tests/Import/MediaReaderTests.cs @@ -121,55 +121,41 @@ public sealed class MediaReaderTests } [TestMethod] - public void AnMp4MadeByFfmpegCarriesItsCreationTime() + public void ARealMp4CarriesItsCreationTime() { using var temp = new TempFolder("mp4"); var path = temp.Combine("prova.mp4"); var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); - if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) - { - Assert.Inconclusive("ffmpeg non è installato: la prova sulle intestazioni sintetiche copre il lettore."); - } + File.WriteAllBytes(path, ImportTestFiles.RealMp4(created)); Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType); var info = Mp4Reader.ReadFile(path, Now); Assert.AreEqual(created, info?.CreatedAt); - Assert.AreEqual(64, info?.Width); - Assert.AreEqual(48, info?.Height); - Assert.IsTrue(info?.Duration > TimeSpan.FromMilliseconds(500)); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (info!.Width!.Value, info.Height!.Value)); + Assert.IsTrue(info.Duration > TimeSpan.FromMilliseconds(500)); } [TestMethod] - public async Task FfprobeIsAnOptionalExtra() + public async Task TheContainerProbeReadsWhatTheMp4ReaderDoesNot() { - var parsed = FfprobeVideoMetadataProbe.Parse(""" - {"streams":[{"codec_type":"audio"},{"codec_type":"video","width":1920,"height":1080,"tags":{"rotate":"90"}}], - "format":{"duration":"12.500000","tags":{"creation_time":"2020-08-09T10:11:12.000000Z"}}} - """); - Assert.AreEqual(new DateTimeOffset(2020, 8, 9, 10, 11, 12, TimeSpan.Zero), parsed?.CreatedAt); - Assert.AreEqual(TimeSpan.FromSeconds(12.5), parsed?.Duration); - Assert.AreEqual((1080, 1920), (parsed?.Width, parsed?.Height)); - Assert.IsNull(FfprobeVideoMetadataProbe.Parse("non json")); - Assert.AreEqual(640, FfprobeVideoMetadataProbe.Parse("""{"streams":[{"codec_type":"video","width":640,"height":480,"tags":{"rotate":0}}],"format":{"tags":{"creation_time":5}}}""")?.Width, "Valori di tipo inatteso non fanno fallire la lettura."); - - var probe = FfprobeVideoMetadataProbe.TryCreate(); - if (probe is null) - { - Assert.Inconclusive("ffprobe non è installato."); - return; - } - - using var temp = new TempFolder("ffprobe"); - var path = temp.Combine("prova.mp4"); + using var temp = new TempFolder("sonda"); + var webm = temp.Combine("prova.webm"); + var mp4 = temp.Combine("prova.mp4"); var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); - if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) + File.WriteAllBytes(webm, ImportTestFiles.RealWebm(created)); + File.WriteAllBytes(mp4, ImportTestFiles.RealMp4(created)); + Assert.AreEqual("video/webm", MediaSniffer.DetectFile(webm)?.ContentType); + + var probe = new ContainerVideoMetadataProbe(); + foreach (var path in new[] { webm, mp4 }) { - Assert.Inconclusive("ffmpeg non è installato."); + var metadata = await probe.ProbeAsync(path); + Assert.AreEqual(created, metadata?.CreatedAt, path); + Assert.AreEqual(ImportTestFiles.RealVideoSize, (metadata!.Width!.Value, metadata.Height!.Value), path); + Assert.IsTrue(metadata.Duration > TimeSpan.FromMilliseconds(500), path); } - var metadata = await probe.ProbeAsync(path); - Assert.AreEqual(created, metadata?.CreatedAt); - Assert.AreEqual(64, metadata?.Width); + Assert.IsNull(await probe.ProbeAsync(temp.Combine("non-esiste.webm"))); } [TestMethod] diff --git a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs index 5ae595c..f2153ff 100644 --- a/tests/Febe.Tests/Import/Support/ImportTestFiles.cs +++ b/tests/Febe.Tests/Import/Support/ImportTestFiles.cs @@ -1,6 +1,6 @@ using System.Buffers.Binary; -using System.Diagnostics; using System.Text; +using Febe.Tests.Codecs.Containers; using Febe.Tests.Support; namespace Febe.Tests.Import.Support; @@ -198,31 +198,16 @@ internal static class ImportTestFiles return output.ToArray(); } - /// Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing. - public static bool TryMakeMp4WithFfmpeg(string path, DateTimeOffset createdAt) - { - var ffmpeg = new[] { "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg" }.FirstOrDefault(File.Exists); - if (ffmpeg is null) - { - return false; - } + /// + /// A real H.264 MP4 (a conformance stream, 176×144, muxed by the in-house writer) with the given creation time. + /// + public static byte[] RealMp4(DateTimeOffset createdAt) => TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"), createdAt); - var start = new ProcessStartInfo(ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; - foreach (var argument in new[] - { - "-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x3366aa:s=64x48:d=1:r=10", - "-metadata", "creation_time=" + createdAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) + "Z", - "-c:v", "mpeg4", "-f", "mp4", path, - }) - { - start.ArgumentList.Add(argument); - } + /// A real H.264 WebM-style Matroska file (the same stream) with the given creation time. + public static byte[] RealWebm(DateTimeOffset createdAt) => TestVideos.Matroska(ElementaryStream.Load("BA1_Sony_D"), createdAt, webm: true); - using var process = Process.Start(start)!; - process.StandardError.ReadToEnd(); - process.WaitForExit(30_000); - return process.ExitCode == 0 && File.Exists(path); - } + /// Width and height of and . + public static (int Width, int Height) RealVideoSize => (176, 144); /// The PNG encoding of a generated scene. public static byte[] Png(int scene, int width = 400, int height = 300) diff --git a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs index f0b23e4..b5973fa 100644 --- a/tests/Febe.Tests/Library/ThumbnailStoreTests.cs +++ b/tests/Febe.Tests/Library/ThumbnailStoreTests.cs @@ -1,6 +1,7 @@ using System.Buffers.Binary; using Febe.Core.Codecs.Images; using Febe.Core.Library; +using Febe.Tests.Codecs.Containers; using Febe.Tests.Imaging; using Febe.Tests.Support; using TestImages = Febe.Tests.Support.TestImages; @@ -189,40 +190,20 @@ public sealed class ThumbnailStoreTests } [TestMethod] - public async Task VideoFramesComeFromFfmpegWhenAvailable() + public async Task VideoFramesComeFromTheInHouseDecoder() { - var ffmpeg = VideoFrameExtractor.TryCreate(); - if (ffmpeg is null) - { - Assert.Inconclusive("ffmpeg non è installato: le miniature dei video senza copertina usano la tessera neutra."); - } - using var temp = new TempFolder(); - var video = temp.Combine("prova.mp4"); - var start = new System.Diagnostics.ProcessStartInfo(ffmpeg.Executable) - { - RedirectStandardError = true, - RedirectStandardOutput = true, - UseShellExecute = false, - }; - foreach (var argument in new[] { "-hide_banner", "-nostdin", "-v", "error", "-f", "lavfi", "-i", "testsrc=duration=2:size=640x360:rate=10", "-pix_fmt", "yuv420p", video }) - { - start.ArgumentList.Add(argument); - } + var es = ElementaryStream.Load("CABA3_SVA_B"); + var video = TestVideos.Write(temp, "prova.mp4", TestVideos.Mp4(es)); - using (var process = System.Diagnostics.Process.Start(start)!) - { - await process.WaitForExitAsync(); - Assert.AreEqual(0, process.ExitCode, "ffmpeg non ha creato il video di prova."); - } - - var frame = await ffmpeg.ExtractJpegAsync(video); + var frame = await VideoFrameDecoder.Instance.ExtractImageAsync(video); Assert.IsNotNull(frame); var store = new ThumbnailStore(temp.Combine("miniature")); Assert.IsTrue(store.Create(Make.Sha(6), new MemoryStream(frame))); - Assert.AreEqual(480, InfoOf(store.PathFor(Make.Sha(6))).Width); + var info = InfoOf(store.PathFor(Make.Sha(6))); + Assert.AreEqual((es.Width, es.Height), (info.Width, info.Height)); - Assert.IsNull(await ffmpeg.ExtractJpegAsync(temp.Combine("non-esiste.mp4"))); + Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mp4"))); } private static void AssertGrey((byte R, byte G, byte B, byte A) pixel, int level, string what) => diff --git a/tests/Febe.Tests/Media/Containers/ContainerTests.cs b/tests/Febe.Tests/Media/Containers/ContainerTests.cs new file mode 100644 index 0000000..661b70b --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/ContainerTests.cs @@ -0,0 +1,312 @@ +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Core.Import; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// The container readers and the MP4 writer on videos built from the H.264 conformance streams: every decoded frame must +/// still have its official MD5 after a trip through MP4 (also fragmented), Matroska and AVI. +/// +[TestClass] +public sealed class ContainerTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + + [TestMethod] + [DataRow("BA1_Sony_D")] + [DataRow("CABA3_SVA_B")] + [DataRow("CANL1_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("HCAFR1_HHI_C")] + public void AnMp4WrittenHereDecodesToTheReferenceFrames(string name) + { + var es = ElementaryStream.Load(name); + var container = Read(TestVideos.Mp4(es)); + Assert.AreEqual(ContainerFormat.IsoBmff, container.Format); + AssertTrack(es, container.Video!); + CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(TestVideos.Mp4(es), container.Video!)); + } + + [TestMethod] + [DataRow("CABA3_SVA_B", false)] + [DataRow("FRExt1_Panasonic_D", false)] + [DataRow("CABA3_SVA_B", true)] + [DataRow("FRExt1_Panasonic_D", true)] + public void AFragmentedMp4IsReadFromItsFragments(string name, bool defaults) + { + // With defaults: durations from trex and two runs per fragment, each with its data_offset from the moof. + var es = ElementaryStream.Load(name); + var file = TestVideos.FragmentedMp4(es, perFragment: 7, defaults: defaults); + var container = Read(file); + AssertTrack(es, container.Video!, startsAtZero: false); // no edit list: composition offsets stay + CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video!)); + Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.05); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void TheProbeTellsTheDurationOfAFragmentedMp4(bool mehd) + { + // Without mehd only the fragments tell the duration: the metadata reading goes on through them. + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("sonda-frammentato"); + var path = TestVideos.Write(temp, "frammentato.mp4", TestVideos.FragmentedMp4(es, perFragment: 5, defaults: mehd)); + var meta = ContainerVideoMetadataProbe.Probe(path, Now); + Assert.IsNotNull(meta); + Assert.AreEqual(es.Count / 30.0, meta.Duration!.Value.TotalSeconds, 0.05); + Assert.AreEqual((es.Width, es.Height), (meta.Width!.Value, meta.Height!.Value)); + } + + [TestMethod] + public void TheMp4WriterKeepsTheOrderOfSamplesWithEqualTimes() + { + // An audio track without times (as AVI gives): every chunk starts at zero, and the order must still hold. + var es = ElementaryStream.Load("BA1_Sony_D"); + var video = new Mp4OutputTrack + { + IsVideo = true, + Timescale = TestVideos.Timescale, + Samples = [.. Enumerable.Range(0, es.Count).Select(i => new Mp4OutputSample(es.LengthPrefixed(i).Length, (long)i * TestVideos.FrameTicks, (long)es.Rank[i] * TestVideos.FrameTicks, es.Key[i]))], + WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)), + Width = es.Width, + Height = es.Height, + AvcConfiguration = es.AvcC, + }; + const int Count = 40_000; // 40 chunks of 1024: enough for the sort to be an unstable one + static byte[] Payload(int i) => [(byte)(i >> 8), (byte)i, 7]; + var audio = new Mp4OutputTrack + { + IsVideo = false, + Timescale = 44100, + Samples = [.. Enumerable.Range(0, Count).Select(_ => new Mp4OutputSample(3, 0, 0, true))], + WriteSample = (i, s) => s.Write(Payload(i)), + AacConfiguration = [0x12, 0x10], + SampleRate = 44100, + Channels = 2, + }; + using var output = new MemoryStream(); + Mp4Writer.Write(output, [video, audio]); + + var file = output.ToArray(); + var container = Read(file); + Assert.AreEqual(Count, container.Audio!.Samples.Count); + using var input = new MemoryStream(file); + var buffer = Array.Empty(); + for (var i = 0; i < Count; i++) + { + CollectionAssert.AreEqual(Payload(i), ContainerReader.ReadSample(input, container.Audio.Samples[i], ref buffer).ToArray(), $"campione {i}"); + } + + CollectionAssert.AreEqual(ElementaryStream.Reference("BA1_Sony_D"), DecodeAll(file, container.Video!)); + } + + [TestMethod] + [DataRow("BA1_Sony_D", false)] + [DataRow("CABA3_SVA_B", true)] + public void AMatroskaOrWebmFileDecodesToTheReferenceFrames(string name, bool webm) + { + var es = ElementaryStream.Load(name); + var file = TestVideos.Matroska(es, webm: webm); + var container = Read(file); + Assert.AreEqual(ContainerFormat.Matroska, container.Format); + Assert.AreEqual(es.Count, container.Video!.Samples.Count); + Assert.AreEqual(VideoCodec.H264, container.Video.Codec); + Assert.AreEqual((es.Width, es.Height), (container.Video.Width, container.Video.Height)); + CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, container.Video)); + } + + [TestMethod] + public void AnAviFileDecodesToTheReferenceFramesAndKeepsItsKeyFrames() + { + var es = ElementaryStream.Load("SVA_BA1_B"); + var file = TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021"); + var container = Read(file); + Assert.AreEqual(ContainerFormat.Avi, container.Format); + Assert.IsTrue(container.Video!.AnnexB); + Assert.AreEqual(VideoCodec.H264, container.Video.Codec); + CollectionAssert.AreEqual(es.Key, container.Video.Samples.Select(s => s.Key).ToArray()); + Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), container.CreatedAt); + Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.01); + CollectionAssert.AreEqual(ElementaryStream.Reference("SVA_BA1_B"), DecodeAll(file, container.Video)); + } + + [TestMethod] + public void TheMp4WriterKeepsDateRotationAudioAndStartsWithTheMovieBox() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var created = new DateTimeOffset(2023, 7, 8, 9, 10, 11, TimeSpan.Zero); + var file = TestVideos.Mp4(es, created, rotation: 90, audio: true); + Assert.AreEqual("ftyp", System.Text.Encoding.ASCII.GetString(file, 4, 4)); + var ftypSize = (int)System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(file); + Assert.AreEqual("moov", System.Text.Encoding.ASCII.GetString(file, ftypSize + 4, 4), "moov prima dei dati"); + + var container = Read(file); + Assert.AreEqual(created, container.CreatedAt); + Assert.AreEqual(90, container.Video!.Rotation); + Assert.AreEqual((es.Height, es.Width), (container.Video.DisplayWidth, container.Video.DisplayHeight)); + Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 0.05); + Assert.IsNotNull(container.Audio); + Assert.AreEqual(AudioCodec.Aac, container.Audio.Codec); + Assert.AreEqual((44100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + CollectionAssert.AreEqual(new byte[] { 0x12, 0x10 }, container.Audio.AacConfiguration); + + // The hand-written header reader of the import agrees on the same file. + using var temp = new TempFolder("mp4-scritto"); + var path = TestVideos.Write(temp, "video.mp4", file); + var info = Mp4Reader.ReadFile(path, Now); + Assert.IsNotNull(info); + Assert.AreEqual(created, info.CreatedAt); + } + + [TestMethod] + public void TheMp4WriterRemuxesAMatroskaFileFrameForFrame() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var mkv = TestVideos.Matroska(es); + var source = Read(mkv); + var video = source.Video!; + using var input = new MemoryStream(mkv); + var buffer = Array.Empty(); + var track = new Mp4OutputTrack + { + IsVideo = true, + Timescale = video.Timescale, + Samples = [.. video.Samples.Select(s => new Mp4OutputSample(s.Size, s.DecodeTime, s.PresentationTime, s.Key))], + WriteSample = (i, o) => o.Write(ContainerReader.ReadSample(input, video.Samples[i], ref buffer)), + Width = video.Width, + Height = video.Height, + AvcConfiguration = video.AvcConfiguration, + }; + using var output = new MemoryStream(); + Mp4Writer.Write(output, [track]); + + var remuxed = Read(output.ToArray()); + Assert.AreEqual(video.Samples.Count, remuxed.Video!.Samples.Count); + CollectionAssert.AreEqual(ElementaryStream.Reference("CABA3_SVA_B"), DecodeAll(output.ToArray(), remuxed.Video)); + } + + [TestMethod] + public void TheMetadataProbeReadsEveryContainerWithoutExternalPrograms() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var created = new DateTimeOffset(2022, 5, 6, 7, 8, 9, TimeSpan.Zero); + using var temp = new TempFolder("sonda"); + var mp4 = TestVideos.Write(temp, "a.mp4", TestVideos.Mp4(es, created, rotation: 270)); + var mkv = TestVideos.Write(temp, "b.mkv", TestVideos.Matroska(es, created)); + var webm = TestVideos.Write(temp, "c.webm", TestVideos.Matroska(es, created, webm: true)); + var avi = TestVideos.Write(temp, "d.avi", TestVideos.Avi(es, "Fri May 06 07:08:09 2022")); + var junk = TestVideos.Write(temp, "e.mp4", [0, 0, 0, 8, .. "ftyp"u8, 1, 2, 3]); + var other = TestVideos.Write(temp, "f.bin", [.. "non è un video"u8]); + + foreach (var path in new[] { mp4, mkv, webm, avi }) + { + var meta = ContainerVideoMetadataProbe.Probe(path, Now); + Assert.IsNotNull(meta, path); + Assert.AreEqual(created, meta.CreatedAt, path); + Assert.AreEqual(es.Count / 30.0, meta.Duration!.Value.TotalSeconds, 0.05, path); + var expected = path == mp4 ? (es.Height, es.Width) : (es.Width, es.Height); + Assert.AreEqual(expected, (meta.Width!.Value, meta.Height!.Value), path); + } + + Assert.IsNull(ContainerVideoMetadataProbe.Probe(other, Now)); + Assert.IsNull(ContainerVideoMetadataProbe.Probe(temp.Combine("non-esiste.mp4"), Now)); + var damaged = ContainerVideoMetadataProbe.Probe(junk, Now); + Assert.IsTrue(damaged is null || damaged.Width is null); + + // A creation time in the future is not believed. + Assert.IsNull(ContainerVideoMetadataProbe.Probe(mkv, created.AddDays(-10))!.CreatedAt); + } + + [TestMethod] + public async Task TheProbeIsTheDefaultOfTheImport() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var temp = new TempFolder("sonda-predefinita"); + var path = TestVideos.Write(temp, "a.webm", TestVideos.Matroska(es, new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero), webm: true)); + var meta = await new ContainerVideoMetadataProbe(new FixedClock(Now)).ProbeAsync(path); + Assert.AreEqual(2020, meta!.CreatedAt!.Value.Year); + } + + [TestMethod] + [DataRow(3_000_000u)] + [DataRow(1_000_000u)] + [DataRow(2_500_000u)] + public void MatroskaTimesStayExactWithAnyTimecodeScale(uint timecodeScale) + { + // A TimecodeScale that does not divide a second (3 ms): the timescale of the track must not be rounded down + // (333 ticks a second instead of 333.3), or every time drifts by 0.1% and disagrees with the duration. + var es = ElementaryStream.Load("CI_MW_D"); + var container = Read(TestVideos.Matroska(es, timecodeScale: timecodeScale)); + var video = container.Video!; + var tick = timecodeScale / 1e9; + Assert.AreEqual(container.Duration!.Value.TotalSeconds, video.Seconds(video.Duration), 1.0 / video.Timescale, "durata della traccia e del file"); + var span = video.Samples.Max(s => s.PresentationTime) - video.Samples.Min(s => s.PresentationTime); + Assert.AreEqual((es.Count - 1) / 30.0, video.Seconds(span), tick, "dal primo all'ultimo fotogramma"); + } + + private static MediaContainer Read(byte[] file) + { + using var stream = new MemoryStream(file); + var container = ContainerReader.Read(stream, Now); + Assert.IsNotNull(container); + return container; + } + + private static void AssertTrack(ElementaryStream es, VideoTrack video, bool startsAtZero = true) + { + Assert.AreEqual(VideoCodec.H264, video.Codec); + Assert.AreEqual((es.Width, es.Height), (video.Width, video.Height)); + Assert.AreEqual(es.Count, video.Samples.Count); + CollectionAssert.AreEqual(es.Key, video.Samples.Select(s => s.Key).ToArray()); + for (var i = 0; i < es.Count; i++) + { + Assert.AreEqual((long)i * TestVideos.FrameTicks, video.Samples[i].DecodeTime, $"decodifica {i}"); + Assert.AreEqual(es.LengthPrefixed(i).Length, video.Samples[i].Size, $"dimensione {i}"); + } + + // Presentation order as the stream says, starting at zero. + var shown = video.Samples.Select((s, i) => (s.PresentationTime, i)).OrderBy(p => p.PresentationTime).Select(p => p.i).ToArray(); + CollectionAssert.AreEqual(Enumerable.Range(0, es.Count).OrderBy(i => es.Rank[i]).ToArray(), shown); + if (startsAtZero) + { + Assert.AreEqual(0, video.Samples.Min(s => s.PresentationTime), "l'elenco delle modifiche porta il primo fotogramma a zero"); + } + } + + private static List DecodeAll(byte[] file, VideoTrack video) + { + using var stream = new MemoryStream(file); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + var lengthSize = video.AnnexB ? 0 : decoder.ConfigureAvcC(video.AvcConfiguration); + var buffer = Array.Empty(); + foreach (var sample in video.Samples) + { + var bytes = ContainerReader.ReadSample(stream, sample, ref buffer); + if (video.AnnexB) + { + decoder.DecodeAccessUnitAnnexB(bytes); + } + else + { + decoder.DecodeSample(bytes, lengthSize); + } + } + + decoder.Flush(); + return ElementaryStream.Md5InOutputOrder(frames); + } + + private sealed class FixedClock(DateTimeOffset now) : Febe.Core.Abstractions.IClock + { + public DateTimeOffset Now { get; } = now; + + public TimeZoneInfo LocalZone => TimeZoneInfo.Utc; + + public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask; + } +} diff --git a/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs b/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs new file mode 100644 index 0000000..826bf57 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/LegacyContainerTests.cs @@ -0,0 +1,377 @@ +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Core.Domain; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// The readers of the older containers — ASF (WMV), FLV and MPEG program streams — on files the tests build from the +/// specifications: what each header says must come out, and an FLV of H.264 must decode to the official frames. +/// +[TestClass] +public sealed class LegacyContainerTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + + // ----- ASF ----- + + [TestMethod] + public void AnAsfHeaderGivesDurationSizeCodecDateAndTitle() + { + var created = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero); + var file = LegacyTestVideos.Asf(new AsfOptions { Created = created, Title = "Vacanze al mare" }); + var container = Read(file); + Assert.AreEqual(ContainerFormat.Asf, container.Format); + Assert.AreEqual(created, container.CreatedAt); + Assert.AreEqual(TimeSpan.FromSeconds(12.5), container.Duration, "la durata di riproduzione senza il preroll"); + Assert.AreEqual("Vacanze al mare", container.Title); + Assert.AreEqual(VideoCodec.Vc1, container.Video!.Codec); + Assert.AreEqual("WMV3", container.Video.CodecTag); + Assert.AreEqual((640, 480), (container.Video.Width, container.Video.Height)); + Assert.IsEmpty(container.Video.Samples); + Assert.AreEqual(AudioCodec.Wma, container.Audio!.Codec); + Assert.AreEqual((44_100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + + using var temp = new TempFolder("asf"); + var meta = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.wmv", file), Now); + Assert.AreEqual(new VideoMetadata(created, TimeSpan.FromSeconds(12.5), 640, 480), meta); + } + + [TestMethod] + public void AVideoStreamInsideTheHeaderExtensionIsFound() + { + var container = Read(LegacyTestVideos.Asf(new AsfOptions { VideoInExtension = true, Width = 1280, Height = 720, Compression = "WMV2" })); + Assert.AreEqual(VideoCodec.Wmv, container.Video!.Codec); + Assert.AreEqual((1280, 720), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(AudioCodec.Wma, container.Audio!.Codec); + } + + [TestMethod] + public void ABroadcastAsfHasNoDurationAndTheEncodingTimeGivesTheDate() + { + var encoded = new DateTimeOffset(2012, 1, 2, 3, 4, 5, TimeSpan.Zero); + var container = Read(LegacyTestVideos.Asf(new AsfOptions { Broadcast = true, EncodingTime = encoded })); + Assert.IsNull(container.Duration, "in una trasmissione i campi della durata non valgono"); + Assert.AreEqual(encoded, container.CreatedAt, "senza data nelle proprietà del file vale WM/EncodingTime"); + + // A date after now is not believed, wherever it comes from. + container = Read(LegacyTestVideos.Asf(new AsfOptions { Created = Now.AddDays(3), EncodingTime = Now.AddDays(5) })); + Assert.IsNull(container.CreatedAt); + } + + [TestMethod] + public void TheSnifferTellsAWmvFromAWma() + { + var wmv = LegacyTestVideos.Asf(new AsfOptions()); + var wma = LegacyTestVideos.Asf(new AsfOptions { Video = false }); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(Head(wmv))?.Kind); + Assert.IsNull(MediaSniffer.Detect(Head(wma)), "solo audio: né foto né video"); + + // A head that does not hold the whole header proves nothing: the file stays a video. + Assert.AreEqual("WMV", MediaSniffer.Detect(wma.AsSpan(0, 200))?.Format); + Assert.IsFalse(AsfReader.IsAudioOnly(wmv)); + Assert.IsTrue(AsfReader.IsAudioOnly(Head(wma))); + } + + // ----- FLV ----- + + [TestMethod] + [DataRow("BA1_Sony_D")] + [DataRow("CABA3_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("HCAFR1_HHI_C")] + public void AnFlvOfH264DecodesToTheReferenceFrames(string name) + { + var es = ElementaryStream.Load(name); + var file = LegacyTestVideos.Flv(es, audio: true); + var container = Read(file); + Assert.AreEqual(ContainerFormat.Flv, container.Format); + var video = container.Video!; + Assert.AreEqual(VideoCodec.H264, video.Codec); + Assert.AreEqual((es.Width, es.Height), (video.Width, video.Height)); + Assert.HasCount(es.Count, video.Samples); + CollectionAssert.AreEqual(es.Key, video.Samples.Select(s => s.Key).ToArray()); + var shown = video.Samples.Select((s, i) => (s.PresentationTime, i)).OrderBy(p => p.PresentationTime).Select(p => p.i).ToArray(); + CollectionAssert.AreEqual(Enumerable.Range(0, es.Count).OrderBy(i => es.Rank[i]).ToArray(), shown, "ordine di presentazione"); + CollectionAssert.AreEqual(ElementaryStream.Reference(name), DecodeAll(file, video)); + Assert.AreEqual(AudioCodec.Aac, container.Audio!.Codec); + Assert.AreEqual((44_100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + CollectionAssert.AreEqual(new byte[] { 0x12, 0x10 }, container.Audio.AacConfiguration); + } + + [TestMethod] + public void TheMetadataGivesDurationAndDateAndTheSpsGivesTheSize() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var file = LegacyTestVideos.Flv(es, creationDate: "Sat Jul 08 09:10:11 2023\n", metadataSize: (999, 777)); + var container = Read(file, samples: false); + Assert.AreEqual(es.Count / 30.0, container.Duration!.Value.TotalSeconds, 1e-6); + Assert.AreEqual(new DateTimeOffset(2023, 7, 8, 9, 10, 11, TimeSpan.Zero), container.CreatedAt); + Assert.AreEqual((es.Width, es.Height), (container.Video!.Width, container.Video.Height), "l'SPS vince sui metadati"); + Assert.IsEmpty(container.Video.Samples, "solo i metadati"); + Assert.IsNotNull(container.Video.AvcConfiguration); + + // A date as an AMF date (milliseconds from 1970). + var instant = new DateTimeOffset(2020, 2, 3, 4, 5, 6, TimeSpan.Zero); + container = Read(LegacyTestVideos.Flv(es, creationMilliseconds: instant.ToUnixTimeMilliseconds()), samples: false); + Assert.AreEqual(instant, container.CreatedAt); + } + + [TestMethod] + public void WithoutMetadataTheLastTagGivesTheDurationAndTheSpsTheSize() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var file = LegacyTestVideos.Flv(es, metadata: false, audio: true); + + // The last video tag plus one frame (the interval from the tag before it), as the MPEG reader counts the last + // frame and as the metadata of the same stream say: es.Count frames at 30 per second, to the millisecond of the + // tag times. + static double Dts(int i) => Math.Round(i * 1000.0 / 30); + var expected = ((2 * Dts(es.Count - 1)) - Dts(es.Count - 2)) / 1000; + Assert.AreEqual(expected, es.Count / 30.0, 0.002, "the metadata of the same stream"); + foreach (var samples in new[] { false, true }) + { + var container = Read(file, samples); + Assert.AreEqual(expected, container.Duration!.Value.TotalSeconds, 1e-6, $"campioni: {samples}"); + Assert.AreEqual((es.Width, es.Height), (container.Video!.Width, container.Video.Height)); + Assert.IsNull(container.CreatedAt); + } + + using var temp = new TempFolder("flv-senza-metadati"); + var meta = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.flv", file), Now); + Assert.AreEqual(new VideoMetadata(null, TimeSpan.FromSeconds(expected), es.Width, es.Height), meta); + } + + [TestMethod] + public async Task TheFrameDecoderMakesTheSameThumbnailOfAnFlvAsOfAnMp4() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("flv-fotogramma"); + var flv = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "video.flv", LegacyTestVideos.Flv(es)), TimeSpan.FromSeconds(1)); + var mp4 = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)), TimeSpan.FromSeconds(1)); + Assert.IsNotNull(flv); + Assert.IsNotNull(mp4); + Assert.AreEqual((mp4.Width, mp4.Height), (flv.Width, flv.Height)); + CollectionAssert.AreEqual(mp4.Rgb, flv.Rgb); + } + + [TestMethod] + [DataRow(0, 200, 150)] + [DataRow(1, 1024, 576)] + [DataRow(5, 320, 240)] + [DataRow(3, 176, 144)] + public void ASorensonH263FlvTakesTheSizeOfItsPictureHeader(int code, int width, int height) + { + var container = Read(LegacyTestVideos.SorensonFlv(code, width, height)); + Assert.AreEqual(VideoCodec.H263, container.Video!.Codec); + Assert.AreEqual((width, height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(0.4, container.Duration!.Value.TotalSeconds, 1e-6, "dal primo tag alla fine dell'ultimo fotogramma: dieci da 40 ms"); + Assert.IsEmpty(container.Video.Samples, "solo H.264 si decodifica"); + } + + [TestMethod] + public void AnEnhancedFlvTellsItsCodecAndAnAudioFlvIsNoVideo() + { + var hevc = LegacyTestVideos.EnhancedOrAudioFlv("hvc1", audioFlag: true, videoFlag: true); + Assert.AreEqual(VideoCodec.Hevc, Read(hevc).Video!.Codec); + Assert.AreEqual(VideoCodec.Av1, Read(LegacyTestVideos.EnhancedOrAudioFlv("av01", audioFlag: true, videoFlag: true)).Video!.Codec); + + var audio = LegacyTestVideos.EnhancedOrAudioFlv(null, audioFlag: true, videoFlag: false); + var container = Read(audio); + Assert.IsNull(container.Video); + Assert.AreEqual(AudioCodec.Mp3, container.Audio!.Codec); + Assert.AreEqual((44_100, 2), (container.Audio.SampleRate, container.Audio.Channels)); + Assert.IsNull(MediaSniffer.Detect(audio), "solo audio: né foto né video"); + + // A header that forgets its video flag, with video tags after it, is still a video. + var forgetful = LegacyTestVideos.EnhancedOrAudioFlv("hvc1", audioFlag: true, videoFlag: false); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(forgetful)?.Kind); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(hevc)?.Kind); + } + + [TestMethod] + public void AnFlvIsAudioOnlyOnlyWithProofInItsHead() + { + using var temp = new TempFolder("flv-solo-audio"); + + // A header that says audio without video, an onMetaData larger than the 512 bytes of MediaSniffer.HeadLength and + // video tags after it: the head ends inside the metadata, which proves nothing, so it stays a video. + var video = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 4000, seconds: 3, videoFromMs: 500); + Assert.IsGreaterThan(MediaSniffer.HeadLength, video.Length); + Assert.IsFalse(FlvReader.IsAudioOnly(video.AsSpan(0, MediaSniffer.HeadLength))); + Assert.AreEqual(MediaKind.Video, MediaSniffer.DetectFile(TestVideos.Write(temp, "video.flv", video))?.Kind); + Assert.AreEqual(MediaKind.Video, MediaSniffer.Detect(Head(video))?.Kind); + Assert.IsNotNull(Read(video).Video, "il video c'è"); + + // The same with audio only: a whole file, or a head with five seconds of audio and no video tag, proves it; the + // first 512 bytes, or a head that holds only a little audio after the metadata, do not. + var audio = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 4000, seconds: 8); + Assert.IsTrue(FlvReader.IsAudioOnly(audio)); + Assert.IsNull(MediaSniffer.Detect(Head(audio))); + Assert.IsTrue(FlvReader.IsAudioOnly(audio.AsSpan(0, audio.Length - 100)), "più di cinque secondi di solo audio"); + Assert.AreEqual(MediaKind.Video, MediaSniffer.DetectFile(TestVideos.Write(temp, "audio.flv", audio))?.Kind); + var audioStart = 13 + 11 + ((audio[14] << 16) | (audio[15] << 8) | audio[16]) + 4; // after onMetaData + Assert.IsFalse(FlvReader.IsAudioOnly(audio.AsSpan(0, audioStart + (20 * 23) + 7)), "venti tag d'audio, mezzo secondo"); + Assert.IsFalse(FlvReader.IsAudioOnly(audio.AsSpan(0, 13 + 11 + 3000)), "la testa finisce dentro i metadati"); + + // Video after five seconds of audio alone: a head that holds it sees the video tag. + var late = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 100, seconds: 8, videoFromMs: 6000); + Assert.IsFalse(FlvReader.IsAudioOnly(late)); + } + + [TestMethod] + public void WithoutADurationAnAudioFlvLastsUntilItsLastFrameEnds() + { + // onMetaData without a duration and no video: the last audio tag plus the interval from the one before it. + var audio = LegacyTestVideos.AudioFlaggedFlv(metadataBytes: 0, seconds: 2); + var last = (2000 - 1) / 26 * 26; + Assert.AreEqual((last + 26) / 1000.0, Read(audio, samples: false).Duration!.Value.TotalSeconds, 1e-6); + } + + // ----- MPEG program stream ----- + + [TestMethod] + [DataRow(720, 576, false)] + [DataRow(4096, 2160, false)] + [DataRow(720, 480, true)] + public void AnMpeg2ProgramStreamGivesCodecSizeDurationAndAudio(int width, int height, bool streamMap) + { + // 4096 needs the size extension: its twelve low bits are zero. + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Width = width, Height = height, StreamMap = streamMap })); + Assert.AreEqual(ContainerFormat.MpegPs, container.Format); + Assert.AreEqual(VideoCodec.Mpeg2, container.Video!.Codec); + Assert.AreEqual((width, height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(2.0, container.Duration!.Value.TotalSeconds, 1e-6, "50 immagini a 25 al secondo"); + Assert.IsEmpty(container.Video.Samples); + Assert.IsNull(container.CreatedAt); + Assert.AreEqual(AudioCodec.Mp2, container.Audio!.Codec); + Assert.AreEqual((48_000, 2), (container.Audio.SampleRate, container.Audio.Channels)); + } + + [TestMethod] + public void AnMpeg1SystemStreamOfMpeg1Video() + { + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Video = "mpeg1", Mpeg1System = true, Width = 352, Height = 288, Frames = 75 })); + Assert.AreEqual(VideoCodec.Mpeg1, container.Video!.Codec); + Assert.AreEqual((352, 288), (container.Video.Width, container.Video.Height)); + Assert.AreEqual(3.0, container.Duration!.Value.TotalSeconds, 1e-6); + Assert.AreEqual(AudioCodec.Mp2, container.Audio!.Codec); + } + + [TestMethod] + [DataRow("CABA3_SVA_B", true)] + [DataRow("CABA3_SVA_B", false)] + [DataRow("FRExt1_Panasonic_D", false)] + public void H264InAProgramStreamTakesItsSizeFromTheSps(string name, bool streamMap) + { + var es = ElementaryStream.Load(name); + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Video = "h264", Stream = es, StreamMap = streamMap, Audio = null })); + Assert.AreEqual(VideoCodec.H264, container.Video!.Codec); + Assert.AreEqual((es.Width, es.Height), (container.Video.Width, container.Video.Height)); + Assert.AreEqual((es.Count - 1) / 30.0, container.Duration!.Value.TotalSeconds, 1e-6, "senza frequenza delle immagini: dal primo all'ultimo tempo"); + Assert.IsNull(container.Audio); + } + + [TestMethod] + public void TheEndOfALongProgramStreamGivesItsDuration() + { + // About 6 MB: the reader looks at the first 2 MB and the last 1 MB only. + var file = LegacyTestVideos.MpegPs(new PsOptions { Frames = 300, PictureBytes = 20_000 }); + Assert.IsGreaterThan(5_000_000, file.Length); + var container = Read(file); + Assert.AreEqual(12.0, container.Duration!.Value.TotalSeconds, 1e-6); + Assert.AreEqual((720, 576), (container.Video!.Width, container.Video.Height)); + + using var temp = new TempFolder("mpeg-lungo"); + var meta = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.mpg", file), Now); + Assert.AreEqual(new VideoMetadata(null, TimeSpan.FromSeconds(12), 720, 576), meta); + } + + [TestMethod] + [DataRow(50)] + [DataRow(300)] + public void TheDurationCrossesTheWrapOfTheClock(int frames) + { + // The times start one second before the 33-bit clock wraps to zero, in a short file and in a long one. + var first = (1L << 33) - 90_000; + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { FirstPts = first, Frames = frames, PictureBytes = frames > 100 ? 20_000 : 1500 })); + Assert.AreEqual(frames / 25.0, container.Duration!.Value.TotalSeconds, 1e-6); + } + + [TestMethod] + public void Ac3InPrivateStreamOneIsRecognised() + { + var container = Read(LegacyTestVideos.MpegPs(new PsOptions { Audio = "ac3" })); + Assert.AreEqual(AudioCodec.Ac3, container.Audio!.Codec); + Assert.AreEqual((48_000, 6), (container.Audio.SampleRate, container.Audio.Channels)); + } + + [TestMethod] + public void TheNewFormatsAreRecognisedByTheirFirstBytes() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + Assert.AreEqual(ContainerFormat.Asf, ContainerReader.Detect(LegacyTestVideos.Asf(new AsfOptions()))); + Assert.AreEqual(ContainerFormat.Flv, ContainerReader.Detect(LegacyTestVideos.Flv(es))); + Assert.AreEqual(ContainerFormat.MpegPs, ContainerReader.Detect(LegacyTestVideos.MpegPs(new PsOptions()))); + Assert.AreEqual(ContainerFormat.MpegPs, ContainerReader.Detect(LegacyTestVideos.MpegPs(new PsOptions { Mpeg1System = true }))); + Assert.AreEqual("MPEG", MediaSniffer.Detect(LegacyTestVideos.MpegPs(new PsOptions()).AsSpan(0, 512))?.Format); + Assert.AreEqual("FLV", MediaSniffer.Detect(LegacyTestVideos.Flv(es).AsSpan(0, 512))?.Format); + } + + [TestMethod] + public void TheSizeOfAnSpsIsTheCroppedSize() + { + foreach (var name in new[] { "BA1_Sony_D", "FRExt1_Panasonic_D" }) + { + var es = ElementaryStream.Load(name); + Assert.IsTrue(H264StreamInfo.TryPictureSizeFromConfiguration(es.AvcC, out var w, out var h), name); + Assert.AreEqual((es.Width, es.Height), (w, h), name); + } + + // Fields, 4:2:2 and 4:0:0: the size the official reconstruction has, from the first line of its MD5 file. + foreach (var name in new[] { "BA1_Sony_D", "FRExt1_Panasonic_D", "CVFI1_SVA_C", "Hi422FR10_SONY_A", "HPCAMOLQ_BRCM_B", "CAPAMA3_Sand_F" }) + { + var header = File.ReadLines(Path.Combine(ElementaryStream.Folder(name), "riferimento.md5")).First().Split(' '); + var size = header[2].Split('x').Select(int.Parse).ToArray(); + Assert.IsTrue(H264StreamInfo.TryPictureSizeFromAnnexB(ElementaryStream.AnnexB(name), complete: true, out var w, out var h), name); + Assert.AreEqual((size[0], size[1]), (w, h), name); + } + + // Not an SPS, or one cut short at the end of what was gathered. + Assert.IsFalse(H264StreamInfo.TryPictureSize([0x68, 0xCE, 0x3C, 0x80], out _, out _)); + var annexB = ElementaryStream.AnnexB("BA1_Sony_D"); + var next = annexB.AsSpan(4).IndexOf((ReadOnlySpan)[0, 0, 1]) + 4; // the start code after the first SPS + Assert.IsTrue(H264StreamInfo.TryPictureSizeFromAnnexB(annexB.AsSpan(0, next - 1), complete: true, out _, out _)); + Assert.IsFalse(H264StreamInfo.TryPictureSizeFromAnnexB(annexB.AsSpan(0, next - 1), complete: false, out _, out _)); + } + + private static byte[] Head(byte[] file) => file[..Math.Min(file.Length, 512 * 1024)]; + + private static MediaContainer Read(byte[] file, bool samples = true) + { + using var stream = new MemoryStream(file, writable: false); + var container = ContainerReader.Read(stream, Now, samples); + Assert.IsNotNull(container); + return container; + } + + private static List DecodeAll(byte[] file, VideoTrack video) + { + using var stream = new MemoryStream(file); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + var lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration); + var buffer = Array.Empty(); + foreach (var sample in video.Samples) + { + decoder.DecodeSample(ContainerReader.ReadSample(stream, sample, ref buffer), lengthSize); + } + + decoder.Flush(); + return ElementaryStream.Md5InOutputOrder(frames); + } +} diff --git a/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs b/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs new file mode 100644 index 0000000..33346bf --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/LegacyTestVideos.cs @@ -0,0 +1,570 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Febe.Tests.Codecs.Containers; + +/// What a test ASF file holds. +internal sealed record AsfOptions +{ + public int Width { get; init; } = 640; + public int Height { get; init; } = 480; + public string Compression { get; init; } = "WMV3"; + public bool Video { get; init; } = true; + public bool Audio { get; init; } = true; + public TimeSpan Duration { get; init; } = TimeSpan.FromSeconds(12.5); + public ulong PrerollMilliseconds { get; init; } = 3000; + public bool Broadcast { get; init; } + public DateTimeOffset? Created { get; init; } + public DateTimeOffset? EncodingTime { get; init; } + public string? Title { get; init; } + + /// The video stream properties sit in an extended stream properties object of the header extension. + public bool VideoInExtension { get; init; } +} + +/// What a test MPEG program stream holds. +internal sealed record PsOptions +{ + /// «mpeg2», «mpeg1» or «h264» (then gives the pictures). + public string Video { get; init; } = "mpeg2"; + public int Width { get; init; } = 720; + public int Height { get; init; } = 576; + public int Frames { get; init; } = 50; + + /// Bytes of slice data per picture: large values make a file longer than the windows the reader looks at. + public int PictureBytes { get; init; } = 1500; + public bool Mpeg1System { get; init; } + public bool StreamMap { get; init; } + + /// «mp2», «ac3» or null. + public string? Audio { get; init; } = "mp2"; + public long FirstPts { get; init; } = 90_000; + public ElementaryStream? Stream { get; init; } + public int Seed { get; init; } = 7301; +} + +/// +/// Builders of ASF, FLV and MPEG program stream files from their specifications, for the readers' tests: no real sample +/// file is needed, and the filler bytes come from a fixed seed. +/// +internal static class LegacyTestVideos +{ + public static readonly Guid AsfHeader = new("75B22630-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly Guid AsfFileProperties = new("8CABDCA1-A947-11CF-8EE4-00C00C205365"); + private static readonly Guid AsfStreamProperties = new("B7DC0791-A9B7-11CF-8EE6-00C00C205365"); + private static readonly Guid AsfHeaderExtension = new("5FBF03B5-A92E-11CF-8EE3-00C00C205365"); + private static readonly Guid AsfReserved1 = new("ABD3D211-A9BA-11CF-8EE6-00C00C205365"); + private static readonly Guid AsfContentDescription = new("75B22633-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly Guid AsfExtendedContentDescription = new("D2D0A440-E307-11D2-97F0-00A0C95EA850"); + private static readonly Guid AsfExtendedStreamProperties = new("14E6A5CB-C672-4332-8399-A96952065B5A"); + private static readonly Guid AsfVideoMedia = new("BC19EFC0-5B4D-11CF-A8FD-00805F5C442B"); + private static readonly Guid AsfAudioMedia = new("F8699E40-5B4D-11CF-A8FD-00805F5C442B"); + private static readonly Guid AsfNoErrorCorrection = new("20FB5700-5B55-11CF-A8FD-00805F5C442B"); + private static readonly Guid AsfData = new("75B22636-668E-11CF-A6D9-00AA0062CE6C"); + private static readonly DateTimeOffset Epoch1601 = new(1601, 1, 1, 0, 0, 0, TimeSpan.Zero); + + // ----- ASF ----- + + /// An ASF file: header object with the objects of , then a data object of filler packets. + public static byte[] Asf(AsfOptions o) + { + var random = new Random(4101); + var children = new List(); + var fileId = new byte[16]; + random.NextBytes(fileId); + + var play = (ulong)o.Duration.Ticks + (o.PrerollMilliseconds * 10_000); + children.Add(AsfObject(AsfFileProperties, [.. fileId, .. Le64(0), .. Le64(o.Created is { } c ? FileTime(c) : 0), .. Le64(10), + .. Le64(play), .. Le64(play), .. Le64(o.PrerollMilliseconds), .. Le32(o.Broadcast ? 1u : 2u), .. Le32(3200), .. Le32(3200), .. Le32(512_000)])); + if (o.Video && !o.VideoInExtension) + { + children.Add(VideoStream(o, 1)); + } + + if (o.Audio) + { + children.Add(AudioStream(2)); + } + + if (o.Title is not null) + { + var title = Encoding.Unicode.GetBytes(o.Title + "\0"); + var author = Encoding.Unicode.GetBytes("Febe\0"); + children.Add(AsfObject(AsfContentDescription, + [.. Le16((ushort)title.Length), .. Le16((ushort)author.Length), .. Le16(0), .. Le16(0), .. Le16(0), .. title, .. author])); + } + + var descriptors = new List { Descriptor("WM/ToolName", 0, Encoding.Unicode.GetBytes("Prove di Febe\0")) }; + if (o.EncodingTime is { } e) + { + descriptors.Add(Descriptor("WM/EncodingTime", 4, Le64(FileTime(e)))); + } + + descriptors.Add(Descriptor("IsVBR", 2, Le32(1))); + children.Add(AsfObject(AsfExtendedContentDescription, [.. Le16((ushort)descriptors.Count), .. descriptors.SelectMany(d => d)])); + + var extension = new List(); + if (o.Video && o.VideoInExtension) + { + var name = Encoding.Unicode.GetBytes("Video\0"); + extension.Add(AsfObject(AsfExtendedStreamProperties, + [.. Le64(0), .. Le64(0), .. Le32(500_000), .. Le32(3000), .. Le32(0), .. Le32(0), .. Le32(0), .. Le32(0), .. Le32(65_536), + .. Le32(0), .. Le16(1), .. Le16(0), .. Le64(400_000), .. Le16(1), .. Le16(1), + .. Le16(0), .. Le16((ushort)name.Length), .. name, + .. Enumerable.Repeat((byte)0x11, 16),.. Le16(4), .. Le32(4), 1, 2, 3, 4, + .. VideoStream(o, 1)])); + } + + var extensionData = extension.SelectMany(x => x).ToArray(); + children.Add(AsfObject(AsfHeaderExtension, [.. AsfReserved1.ToByteArray(), .. Le16(6), .. Le32((uint)extensionData.Length), .. extensionData])); + + var body = children.SelectMany(x => x).ToArray(); + byte[] header = [.. AsfHeader.ToByteArray(), .. Le64((ulong)(30 + body.Length)), .. Le32((uint)children.Count), 1, 2, .. body]; + var packets = new byte[10 * 3200]; + random.NextBytes(packets); + var data = AsfObject(AsfData, [.. fileId, .. Le64(10), 1, 1, .. packets]); + return [.. header, .. data]; + } + + private static byte[] VideoStream(AsfOptions o, int number) + { + var bitmap = new List(); + bitmap.AddRange(Le32(40)); + bitmap.AddRange(Le32((uint)o.Width)); + bitmap.AddRange(Le32((uint)o.Height)); + bitmap.AddRange(Le16(1)); + bitmap.AddRange(Le16(24)); + bitmap.AddRange(Encoding.ASCII.GetBytes(o.Compression)); + bitmap.AddRange(new byte[20]); + byte[] specific = [.. Le32((uint)o.Width), .. Le32((uint)o.Height), 2, .. Le16((ushort)bitmap.Count), .. bitmap]; + return StreamObject(AsfVideoMedia, number, specific); + } + + private static byte[] AudioStream(int number) + { + // WAVEFORMATEX of WMA 2: 44.1 kHz stereo, with ten bytes of codec data. + byte[] specific = [.. Le16(0x161), .. Le16(2), .. Le32(44_100), .. Le32(16_000), .. Le16(2_973), .. Le16(16), .. Le16(10), .. new byte[10]]; + return StreamObject(AsfAudioMedia, number, specific); + } + + private static byte[] StreamObject(Guid type, int number, byte[] specific) => AsfObject(AsfStreamProperties, + [.. type.ToByteArray(), .. AsfNoErrorCorrection.ToByteArray(), .. Le64(0), .. Le32((uint)specific.Length), .. Le32(0), + .. Le16((ushort)number), .. Le32(0), .. specific]); + + private static byte[] Descriptor(string name, ushort type, byte[] value) + { + var n = Encoding.Unicode.GetBytes(name + "\0"); + return [.. Le16((ushort)n.Length), .. n, .. Le16(type), .. Le16((ushort)value.Length), .. value]; + } + + private static byte[] AsfObject(Guid id, byte[] body) => [.. id.ToByteArray(), .. Le64((ulong)(24 + body.Length)), .. body]; + + private static ulong FileTime(DateTimeOffset instant) => (ulong)(instant - Epoch1601).Ticks; + + // ----- FLV ----- + + /// + /// An FLV file of an H.264 stream at 30 frames per second: onMetaData (unless is false), + /// the AVC sequence header, one tag per access unit with its composition time and, with , an + /// AAC sequence header and AAC tags between the frames. + /// + public static byte[] Flv(ElementaryStream es, bool metadata = true, string? creationDate = null, bool audio = false, + (int Width, int Height)? metadataSize = null, double? creationMilliseconds = null) + { + var shift = 0; + for (var i = 0; i < es.Count; i++) + { + shift = Math.Max(shift, i - es.Rank[i]); + } + + using var output = new MemoryStream(); + FlvHeader(output, audio, video: true); + if (metadata) + { + var size = metadataSize ?? (es.Width, es.Height); + var properties = new List + { + AmfProperty("duration", AmfNumber(es.Count / 30.0)), + AmfProperty("width", AmfNumber(size.Width)), + AmfProperty("height", AmfNumber(size.Height)), + AmfProperty("framerate", AmfNumber(30)), + AmfProperty("videocodecid", AmfNumber(7)), + AmfProperty("stereo", [1, 1]), + AmfProperty("encoder", AmfString("Prove di Febe")), + AmfProperty("keyframes", [3, .. AmfProperty("times", AmfArray(Enumerable.Range(0, es.Count).Where(i => es.Key[i]).Select(i => i / 30.0))), + .. AmfProperty("filepositions", AmfArray(Enumerable.Range(0, es.Count).Where(i => es.Key[i]).Select(i => i * 1000.0))), 0, 0, 9]), + }; + if (creationDate is not null) + { + properties.Add(AmfProperty("creationdate", AmfString(creationDate))); + } + + if (creationMilliseconds is { } ms) + { + properties.Add(AmfProperty("creationdate", [11, .. F64(ms), 0, 0])); + } + + FlvTag(output, 18, 0, [.. AmfString("onMetaData"), 8, .. U32((uint)properties.Count), .. properties.SelectMany(p => p), 0, 0, 9]); + } + + FlvTag(output, 9, 0, [0x17, 0, 0, 0, 0, .. es.AvcC]); + if (audio) + { + FlvTag(output, 8, 0, [0xAF, 0, 0x12, 0x10]); // AAC LC, 44.1 kHz, stereo + } + + for (var i = 0; i < es.Count; i++) + { + var dts = (int)Math.Round(i * 1000.0 / 30); + var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30); + var cts = pts - dts; + FlvTag(output, 9, dts, [es.Key[i] ? (byte)0x17 : (byte)0x27, 1, (byte)(cts >> 16), (byte)(cts >> 8), (byte)cts, .. es.LengthPrefixed(i)]); + if (audio && i % 2 == 0) + { + FlvTag(output, 8, dts, [0xAF, 1, 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C]); + } + } + + return output.ToArray(); + } + + /// An FLV with one script tag of the given AMF0 body and one H.263 video tag. + public static byte[] FlvWithScript(byte[] script) + { + using var output = new MemoryStream(); + FlvHeader(output, audio: false, video: true); + FlvTag(output, 18, 0, script); + FlvTag(output, 9, 0, [0x12, 0, 0, 0x80, 0, 0x0A, 0x00, 0x00, 0x00, 0x00]); + return output.ToArray(); + } + + /// An FLV of Sorenson H.263 tags whose picture headers give the size (code 0, 1 or a fixed size code). + public static byte[] SorensonFlv(int sizeCode, int width, int height, int frames = 10) + { + using var output = new MemoryStream(); + FlvHeader(output, audio: false, video: true); + var random = new Random(4102); + for (var i = 0; i < frames; i++) + { + var bits = new BitWriterForTests(); + bits.Write(1, 17); // picture start code + bits.Write(0, 5); // version + bits.Write(i & 0xFF, 8); // temporal reference + bits.Write(sizeCode, 3); + if (sizeCode == 0) + { + bits.Write(width, 8); + bits.Write(height, 8); + } + else if (sizeCode == 1) + { + bits.Write(width, 16); + bits.Write(height, 16); + } + + bits.Write(i == 0 ? 0 : 1, 2); // picture type: intra, then inter + var filler = new byte[200]; + random.NextBytes(filler); + FlvTag(output, 9, i * 40, [(byte)((i == 0 ? 0x10 : 0x20) | 2), .. bits.ToArray(), .. filler]); + } + + return output.ToArray(); + } + + /// An FLV whose video tags use the enhanced header with , or only audio tags. + public static byte[] EnhancedOrAudioFlv(string? fourCc, bool audioFlag, bool videoFlag) + { + using var output = new MemoryStream(); + FlvHeader(output, audioFlag, videoFlag); + for (var i = 0; i < 20; i++) + { + if (fourCc is not null) + { + FlvTag(output, 9, i * 40, [(byte)(0x80 | (i == 0 ? 0x10 : 0x20) | 1), .. Encoding.ASCII.GetBytes(fourCc), 0, 0, 0, 0x55, 0x66]); + } + + FlvTag(output, 8, i * 40, [0x2F, 0xFF, 0xFB, 0x90, 0x64, 0, 0, 0]); // MP3, 44 kHz, stereo + } + + return output.ToArray(); + } + + /// + /// An FLV whose header says audio and no video, opened by an onMetaData tag of about + /// bytes (a keyframe index), then MP3 tags every 26 ms for , and from + /// on (when given) H.263 video tags among them every 40 ms. + /// + public static byte[] AudioFlaggedFlv(int metadataBytes, double seconds, int? videoFromMs = null) + { + using var output = new MemoryStream(); + FlvHeader(output, audio: true, video: false); + var times = Enumerable.Range(0, Math.Max(1, metadataBytes / 9)).Select(i => i * 0.04); + FlvTag(output, 18, 0, [.. AmfString("onMetaData"), 8, .. U32(1), .. AmfProperty("times", AmfArray(times)), 0, 0, 9]); + var nextVideo = videoFromMs ?? int.MaxValue; + for (var time = 0; time < seconds * 1000; time += 26) + { + while (nextVideo <= time) + { + FlvTag(output, 9, nextVideo, [0x22, 0, 0, 0x80, 0, 0x0A, 0x00, 0x00, 0x00, 0x00]); + nextVideo += 40; + } + + FlvTag(output, 8, time, [0x2F, 0xFF, 0xFB, 0x90, 0x64, 0, 0, 0]); // MP3, 44 kHz, stereo + } + + return output.ToArray(); + } + + private static void FlvHeader(MemoryStream output, bool audio, bool video) + { + output.Write("FLV"u8); + output.WriteByte(1); + output.WriteByte((byte)((audio ? 4 : 0) | (video ? 1 : 0))); + output.Write(U32(9)); + output.Write(U32(0)); + } + + private static void FlvTag(MemoryStream output, int type, int time, byte[] data) + { + output.Write([(byte)type, (byte)(data.Length >> 16), (byte)(data.Length >> 8), (byte)data.Length, + (byte)(time >> 16), (byte)(time >> 8), (byte)time, (byte)(time >> 24), 0, 0, 0]); + output.Write(data); + output.Write(U32((uint)(11 + data.Length))); + } + + private static byte[] AmfString(string text) + { + var bytes = Encoding.UTF8.GetBytes(text); + return [2, .. U16((ushort)bytes.Length), .. bytes]; + } + + private static byte[] AmfNumber(double value) => [0, .. F64(value)]; + + private static byte[] AmfArray(IEnumerable values) + { + var items = values.ToList(); + return [10, .. U32((uint)items.Count), .. items.SelectMany(AmfNumber)]; + } + + private static byte[] AmfProperty(string name, byte[] value) + { + var bytes = Encoding.UTF8.GetBytes(name); + return [.. U16((ushort)bytes.Length), .. bytes, .. value]; + } + + // ----- MPEG program stream ----- + + /// + /// An MPEG program stream: a pack header before each picture, a system header, optionally a program stream map, the + /// pictures as PES packets of at most 2,000 bytes (the first with its presentation time), and audio frames between. + /// MPEG-1 and MPEG-2 pictures are a sequence header (with its extension in MPEG-2), a GOP header, a picture header + /// and filler slice bytes; H.264 pictures are the access units of . + /// + public static byte[] MpegPs(PsOptions o) + { + var random = new Random(o.Seed); + var frameTicks = o.Video == "h264" ? 3000 : 3600; // 30 or 25 pictures a second + var frames = o.Video == "h264" ? o.Stream!.Count : o.Frames; + using var output = new MemoryStream(); + var audioTime = o.FirstPts; + for (var i = 0; i < frames; i++) + { + var pts = (o.FirstPts + ((long)i * frameTicks)) & ((1L << 33) - 1); + Pack(output, o, pts > 9000 ? pts - 9000 : 0); + if (i == 0) + { + output.Write([0, 0, 1, 0xBB, 0, 12, 0x80, 0x00, 0x01, 0x04, 0xE1, 0xFF, 0xE0, 0xE0, 0xE8, 0xC0, 0xC0, 0x20]); + if (o.StreamMap) + { + var videoType = o.Video switch { "h264" => (byte)0x1B, "mpeg1" => (byte)0x01, _ => (byte)0x02 }; + byte[] map = [videoType, 0xE0, 0, 0, 0x04, 0xC0, 0, 0]; + byte[] body = [0x80, 0x01, 0, 0, .. U16((ushort)map.Length), .. map, 0, 0, 0, 0]; + output.Write([0, 0, 1, 0xBC, .. U16((ushort)body.Length), .. body]); + } + } + + var picture = o.Video == "h264" ? o.Stream!.WithStartCodes(i) : MpegPicture(o, i, random); + for (var offset = 0; offset < picture.Length; offset += 2000) + { + var chunk = picture.AsSpan(offset, Math.Min(2000, picture.Length - offset)).ToArray(); + Pes(output, 0xE0, offset == 0 ? pts : -1, chunk, o.Mpeg1System); + } + + while (o.Audio is not null && audioTime <= o.FirstPts + ((long)i * frameTicks)) + { + var t = audioTime & ((1L << 33) - 1); + if (o.Audio == "ac3") + { + // Private stream 1, sub-stream 0x80: one AC-3 frame at 48 kHz, 3/2 channels with LFE (5.1). + var frame = new byte[768]; + frame[0] = 0x0B; + frame[1] = 0x77; + frame[4] = 0x00 | 0x0E; // fscod 0 (48 kHz), frmsizecod + frame[5] = 0x08 << 3; // bsid 8, bsmod 0 + var bits = new BitWriterForTests(); + bits.Write(7, 3); // acmod 3/2 + bits.Write(1, 2); // cmixlev + bits.Write(1, 2); // surmixlev + bits.Write(1, 1); // lfeon + bits.ToArray().CopyTo(frame, 6); + Pes(output, 0xBD, t, [0x80, 1, 0, 1, .. frame], o.Mpeg1System); + audioTime += 2880; // 1,536 samples + } + else + { + var frame = new byte[576]; + frame[0] = 0xFF; + frame[1] = 0xFD; // MPEG-1 layer II, no CRC + frame[2] = 0xA4; // 192 kbit/s, 48 kHz + frame[3] = 0x04; // stereo + Pes(output, 0xC0, t, frame, o.Mpeg1System); + audioTime += 2160; // 1,152 samples + } + } + } + + output.Write([0, 0, 1, 0xB9]); + return output.ToArray(); + } + + private static byte[] MpegPicture(PsOptions o, int index, Random random) + { + var data = new List(); + if (index % 12 == 0) + { + var bits = new BitWriterForTests(); + bits.Write(o.Width & 0xFFF, 12); + bits.Write(o.Height & 0xFFF, 12); + bits.Write(1, 4); // square pixels + bits.Write(3, 4); // 25 pictures a second + bits.Write(0x3FFFF, 18); + bits.Write(1, 1); + bits.Write(112, 10); + bits.Write(0, 3); + data.AddRange([0, 0, 1, 0xB3, .. bits.ToArray()]); + if (o.Video == "mpeg2") + { + var ext = new BitWriterForTests(); + ext.Write(1, 4); // sequence extension + ext.Write(0x48, 8); // main profile, main level + ext.Write(1, 1); // progressive + ext.Write(1, 2); // 4:2:0 + ext.Write(o.Width >> 12, 2); + ext.Write(o.Height >> 12, 2); + ext.Write(0, 12); + ext.Write(1, 1); + ext.Write(0, 8); + ext.Write(0, 8); + data.AddRange([0, 0, 1, 0xB5, .. ext.ToArray()]); + } + + data.AddRange([0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]); + } + + data.AddRange([0, 0, 1, 0x00, (byte)(index >> 2), (byte)((index << 6) | 0x08), 0xFF, 0xF8]); + var slice = new byte[o.PictureBytes]; + random.NextBytes(slice); + for (var k = 0; k < slice.Length; k++) + { + slice[k] |= 0x01; // no zero bytes: no start code inside the filler + } + + data.AddRange([0, 0, 1, 0x01, .. slice]); + return [.. data]; + } + + private static void Pack(MemoryStream output, PsOptions o, long scr) + { + if (o.Mpeg1System) + { + // '0010', SCR in the layout of a time stamp, then the mux rate between two marker bits. + output.Write([0, 0, 1, 0xBA, .. Timestamp(0x2, scr), 0x80, 0x1B, 0x83]); + return; + } + + var b = new byte[] { 0, 0, 1, 0xBA, + (byte)(0x44 | ((scr >> 27) & 0x38) | ((scr >> 28) & 3)), + (byte)(scr >> 20), + (byte)(((scr >> 12) & 0xF8) | 0x04 | ((scr >> 13) & 3)), + (byte)(scr >> 5), + (byte)(((scr << 3) & 0xF8) | 0x04), + 0x01, 0x01, 0x89, 0xC3, 0xF8 }; + output.Write(b); + } + + private static void Pes(MemoryStream output, int id, long pts, byte[] payload, bool mpeg1) + { + byte[] header = mpeg1 + ? pts >= 0 ? Timestamp(0x2, pts) : [0x0F] + : pts >= 0 ? [0x81, 0x80, 5, .. Timestamp(0x2, pts)] : [0x81, 0x00, 0]; + var length = header.Length + payload.Length; + output.Write([0, 0, 1, (byte)id, (byte)(length >> 8), (byte)length, .. header, .. payload]); + } + + /// A 33-bit time in five bytes with a four-bit prefix and three marker bits. + private static byte[] Timestamp(int prefix, long t) => + [ + (byte)((prefix << 4) | (int)((t >> 29) & 0x0E) | 1), + (byte)(t >> 22), + (byte)(((t >> 14) & 0xFE) | 1), + (byte)(t >> 7), + (byte)(((t << 1) & 0xFE) | 1), + ]; + + // ----- bytes ----- + + private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v]; + + private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v]; + + private static byte[] F64(double v) + { + var b = new byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(b, v); + return b; + } + + private static byte[] Le16(ushort v) => [(byte)v, (byte)(v >> 8)]; + + private static byte[] Le32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, v); + return b; + } + + private static byte[] Le64(ulong v) + { + var b = new byte[8]; + BinaryPrimitives.WriteUInt64LittleEndian(b, v); + return b; + } + + /// Writes bits from the most significant one, as the codec headers want them. + private sealed class BitWriterForTests + { + private readonly List bytes = []; + private int used = 8; + + public void Write(int value, int count) + { + for (var i = count - 1; i >= 0; i--) + { + if (used == 8) + { + bytes.Add(0); + used = 0; + } + + if (((value >> i) & 1) != 0) + { + bytes[^1] |= (byte)(0x80 >> used); + } + + used++; + } + } + + public byte[] ToArray() => [.. bytes]; + } +} diff --git a/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs new file mode 100644 index 0000000..d283c7e --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/MalformedInputTests.cs @@ -0,0 +1,363 @@ +using System.Buffers.Binary; +using Febe.Core.Codecs.Containers; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// Truncated and garbled videos: the container readers, the metadata probe and the frame decoder must survive every one +/// of them with a (or ), a null result or a frame, +/// and must never allocate much more than the file holds, whatever its damaged headers claim. +/// +[TestClass] +public sealed class MalformedInputTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + + [TestMethod] + [DataRow("mp4")] + [DataRow("frammentato.mp4")] + [DataRow("mkv")] + [DataRow("avi")] + [DataRow("wmv")] + [DataRow("flv")] + [DataRow("mpg")] + [DataRow("h264.mpg")] + public void TruncatedFilesNeverBreakTheReaders(string kind) + { + var file = Build(kind); + var step = Math.Max(1, file.Length / 300); + for (var length = 0; length < file.Length; length += step) + { + AssertReadersSurvive(file[..length], $"{kind} troncato a {length}"); + } + } + + [TestMethod] + [DataRow("mp4", 5801)] + [DataRow("frammentato.mp4", 5802)] + [DataRow("mkv", 5803)] + [DataRow("avi", 5804)] + [DataRow("wmv", 5805)] + [DataRow("flv", 5806)] + [DataRow("mpg", 5807)] + [DataRow("h264.mpg", 5808)] + public void GarbledFilesNeverBreakTheReaders(string kind, int seed) + { + var file = Build(kind); + var random = new Random(seed); + for (var trial = 0; trial < 400; trial++) + { + AssertReadersSurvive(Garble(file, random), $"{kind}, variante {trial} del seme {seed}"); + } + } + + [TestMethod] + [DataRow("mp4", 5811)] + [DataRow("frammentato.mp4", 5812)] + [DataRow("mkv", 5813)] + [DataRow("avi", 5814)] + [DataRow("wmv", 5815)] + [DataRow("flv", 5816)] + [DataRow("mpg", 5817)] + public async Task GarbledFilesNeverBreakTheProbeOrTheFrameDecoder(string kind, int seed) + { + var file = Build(kind); + var random = new Random(seed); + using var temp = new TempFolder("rovinati"); + var decoded = 0; + for (var trial = 0; trial < 60; trial++) + { + var path = TestVideos.Write(temp, $"{trial}.{kind}", Garble(file, random)); + _ = ContainerVideoMetadataProbe.Probe(path, Now); // null or metadata, never an exception + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)); + var stillness = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path); + decoded += image is null ? 0 : 1; + _ = stillness; + } + + // Most damage hits frame data, not headers: many variants still give a frame. WMV and MPEG program streams have + // no samples Febe decodes, so no frame ever. + if (kind is "wmv" or "mpg") + { + Assert.AreEqual(0, decoded); + } + else + { + Assert.IsGreaterThan(0, decoded, "nessuna variante ha dato un fotogramma"); + } + } + + [TestMethod] + public void AHugeSampleCountInATinyMp4AllocatesNothing() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + + // stsz with a fixed sample size of 1 and almost two million samples: far more than the file can hold. + var file = TestVideos.Mp4(es); + var stsz = IndexOf(file, "stsz"u8); + BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(stsz + 8), 1); + BinaryPrimitives.WriteUInt32BigEndian(file.AsSpan(stsz + 12), 1_999_999); + var container = ReadMeasured(file, out var allocated); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + Assert.IsEmpty(container!.Video!.Samples, "una tabella impossibile non dà campioni"); + + // A trun of almost two million samples without per-sample fields: under the sample limit, but far more than the + // file can hold (the trex default size is 0, so each would take at least a byte). That fragment gives nothing, + // the others give their samples. + var fragmented = TestVideos.FragmentedMp4(es, perFragment: 5); + var trun = IndexOf(fragmented, "trun"u8); + BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 4), 0x000001); // only data_offset + BinaryPrimitives.WriteUInt32BigEndian(fragmented.AsSpan(trun + 8), 1_999_999); + container = ReadMeasured(fragmented, out allocated); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + Assert.HasCount(es.Count - 5, container!.Video!.Samples, "nessun campione inventato"); + } + + [TestMethod] + public async Task AMatroskaFileWithADamagedOrTruncatedBlockKeepsTheBlocksBefore() + { + var es = ElementaryStream.Load("CI_MW_D"); + var file = TestVideos.Matroska(es); + using var temp = new TempFolder("matroska-rovinato"); + var intact = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "intero.mkv", file), TimeSpan.FromSeconds(1)); + Assert.IsNotNull(intact); + + // The blocks close the file: each is the ID, an eight-byte size, track, time, flags and the sample. + int StartOf(int block) => file.Length - Enumerable.Range(block, es.Count - block).Sum(i => 1 + 8 + 4 + es.LengthPrefixed(i).Length); + + // Cut inside the fixed part of the last block. + var truncated = file[..(StartOf(es.Count - 1) + 1 + 8 + 2)]; + Assert.HasCount(es.Count - 1, ReadMeasured(truncated, out _)!.Video!.Samples); + + // Block 50 says it holds nothing but its own header: the blocks before it stand, the frame at one second too. + var damaged = (byte[])file.Clone(); + var block = StartOf(50); + Assert.AreEqual(0xA3, damaged[block]); + damaged.AsSpan(block + 2, 7).Clear(); + damaged[block + 8] = 4; + Assert.HasCount(50, ReadMeasured(damaged, out _)!.Video!.Samples); + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(TestVideos.Write(temp, "rovinato.mkv", damaged), TimeSpan.FromSeconds(1)); + CollectionAssert.AreEqual(intact.Rgb, image!.Rgb); + } + + [TestMethod] + public void ADamagedAudioTrackDoesNotCostTheVideo() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + + // The descriptors of the audio esds run to its very end: the ES_Descriptor starts at its last two bytes. + var file = TestVideos.Mp4(es, audio: true); + var esds = IndexOf(file, "esds"u8); + var length = (int)BinaryPrimitives.ReadUInt32BigEndian(file.AsSpan(esds - 4)) - 8; + var body = file.AsSpan(esds + 4, length); + body[4..].Clear(); + body[4] = 0x7F; // an unknown descriptor that covers the body... + body[5] = (byte)(length - 8); + body[length - 2] = 0x03; // ...up to an ES_Descriptor with no room for its fields + var container = ReadMeasured(file, out _)!; + Assert.HasCount(es.Count, container.Video!.Samples); + Assert.IsNotNull(container.Audio); + Assert.IsNull(container.Audio.AacConfiguration); + + // The audio track header claims version 1, whose fields lie past the end of the box: that track is dropped. + file = TestVideos.Mp4(es, audio: true); + var audioTkhd = file.AsSpan(IndexOf(file, "tkhd"u8) + 4).IndexOf("tkhd"u8) + IndexOf(file, "tkhd"u8) + 4; + file[audioTkhd + 4] = 1; + container = ReadMeasured(file, out _)!; + Assert.HasCount(es.Count, container.Video!.Samples); + Assert.IsNull(container.Audio); + using var temp = new TempFolder("audio-rovinato"); + var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.mp4", file), Now); + Assert.AreEqual((es.Width, es.Height), (metadata!.Width, metadata.Height)); + } + + [TestMethod] + public void AnAviWithAnImpossibleDurationKeepsItsDate() + { + // One frame per million seconds for a million frames: 10¹² seconds, beyond what a TimeSpan holds. + var es = ElementaryStream.Load("BA1_Sony_D"); + var file = TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021", scale: 1_000_000, rate: 1, length: 1_000_000); + var container = ReadMeasured(file, out _)!; + Assert.IsNull(container.Duration); + Assert.AreEqual(2021, container.CreatedAt!.Value.Year); + + using var temp = new TempFolder("avi-durata"); + var metadata = ContainerVideoMetadataProbe.Probe(TestVideos.Write(temp, "video.avi", file), Now); + Assert.IsNotNull(metadata, "la data scritta nel file non va persa"); + Assert.AreEqual(2021, metadata.CreatedAt!.Value.Year); + Assert.IsNull(metadata.Duration); + } + + [TestMethod] + public void AMatroskaElementLargerThanTheFileAllocatesNothing() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var file = TestVideos.Matroska(es); + + // CodecPrivate (0x63A2) with an eight-byte size: claim 60 MB in a file of a few kilobytes. + var codecPrivate = IndexOf(file, [0x63, 0xA2, 0x01]); + file[codecPrivate + 2] = 0x01; + var size = new byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(size, 60L * 1024 * 1024); + size.AsSpan(1).CopyTo(file.AsSpan(codecPrivate + 3)); + long allocated = 0; + Assert.ThrowsExactly(() => ReadMeasured(file, out allocated)); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + } + + [TestMethod] + public void DeepOrEndlessFlvMetadataKeepsWhatCameBefore() + { + // onMetaData: a duration, then objects nested a hundred thousand deep (a stack overflow if followed blindly). + var deep = new List { 2, 0, 10 }; + deep.AddRange("onMetaData"u8.ToArray()); + deep.Add(3); + deep.AddRange([0, 8, .. "duration"u8, 0, .. Be64(5.0)]); + for (var i = 0; i < 100_000; i++) + { + deep.AddRange([0, 1, (byte)'a', 3]); + } + + var container = ReadMeasured(LegacyTestVideos.FlvWithScript([.. deep]), out var allocated); + Assert.AreEqual(TimeSpan.FromSeconds(5), container!.Duration); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + + // A strict array that claims four billion values, then a width: the array ends the reading, the duration stays. + List endless = [2, 0, 10, .. "onMetaData"u8, 8, 0, 0, 0, 2, 0, 8, .. "duration"u8, 0, .. Be64(7.0), + 0, 4, .. "list"u8, 10, 0xFF, 0xFF, 0xFF, 0xFF, 0, .. Be64(1), 0, 5, .. "width"u8, 0, .. Be64(640)]; + container = ReadMeasured(LegacyTestVideos.FlvWithScript([.. endless]), out _); + Assert.AreEqual(TimeSpan.FromSeconds(7), container!.Duration); + } + + [TestMethod] + public void AnAsfObjectLargerThanItsFileAllocatesNothing() + { + var file = LegacyTestVideos.Asf(new AsfOptions { Title = "Prova" }); + + // The file properties object (the first after the 30 bytes of the header) claims a gigabyte. + BinaryPrimitives.WriteUInt64LittleEndian(file.AsSpan(30 + 16), 1L << 30); + var container = ReadMeasured(file, out var allocated); + Assert.IsLessThan(4L * 1024 * 1024, allocated, $"{allocated} byte allocati"); + Assert.IsNull(container!.Duration, "nulla dopo l'oggetto rovinato"); + + // A header object smaller than its own fields. + file = LegacyTestVideos.Asf(new AsfOptions()); + BinaryPrimitives.WriteUInt64LittleEndian(file.AsSpan(16), 12); + Assert.ThrowsExactly(() => ReadMeasured(file, out _)); + } + + private static byte[] Be64(double value) + { + var bytes = new byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(bytes, value); + return bytes; + } + + private static void AssertReadersSurvive(byte[] data, string what) + { + foreach (var samples in new[] { false, true }) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + try + { + using var stream = new MemoryStream(data, writable: false); + var container = ContainerReader.Read(stream, Now, samples); + if (samples && container?.Video is { } video) + { + // Every sample listed is inside the file, or reading it says so. + var buffer = Array.Empty(); + foreach (var sample in video.Samples.Take(50)) + { + try + { + _ = ContainerReader.ReadSample(stream, sample, ref buffer); + } + catch (ContainerException) + { + } + } + } + } + catch (ContainerException) + { + } + catch (EndOfStreamException) + { + } + catch (Exception ex) + { + Assert.Fail($"{what} (campioni: {samples}): {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}"); + } + + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.IsLessThan((16L * 1024 * 1024) + (64L * data.Length), allocated, $"{what}: {allocated} byte allocati per {data.Length} byte di file"); + } + } + + private static MediaContainer? ReadMeasured(byte[] file, out long allocated) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + try + { + using var stream = new MemoryStream(file, writable: false); + return ContainerReader.Read(stream, Now); + } + finally + { + allocated = GC.GetAllocatedBytesForCurrentThread() - before; + } + } + + private static byte[] Build(string kind) + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + return kind switch + { + "frammentato.mp4" => TestVideos.FragmentedMp4(es, perFragment: 6, defaults: true), + "mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), + "avi" => TestVideos.Avi(es, "Thu Mar 04 05:06:07 2021"), + "wmv" => LegacyTestVideos.Asf(new AsfOptions + { + Created = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero), + EncodingTime = new DateTimeOffset(2009, 6, 7, 8, 9, 10, TimeSpan.Zero), + Title = "Prova", + VideoInExtension = true, + }), + "flv" => LegacyTestVideos.Flv(es, creationDate: "Thu Mar 04 05:06:07 2021", audio: true), + "mpg" => LegacyTestVideos.MpegPs(new PsOptions { Frames = 30, PictureBytes = 300, StreamMap = true }), + "h264.mpg" => LegacyTestVideos.MpegPs(new PsOptions { Video = "h264", Stream = es, Audio = "ac3" }), + _ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero), rotation: 90, audio: true), + }; + } + + /// A copy with a few bytes changed: mostly in the first kilobytes, where the headers are. + private static byte[] Garble(byte[] file, Random random) + { + var copy = (byte[])file.Clone(); + var changes = 1 + random.Next(12); + for (var k = 0; k < changes; k++) + { + var range = random.Next(3) == 0 ? copy.Length : Math.Min(copy.Length, 2048); + var p = random.Next(range); + copy[p] = random.Next(4) switch + { + 0 => (byte)random.Next(256), + 1 => (byte)(copy[p] ^ (1 << random.Next(8))), + 2 => 0xFF, + _ => 0, + }; + } + + return random.Next(5) == 0 ? copy[..random.Next(copy.Length)] : copy; + } + + private static int IndexOf(byte[] data, ReadOnlySpan pattern) + { + var index = data.AsSpan().IndexOf(pattern); + Assert.IsGreaterThanOrEqualTo(0, index); + return index; + } +} diff --git a/tests/Febe.Tests/Media/Containers/TestVideos.cs b/tests/Febe.Tests/Media/Containers/TestVideos.cs new file mode 100644 index 0000000..879d3b3 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/TestVideos.cs @@ -0,0 +1,503 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// An H.264 conformance stream cut into access units, with what a container needs: key frames, presentation order, +/// parameter sets. The test videos are built from these streams, so every frame has an official MD5. +/// +internal sealed class ElementaryStream +{ + private ElementaryStream(string name, List> units, int[] rank, bool[] key, byte[] avcC, int width, int height) + { + Name = name; + Units = units; + Rank = rank; + Key = key; + AvcC = avcC; + Width = width; + Height = height; + } + + public string Name { get; } + + /// The NAL units (without start codes) of each access unit, in decoding order. + public List> Units { get; } + + /// Position of each access unit in presentation order. + public int[] Rank { get; } + + /// True for access units with an IDR picture. + public bool[] Key { get; } + + public byte[] AvcC { get; } + + public int Width { get; } + + public int Height { get; } + + public int Count => Units.Count; + + public static string Folder(string name) => Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name); + + public static byte[] AnnexB(string name) => + File.ReadAllBytes(Directory.EnumerateFiles(Folder(name)).Single(f => Path.GetExtension(f) is ".264" or ".jsv" or ".avc")); + + /// The official per-frame MD5 values, in output order. + public static List Reference(string name) => + File.ReadAllLines(Path.Combine(Folder(name), "riferimento.md5")) + .Select(l => l.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + .Where(p => p.Length == 2 && int.TryParse(p[0], out _)) + .Select(p => p[1]) + .ToList(); + + /// MD5 values of frames in output order. + public static List Md5InOutputOrder(IEnumerable frames) => + frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex) + .Select(f => Convert.ToHexStringLower(MD5.HashData(f.ToPlanar()))) + .ToList(); + + public static ElementaryStream Load(string name) => FromAnnexB(name, AnnexB(name)); + + public static ElementaryStream FromAnnexB(string name, byte[] annexB) + { + var units = new List>(); + List? current = null; + var hasSlice = false; + foreach (var nal in SplitAnnexB(annexB)) + { + var type = nal[0] & 0x1F; + var startsPicture = type is 1 or 5 && nal.Length > 1 && (nal[1] & 0x80) != 0; // first_mb_in_slice == 0 + var beforePicture = type is 6 or 7 or 8 or 9 or (>= 14 and <= 18); + if (current is null || (hasSlice && (startsPicture || beforePicture))) + { + current = []; + units.Add(current); + hasSlice = false; + } + + current.Add(nal); + hasSlice |= type is 1 or 5; + } + + var key = units.Select(u => u.Any(n => (n[0] & 0x1F) == 5)).ToArray(); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(annexB); + Assert.AreEqual(units.Count, frames.Count, $"{name}: unità di accesso e fotogrammi"); + var order = frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList(); + var rank = new int[frames.Count]; + for (var i = 0; i < order.Count; i++) + { + rank[order[i].DecodeIndex] = i; + } + + var sps = units.SelectMany(u => u).Where(n => (n[0] & 0x1F) == 7).DistinctBy(Convert.ToBase64String).ToList(); + var pps = units.SelectMany(u => u).Where(n => (n[0] & 0x1F) == 8).DistinctBy(Convert.ToBase64String).ToList(); + var avcC = new List { 1, sps[0][1], sps[0][2], sps[0][3], 0xFF, (byte)(0xE0 | sps.Count) }; + foreach (var s in sps) + { + avcC.Add((byte)(s.Length >> 8)); + avcC.Add((byte)s.Length); + avcC.AddRange(s); + } + + avcC.Add((byte)pps.Count); + foreach (var p in pps) + { + avcC.Add((byte)(p.Length >> 8)); + avcC.Add((byte)p.Length); + avcC.AddRange(p); + } + + return new ElementaryStream(name, units, rank, key, [.. avcC], frames[0].Width, frames[0].Height); + } + + /// The same stream with only its first access unit, repeated: a video of a still picture. + public ElementaryStream FirstPictureRepeated(int times) + { + var units = Enumerable.Repeat(Units[0], times).ToList(); + return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height); + } + + /// + /// The same stream with its SPS and PPS repeated in every access unit, as some cameras and recorders write them: a + /// decoder started at any of its P or B frames finds its parameter sets. + /// + public ElementaryStream WithParameterSetsEverywhere() + { + var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList(); + var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList(); + return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height); + } + + /// An access unit with 4-byte length prefixes (MP4, Matroska). + public byte[] LengthPrefixed(int index) + { + using var output = new MemoryStream(); + Span length = stackalloc byte[4]; + foreach (var nal in Units[index]) + { + BinaryPrimitives.WriteInt32BigEndian(length, nal.Length); + output.Write(length); + output.Write(nal); + } + + return output.ToArray(); + } + + /// An access unit with start codes (AVI). + public byte[] WithStartCodes(int index) + { + using var output = new MemoryStream(); + foreach (var nal in Units[index]) + { + output.Write([0, 0, 0, 1]); + output.Write(nal); + } + + return output.ToArray(); + } + + private static List SplitAnnexB(byte[] data) + { + var starts = new List<(int Payload, int Code)>(); + for (var i = 0; i + 2 < data.Length; i++) + { + if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) + { + var code = i > 0 && data[i - 1] == 0 ? i - 1 : i; + starts.Add((i + 3, code)); + i += 2; + } + } + + var nals = new List(); + for (var k = 0; k < starts.Count; k++) + { + var end = k + 1 < starts.Count ? starts[k + 1].Code : data.Length; + while (end > starts[k].Payload && data[end - 1] == 0) + { + end--; // trailing zero bytes belong to no NAL unit + } + + if (end > starts[k].Payload) + { + nals.Add(data[starts[k].Payload..end]); + } + } + + return nals; + } +} + +/// Builders of test videos in the three containers, from an . +internal static class TestVideos +{ + /// Ticks per frame at timescale 30000: 30 frames per second. + public const int FrameTicks = 1000; + public const int Timescale = 30000; + + /// An MP4 written with ; with , also an AAC track of silence-shaped samples. + public static byte[] Mp4(ElementaryStream es, DateTimeOffset? created = null, int rotation = 0, bool audio = false) + { + var samples = new List(); + var data = new List(); + for (var i = 0; i < es.Count; i++) + { + var bytes = es.LengthPrefixed(i); + data.Add(bytes); + samples.Add(new Mp4OutputSample(bytes.Length, (long)i * FrameTicks, (long)es.Rank[i] * FrameTicks, es.Key[i])); + } + + var tracks = new List + { + new() + { + IsVideo = true, + Timescale = Timescale, + Samples = samples, + WriteSample = (i, s) => s.Write(data[i]), + Width = es.Width, + Height = es.Height, + Rotation = rotation, + AvcConfiguration = es.AvcC, + }, + }; + if (audio) + { + var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024); + var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C }; + tracks.Add(new Mp4OutputTrack + { + IsVideo = false, + Timescale = 44100, + Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))], + WriteSample = (_, s) => s.Write(payload), + AacConfiguration = [0x12, 0x10], // AAC LC, 44.1 kHz, stereo + SampleRate = 44100, + Channels = 2, + }); + } + + using var output = new MemoryStream(); + Mp4Writer.Write(output, tracks, created); + return output.ToArray(); + } + + /// + /// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of frames). + /// With the sample durations come from trex, each fragment has two runs that + /// both give their data_offset from the start of the moof, and an mehd box tells the duration. + /// + public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10, bool defaults = false) + { + var shift = 0; + for (var i = 0; i < es.Count; i++) + { + shift = Math.Max(shift, i - es.Rank[i]); + } + + using var output = new MemoryStream(); + output.Write(Box("ftyp", [.. "iso6"u8, 0, 0, 2, 0, .. "iso6mp41"u8])); + var stbl = Box("stbl", + FullBox("stsd", 0, [0, 0, 0, 1, .. Avc1(es)]), + FullBox("stts", 0, [0, 0, 0, 0]), + FullBox("stsc", 0, [0, 0, 0, 0]), + FullBox("stsz", 0, [0, 0, 0, 0, 0, 0, 0, 0]), + FullBox("stco", 0, [0, 0, 0, 0])); + var minf = Box("minf", FullBox("vmhd", 1, new byte[8]), Box("dinf", FullBox("dref", 0, [0, 0, 0, 1, .. FullBox("url ", 1, [])])), stbl); + var mdia = Box("mdia", + FullBox("mdhd", 0, [.. new byte[8], .. U32(Timescale), .. U32(0), 0x55, 0xC4, 0, 0]), + FullBox("hdlr", 0, [0, 0, 0, 0, .. "vide"u8, .. new byte[12], 0]), + minf); + var tkhd = FullBox("tkhd", 3, [.. new byte[8], .. U32(1), .. new byte[4], .. U32(0), .. new byte[16], + .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000), + .. U32((uint)es.Width << 16), .. U32((uint)es.Height << 16)]); + var mvhd = FullBox("mvhd", 0, [.. new byte[8], .. U32(1000), .. U32(0), .. U32(0x10000), 1, 0, .. new byte[10], + .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000), + .. new byte[24], .. U32(2)]); + // trex: track_ID, default_sample_description_index, default duration, size and flags (non-sync). + var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0x01010000)]); + var mvex = defaults + ? Box("mvex", FullBox("mehd", 0, U32((uint)(es.Count * 1000 / 30))), trex) // movie timescale 1000 + : Box("mvex", trex); + output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), mvex)); + + for (int first = 0, sequence = 1; first < es.Count; first += perFragment, sequence++) + { + var count = Math.Min(perFragment, es.Count - first); + var payloads = Enumerable.Range(first, count).Select(es.LengthPrefixed).ToList(); + byte[] Run(int from, int length, int dataOffset) + { + var run = new List(); + run.AddRange(U32((uint)length)); + run.AddRange(U32((uint)dataOffset)); + for (var k = from; k < from + length; k++) + { + var i = first + k; + if (!defaults) + { + run.AddRange(U32(FrameTicks)); + } + + run.AddRange(U32((uint)payloads[k].Length)); + run.AddRange(U32(es.Key[i] ? 0x02000000u : 0x01010000u)); + run.AddRange(U32((uint)((es.Rank[i] - i + shift) * FrameTicks))); + } + + // Without the duration field (0x100) every sample takes the trex default. + return FullBox("trun", defaults ? 0x000E01u : 0x000F01u, [.. run]); + } + + var split = defaults ? (count + 1) / 2 : count; + var secondData = payloads.Take(split).Sum(p => p.Length); + byte[] Moof(int dataOffset) + { + var runs = new List { Run(0, split, dataOffset) }; + if (split < count) + { + runs.Add(Run(split, count - split, dataOffset + secondData)); + } + + return Box("moof", + FullBox("mfhd", 0, U32((uint)sequence)), + Box("traf", [FullBox("tfhd", 0x020000, U32(1)), FullBox("tfdt", 0, U32((uint)(first * FrameTicks))), .. runs])); + } + + var size = Moof(0).Length; + output.Write(Moof(size + 8)); + output.Write(Box("mdat", payloads.SelectMany(p => p).ToArray())); + } + + return output.ToArray(); + } + + /// + /// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of + /// nanoseconds (milliseconds by default). + /// + public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000) + { + var shift = 0; + for (var i = 0; i < es.Count; i++) + { + shift = Math.Max(shift, i - es.Rank[i]); + } + + var header = Element(0x1A45DFA3, + Element(0x4286, [1]), Element(0x42F7, [1]), Element(0x42F2, [4]), Element(0x42F3, [8]), + Element(0x4282, Encoding.ASCII.GetBytes(webm ? "webm" : "matroska")), Element(0x4287, [4]), Element(0x4285, [2])); + var tickMs = timecodeScale / 1e6; + var durationTicks = es.Count * 1000.0 / 30 / tickMs; + var info = new List { Element(0x2AD7B1, U32(timecodeScale)), Element(0x4489, F64(durationTicks)), Element(0x4D80, "febe-prove"u8.ToArray()) }; + if (created is { } c) + { + var ns = (c - new DateTimeOffset(2001, 1, 1, 0, 0, 0, TimeSpan.Zero)).Ticks * 100; + info.Add(Element(0x4461, I64(ns))); + } + + var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height))); + var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]), + Element(0x86, "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video); + var blocks = new List { Element(0xE7, [0]) }; + for (var i = 0; i < es.Count; i++) + { + var pts = (int)Math.Round((es.Rank[i] + shift) * 1000.0 / 30 / tickMs); + var payload = es.LengthPrefixed(i); + blocks.Add(Element(0xA3, [0x81, (byte)(pts >> 8), (byte)pts, es.Key[i] ? (byte)0x80 : (byte)0, .. payload])); + } + + var segment = Element(0x18538067, Element(0x1549A966, [.. info]), Element(0x1654AE6B, track), Element(0x1F43B675, [.. blocks])); + return [.. header, .. segment]; + } + + /// + /// An AVI file with one H.264 stream in Annex B form, an idx1 index (unless is false, as in a + /// recording cut short) and, when given, an IDIT date. The stream header says / + /// frames per second and frames (default: the stream's). + /// + public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true, uint scale = 1, uint rate = 30, uint? length = null) + { + var avih = new List(); + foreach (var v in new uint[] { 33333, 0, 0, 0x10, (uint)es.Count, 0, 1, 0, (uint)es.Width, (uint)es.Height, 0, 0, 0, 0 }) + { + avih.AddRange(Le32(v)); + } + + var strh = new List(); + strh.AddRange("vidsH264"u8.ToArray()); + foreach (var v in new uint[] { 0, 0, 0, scale, rate, 0, length ?? (uint)es.Count, 0, 0xFFFFFFFF, 0 }) + { + strh.AddRange(Le32(v)); + } + + strh.AddRange(new byte[8]); + var strf = new List(); + foreach (var v in new uint[] { 40, (uint)es.Width, (uint)es.Height }) + { + strf.AddRange(Le32(v)); + } + + strf.AddRange([1, 0, 24, 0]); + strf.AddRange("H264"u8.ToArray()); + strf.AddRange(new byte[20]); + var hdrl = new List { Chunk("avih", [.. avih]), List("strl", Chunk("strh", [.. strh]), Chunk("strf", [.. strf])) }; + if (idit is not null) + { + hdrl.Add(Chunk("IDIT", [.. Encoding.ASCII.GetBytes(idit), (byte)'\n', 0])); + } + + var chunks = new List(); + var idx = new List(); + var offset = 4u; // from the «movi» code + for (var i = 0; i < es.Count; i++) + { + var chunk = Chunk("00dc", es.WithStartCodes(i)); + chunks.Add(chunk); + idx.AddRange("00dc"u8.ToArray()); + idx.AddRange(Le32(es.Key[i] ? 0x10u : 0)); + idx.AddRange(Le32(offset)); + idx.AddRange(Le32((uint)es.WithStartCodes(i).Length)); + offset += (uint)chunk.Length; + } + + var body = new List { List("hdrl", [.. hdrl]), List("movi", [.. chunks]) }; + if (index) + { + body.Add(Chunk("idx1", [.. idx])); + } + + var content = body.SelectMany(b => b).ToArray(); + return [.. "RIFF"u8, .. Le32((uint)(content.Length + 4)), .. "AVI "u8, .. content]; + } + + public static string Write(TempFolder folder, string name, byte[] data) + { + var path = folder.Combine(name); + File.WriteAllBytes(path, data); + return path; + } + + private static byte[] Avc1(ElementaryStream es) => Box("avc1", + [.. new byte[6], 0, 1, .. new byte[16], .. U16((ushort)es.Width), .. U16((ushort)es.Height), .. U32(0x00480000), .. U32(0x00480000), + .. U32(0), 0, 1, .. new byte[32], 0, 0x18, 0xFF, 0xFF, .. Box("avcC", es.AvcC)]); + + private static byte[] Box(string type, params byte[][] children) + { + var body = children.SelectMany(c => c).ToArray(); + return [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body]; + } + + private static byte[] Box(string type, byte[] body) => [.. U32((uint)(body.Length + 8)), .. Encoding.ASCII.GetBytes(type), .. body]; + + private static byte[] FullBox(string type, uint flags, byte[] body) => Box(type, [.. U32(flags & 0xFFFFFF), .. body]); + + private static byte[] Element(uint id, params byte[][] children) => Element(id, children.SelectMany(c => c).ToArray()); + + private static byte[] Element(uint id, byte[] body) + { + var idBytes = id > 0xFFFFFF ? U32(id) : id > 0xFFFF ? U32(id)[1..] : id > 0xFF ? U16((ushort)id) : [(byte)id]; + return [.. idBytes, 0x01, .. BitConverter.GetBytes((ulong)body.Length).Reverse().Skip(1), .. body]; + } + + private static byte[] Chunk(string id, byte[] body) => + [.. Encoding.ASCII.GetBytes(id), .. Le32((uint)body.Length), .. body, .. (body.Length % 2 == 1 ? new byte[] { 0 } : [])]; + + private static byte[] List(string type, params byte[][] children) + { + var body = children.SelectMany(c => c).ToArray(); + return [.. "LIST"u8, .. Le32((uint)(body.Length + 4)), .. Encoding.ASCII.GetBytes(type), .. body]; + } + + private static byte[] U16(ushort v) => [(byte)(v >> 8), (byte)v]; + + private static byte[] U32(uint v) => [(byte)(v >> 24), (byte)(v >> 16), (byte)(v >> 8), (byte)v]; + + private static byte[] I64(long v) + { + var b = new byte[8]; + BinaryPrimitives.WriteInt64BigEndian(b, v); + return b; + } + + private static byte[] F64(double v) + { + var b = new byte[8]; + BinaryPrimitives.WriteDoubleBigEndian(b, v); + return b; + } + + private static byte[] Le32(uint v) + { + var b = new byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(b, v); + return b; + } +} diff --git a/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs new file mode 100644 index 0000000..fb3908e --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/VideoFrameDecoderTests.cs @@ -0,0 +1,262 @@ +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Codecs.Containers; + +/// The frame decoder that replaces ffmpeg for thumbnails, and the recognition of videos of a still picture. +[TestClass] +public sealed class VideoFrameDecoderTests +{ + [TestMethod] + [DataRow("mp4")] + [DataRow("mkv")] + [DataRow("avi")] + [DataRow("frammentato.mp4")] + [DataRow("senza-indice.avi")] + [DataRow("senza-indice-con-parametri.avi")] + [DataRow("flv")] + public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind) + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("fotogramma"); + + // Without idx1 (a recording cut short) every chunk counts as a key frame: decoding must still start from the + // IDR picture, also when every chunk carries its own parameter sets (then a decoder started at the P frame itself + // would give a corrupt picture rather than none). + var data = kind switch + { + "mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), + "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), + "flv" => LegacyTestVideos.Flv(es, audio: true), + _ => TestVideos.Mp4(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)), // a dated file, as from a phone + }; + var path = TestVideos.Write(temp, "video." + kind, data); + + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)); + Assert.IsNotNull(image); + + // The same frame straight from the decoder: the one shown at frame 30 (30 frames per second). AVI has no + // presentation times: there frames are shown in decoding order. + var position = Math.Min(30, es.Count - 1); + var expected = kind.EndsWith("avi", StringComparison.Ordinal) ? DecodedFrame(es, position) : ShownFrame(es, position); + var reference = VideoFrameDecoder.ToImage(expected, 0, 0); + Assert.AreEqual((reference.Width, reference.Height), (image.Width, image.Height)); + CollectionAssert.AreEqual(reference.Rgb, image.Rgb); + } + + [TestMethod] + public async Task ShortVideosGiveTheirFirstFrameAndTheBmpIsWellFormed() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var temp = new TempFolder("fotogramma-breve"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)); + var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path, TimeSpan.FromSeconds(3600), 0); + Assert.IsNotNull(bmp); + Assert.AreEqual((byte)'B', bmp[0]); + Assert.AreEqual((byte)'M', bmp[1]); + Assert.AreEqual(bmp.Length, BitConverter.ToInt32(bmp, 2)); + Assert.AreEqual(es.Width, BitConverter.ToInt32(bmp, 18)); + Assert.AreEqual(es.Height, BitConverter.ToInt32(bmp, 22)); + Assert.AreEqual(24, BitConverter.ToInt16(bmp, 28)); + + var first = VideoFrameDecoder.ToImage(ShownFrame(es, 0), 0, 0); + CollectionAssert.AreEqual(first.ToBmp(), bmp); + } + + [TestMethod] + public async Task RotationAndSizeLimitAreApplied() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var temp = new TempFolder("fotogramma-ruotato"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es, rotation: 90)); + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero); + Assert.AreEqual((es.Height, es.Width), (image!.Width, image.Height)); + + var upright = VideoFrameDecoder.ToImage(ShownFrame(es, 0), 0, 0); + // Rotated clockwise: the top-left pixel of the frame ends at the top-right corner. + CollectionAssert.AreEqual(upright.Rgb[..3], image.Rgb[((image.Width - 1) * 3)..(image.Width * 3)]); + + var small = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.Zero, maxLongSide: es.Width / 2); + Assert.AreEqual((es.Height / 2, es.Width / 2), (small!.Width, small.Height)); + } + + [TestMethod] + public void ColoursFollowTheMatrixAndTheRange() + { + static H264Frame Flat(byte y, byte cb, byte cr, int matrix, bool full) => + new(2, 2, [y, y, y, y], [cb], [cr], 0, 0, 0, matrix, full); + + CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(16, 128, 128, 1, false), 0, 0).Rgb[..3]); + CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(235, 128, 128, 1, false), 0, 0).Rgb[..3]); + CollectionAssert.AreEqual(new byte[] { 128, 128, 128 }, VideoFrameDecoder.ToImage(Flat(128, 128, 128, 6, true), 0, 0).Rgb[..3]); + + // Pure red of BT.601 (limited range): Y 81, Cb 90, Cr 240. + var red = VideoFrameDecoder.ToImage(Flat(81, 90, 240, 6, false), 0, 0).Rgb; + Assert.IsTrue(red[0] >= 250 && red[1] <= 3 && red[2] <= 3, $"{red[0]} {red[1]} {red[2]}"); + + // The same values read as BT.709 are no longer pure red. + var other = VideoFrameDecoder.ToImage(Flat(81, 90, 240, 1, false), 0, 0).Rgb; + Assert.IsTrue(other[1] > 20, $"{other[0]} {other[1]} {other[2]}"); + } + + [TestMethod] + public void TenBitSamplesKeepTheirRange() + { + // 10 bits, two bytes each, little-endian: limited range has black at 64, white at 940, neutral chroma at 512. + static byte[] Samples(int count, int value) => [.. Enumerable.Range(0, count).SelectMany(_ => new[] { (byte)value, (byte)(value >> 8) })]; + static H264Frame Flat(int y, int cb, int cr, bool full) => + new(2, 2, Samples(4, y), Samples(1, cb), Samples(1, cr), 0, 0, 0, 1, full, ChromaFormat: 1, BitDepthLuma: 10, BitDepthChroma: 10); + + CollectionAssert.AreEqual(new byte[] { 0, 0, 0 }, VideoFrameDecoder.ToImage(Flat(64, 512, 512, false), 0, 0).Rgb[..3]); + CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(940, 512, 512, false), 0, 0).Rgb[..3]); + CollectionAssert.AreEqual(new byte[] { 255, 255, 255 }, VideoFrameDecoder.ToImage(Flat(1023, 512, 512, true), 0, 0).Rgb[..3]); + + // Pure red of BT.709 at 8 bits (Y 63, Cb 102, Cr 240) is the same colour at 10 bits (× 4). + var eight = VideoFrameDecoder.ToImage(new H264Frame(2, 2, [63, 63, 63, 63], [102], [240], 0, 0, 0, 1, false), 0, 0).Rgb[..3]; + var ten = VideoFrameDecoder.ToImage(Flat(63 * 4, 102 * 4, 240 * 4, false), 0, 0).Rgb[..3]; + for (var i = 0; i < 3; i++) + { + Assert.IsLessThanOrEqualTo(1, Math.Abs(eight[i] - ten[i]), $"componente {i}: {eight[i]} e {ten[i]}"); + } + } + + [TestMethod] + [DataRow(2)] + [DataRow(3)] + public void EveryChromaSamplingReachesItsOwnPixels(int chromaFormat) + { + // A 2×2 frame of grey luma; in 4:2:2 each row has its own chroma sample, in 4:4:4 each pixel. The top row is + // blue (Cb high), the bottom one red (Cr high). + var cw = chromaFormat == 3 ? 2 : 1; + byte[] cb = [.. Enumerable.Repeat((byte)200, cw), .. Enumerable.Repeat((byte)128, cw)]; + byte[] cr = [.. Enumerable.Repeat((byte)128, cw), .. Enumerable.Repeat((byte)200, cw)]; + var frame = new H264Frame(2, 2, [128, 128, 128, 128], cb, cr, 0, 0, 0, 1, true, ChromaFormat: chromaFormat); + var rgb = VideoFrameDecoder.ToImage(frame, 0, 0).Rgb; + Assert.IsGreaterThan(rgb[0] + 50, (int)rgb[2], "in alto prevale il blu"); + Assert.IsGreaterThan(rgb[(2 * 3) + 2] + 50, (int)rgb[2 * 3], "in basso prevale il rosso"); + CollectionAssert.AreEqual(rgb[..3], rgb[3..6], "la riga in alto è uniforme"); + } + + [TestMethod] + public async Task AVideoOfAStillPictureIsRecognised() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var temp = new TempFolder("fermo"); + 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.IsTrue(result.SampledFrames >= 2); + Assert.AreEqual(0, result.Difference); + } + + [TestMethod] + [DataRow("CABA3_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + public async Task AVideoThatMovesIsNotStill(string name) + { + var es = ElementaryStream.Load(name); + using var temp = new TempFolder("movimento"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)); + var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path); + Assert.IsNotNull(result); + Assert.IsFalse(result.IsStill, $"differenza {result.Difference}"); + } + + [TestMethod] + public async Task AFrameFarFromWhereDecodingCanStartGivesWayToTheFrameThere() + { + // At most five samples from the random access point: the frame at one second (sample 30, one IDR at sample 0) + // is too far, the IDR picture stands for it instead of decoding the whole run (a damaged time table can put the + // frame asked for two million samples after the only key frame). + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("fotogramma-lontano"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)); + var decoder = new VideoFrameDecoder(VideoFrameDecoder.DefaultBudget, maxRun: 5); + var image = await decoder.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)); + CollectionAssert.AreEqual(VideoFrameDecoder.ToImage(DecodedFrame(es, 0), 0, 0).Rgb, image!.Rgb); + Assert.IsNotNull(await decoder.AnalyseStillnessAsync(path), "anche l'analisi resta limitata e risponde"); + } + + [TestMethod] + public async Task PastItsBudgetTheDecoderGivesNothingButTheCallerCanStillCancel() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var temp = new TempFolder("fotogramma-tempo"); + var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es)); + var late = new VideoFrameDecoder(TimeSpan.Zero, maxRun: 300); + Assert.IsNull(await late.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)), "oltre il tempo concesso: nessun fotogramma"); + Assert.IsNull(await late.AnalyseStillnessAsync(path)); + + // A cancellation asked by the caller is not a missing frame: it stays a cancellation. + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + await Assert.ThrowsAsync(() => VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1), 0, cancelled.Token)); + } + + [TestMethod] + [DataRow("filmato-muto.mp4", false)] + [DataRow("filmato-con-audio.mp4", true)] + public async Task TheVideosOfARealEncoderAreReadAndDecoded(string name, bool audio) + { + // The two small MP4s of the test site come from a real muxer and encoder (libavformat, x264 High profile: the + // shape of the videos Instagram serves); no official MD5 exists for them, so the frame is checked coarsely. + var path = Repository.PathOf("tools", "Febe.SitoDiProva", "Risorse", name); + var now = new DateTimeOffset(2026, 11, 18, 12, 0, 0, TimeSpan.Zero); + var metadata = ContainerVideoMetadataProbe.Probe(path, now); + Assert.IsNotNull(metadata); + Assert.IsTrue(metadata.Width > 0 && metadata.Height > 0, $"{metadata.Width}×{metadata.Height}"); + Assert.IsTrue(metadata.Duration > TimeSpan.Zero && metadata.Duration < TimeSpan.FromMinutes(1), $"{metadata.Duration}"); + + var container = ContainerReader.ReadFile(path, now); + Assert.AreEqual(VideoCodec.H264, container!.Video!.Codec); + Assert.AreEqual(audio, container.Audio is not null); + + var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)); + Assert.IsNotNull(image, "nessun fotogramma da un video di un codificatore vero"); + Assert.AreEqual((metadata.Width, metadata.Height), (image.Width, image.Height)); + + // A real picture: not a flat field of one value, not out of range. + var luma = new double[image.Width * image.Height]; + for (var i = 0; i < luma.Length; i++) + { + luma[i] = (0.299 * image.Rgb[i * 3]) + (0.587 * image.Rgb[(i * 3) + 1]) + (0.114 * image.Rgb[(i * 3) + 2]); + } + + var mean = luma.Average(); + Assert.IsTrue(mean is > 2 and < 253, $"luminanza media {mean:F1}"); + var bmp = await VideoFrameDecoder.Instance.ExtractImageAsync(path); + Assert.IsNotNull(bmp); + } + + [TestMethod] + public async Task UnreadableFilesGiveNothing() + { + using var temp = new TempFolder("illeggibile"); + var junk = TestVideos.Write(temp, "rotto.mp4", [0, 0, 0, 16, .. "ftypisom"u8, 0, 0, 0, 0, 0, 0, 0, 9, .. "mdat"u8, 1]); + Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(junk)); + Assert.IsNull(await VideoFrameDecoder.Instance.AnalyseStillnessAsync(junk)); + Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mkv"))); + } + + /// The frame decoded at position , straight from the stream. + private static H264Frame DecodedFrame(ElementaryStream es, int index) => ShownFrame(es, es.Rank[index]); + + /// The frame shown at position , decoded straight from the stream. + private static H264Frame ShownFrame(ElementaryStream es, int rank) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name)); + var index = Array.IndexOf(es.Rank, rank); + return frames.Single(f => f.DecodeIndex == index); + } +} diff --git a/tests/Febe.Tests/Media/H264/BitWriter.cs b/tests/Febe.Tests/Media/H264/BitWriter.cs new file mode 100644 index 0000000..a3044e4 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/BitWriter.cs @@ -0,0 +1,92 @@ +namespace Febe.Tests.Codecs.H264; + +/// The bits of an RBSP written one by one (§7.2): fixed-length fields, Exp-Golomb codes, bits copied from another RBSP. +internal sealed class BitWriter +{ + private readonly List bits = []; + + /// Bits written so far. + public int Count => bits.Count; + + public void Bits(uint value, int count) + { + for (var i = count - 1; i >= 0; i--) + { + bits.Add(((value >> i) & 1) != 0); + } + } + + public void Ue(uint value) + { + var code = value + 1; + var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code); + Bits(0, length - 1); + Bits(code, length); + } + + public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1)); + + /// Zero bits up to the next byte. + public void Align() + { + while (bits.Count % 8 != 0) + { + bits.Add(false); + } + } + + /// One bits up to the next byte (cabac_alignment_one_bit). + public void AlignWithOnes() + { + while (bits.Count % 8 != 0) + { + bits.Add(true); + } + } + + /// Bits (included) to (excluded) of , most significant first. + public void Copy(byte[] data, int from, int to) + { + for (var i = from; i < to; i++) + { + bits.Add(((data[i >> 3] >> (7 - (i & 7))) & 1) != 0); + } + } + + /// rbsp_trailing_bits(): the stop bit and zeros up to the byte. + public void Trailing() + { + bits.Add(true); + Align(); + } + + /// The bytes, padded with zeros to the byte, with emulation prevention (§7.4.1). + public byte[] ToArray() + { + var bytes = new byte[(bits.Count + 7) / 8]; + for (var i = 0; i < bits.Count; i++) + { + if (bits[i]) + { + bytes[i / 8] |= (byte)(0x80 >> (i % 8)); + } + } + + // Emulation prevention (§7.4.1): never two zero bytes followed by a byte up to 3. + var output = new List(bytes.Length + 16); + var zeros = 0; + foreach (var b in bytes) + { + if (zeros >= 2 && b <= 3) + { + output.Add(3); + zeros = 0; + } + + output.Add(b); + zeros = b == 0 ? zeros + 1 : 0; + } + + return [.. output]; + } +} diff --git a/tests/Febe.Tests/Media/H264/Conformita/BA1_Sony_D/BA1_Sony_D.jsv b/tests/Febe.Tests/Media/H264/Conformita/BA1_Sony_D/BA1_Sony_D.jsv new file mode 100644 index 0000000..612f763 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/BA1_Sony_D/BA1_Sony_D.jsv differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/BA1_Sony_D/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/BA1_Sony_D/riferimento.md5 new file mode 100644 index 0000000..015b6ae --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/BA1_Sony_D/riferimento.md5 @@ -0,0 +1,19 @@ +# BA1_Sony_D.yuv 176x144 4:2:0 8 bit, 17 fotogrammi, 646272 byte +tutto 114d1cf94a2fcaffda0cf1b49964bf3d +0 b46500b37abd2767385fbf80d1222fa3 +1 f6a17dfe91a93ca0b02794a8083a1b8c +2 3f325cd918838dff3ffd356561484e8b +3 731340720bcd24433f3bbe632ef539b9 +4 b9b6f585fdbb83882083af6584c3a772 +5 529e0a65608f5102a8ef0f97f80a7e8b +6 ca57f9cd3ce03adc49c938447a2006b1 +7 75d0d4421bba346692f678a9816f1cf3 +8 5b2251fb59a829ccadd4cbb08f52e174 +9 002ff953316237c7896e1c2812e297cd +10 eb7612198135bc2d221e6ca09edd0920 +11 c0a8afa3299e88aa49885a9776a321d2 +12 40875bb4d742e8664f3efe54fda5514f +13 23a46caa9f25e2cc32e82e3ac3378230 +14 8df70189924b2226bac692e40f01352d +15 835574cfdb658f1075e14f77a80b10fe +16 2abc7e3b21692cc985f61c062d8ae4e2 diff --git a/tests/Febe.Tests/Media/H264/Conformita/BA3_SVA_C/BA3_SVA_C.264 b/tests/Febe.Tests/Media/H264/Conformita/BA3_SVA_C/BA3_SVA_C.264 new file mode 100644 index 0000000..1129eb0 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/BA3_SVA_C/BA3_SVA_C.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/BA3_SVA_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/BA3_SVA_C/riferimento.md5 new file mode 100644 index 0000000..307e21b --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/BA3_SVA_C/riferimento.md5 @@ -0,0 +1,35 @@ +# BA3_SVA_C_rec.yuv 176x144 4:2:0 8 bit, 33 fotogrammi, 1254528 byte +tutto 7518b0f80c079db0a51aa4e0c84aea95 +0 74d707f4b157aec662612a0fb3cd3f72 +1 182156239309685ef343b1d4a1e596d5 +2 0092005a7dfbfb5ede635000fe537c63 +3 0d84d3af2a1c68fde7a1019595546dfa +4 313c6342b4b1ad31a1e1caa151e6009c +5 f15e5b68856ca888292ef5ed4803e181 +6 04c8e2dfcc3a542ad92850916e6bff6f +7 e603f5f1beac89dd373d384b2aa74ca6 +8 7b89ed14aa88cb155f1c1dd5a3baa292 +9 51a0d28b470e61e1214146ffe5ed8a55 +10 d916aa42380d08c82dc0f72fedd76d15 +11 6d074605e141fdbe594b7cbc83a1f123 +12 cff18c7f73d714bc6c02d7abdb49b4e2 +13 e42e25ee0bbdc87b4967f1681e2a0bb6 +14 267c0b7cf86db16c794aadc3fa646f90 +15 fc526fc345a5bbea7011b0e30395d7e8 +16 b17da0e1a21d0fb7f0b9464bc23ecd1a +17 8f20fdc94e60c63f07a644771c509d85 +18 ab759262d5cad77d1863a57f99a3b5b5 +19 f9657d572144a9bdb4b04702298144d2 +20 ef2fdd54781d3e5bc64178158e55c3c7 +21 84589045637466c35754ce4dcd47d445 +22 c5d3cb85662770a50c0dd096d1eaa21d +23 cab165068843b76f9f528fedcebddfb7 +24 43c802d985b9e44e84de66a598d0624a +25 0795c028323e25c143346c0e315521a2 +26 e1b69ad3ca6e4a98b41098d909c4c6b8 +27 6a3deabe73b6a41ab144ef682c704e6a +28 3504b5582d9db20a8b59cc51f3faefa8 +29 1b67f58eb19d38dd521992c8c7abe154 +30 ac2aa0a6c7fda396efbab9a28b9a2667 +31 40253092734cb26703f10dfc9fee485f +32 06277112d9dd7812373b8581001768c4 diff --git a/tests/Febe.Tests/Media/H264/Conformita/BASQP1_Sony_C/BASQP1_Sony_C.jsv b/tests/Febe.Tests/Media/H264/Conformita/BASQP1_Sony_C/BASQP1_Sony_C.jsv new file mode 100644 index 0000000..872323d Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/BASQP1_Sony_C/BASQP1_Sony_C.jsv differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/BASQP1_Sony_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/BASQP1_Sony_C/riferimento.md5 new file mode 100644 index 0000000..cb88339 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/BASQP1_Sony_C/riferimento.md5 @@ -0,0 +1,6 @@ +# BASQP1_Sony_C.yuv 176x144 4:2:0 8 bit, 4 fotogrammi, 152064 byte +tutto 9e9c06cfc882a3f618b6ad40811c1331 +0 a9a89cef8c1107c754a5e02a5789d44e +1 14f3b4e9e30e054a5c47df74bfd02f2e +2 710bc67c45c9e60ba844e0fc99c143fc +3 d0170c3bffcbd36bcf4a999435523db7 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CABA1_SVA_B/CABA1_SVA_B.264 b/tests/Febe.Tests/Media/H264/Conformita/CABA1_SVA_B/CABA1_SVA_B.264 new file mode 100644 index 0000000..1926479 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CABA1_SVA_B/CABA1_SVA_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CABA1_SVA_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CABA1_SVA_B/riferimento.md5 new file mode 100644 index 0000000..34c8eba --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CABA1_SVA_B/riferimento.md5 @@ -0,0 +1,19 @@ +# CABA1_SVA_B_rec.yuv 176x144 4:2:0 8 bit, 17 fotogrammi, 646272 byte +tutto 2f5cabd5bb4954c0386cafd8a9aa782a +0 ad02f985ed0a451fe9a9e0a192f02e4f +1 680d5fb7eea63ba10424428260c87ced +2 b5e85433c841a4a28928092dee476935 +3 5575cd3fedec0007e69048de67c5a47e +4 bc294e03dd03b3de5c15c94f09d1187c +5 2e19d4135101901de445036faceae7c7 +6 42d5a7a3277529dd3fe5455694266fce +7 ce501ca34c4b254e271bf725c2c4d40a +8 cf25dbf2f3ffcf85a2242bb1b60a15c7 +9 8a411af635b4b7a8a59187fd76f709e3 +10 6671866c0f5c5d80bf8a1e89f5839f36 +11 82e946f3911309615c245c32aa92a84d +12 81614930d9b5882aa70fce31271a5b4e +13 75d1d4ac08264f9f8b3708daf256eb49 +14 4aa4764221a70ccbba8d60cf905ac1d6 +15 fd8d0348ac45a1b4ee23d97168233a81 +16 94d0da8b8a9037d0066e3f3571ba3c5d diff --git a/tests/Febe.Tests/Media/H264/Conformita/CABA2_SVA_B/CABA2_SVA_B.264 b/tests/Febe.Tests/Media/H264/Conformita/CABA2_SVA_B/CABA2_SVA_B.264 new file mode 100644 index 0000000..543955c Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CABA2_SVA_B/CABA2_SVA_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CABA2_SVA_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CABA2_SVA_B/riferimento.md5 new file mode 100644 index 0000000..bb4089a --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CABA2_SVA_B/riferimento.md5 @@ -0,0 +1,19 @@ +# CABA2_SVA_B_rec.yuv 176x144 4:2:0 8 bit, 17 fotogrammi, 646272 byte +tutto 6d4277a7fc70ed1fbe3c5f10b0a70671 +0 ad02f985ed0a451fe9a9e0a192f02e4f +1 b893f323b37f1b4f091e4515a7b2fad0 +2 d2bdf37045c03ca09c184d8960e4c970 +3 8d032e049e27e362887ea5e47e126d40 +4 12cae55e2d2c57d2fe5b03d9ed2dda8f +5 b1714bb9956b9a7bbdd5a786d207743e +6 c97c923b69bc48fdc55cf880ebbd6cec +7 4cd4e256d322af40539d4c8e57e6326c +8 6ad9400217e520bd00fb4f19ced62f08 +9 cf966edf67df42ac4e6a72641b98eda1 +10 6671866c0f5c5d80bf8a1e89f5839f36 +11 d4593f69918095750b9b1ca471ff8319 +12 4a8dbac5e19400e9da61903ef25ae8eb +13 0af406d38a49fcf16a6e99cb82439c38 +14 0db23e3dde2e200761c210d5e1489d02 +15 350c2037a9f7a81bd2d43993fc6aafe8 +16 122a55e62d054783ab07bf19624f242d diff --git a/tests/Febe.Tests/Media/H264/Conformita/CABA3_SVA_B/CABA3_SVA_B.264 b/tests/Febe.Tests/Media/H264/Conformita/CABA3_SVA_B/CABA3_SVA_B.264 new file mode 100644 index 0000000..81d710f Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CABA3_SVA_B/CABA3_SVA_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CABA3_SVA_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CABA3_SVA_B/riferimento.md5 new file mode 100644 index 0000000..97e24f1 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CABA3_SVA_B/riferimento.md5 @@ -0,0 +1,35 @@ +# CABA3_SVA_B_rec.yuv 176x144 4:2:0 8 bit, 33 fotogrammi, 1254528 byte +tutto 63a0f8fdcbb87b0dff330acdd10905c0 +0 c5c5fcdd8bc70c4ae0935ca68662359a +1 0198c7176fce9d5c845fbe83c7ab00d1 +2 3d45daf1f14dc1eb5dfac793a4baeb84 +3 36388edd37af5ca842dcfa7dcffca4d8 +4 03600b18a8f29176c695c5cfcf514bc5 +5 0452e0d6240a121435095ccf71c53520 +6 11fe16d222d8f090dfe5172108881d5a +7 233c6f8835d379d5343e772cbcf7f624 +8 d6e526e9c980866faf1ebe6e762b4365 +9 3e959e7d8dacd95827c2b7718f19881a +10 1c231d7a573546c79d9dce68897ccfa8 +11 d63bbea20c2e0afa3a7701f88116761a +12 5db5c5328f7b1b498068f02a316537a9 +13 6671e191380026a94e89a989e416f7e1 +14 28d0e14110913d9a8edd3c02bc0f2a97 +15 0275a52804e89f72162f99fae34cb7d1 +16 34873676824556e3b365bf3b270abc0f +17 79bd801226aa600f2470c2e7abf8fe47 +18 9f107047241f1527bf2478e1dc6e3dc0 +19 c0fc5dbf9b071fd0aafa3a0565020398 +20 db5c432aa7e7650eccc32872dae94ecf +21 bfa217b37f9545f4ede37d2c30a90fc9 +22 24a2e3e9ffc8c08020e34e0e94431c7a +23 f6355041a1fa73dfaf05505e1757188e +24 61f7c0ebd6c0c7374c47378062b17b72 +25 03b1a09f41118bcc0c487e9a80150b5a +26 cb5eca6c1b94a76a4e356cf23cacdeb4 +27 509d0862e86af8d7c9d62db9c66fdf7f +28 45b86e780d1f04fd9c38007a2ceb022b +29 19d8fafd5452028f872a3533df14065c +30 cb164221dbb784d4462ec28789d1c95a +31 3e76df8860d0f54e54074c2551bb950f +32 0ae2ef31760da963afa74608c76245cb diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAFI1_SVA_C/CAFI1_SVA_C.264 b/tests/Febe.Tests/Media/H264/Conformita/CAFI1_SVA_C/CAFI1_SVA_C.264 new file mode 100644 index 0000000..f21f51c Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CAFI1_SVA_C/CAFI1_SVA_C.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAFI1_SVA_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CAFI1_SVA_C/riferimento.md5 new file mode 100644 index 0000000..95324c6 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CAFI1_SVA_C/riferimento.md5 @@ -0,0 +1,35 @@ +# CAFI1_SVA_C_rec.yuv 720x480 4:2:0 8 bit, 33 fotogrammi, 17107200 byte +tutto 8f249706ddaeda94c4899c1f3954476e +0 e08d5bcde99cabb731a47e689bb58ad6 +1 93adef8443eb0d60796f34781277bcac +2 a5505502c028801e6ba0a0887d43a41f +3 34f773fe4a66ed10a5094c6b880fde36 +4 ba2357aefd5ffb60add25b57feeb3604 +5 4a520113d72c268611410a1ef5866f72 +6 2d853b6309067c23edd3a936464db462 +7 8722127ec2e511e42ac91a6314b80116 +8 f2eb5f4ad05ae48f528416d12e1890a1 +9 da6b5adbc96ad926f59cae9928805b15 +10 a9d2c8dc2aadd569e4c777a06883f69b +11 c68e254abb00d8b2c15095aab850f82b +12 b56c704f48470c0f3e82db573eecca5b +13 3ed9f2b2e009fb9fe19b9722e0722681 +14 95621c718fb613479ae71e08aa0b2f34 +15 4c40495d3f345c099cc8f49cb1e359b6 +16 e1511fca61da5ea029d6f02568c8cd34 +17 b1f956c25b88b7cc5c699f4944a9e295 +18 96e0ad2712affdc99bfe9a185253b869 +19 9ae5d5042081ea26ea3bf0cdc6c57958 +20 8912c79fca79921c8745b7c8d684979b +21 83d1060170735cfec5006f107520aeb8 +22 8be9fa53fb2eec2692ab3ed1d84e6ded +23 a6c02ccb3c2ed8018cbfe6058156a833 +24 7d240c7f48e837c9a7cb7c0a0038e9d6 +25 05a26a0e7fa0631efb6481b4219da866 +26 df91f6d274ccae22859e6a620fa51f48 +27 f6ee76f33ebea9791fded8e08e89a9e1 +28 b7aaa5d75b57ecad210e6ae38ea0c9e5 +29 5f1e7f923122bbb872ab57295772a584 +30 91cc263ca561ff3bc6c367bd4e116517 +31 2f1dd18e37ec082800060332c5f774dd +32 5e1e4c1baa8b71a059705316d85759e6 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAMACI3_Sony_C/CAMACI3_Sony_C.jsv b/tests/Febe.Tests/Media/H264/Conformita/CAMACI3_Sony_C/CAMACI3_Sony_C.jsv new file mode 100644 index 0000000..d519f8c Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CAMACI3_Sony_C/CAMACI3_Sony_C.jsv differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAMACI3_Sony_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CAMACI3_Sony_C/riferimento.md5 new file mode 100644 index 0000000..f5429b6 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CAMACI3_Sony_C/riferimento.md5 @@ -0,0 +1,19 @@ +# CAMACI3_Sony_C.yuv 192x128 4:2:0 8 bit, 17 fotogrammi, 626688 byte +tutto 0f3edb4f003b8fb4838f6a35c572fe70 +0 cc4f5f72e34ae3bb8f3b33e332d676d9 +1 f2a0db5d3e5f6893885e7b95bb5226bd +2 c8e5aca8cf4170445eda1db98539aabf +3 285dca292c27b1cf03a0fbb581d4469e +4 16da33f8efafe3da01fb29a2be273925 +5 4a6db8b9888b8a7306ad2ce067485f8d +6 ecb7f1d010296193795f36fd7dc8b635 +7 91e64a3e9eb3fee9401f84e43904abae +8 5fd46d3153c8d39547b0edda78a4beaa +9 fd031c97b6a51f201334298c9ae4eba9 +10 a783f654f4c338e402bc0e81c214a4fc +11 b17a23cf031e9f8592a74523e82cb473 +12 37363e27d6769f5ae05fdf1962fd94e1 +13 9be4828cef7f67a94efc25523a6da301 +14 eafd08304f575afea6480cf69d1fffd7 +15 8a8552637ab14b98aaa8cb122f8555eb +16 2235195dd0a7cb6aa4df6c1ae9908316 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAMASL3_Sony_B/CAMASL3_Sony_B.jsv b/tests/Febe.Tests/Media/H264/Conformita/CAMASL3_Sony_B/CAMASL3_Sony_B.jsv new file mode 100644 index 0000000..a0bf049 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CAMASL3_Sony_B/CAMASL3_Sony_B.jsv differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAMASL3_Sony_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CAMASL3_Sony_B/riferimento.md5 new file mode 100644 index 0000000..832bfef --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CAMASL3_Sony_B/riferimento.md5 @@ -0,0 +1,19 @@ +# CAMASL3_Sony_B.yuv 192x128 4:2:0 8 bit, 17 fotogrammi, 626688 byte +tutto d95dc479f23791df4f166145e5c011a4 +0 61af8e5e54c21077422853dc878bf2b2 +1 15d7ef86b6005c62b2acbfeda839a8cb +2 2ca0b217cf1ee4e998ec890fb9935796 +3 7adfdfea5641ac9f58884284d762e310 +4 55b94657d5696e64031e6c2e5a59cf8c +5 a221541845db1a51cca7e7f8e82936b7 +6 9be116096d4df5afc71434f4f1e2fee1 +7 76b646e056afd3253a9c4934b6e3e674 +8 f606326c33ee78d069a3383ab28a0540 +9 b6584e7a23904904aaaaa2530aa6b42d +10 c9ac3d9e35c5bbd005392a5f6038d4aa +11 b3e1d88ac4aee9dab38fe6e75daf68a7 +12 55b9789470dba2984ed7f23e6a51ee46 +13 943a2df481e15f541ce2ec56a810f997 +14 dbde1d35469282489a0049001abfb1d8 +15 13e9ad84dca3d59640207dafb4555439 +16 468108eb53b485e218d48fc62aa16963 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CANL1_SVA_B/CANL1_SVA_B.264 b/tests/Febe.Tests/Media/H264/Conformita/CANL1_SVA_B/CANL1_SVA_B.264 new file mode 100644 index 0000000..8fc73d8 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CANL1_SVA_B/CANL1_SVA_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CANL1_SVA_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CANL1_SVA_B/riferimento.md5 new file mode 100644 index 0000000..e5f8c7c --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CANL1_SVA_B/riferimento.md5 @@ -0,0 +1,19 @@ +# CANL1_SVA_B_rec.yuv 176x144 4:2:0 8 bit, 17 fotogrammi, 646272 byte +tutto b02defcb741c0e982313c5749f2008ed +0 3b05437e27cea07099478058c32e524a +1 9088117bbde8bdc46df419d88a763556 +2 da0fcf66d49fce3b02ccae9821a94b86 +3 14c8841fd02b89411fe29e91fe5aaba1 +4 6069d8a4067e91d55eeb50fe50a3256a +5 c4d8e3da13d242e651ed7a597159def8 +6 00c66b1c3a19c0deeaa358fe62250010 +7 ae98700d5d445b8f3bd7398628228588 +8 c88c92360acc6177bcc125638965a7cc +9 961377e7cbe70f31b65fcd6f0ddc99f8 +10 14e518bda52726122483fef9fe633725 +11 a66aec069eb298d21764b90bf7d4c93b +12 3c6ed1f698338877022aee6a5ab914d9 +13 0012f25e91655c40edfa5752012c0284 +14 ed97eccd456c219e1e80a90162e62a38 +15 4f8b663002b94ff3e6222c82130fb793 +16 c8d777b6cd86124bd01642aeeeb58aa2 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAPAMA3_Sand_F/CAPAMA3_Sand_F.264 b/tests/Febe.Tests/Media/H264/Conformita/CAPAMA3_Sand_F/CAPAMA3_Sand_F.264 new file mode 100644 index 0000000..36ed596 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CAPAMA3_Sand_F/CAPAMA3_Sand_F.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CAPAMA3_Sand_F/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CAPAMA3_Sand_F/riferimento.md5 new file mode 100644 index 0000000..86c9b13 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CAPAMA3_Sand_F/riferimento.md5 @@ -0,0 +1,52 @@ +# CAPAMA3_Sand_F.yuv 352x288 4:2:0 8 bit, 50 fotogrammi, 7603200 byte +tutto 44d78296fb12c2e523cf02886e3ee4ad +0 3234a21fae65cedbecb815348cfcd025 +1 32726bfa95b76622b9316a06d62ef04d +2 596c98dfaff72a38a0ea2bf346db131b +3 54ac922859f57559eb5c813b621fda0f +4 19c0806c2070678854fc147c67c773c3 +5 d4efbb7fa35fbc1322cb56ced0dadeae +6 c048a396f71583a4ea6c149170373911 +7 cb93e645f01eddfeb8347ec28329ad56 +8 f9044b5c482275437874d845a58c9f2d +9 a533beed5336fbb94c96c4c1bc973588 +10 e22eb06e7cf73f8f0536599c53a55b71 +11 cb25b9a1d6a60a6f7fdf3c5b4e42e5a4 +12 3052aaf7ddfa1f6fb460fed1da90da04 +13 0c32595dd75080b1d057525894bd7ff1 +14 9cedd4d8286a692108fa5af04fd9b9ef +15 54d8122d5848187d8759834e5801ed9f +16 cdf6aea31d7c7140014deb38e2aa74d5 +17 843999bc87563ceb15228c0b9e508577 +18 2b74640a619894e5ba47a3af66e62849 +19 b9a1da5793be06dc30533cdc085b2205 +20 8d8449c5496fb1bd266718fb4efb5631 +21 8f5d297f89ffcf5cad2509425b4be68b +22 642da5f5a6c44ea100b61f2c8adc300b +23 5e7c913cb269c28b1dedca5833b6a81b +24 9fe571b3e65f17bb02ce28a49ca9f6d6 +25 7fa282bf4294012736adef04ae573970 +26 6b6c51edf6d7fab586913b9f117de17b +27 380e2b587e045033ff4f02ae0b5e989f +28 3c38e7f4b75dd85778250b50fbc664df +29 7c908ce32f078f533379b4346ae7310d +30 4b322dda6b94336ea0fc689b8ea08a34 +31 4f533c4f9cff2adc60e52f3353c3ee68 +32 f913769b5b0280c619a2caf7569b5ad2 +33 f0c0dd01b1c9dc4c6ef0e18acd0321f9 +34 db36b451e8b069caa5c479054a54b76f +35 ad8a7ea9090dcb5ff913c9ae38acefa5 +36 d66546fa56c8cb8f282170c6e3f74881 +37 0e366555a9cbbd6b5e2e79911ca331b4 +38 cad884253942469ec8f5409ff336ae6a +39 8fe2651de7b2f404e409d302bdcdf6a5 +40 8f1810c08b8c67c60cb7fcfe2aaf8e43 +41 6c1a851ad4b937500f4a1d0ba2523441 +42 0bb273f93c17d3ca695224639525ae42 +43 29e1d63a4ee4cb9de91cd39d9b63ec19 +44 47361da8407b7f461003da8969dd2d0f +45 334183f1393f500f7a4a8f0c8c736108 +46 1c2b333f24c8a8f5056471c6aa6d1d1d +47 26dc5b2c2966ed3585955e0e88a75a0a +48 1a9ec0010cb1b2350e57403a3d73d147 +49 53a6bf321d241520b2da772b5a81f757 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CI_MW_D/CI_MW_D.264 b/tests/Febe.Tests/Media/H264/Conformita/CI_MW_D/CI_MW_D.264 new file mode 100644 index 0000000..75ab668 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CI_MW_D/CI_MW_D.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CI_MW_D/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CI_MW_D/riferimento.md5 new file mode 100644 index 0000000..3c87140 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CI_MW_D/riferimento.md5 @@ -0,0 +1,102 @@ +# CI_MW_D_rec.qcif 176x144 4:2:0 8 bit, 100 fotogrammi, 3801600 byte +tutto 037becca5bc836b869aba825293d39a3 +0 b2ea86aa3bdc9d18515fa129d29b043f +1 4ad866300eadf1f20b7a892310cfae8a +2 bc4e45faf42f3bb98ea9335eed6dcb3b +3 1ffe43c1b2790ca4bb0478a1cb572f72 +4 5db1858014907dc8913e3bd36ea182a7 +5 182868aafd3317ca4972743b1046c159 +6 a16de3deb8a481e7a4c11e1d99b25355 +7 60f65b17a1ff177e806ef584b7677e26 +8 be5ee7628f24ae35984990aae06dd82e +9 fb9501d77b54f52232dbd4a40508ba21 +10 bc8e4108c9b255339b4f220209ba03a1 +11 709c736bfa12030bb1500f5cc8299166 +12 e94f4588159c54af7838ff2a1f3c29fc +13 b9d7c04d29b7e807b76eab1f13ece044 +14 98ee00489d089419bcfabf454712579d +15 c0f2959f126bddc4ee8059b0934c8cfa +16 1f0c7b169a9a0f782efbf3e4d5f92957 +17 f99052d837977f26ff4802f2601bed67 +18 29220c4ba68c4ab121892b78c1a7f263 +19 81b955fde1bb885b2ef3c169c2bff52f +20 a254f4f4dad316c209819c714b987b7b +21 9a1fbba36129ca4a8180df312cb527d7 +22 31d8418458011c01d0460b0fa4a0d8e3 +23 d631018a1e8c6b12eedf9da4f9b916e7 +24 c3b0890cf67779bee17c6fde851a3c9e +25 d023bddefc36182caaf7d5ef7f6d63d9 +26 6d33cf8ffb5f5e4a6c37bbbe410c3091 +27 434601b81a66eacf2123a4b22ef5ef94 +28 7f3ae44db78fe0640f9014362b556692 +29 aea04c84fe1f9adaf72ab00d3f278d0a +30 da08e6eee4112876b6e989e9efaed0b3 +31 81dcc20288cc1279b82de743e4bb36e7 +32 407cffe9a019977fb5c1e4dbe042df4c +33 856e69fbfdf4f49627a00c84f5edf5e1 +34 20dd0b1d1f5fb11b65290f5b05d085ab +35 406ffc086960bfd35047f4f562777540 +36 f0b2e573152f36e9e76fa4fe5dc8e315 +37 73f81f9b37c22594721cf372abbff4fa +38 f2abd39dc5ed62b3dbd23dd262b47d0d +39 27542f7596ecc8c213130da8c910245e +40 d2ecfc614a9c2b94cfb3a5f2ecaed3cf +41 cab97673c335dc697a10fdc8ae8e1979 +42 ce669c22cbc18df96e30eeb4554e9dcb +43 f9a910164be3d4571ff9032c9dd6d2cc +44 33ef15ee3f8a1b73caea2587d3a04dc1 +45 278a979e0d7aadf9c58701dd26e7be36 +46 7bdfaa80c460919533c64d265157c516 +47 d6e2b1397e78c78bb796ae22a2a3e9a7 +48 37655872ff3b5185e183abd91d9c7856 +49 4a872f6cec350b95a2c54f3c8bb8ee40 +50 23d092e049734c5636edcfca169fd345 +51 9465c158f4d09891019adcbd7f7a6343 +52 d66279fa885f6a31bcfabe8b2ee018ea +53 b3aa99e4c2cb71dbec5e884e6aaca5c3 +54 a9f19dc27ff6476714115ede96cd9db1 +55 48d39fb4999c3188af96bd5328a481f5 +56 453ad225c9659ffc8fad916083b27689 +57 dca366cb02123b2b4eecbeb9291ee46a +58 058a29fb9885934ddd57e2d14861f0e5 +59 f126b4b74b52dc4c08d52683e75891d3 +60 172c6122ea174240160394745667a101 +61 0aa03016fcf4132c4d62efea8ce8ce5d +62 214545816f4cc25a3b944c86821e8b8e +63 23ccf153fef1a70149226363728cd04f +64 ab16e5782a5278b8ab1556f3b1126ed4 +65 d03842abfefa49653f7f70a3ffd0f86a +66 45d218429281c0f22f38bc18ca50e7a8 +67 2c32f3f35a7946f0b876ba33941cbde4 +68 f7c3911b31f0115b2bd9432c7e4bc4ad +69 730d0f72840d07e6a3dfa83301fc5195 +70 c3ff305f4e00959e1985c03945b400d3 +71 373dfd1b6a5b1c20cacab43718c3c5d3 +72 97cbc737314386f6a2d628d0075a88a3 +73 7dfbe2bf1c4898aee98ff5fb658a87d5 +74 a2323ca3480eb92858dcf7ff48e77585 +75 8fe4656e98dcd3f705b6be583a800078 +76 e79d93f450d65852ea26e22c6774e231 +77 7faf004281838bde2eeed1d5a82d04ff +78 5a57697148bc4ad0e940421727010f90 +79 7074b6e4ede6523bd5472e11f2f20eea +80 d63b962e50266768b7ebd4423fabbf57 +81 7062b271e88e2a3826a32d130203285c +82 3e1021da9fde73899d5ae7f03b4cbee3 +83 37cdbca39a16072f6c7fb55cdb84cefa +84 cb4ff7d17a23405e63465315f6949f67 +85 f836059e0b1a524d77b56482e250c0e9 +86 acfdca1d7f38304f72c3fdf7a3023c78 +87 6fa534d03efcd9e82ad4e6515cfbe6be +88 e60aed27de11a47c753c5eb16559b7c9 +89 1dbbdf914cf2aa6b566cc60dd69e5787 +90 6d39622a6afc81575b08af39f2e2c5e3 +91 7202033c3e638858a12238ca8f377204 +92 6d971086221252d813f099917cac3a2c +93 a8dd021a45dcdda3dd00751d0e556725 +94 5a96fab55ed543b43a753db5d4aeac6d +95 50109c8e94c26f40dce80f8599ea980a +96 45d7390b749fc8541b0a5ac244c12ef6 +97 efec4919dd2daa91fa122d633e3bcaa9 +98 d0190fd541e801de61f3cf80aafbd310 +99 d732e1169c8b2f983f30ee942c8f76d7 diff --git a/tests/Febe.Tests/Media/H264/Conformita/CVFI1_SVA_C/CVFI1_SVA_C.264 b/tests/Febe.Tests/Media/H264/Conformita/CVFI1_SVA_C/CVFI1_SVA_C.264 new file mode 100644 index 0000000..7b59fe9 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CVFI1_SVA_C/CVFI1_SVA_C.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CVFI1_SVA_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CVFI1_SVA_C/riferimento.md5 new file mode 100644 index 0000000..8954be8 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CVFI1_SVA_C/riferimento.md5 @@ -0,0 +1,9 @@ +# CVFI1_SVA_C_rec.yuv 720x480 4:2:0 8 bit, 7 fotogrammi, 3628800 byte +tutto af3086f97e7316670af7a4bdf3d53fea +0 eb56be79aca5582cd9579555be55bb6e +1 5c33e0bf5c5158cb4d51920976f8617f +2 62be84d5c69ee13f43a14b42b56eb6b9 +3 e4120e1dc2802be4974c3f112ed26027 +4 0e71b29c56798518235b2885c18dc5df +5 1bdd7d82b7cc77af26c48f557383a59e +6 ee95cdfc1fcef0185a16984b9a31301f diff --git a/tests/Febe.Tests/Media/H264/Conformita/CVMAQP3_Sony_D/CVMAQP3_Sony_D.jsv b/tests/Febe.Tests/Media/H264/Conformita/CVMAQP3_Sony_D/CVMAQP3_Sony_D.jsv new file mode 100644 index 0000000..3c8efcb Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/CVMAQP3_Sony_D/CVMAQP3_Sony_D.jsv differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/CVMAQP3_Sony_D/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/CVMAQP3_Sony_D/riferimento.md5 new file mode 100644 index 0000000..e17cb31 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/CVMAQP3_Sony_D/riferimento.md5 @@ -0,0 +1,19 @@ +# CVMAQP3_Sony_D.yuv 192x128 4:2:0 8 bit, 17 fotogrammi, 626688 byte +tutto fa8cf12561c04bbf68f93769ae2d1443 +0 ee3eb73ad8ff3be3f23d8df562c88e2e +1 cb7f4b0d41456a10a5e4d8e3c38d6254 +2 6458fe2a9582eceefaa0dc4caa84fcae +3 4ac1b3ae1a958eef71ea3adb6a415d3d +4 773c72fdad07342a43559786e68e43ce +5 9f91dc9d8abc23786abf9c3f38ab29b2 +6 5953c1d34befdecb10388217a129180e +7 62e50244ac757a7472c60a41613366ea +8 a3ace4d70a84302fe5232c2b73aedb61 +9 254863c8b449513539308cc727c3b21f +10 1ca092f6595405d7a4f3779e4400de9d +11 3358a1b18e603f092af684fb7f6d32ee +12 56e2ec5b9d168fad95aed9cf5ce5f6e3 +13 3068eebb45aa711d59a622c6731cccb3 +14 7fc207d5b28043704b72fc566be937cc +15 6b6166cce3960edd29a0336c053630d1 +16 82ef7817702733360742d80590b42a51 diff --git a/tests/Febe.Tests/Media/H264/Conformita/FI1_Sony_E/FI1_Sony_E.jsv b/tests/Febe.Tests/Media/H264/Conformita/FI1_Sony_E/FI1_Sony_E.jsv new file mode 100644 index 0000000..c2b2412 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FI1_Sony_E/FI1_Sony_E.jsv differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FI1_Sony_E/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FI1_Sony_E/riferimento.md5 new file mode 100644 index 0000000..c7c6d70 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FI1_Sony_E/riferimento.md5 @@ -0,0 +1,19 @@ +# FI1_Sony_E.yuv 192x128 4:2:0 8 bit, 17 fotogrammi, 626688 byte +tutto e56dee215cec5912300406975ffdc56c +0 a3f6def234d0c0c65bf4a6ee8e499790 +1 d2581abb4ae38fbef28a8ba8cbde01f8 +2 0f1ced733f4bc0a80ad9439123c68d4c +3 183c7420601607a245b2d4c9df29db97 +4 caa15f3b5a0cdccea75a6a35262b39c7 +5 bed91493e612bfffb91100e2fcf59eac +6 a05e7a82ac602eb3e92b5ca1d6670663 +7 c32997acdd9295c90080d2a6211c76e3 +8 02776ea4a1ebdaa6bfc31910634f0dc5 +9 6b5e16763ed0f3b2aa22b4a5a732d672 +10 b522772dc6dcf557a1a480cf0e4abfe4 +11 1e496c62aae7cb3ce8dd0413c7678084 +12 c30bf7c55db3f02c4c1ea250f8dec7f5 +13 21c7654feeda9ac5152924d4ea83eaaa +14 5c5ebfd907f5853c357dc509758f654f +15 41995ffb29bc943144488f7502277e6f +16 9313510b3ebfa99cae8197c79f113516 diff --git a/tests/Febe.Tests/Media/H264/Conformita/FM1_BT_B/FM1_BT_B.h264 b/tests/Febe.Tests/Media/H264/Conformita/FM1_BT_B/FM1_BT_B.h264 new file mode 100644 index 0000000..ee95442 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FM1_BT_B/FM1_BT_B.h264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FM1_BT_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FM1_BT_B/riferimento.md5 new file mode 100644 index 0000000..9d195bb --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FM1_BT_B/riferimento.md5 @@ -0,0 +1,402 @@ +# FM1_BT_B.yuv 176x144 4:2:0 8 bit, 400 fotogrammi, 15206400 byte +tutto f21ad956409cfa237099f7ac28390614 +0 0b68ef64cb981c6986caacdaf7f132c2 +1 0fefa9a35699ce1b7951290780f47692 +2 53472b30cedad75b4213f9f444ba5512 +3 322f432a465d41949a770b900da8eca3 +4 2063ed85780c4f744951891f50317f89 +5 962218dde757bd9291d4e1ff55ac9291 +6 416e20544df92cf6d76ca1a05bf69a27 +7 cb13a53d9a5feb29c8397fdc36ed0578 +8 8d09f7027d9d28a43fbc948fceaa5c04 +9 4a4b6d534ff3b613b23ce8ae0cf8e101 +10 23463d26902964e57a07739e9b20c767 +11 469913bde4173cf8201db915ea24e27d +12 e2c7004f9a882493b1cf7b3c58b61722 +13 5d1667eaace172f02409989c033e3da0 +14 eb875badffb87b2f03e270d23d42e304 +15 e06c208dacae1f8f62f3965fa19bb244 +16 14b04da2ca90c34762ef48a0b51fecdd +17 2cb2c2e6be25312aad855f364591e6e0 +18 37459f7513c9e1ff3e61065979a9c938 +19 29db057ced5d6155812c4b4c308a68b3 +20 0e12f9cd98892d69e74ab95624704115 +21 0653293ed02f1cb46b3a21b1e11b5661 +22 f7b31fe9e83cf586d9c058ffef3f824c +23 2748839a3cd36cb34fe2a736cd5e002b +24 1ab6bffdebb7ee6237eeacf2deb7cce2 +25 ddb3263805f4ab68c9f5ebff2c47e4e2 +26 ea5ec00e286ee70d469404dc83213000 +27 3c6fe975c887b442f7f20315824e3d24 +28 aaaf9eaadacb4628c5dadfc8f35158e1 +29 664c4635b8726b8d859f338d75358247 +30 3672023eb64c5161423384ca911dd22b +31 2ef76accd4f1196630b56244a6874ff7 +32 a79633ee0ac6cd9b1a3777b9f94b60f9 +33 cd84d8252c0c58a74fc6ca859a7026e2 +34 48a01aa00c9151269a0dce5442e61a84 +35 c3e3f8d7f910365afc6ef80b4880c518 +36 cdff513ded6170d7b24155854cbf8531 +37 e8745f7f4ebd474e2b8dc8f394fb04ca +38 5048b4f175b8bbb5bc50d271e2431644 +39 5bf45096d36a4bd93e9a87ed07ee51d4 +40 f6cd5d5db97b85ddb6b6aab1983a5b1c +41 595ee3e40e29b4a34342d48a8f628b5a +42 217d66a17a2db4cea219619530177761 +43 dbe3867a3430d727bbd86eeaa6918152 +44 b8c1b5117e255b97a5a3639afea86aeb +45 2c967d8a3e5e2b950bdfd99c5f461ba5 +46 036e7766488093491db1f6daa1571bae +47 0acd197352f1a22dee2202d312d93cf1 +48 ab52dac4147e8338b13766124161ae88 +49 af6445e8cfdab99281ad88dbcbfbc551 +50 35730929fdecd9daf5a3cb35d180d6d3 +51 ad5f854d889f18ced5daaf4ad645ede2 +52 5d563a1b528a33ba2ddb93195c8d1cb3 +53 9b2eb08cf296df80bbb4ad81656e11e6 +54 fa375841cb90a301547a4a401e1223c7 +55 a2e84ee21a47cc6bde8e4670df063143 +56 2196d89511043dc1f4c5eabed8eb6367 +57 3c8129f7de45f782beff748bbf0da49a +58 d565ad743962a199ec7eef5535bce1e2 +59 090cf20322b2748d78df94b28bdc642b +60 ddf2445e392d1af00bc4a3339bc2551a +61 2f728a68d2bbdb14806fe61370970e81 +62 580d8694c4de3ddb34b9a6f26f10904c +63 96ad644a9c8b2eb84969ea1572df7a8e +64 2fd8b88fa0601d29f7ace22a89ca7cc1 +65 ea0bf7feee61720f71018d7c806386c7 +66 31a600384da4b2298f9e80a068087e50 +67 fc46c062e75246c6aa64bef226ac2461 +68 3d11f39457a738f6fe2b1450d6341960 +69 134a9b9883c6600b04bb6c4b9c7a0c33 +70 b5c704e111b43ab5d2e162ffde3e8937 +71 0f937466e39dbf7bb89090d5decf03e5 +72 20d99ff844736453801c67d12fa79e93 +73 1db1d01503253a1a5d3ca68404eaafb7 +74 3c602464d0840bc446ff50efaf64f47d +75 4aa4020a92c5e643a5739ec8b7b9e10a +76 8d01190423b2dfa38cee8f991ce2ebfa +77 4bcd150c903c71032df93236917d7919 +78 1dcfdd58fb327c553cd99d4d7469f448 +79 34fbc38c0f8eab11b75064214062660b +80 a9f81f471509b0748bf812912bd32dd2 +81 e081bfec1d77af2d3f0db28457d79715 +82 fe9cafdd295444ca56dcd380bdc1f98f +83 a831b4bf39df1dc89aa94d74324d82a5 +84 48cef03de157a77d04c1039b23a88155 +85 21f1f724dc7255706ac1b05425efdd25 +86 3c3b80b2feb76dcfb7576f3440f2f6da +87 70e94619bb068a552876564574351717 +88 ba897f1aa64268cab3f4160b4bfab861 +89 ef80b155826c66c63c6e2592509e8ab7 +90 4057433248337d77127b1d07bddcd537 +91 af07c22bd3b28fc4b814e3cc89c554a1 +92 dd99e5f9d406f436d2624c8d964ac54a +93 f1c1f6aea219de304485a05fd49d6021 +94 d2d06534a2276c5468903f242a9bea66 +95 fb3f8223fcb9fcf7c95d7dc1e844cb05 +96 669c80c859a05c27a08b8af20820a4ef +97 ce4c0ebe3d4bdd00f82b0f2ca9fdc9ab +98 26d2e612a3be1eaccb14aeee77a6b3b0 +99 1d13a1a520f57ce65121a31fd30ca379 +100 9f0c25616ccacd8fe4879d9090737d82 +101 2a11c9a1f6e4223b3219542ac55a9655 +102 a259b032acb1848cc00894a846c1eae7 +103 d18f9fe5c7e7cd54ca8a1e550cd8f925 +104 7693140958a20b076028b8caf0f48d29 +105 108b9a861ca6ee9d895f89e7ff97285c +106 caf1add7c53eb7bcd4164f846563c6c7 +107 525bbe0becd65afcb75f7fa2a8bb87e2 +108 8c4e0fbeff5ced70187d5cd9a93d528f +109 d9b2358711006a04915da1a694f4ca80 +110 39d553bc6a783225692cea10da594c4f +111 779b14deee6ca2468e517e99ca4a7f13 +112 e3409ebd2ab32e1504d9c482de3a83d5 +113 c8f5ef6f52ea5b1d161e8531df319bca +114 2a4949faedd88840199323dacb66e457 +115 7b47265ad16cc443ad8058035f5fce5f +116 fc819d8d69f77d0a4f77708f0e26b4a5 +117 eb838bb23844bf9e52adec4ff74fa03d +118 e62f490ddd0864a698a22ee716d8f8ae +119 f7a42b0d1caaec33dbe06b492db3282d +120 25563fb608cf0126a258b1eafc20be73 +121 196b1dbb16fae60939c81f236c6d7eff +122 c09279b7c98b11e9737e97f85a01e911 +123 2c3f75965ab2ad596c898f5a2fc35ea5 +124 4ff7f6bfd08598b31f433011de824282 +125 dc67f4c243362f156193192a3e743d90 +126 b104afbfb6849d0783653b4a09487d4f +127 137ca5fb46d44a5b71dbc284fcc74e86 +128 94fc1b0b228e866d1339ad19a7ec08a6 +129 471515e9b9b2a4d28fbf3a2f72b84c2d +130 dcb8cf8889f7df24847f106a5c5055a7 +131 a5adfad6c6dd5aef1dffa487bafb19b2 +132 6cd64e07c1ff6daa6ee2c37404097447 +133 45eeb25f191ab243f46f595060f245b5 +134 1e08e53258de994c27f0a019cde87946 +135 c21118b0a65bdcc67499b5e7975d1e52 +136 28df4c4666166edf5499894ae6b996b7 +137 4cf111dac679ccd5141fed87e285d493 +138 5c3cc38fdecb5b0b218cec4dd5879c3b +139 ae41b0014cbb8dd1c27ddb8bd4130214 +140 7e717b47074b65c967b67c369d4e7106 +141 33ad4a57d04a32f90aba41c0b75b327c +142 535c0caa04f267b8fa549c9d012a67d9 +143 8325cb9dee99f380319d6555cf5112b8 +144 4336309eb2869fd8b92ddb586aead8f3 +145 2885bb91b95d92281db148761777f8ab +146 5ea22dc17d546815dc46bf698f44e604 +147 b7c55ce1a0b69534da1f3663316626f6 +148 7fa2b0d0907f11f1ca267b94b5ec7b4f +149 2a19c45373a77f2f23ef8d1bd365562b +150 3b119219dba751a1a4c77587d5229fd2 +151 6822eb05d27fcceea0a08d2d8160d5b1 +152 757b101c72db0b71c321a3639e0d7121 +153 a99b9939ab49ac9231c79f0f2ca3dac4 +154 1edf2bc0c344b0f54d33e64860e12ba0 +155 4ca2bc5c3cc245014669bc0b0591176d +156 dd4505be34302abb6fe17a9d2c86c773 +157 0cda91f4bfd6a28e68a9eeed1a962c18 +158 fc605d57e5d1f99a06ceb52ca473dc9f +159 64b888cee9d4b1bc89f73fa6fe11ce5f +160 505218d6f7d4c08c6d8a596cb8cd2343 +161 0aaa9f1c51a84b987d5998475833642b +162 cca38288a30659cc2fb92126b4aeea9a +163 15e778febb0c2b6e7cea27131c7011f9 +164 9802703c072b6776ce5f2da2dfc954e4 +165 53f67b2c04b96711cdd2a66a23f2e9b9 +166 c7f9b1151a83cdf36fc1af3b1d074a0d +167 9bdea2493f1f0fc0b7cadad70e330945 +168 a5f9c813f5ad9cbf61f4f78aa544c317 +169 d27854f513b413719e82a62fdf85aa0a +170 6bf44eecd81aac50ddfb20cdc8769f6e +171 d108ee33298f2063014e823969ad26b5 +172 15685851355d2806d46d908337070a31 +173 05e62aa412a95a3c11358ad1b34fb8f1 +174 0f6120a9629ba378c8289fbe84ff5771 +175 82dba9f241cc8f1ef7082e52bef7ac10 +176 264a4de33886a3d4150f3056cd5f2269 +177 179313f4a353779f63f20d8bca752598 +178 f9f46ee73dfa9a8801f641c86e06a976 +179 09b4134d15af839f4c34552bb2041085 +180 048f322aec1a7bd1e98021deeca67de4 +181 466d14220c07b9b3f821e59e40eee76a +182 ce3ad44d50154dbfd5f4c4a3b9241782 +183 499de08cb3f27aeb524b209818395fb6 +184 1aedd40c7711c7e305e0ff4be3adc833 +185 99ecea5a1a37684b471e7581cc434a6d +186 2d6024a591213dc3d6366f0d38eb0318 +187 4410a5fbc2c01545d24774391aae73bb +188 764694d7145f3a90ff4c73b47e3eb65d +189 9daadffdda4287759d86bfa0d3bf73a9 +190 1a29df303dbf199dccddee135cea8b36 +191 54cef0c96d59fee3f18ebe91f8036f67 +192 45ba69819ae51d38438002d494022c51 +193 f656eac270e0ac0aa2085c3a0f58a2a5 +194 ac96193b76087833842da6b57266e4be +195 41a3f853dd3c0945ad8c1dea79f4e5ee +196 ff7cc023e7d6a58b4957cede41f7e873 +197 e868f8c480cc8a5ca3bc03a614549c20 +198 3a44b38efcd04d800f035700117fefae +199 5f43a1b107d91e5a1971d94c4346c022 +200 f69e6e1522ce9ff5d5589126b553a51b +201 a1dc045d01a7b4109447a0445923be7e +202 b47a0ed9abae12b79052ed4006fd948b +203 08370bcc88c596f1e20905adfb0153da +204 e4b297012de537d076e5c67eac0e0b56 +205 bf09e451942d9d6b4ec313e4a80fc3fe +206 e30f0f1765ff768a58892c7656b21106 +207 7ff6b6feda5ee0c090e02765c9ae651b +208 0526b618545fa0943b8513cab09d2511 +209 96ab54182faf91998053aa89d486067e +210 ad203bcc17398f7d8067c873800574d0 +211 dc42e59941291b8034d965ba07fba999 +212 4b676f806edf31e7eed2d92033a2a070 +213 30c7ccd13f144f4373804963b86d04fe +214 5e6200c19460d9a5c7e0a1d9201b19e7 +215 cb48ede1e04c1eba135200edcf8d2ac0 +216 31060e79f95a9e8179a6e654963719df +217 23fbfe0a116d51ac04f72f33fe56c0e4 +218 d16ce13522f6adbe5c8d62c3caa2ee9e +219 f3fcdccd16276ff040c67a61f78d1442 +220 fc2fb24ec254522c07e5303765a12adc +221 310a059ab7c5cdc720a38d04d6c2f863 +222 113c7593fee493bea32fa6103dff558c +223 6e2ddbff00cb5a2bbf3591a5357d8b2c +224 484f302308212cf5bf1710a4163e5f8c +225 7de3fedfd31c3ccf8a0b577be3386a34 +226 6cd04960458d48f2d62d429078eb4a9a +227 7bef5d9439e18aac8ee4a11fbe1bb1b0 +228 e857c1eddcd886e520f202a1b87d1751 +229 41f59b53b35715ebd3ec92b2d868eb3b +230 58e1056b7455546642a3128919ad7f5e +231 e43b754c7b964df7e3316684d7014c1c +232 1e729f694c966b6b59cbb60cfd4598c3 +233 f04c7ffb9d20bc5e1350c19c0c32aa2e +234 6f327031d0a2cc79b34c0273a2d0bd6a +235 6dfabec70b3fbd8d3acfa606e87fd020 +236 8b081a0a7c4c4034b3c890c41821bcca +237 6025bc92470484cbab959c0cb6e4de11 +238 2861062e53a6feb505e87a98e04d0c63 +239 16296222826a7441ed29ced3f02456ea +240 3936e5c1e5f5d044188bdf6dab00c16b +241 b01c53e570a761a13aa821c7168efe0e +242 9631b4a42f7b86e4aca30d2f4f300f4d +243 110632c1fe728bb87abc4d319f5b3a9e +244 db726c48fd1d0c3a64998b9509330359 +245 7b78517e3f6cf737facb8f38520ed7ff +246 7866e1e82737a647a109a08bd421bb7a +247 d7491e923930489a0f2a7567a57e2481 +248 d4b3a9b822b45c72b1ec6d9c8bef857d +249 3b33381a56bdf581aa3ea9a9e01203ed +250 cd87448fdc71791e08e2092f6d53b3ad +251 aef3f408995b0acf321253243e2435f6 +252 764980808aa514d402c0439e48401457 +253 224cc6416496dd57c3268d48bb9a44db +254 0748d9346d4e9d67b6e91a2256fef019 +255 c5e69d08ac056903b88817b6b9260615 +256 56b360d1998423e09766aa0264dbabf5 +257 d0f53bb64d2adbf54a3f1a863c630505 +258 5d3911254ffd8cb455ca02c3d074c167 +259 01b494e9835c72395392e3bb033e1b36 +260 3d5f90ffd1918cce5fd6bc250ca5b925 +261 26873c041f5215ed8f7b75302d0935c8 +262 acbe1c37713f1a00c32622314edd515e +263 3f1f6e22038411090fea75b86205eb5f +264 33286932bbcfb0740bcc2786006f24bd +265 aa4378111fe81a22b001b4edf9d69d24 +266 c1e877cea7ceb83c6494f765718fae89 +267 5bdb82ae089441a8f07e66ddf016e0ef +268 8e2ce54d75d80a63ca083777e8bb80d3 +269 698f60c997be5e2953c0ac1ae5b1c9dc +270 1f572c5368e9fe988fcbc863ea4ceb44 +271 268ef4cec15e54d053d4d80f94834773 +272 0badb71670e0e3fe3cf579800ecb6402 +273 7178cbe58b7608b2a7305115046f3734 +274 a55e28303e12d9115ad2be85fd4a97f3 +275 c0b14d44ae4b5d0d63b7ba81ad5741ff +276 2a750be063e3d7bee1d816b21c8767ef +277 3e745af1ce7be369eff166bb7f83552c +278 0c68261dfdb63193ad9868c16144088e +279 66941e30e48268f242d3d790def0bd37 +280 c5cc31128e01613b1639c86cecb68fc2 +281 dbd670b58596050f15b0211f771efca6 +282 d6885e9a08125db753d19f7ec4500164 +283 23b27742cfdd70cdd2c0e02441ff038c +284 ac0245a78ad5c0398df3ce153126409c +285 bbcffc1ef6562449ba4ccedeb8fd98b8 +286 ebed592157012831031b4fdfe4e4fc64 +287 31881b847f86c6d26ab58b1573f1cadf +288 61933434e88774c139161b635ac29efe +289 8f3524d428940f35b15cab768719f731 +290 5ab49d7ab1dbb2d5e9c981dd92e46ad3 +291 07185ffd1dbc5c72708e26bcd16b69ec +292 750129e050c7deb075ab7dba63f46f41 +293 3c0dc849a42a6cabc67425888d97a86e +294 07078671d3b8a481e542090bd2e09c16 +295 c2acda493eda861db309f166143d76f2 +296 1068f42c0794b19d3b9d398b38ba3134 +297 9ef8e269118c3dcc0b538b4dc59f6ccb +298 ca9bd324210e89f73183dacf2e60271e +299 b5621f0c70ab68118f6be0bb866cfb11 +300 3f1671e2fa8f6111dbfc57abb023364f +301 e0706a0eaa3f6b53e3eaa7c49e62bcb7 +302 0fc7d0975fa3c7e0124a4330248cd00b +303 4607554032467968848b9df46eb83494 +304 6ebbba6199fe6371d55420b8f41fe5a9 +305 e3f14d9744039bae2dbaa63697372aaf +306 abe8a805e13d1f79976fe19aab8ddcff +307 157cd34f4947c62ced8e66644d95d1ad +308 aea9b093d17e1c4b8bd5162c8aac07e2 +309 f397df2be27d927c8be49825f5b00702 +310 2c8ec2893efbc5463c5bc9175df9abbf +311 ac7c7b808341fbae9feafe2f307acde9 +312 ec575dfb8ca4931ab6b10edc595323fb +313 a977e4895d1419da3d885572d8f1ba27 +314 e2fe2bef883514fc816e3e99e1eb11ac +315 c8ee9401d7e8b991cbad4472d1329d16 +316 907040ddfc54fafbc9fac71e7872faa9 +317 16a120d3f8f334d43eb6df726a18bfe1 +318 94848bcfdcfd30c63df437ba038ec639 +319 646f27e228d1dfb82a7e34273e6a83c1 +320 81f1aeecfa9dda4ac03b3054dd0d6594 +321 f5289fb3399d02814ce8d4b1176dcf1c +322 ab805ed83cf3e0a061d07e44a75432a1 +323 d57f72615b15acc1635e5c6c2244b7c7 +324 ff1839ef359e45fee7c025edae6567b9 +325 df37d770e49ef46a4e11649cd7e3298a +326 807eea9b9c50ea90a80b92445a8b6009 +327 354b97fa55f212d88b4cd1e96d0de210 +328 7e7d0ac0e2937a6e80f7fd42d810e120 +329 748962f21d58885d0f9ddc73fb4df6a2 +330 7dbed2a62cb9663c7a2981fd4de063c4 +331 4b60c210348ada6c775ccf307d035f72 +332 4b3e6adc8429415246b2c1da1d6e4986 +333 8a1ca8e27465ee45461c42fe2daecbea +334 f2aace7a15740c4efc75da794cd9bd88 +335 cd1f5c8131b607df3ea26940d242b438 +336 04897cd0d37964009218d644d750bd1d +337 6a9a4c96a0bd8ce2f33ab835e4cbbaac +338 2d4078e099177811cbfae747abe91ba6 +339 79a768c0769e0ff78d5c92affb788126 +340 fc2eb42930b86aed34175c78b96b8898 +341 6a11cbcc3b8363c59ad489e2ccec5cee +342 e63f4f7943609d4cc7a07c336e52b8c9 +343 8cfcd95ec1992704f452dd76dad74f5c +344 ccc42eef2e8fe26b62db825bd3f143eb +345 54ff5304881df86bf15ea77aea755df0 +346 d958a4fb8852e9fa1caf1f8782f5f3a3 +347 cbb263cae8a3fa8a8e1e19fec50d53df +348 6de18e29043df5f1c9954ef708d5071f +349 4d8a030731de7c07df9235f4078ee94b +350 84c9274fa2da90b95c5a0da7ad93fe26 +351 849361567ecf1fe819353a6c2f9ca4a0 +352 429a5e95e8694b1a19e31be7297e0025 +353 91876732a670da363dd8aa72a69a63c5 +354 ea98cb270dae066cd9c0835091501dee +355 e15533d4ed81fb51f691be5fce729ffb +356 9c0866ea0b20c60d0aa12a16d7010886 +357 a868c1b00f72599e68693d222c3a33c3 +358 1193018a77c16cb449379f4406b7d5fb +359 d63060e3fbce33e4da4bde9d4a1d6d0c +360 399438d45b94d4a8b67379f95d2463a3 +361 c1aaba02ff63034f59cce9653c430779 +362 bf74fbb72397f1302609ca47a361b3c4 +363 c45c799e6abc31277970af875e05b898 +364 6766b29942e34b8614a9c28a195a1493 +365 5b7412fb3c9067cfcf02c25bc5aed768 +366 fd5cee26886e10bff6a26c58f8d9eb7d +367 bfa469db70766fc3c5efebf84bd0ec50 +368 af0be8189a150e20c5ce1e5a94c43fa8 +369 784d9307fc1464401146845aa6f7f428 +370 b04439841c7fe8a84a738921c53c5227 +371 bdc8932d9bf93751ec417752b799554f +372 c271bd060501683b0afceea25a5b4024 +373 47514d87a5c94d45da9e9fddc6161bfd +374 d2010576b68e21e4e5d007f359091dd4 +375 ac87961aeaebfba3e6d62cb8f8042554 +376 fccb0f869d0ab6bca411d1e534feab81 +377 af401e628a82ef4edfe5291e67ebbc5d +378 6fc380e1b92033c58c7be1f57f8367d1 +379 a8233ef78f010b2207ee593487da0500 +380 e958bb8984c5ebdc621d22c6055fda1e +381 09f107b843b56f80f4ba3378fa6c675e +382 b194e32697d34c8379b51bbf28fcb580 +383 153ebc7328f5e54739b48467b75d3eb8 +384 25d6901c0a1a931c91a0f8490334b3fb +385 080bbac779ae96e602d97ddbcb71932c +386 38d2da3b939f8e11dd63cc3f58eafc23 +387 3b79caff996052723337ae3301a3aa4d +388 7dc80a7cf43b47acd5a1645b4e1c97ea +389 4e62f391d26e02c811b939afc74bd20d +390 7108dbbed45145871b685a79df109e05 +391 a16aba6581396bba7a6d5de49290f5b8 +392 ac8c1b1e493c3f96ec8dc38c79e58c4f +393 963a798f8aa9c7ff018a18f834c381a4 +394 f910a7e550bd4728c082a4d27a681e63 +395 c70d2a4edd13b578d241b2c9cb1b7dcf +396 ad22873c13f5acd0011494ac39474ce3 +397 654b13cb35f8784569488f5fc56dc555 +398 22bc48dc1a7e296e26640ce0d60ba4b7 +399 75762ea42c5929f4096b902f156295de diff --git a/tests/Febe.Tests/Media/H264/Conformita/FM1_FT_E/FM1_FT_E.264 b/tests/Febe.Tests/Media/H264/Conformita/FM1_FT_E/FM1_FT_E.264 new file mode 100644 index 0000000..5f0ae89 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FM1_FT_E/FM1_FT_E.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FM1_FT_E/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FM1_FT_E/riferimento.md5 new file mode 100644 index 0000000..615ca80 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FM1_FT_E/riferimento.md5 @@ -0,0 +1,302 @@ +# FM1_FT_E.yuv 176x144 4:2:0 8 bit, 300 fotogrammi, 11404800 byte +tutto bf2d60e2a0140368e087580a8565fc99 +0 572519c836e36352e6c16725a4f8b999 +1 280bbd76dee30f4840aebe6e68a10559 +2 6a402a0a24b919c7202cc74ff7c680cb +3 d2a1dc882041956e0d02fee801447c88 +4 c0c754509a9c78740292f0f48f7bad73 +5 b6501485b8f70bc9bebf8185b6add208 +6 d0b4acb92c41cc3f6a8ec053f0c2c3d6 +7 b8ceb15297197141f38a669dabad5c10 +8 9c3e2d1681b164f7abe03e139c8e8ea8 +9 060b5266449b21541c068f071f03c48c +10 485547c31003aa19d5b8ce4e94e35425 +11 50f80d0a6ae43c9b4c43249d46ac838d +12 1e466c88c49f3a4639bfde5a0e5045a4 +13 a8c634ea730e750ee20951a8edc69406 +14 ba6ad486535e250bd30e0fa51028af33 +15 87fb8913eff8475ed1d403ef283af877 +16 396ae52d3067f6cbd7e34226814dbe72 +17 8c191bb7fd086965b27d9ed535b83355 +18 f406d46a1401417143057cc5078dc115 +19 7c144db7b3c15d006145361c4864bfa3 +20 cf0112a16470068621fd4a2b84612264 +21 56b001cf558a1dbbd99394587a695b8a +22 51d7bc2cf34d292c285cd9356d53f827 +23 2a9bbde6736737e019389541ef77c923 +24 d99e69694add5e89e0f9451feb7750ee +25 cf1c5089d687e738a084b4502f26a500 +26 ebc9c69ffd034e00379687cf0f302a47 +27 30f4723a549d87aa619f0eb4aa582971 +28 6dc000b0e82436921293e9b3ef5b4fa0 +29 9eb7453e6a874d2d2371ea7303fafd50 +30 b029d2019f5e9938f4d849b4e9ec86d2 +31 d1444678fc13aeeb76a4abd1cddd8085 +32 43f6f645b1edd499e760c8bbc8ce2b39 +33 0072937b59f6200d19678aa5b9fbe3fb +34 0098df16a02c76bda98087051ac4cb68 +35 7ddc7a6f68e7996e4455c21189acddbd +36 716907c813b5aff720f71eba85e2434f +37 517b980a433c7ac5c3c4e3337e695c71 +38 739c767a9c4c21d71737a756a3335788 +39 40dc06f2ea87d745ba4a8d7a3ffddccb +40 4e25ecf4e2441adc45d3c3ae4f710fdb +41 c092f0d512f8165c2778bd9ef3761aa7 +42 40d32f172510c8061b4889dc524b0b9f +43 193d21b2376ee980c062931d0296e565 +44 2b8686a156d45d2b8a139860965dbe7f +45 e25ec5c166c5dff813a6300de6458bf6 +46 b73716a5ddfe118def9231655427636c +47 990f6ca0c754242ea32adb7958ac3f05 +48 98dfb449b415e6a66d78729afad5756e +49 1a947b9d2e4ffbdb3947c650440de5d1 +50 dda49a78d1183417a509d595108b118f +51 6a6943782e034435be9d3b6e0bdcdee1 +52 ce143555494da9aece594cf808c02f42 +53 6ce680f6dbe91606ed63077baae6bd66 +54 367bf70bde0dfe2109e4b009b6e35830 +55 e24052c4df2594ec809c5bf3695404d9 +56 8d1e8f99dc37034b19167da6233f84e3 +57 4fa3e5c8eb99442a350952a57453e3e8 +58 85932b6b98aa7d928e689479fa0b15ff +59 661100f281d1110b652939b781306bc8 +60 197ececc2dcb2c5b64fe83af6cfa4abb +61 3a4e22acdb7fbaa5736a45bd92458261 +62 233e910e251ecca77cb0e5a5fd55b6d4 +63 cd62429a6b47c765de0ae562637da478 +64 1acc6ab2c664a4071a1f4d5379dc70a2 +65 a3ac93a575ef44f0a4f6c291144039ab +66 857b63baf95a414e320ece38dfe16832 +67 aa16e88b1f08b946d3e09c1abc28661c +68 7e0cc58c808982bb391d4554a773861b +69 b70a07ffeee0602c894bd52bc1788c27 +70 cfe39f76fa79d5a4de95ae333358f813 +71 fbd876859feeac1b5cc6f0c72c3296c0 +72 9dcd08ea810e43b383dc84e498bc03aa +73 c99da294e2d5632d94c772c784e2da77 +74 0224bb40671c4be09fc5f04688437245 +75 7e41b0ff7d818cd7745194159b2df376 +76 22f515221ff394fbb54c69e219cc3bab +77 e8216984798ef443eb1e96a688e9a427 +78 f87c6a3f796540a70fd6edef0019a568 +79 c460db0b767cda4940370a027cc4345c +80 223d1eea0fb87bf2d57254d155f137e2 +81 0dd621cd8087fefbea20d27c0a09c311 +82 48bbd87bc519eefa2300b8439ed7590b +83 acda957189bd915fb9793dc7e7a73c39 +84 e106816e64bd2eec67e4ffd5d24ff4f9 +85 32fb665f0b742295a45d4015394ac047 +86 becae53e4cfadc71535a3bcd6b0a011f +87 665ceccaf408e953fa73725ff27c5f30 +88 8c8b9245d413fd66846dd1b2d7cc4c7c +89 0f02697eb079df300a03372570e11292 +90 f119af949283f3c43837175c19cba7ca +91 6e94a3c250a2bf0fb126c50e06796911 +92 4267c890f46fbd96f53f896e41db0112 +93 cfedf0fb9cdbfa3b5f8fc56b914757e5 +94 9ca6810e18753ff36b5f0b9bd23f74e1 +95 3c982d88ebef3f89702953c765d309ba +96 096b0a09df4e3444ebd56a1086aaae7b +97 671cedb4704b0bbe4d7aa766a0733db7 +98 d6581246cb194705b692a908fd676f59 +99 bd42be9927b7ef5780eeff41529a01c1 +100 184a6843a7dd4f9041f6987a2c269d6b +101 a3bd76974374d8f6b5a1b164f471c45b +102 1ea797706d6a0b96b8b1a1ae13b80cfa +103 f26a49512e43a1e0f4a2e6364a85b038 +104 86f53cfe776eedf61d36741583c81ff8 +105 cb5b355ade8b025d21f289eb76d22165 +106 63fbec1313226698a3a79819fe4ecb14 +107 c466e3d6bf04a441426927419ee7d71f +108 fdb49d4373b8a940b6471c9bc58c8327 +109 a375f2d75d55dda4fe85278a9c85a436 +110 eaddb917e3794f64b37e3f1e47ce4ff7 +111 3cfd6a266f4efa2152a25b783af9c79e +112 7f6b07f744dcf8aac52b7806fccc28d0 +113 4c96763c8c12b659596232f286832089 +114 8d7668ce620d6ca64c6b7757784d0a74 +115 a6a1f3984f452983134c57e1ae9ab422 +116 becfa80ee094b516634a49d949f63808 +117 e6abfc2cebea91172fdf9ed3a3c5bd5e +118 d8c44b563590b17fe57bb150e264ca0a +119 bfe22b8adf46edd7bff340d4ae23fa42 +120 35f7f886fae631c960bb01c2b4b9e7da +121 49a8b266909e0329749cd78ff91793c0 +122 4cf4c357136f6cc1c9cd61e51aecf143 +123 2e5c1655969e7272db32400301ad0830 +124 8736d7a3e4d2de7eddbdc216b532c196 +125 01e9ab0bebfc7afed3385160e9fc0b11 +126 c4bea79544ca820ead2b51a5597a07e9 +127 1592ffcc235b18db1b9e102918fbe4ba +128 beee7d3f4703dadda42591f1c4f8453c +129 a6ffc5522c596f742e24f7a4d679ebea +130 d607e5be35fbe0e073aa305a563507d1 +131 575cac4c4397f2a5899bdebf9da5f80f +132 94f74beb55dd7031b52a94fe6af0feb2 +133 99587faf30c1d6d865e57ef96f6e1fdf +134 f451a77d8c37246227bc7a02b6846f33 +135 f11a742479938b220c56fcfaa2d14210 +136 536fbac4048db61f16813562a89af926 +137 85351a7e1ab892d5482c2b6d208a65b5 +138 23dd7397accebfb66478488bf5b252ff +139 1281be053b3967272159df6a6824c7a4 +140 d6b53c1cc2fd79a93fd80c57854f09d5 +141 0d60cce30bf3f5596fe46495bf091376 +142 1cbc1d8ed537db35b39ee004379477d2 +143 24ecd9abeefe646c97caa626a19b9e29 +144 5b5ceb0732cf92ebbfb8326a0dad36af +145 de7a6f5b44f81f7f3f7ef9d845d39759 +146 16c9ac1494f163f832cb2cca2e873068 +147 466c59a5cbca6f9e26c8b915dd906713 +148 ba0e2df2236c37def508ed3c7ae89fd4 +149 e7648a7c8a451c0cf06b2673955d716e +150 d512f6f52fa2ecbdbdea8e808dd1b0a2 +151 5ad73bccdb3dd98aed65a7c1e560bc44 +152 2f2e36ba1282f6ae7075ca1afbbc0c1c +153 af07750a3a3ec49dc90af3004f72bb06 +154 26eb4caf4105994799651a75478d91f8 +155 8db43eeb18ed8351bdf32de8fc030df6 +156 61a64b31b30b096d6346258abf1cb6eb +157 2888a9f33784d73d609da986f3207841 +158 00393bd5f65ea80261833adde3d16ccb +159 e1258733f058fcbaf24ef471b01c6590 +160 a3054ca1680823c2e3c94f066eead8bd +161 e46fdd0068ad397d2fb25705a62459ec +162 cf186f70ec8705f9703deb34c32d9e60 +163 e7e4a070c5dabf4c25c8ad8dd8ab4c77 +164 4adb6d97416ccba41b584b4973ed826e +165 a773d6e595d6f3b4da5f040d69c04910 +166 cd8a53edf58b39484a34a314ae089eae +167 d227d58fe69d65a7ea4ceb78f0d66c4a +168 59cb1b3f49abad838c0edbfe896842bc +169 9d013831123526cf1c86b461aa59aa77 +170 64778d3084471567d7b3d4f8018d7f08 +171 4a48a72e81774ecf8782962ba0dddaa6 +172 8e223ead0cbe215e5530f9cce47855dc +173 34752e332933465450c9e4498208f7c6 +174 c4753815802756cd8ad830af5f438875 +175 5cadfa16c56f6d0e3d574f5993b4fc5e +176 2916e6091664f89882919e290297044b +177 82c1ce24b968669367e7acd314d223c4 +178 dd602d12c5b33b7d7be7c84db1b6400f +179 d0f5d8c5f11bab27c06f3213ea4805e0 +180 b94f44fffc88c11aae1c8070e71bfb49 +181 3bfc7a6cc9fb9025dd815041055940c7 +182 43dbb0cbf049343fe4549db3f05eca3b +183 589600326edfae823fab9a82a243b4ba +184 3650804ff34d761ff8e9d7d285151ded +185 83bfbffdedb9f48e62fd43b932560f2e +186 3004f4902549391a372ed16fff3e6268 +187 800d2bd7a796fe9bfc57cab330b0d4d9 +188 691c8caec8a836ccb3768207b5948800 +189 d29f655c4806052eb209f7ee38eba6a9 +190 69cd8b50fa9b39bc3a77f9fb3a543dc1 +191 bbff112e5b85ca32c632c629d8de9aad +192 d01335e2d6eb72f143af455d995427cf +193 26f044c6fc84b8f9706ec3cc756aa2cf +194 a2584b258d919a1678e57e7b6cac582f +195 a2c0560c7cfa094f1e3ccb30b0b05d27 +196 906dd3dd2400086afbca1d34f317ae4a +197 e09087feeb4481735107b9206f38afc0 +198 1090f541fc5942590187e8f73ec67ff4 +199 a238af8aefcb366d6344487fefa0c238 +200 d5886da69964bd676f96bca910c08845 +201 d43ecfde22f95b1ccf58a32b380cb855 +202 8d8f17e6f64e136993079a8510480bdf +203 e83d51eb5943c48ba9866b9616799c14 +204 2d37da634ac2f02c658797fc5b22e923 +205 dd8c008f3a271b4bf9d7422e47a9236c +206 017d2e7d88af865cfe0dcb9bfc0d8530 +207 ac9d94e63d8f82115de40295d554bb93 +208 d966a64423669f91110147f820836b4a +209 f43e1a1ae151277f6bf61060a39135b5 +210 029b78c957a1ac9606154b413d44611b +211 67d58769894d26b8d4e5384dc2cb56b5 +212 bdf15e5f71215cd4461f048740a1a8bf +213 36ae6ac33bdf4ef12ddb11fac5ba9d30 +214 67ab9f37472110181fba1360635fd914 +215 c79032c4fdb48559169b6baa4cdc8d98 +216 4367a1f5a592dda29dcfc7ebdab3f5a6 +217 c6f53ecb4acb49caffe4d1332ea4459b +218 917ee622e2743e405e0c09dcce1c03f1 +219 5c0a6dbb30a31d507a7e1f254f624d3b +220 dd6d184c9bc70c79f0628c2f20ec7949 +221 d80686d4b253206daf616890ff3e39ae +222 aca08e3df4e35e34abd4c930b59998ba +223 efe0c3f4d58cdf4f39f7d8e229e0f971 +224 57839c974a9da80deeebed653604b6b6 +225 ef1b6da541b1eace5555c11b59f424e7 +226 8d93a9cfd89f70deab8c1bbb884ce044 +227 f16d230f8bed9a28ed1758354045a0d0 +228 746d509c16da6054b03e979aefe40428 +229 409e7fd4172812dd014657d263cf930d +230 b5f6ae626965ef5b5a531af5120d3e99 +231 f7c3c12095869ccf2c4d116e720491c4 +232 728cc97ec9d01e8c70ce86363c0e7b22 +233 8d4ac0b5a049bfa44bf02654c4d66810 +234 0c4bbab283d5a8ce653335d5bc1fd84a +235 506d691a3a856c9d348e81de20f77b21 +236 78879bdafe46a397668f411307b444f3 +237 b4db069bb8cdd82c6ae0953d22751f9e +238 f4eadac159b190ed68852a2d8f018e03 +239 e9676007230258c86fdfa3e38ade1e7f +240 e5b4659047205b6b3471e3a7c7f8b199 +241 b0cc438d7cc7161e452540aec799c7b4 +242 ec36e09f1d87321a433fdcc702cfc2a5 +243 1e2bb4caaeb4694171e50be3b5b77bdc +244 f16fa56edd6379dbe25422e83c1198e9 +245 bf75ae2efe566b84b4d5ed649097a0d1 +246 8102188df66bb7121f6e1cdb8ee4d7ca +247 62c4082b39d5164ab71c879279cf91d4 +248 76410de61f825dc0aa3f8512caec6727 +249 d23aa066bb4748e057f70fceff5038b0 +250 4e86dc386db9d1e5b9b140f074754dad +251 0a40c6469a58f9953bb45ab45f1ed2f7 +252 d71d30d3bef91369e81063d44a58b774 +253 9030bc6f323035111b9d74ce101ca568 +254 9c23b22975acdfbda55b9be7b9ec0b02 +255 bdab7bc6f89041e0ee65feaa80736029 +256 9e2bb7d095672d15ed03d80777a4c367 +257 b0b98c561b961f072aa91a399e39d2fa +258 6932ef057eacee727cf12f3eba388c09 +259 098413cf05cf8f96bbba96ed99168c28 +260 64f12427fa8592606c5e8d8770443362 +261 8e7aa8af1f2488e95154c0094d893bd3 +262 2ebe460e5f7e89868de20bb3a0e41a2f +263 c825ae4c7e1fb9cf85de3f240ac2b8fb +264 8270575c277a81aa01155a9297cddcdb +265 d274eb7ba9722078d14d83c309555375 +266 a6350fc9bc9484620352c6c7a6f85103 +267 ed1e5e7e9a0f010b858ead82412b9e58 +268 6270dad712dbd6d3712419b5b95f425c +269 6fc25fca2cc7908e014241c041acb967 +270 81ad4eb90aa5965caff9689d4b4052e8 +271 7f6e0a834767210282dbb6422b73e8b7 +272 0bf4ab1c055677c35edb1154c01ebb85 +273 dd1017e08b236e7f6661c323bec8c0d0 +274 be97520b63a40ddb7ef0cac4edaa0e5a +275 ede206334431671223d395fef0dffc47 +276 763f3607c6fdc2825d9c46b0da8693be +277 3f32b27ddf7e13f974aed81c79cf25f6 +278 a72a51e1d3dc04b4b734ba3317129040 +279 c6bd0eb482d6b5398cd30e9fb0b9483b +280 64d41766b63d7e04760b58f6466e8ded +281 77ba19473c8f392f08794a7d65d2668c +282 832e253709d3dc56ff079ca50cf3c25a +283 4bcc9e67ddda1ca18a50dc69d1e71c4a +284 99592a9adfacccb7ed5b3d58c589cd81 +285 0052d68e2274da8a4374b3add2ca3be3 +286 1fab367fa2822b612e63940ebfefe5b2 +287 897212371d67d221b74b3d1dfadf1832 +288 6f5f799e5e4b66d9263e541e66c97b3e +289 46f80da7cab9df9a16b338d7b2753c89 +290 0301dde14fb2b3da321fce1646dc888a +291 766e4265ca799b282039208e1aacb829 +292 1f8135c336b8d6ac512d160e8d034ca9 +293 1b770faacdb34122d2b66b58dc4a45df +294 b7844a3253b97aaffd41546191173ff4 +295 f943541c5d744fef9a686e190d3e4c3c +296 b17fe991b77f9c7be3300d1e8b281ac9 +297 04a251d095aa3cff5954e43e4b05034a +298 16e5ba9779680c40344d89f636e3d38a +299 43843b5a34923236ca379465c6062aeb diff --git a/tests/Febe.Tests/Media/H264/Conformita/FM2_SVA_C/FM2_SVA_C.264 b/tests/Febe.Tests/Media/H264/Conformita/FM2_SVA_C/FM2_SVA_C.264 new file mode 100644 index 0000000..6d61794 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FM2_SVA_C/FM2_SVA_C.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FM2_SVA_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FM2_SVA_C/riferimento.md5 new file mode 100644 index 0000000..b8e47f0 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FM2_SVA_C/riferimento.md5 @@ -0,0 +1,19 @@ +# FM2_SVA_C_rec.yuv 176x144 4:2:0 8 bit, 17 fotogrammi, 646272 byte +tutto 2ca2331ff02689d0cc036935a7f0d4bf +0 b150e95bbaa94aca05a8896f5983c030 +1 d18d809913ec8d1e2f6f0f2dd543e1c4 +2 6e8c0944f3aa8776ff0d00d9159a5f2a +3 3f2ddc08c27555f525091f6e20113fe6 +4 65e02a167003089d0ecc8a84778a4aa5 +5 46d0b60a5ba0176ab94233883218dcdf +6 d37421cc1e836877515bd0057a74144f +7 0361c203164f529759cad5bb0e543c09 +8 35f6846f8d649eaccb9f57885410d2e5 +9 ce58323b9b6f9c60bb8d4c71e9577a9f +10 5c5dd4fb5c77c0c30085641cb78e0a4d +11 bfa80ec9f944c27094e48a7334e91486 +12 9437e70a86d2f702a3f97845bbeba4e5 +13 922c09ed8bcafb146ea63ebb7919a646 +14 ac89adbf6892642cc115f845443569b1 +15 42de20ef616f0ec23ba6811cb605db0b +16 f7878f243471eeb2a28ae6ab5e4cc1dd diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT01_JVC_D/FREXT01_JVC_D.264 b/tests/Febe.Tests/Media/H264/Conformita/FREXT01_JVC_D/FREXT01_JVC_D.264 new file mode 100644 index 0000000..8c0b228 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FREXT01_JVC_D/FREXT01_JVC_D.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT01_JVC_D/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FREXT01_JVC_D/riferimento.md5 new file mode 100644 index 0000000..91230bc --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FREXT01_JVC_D/riferimento.md5 @@ -0,0 +1,18 @@ +# FREXT01_JVC_D.yuv 352x288 4:2:0 8 bit, 16 fotogrammi, 2433024 byte +tutto 34287e0608dc68efc9edf4eda6bbb434 +0 62886edd936d2e1e459f703eb666ead7 +1 09ab0afa3f8bf57eb8673061c5e351e8 +2 430e112814f164e3be76969a593af962 +3 bd6242497ec9dee434d3d49a35103ed7 +4 9b639ce8ed58788053e60fd53dcfd492 +5 f6f582d872f7dc1848a5f7816f3260be +6 05f700d8cb43b9e07dd4a66387188422 +7 fd6bba967db2aa969abf60b383256b7f +8 53d9ed6b79e22614653f0674a1c60c11 +9 bb2f11103430bd203afff52cf7e04be3 +10 36b82dc46cdf245e8698df25bedd9375 +11 a4b10ba9d7210d51b7c76455c1dfed54 +12 c1b08a780a8c1ef443b062aa5cf247ad +13 a84229899cecf403f76baa709e27885f +14 86a3f4c283c27a1abe1fa18b0addc702 +15 ee94d3c99739da376c38897189843281 diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT02_JVC_C/FREXT02_JVC_C.264 b/tests/Febe.Tests/Media/H264/Conformita/FREXT02_JVC_C/FREXT02_JVC_C.264 new file mode 100644 index 0000000..84288af Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FREXT02_JVC_C/FREXT02_JVC_C.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT02_JVC_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FREXT02_JVC_C/riferimento.md5 new file mode 100644 index 0000000..7dabe54 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FREXT02_JVC_C/riferimento.md5 @@ -0,0 +1,18 @@ +# FREXT02_JVC_C.yuv 352x288 4:2:0 8 bit, 16 fotogrammi, 2433024 byte +tutto 34287e0608dc68efc9edf4eda6bbb434 +0 62886edd936d2e1e459f703eb666ead7 +1 09ab0afa3f8bf57eb8673061c5e351e8 +2 430e112814f164e3be76969a593af962 +3 bd6242497ec9dee434d3d49a35103ed7 +4 9b639ce8ed58788053e60fd53dcfd492 +5 f6f582d872f7dc1848a5f7816f3260be +6 05f700d8cb43b9e07dd4a66387188422 +7 fd6bba967db2aa969abf60b383256b7f +8 53d9ed6b79e22614653f0674a1c60c11 +9 bb2f11103430bd203afff52cf7e04be3 +10 36b82dc46cdf245e8698df25bedd9375 +11 a4b10ba9d7210d51b7c76455c1dfed54 +12 c1b08a780a8c1ef443b062aa5cf247ad +13 a84229899cecf403f76baa709e27885f +14 86a3f4c283c27a1abe1fa18b0addc702 +15 ee94d3c99739da376c38897189843281 diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT2_TANDBERG_A/FREXT2_TANDBERG_A.264 b/tests/Febe.Tests/Media/H264/Conformita/FREXT2_TANDBERG_A/FREXT2_TANDBERG_A.264 new file mode 100644 index 0000000..ba2be5c Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FREXT2_TANDBERG_A/FREXT2_TANDBERG_A.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT2_TANDBERG_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FREXT2_TANDBERG_A/riferimento.md5 new file mode 100644 index 0000000..bc4bcc1 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FREXT2_TANDBERG_A/riferimento.md5 @@ -0,0 +1,7 @@ +# FREXT2_TANDBERG_A.yuv 352x288 4:2:2 8 bit, 5 fotogrammi, 1013760 byte +tutto 6462d635c5ba8ffa8e4fdefbf168faa5 +0 ff2cc2ecb471f79873db9f55329c7d4c +1 00f670f7ec843b457317fd0ea6f31652 +2 bb70892a75fede5aad896817381f047a +3 4cfc791483e9a39330ffbf94d1eb3da3 +4 c4ddef812bb5b067ba4b89b94ec99a1c diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT3_TANDBERG_A/FREXT3_TANDBERG_A.264 b/tests/Febe.Tests/Media/H264/Conformita/FREXT3_TANDBERG_A/FREXT3_TANDBERG_A.264 new file mode 100644 index 0000000..15c77b1 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FREXT3_TANDBERG_A/FREXT3_TANDBERG_A.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FREXT3_TANDBERG_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FREXT3_TANDBERG_A/riferimento.md5 new file mode 100644 index 0000000..3eef95b --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FREXT3_TANDBERG_A/riferimento.md5 @@ -0,0 +1,7 @@ +# FREXT3_TANDBERG_A.yuv 352x288 4:2:2 8 bit, 5 fotogrammi, 1013760 byte +tutto 10b71582637298df8df7eea8f6ffb3e5 +0 ff2cc2ecb471f79873db9f55329c7d4c +1 847e2f31aacb9219542a289549224cfc +2 00f670f7ec843b457317fd0ea6f31652 +3 79a09e8635fb24fd8375ab20d0e9e668 +4 bb70892a75fede5aad896817381f047a diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt1_Panasonic_D/FRExt1_Panasonic.avc b/tests/Febe.Tests/Media/H264/Conformita/FRExt1_Panasonic_D/FRExt1_Panasonic.avc new file mode 100644 index 0000000..2a5a027 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FRExt1_Panasonic_D/FRExt1_Panasonic.avc differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt1_Panasonic_D/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FRExt1_Panasonic_D/riferimento.md5 new file mode 100644 index 0000000..04aba23 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FRExt1_Panasonic_D/riferimento.md5 @@ -0,0 +1,10 @@ +# FRExt1_Panasonic_rec.yuv 352x288 4:2:0 8 bit, 8 fotogrammi, 1216512 byte +tutto f7023a3a93cc98c0c8d83c1deaf11048 +0 8a6fa137089372450f792db3c2a69170 +1 e81176e529bc97071e87c6a5303cc4db +2 d3ea5554111369aa268a23598620a8ff +3 0096a3c281d2513f9822394a0eed62d3 +4 370da672eb79f32fb73a4fe62bfd1516 +5 c5228727a11e191778329cb8e894602c +6 0e92366f256eef4f440d7897696619ae +7 fe54f4bb6ad377819bd8a8f0dd89675e diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt2_Panasonic_C/FRExt2_Panasonic.avc b/tests/Febe.Tests/Media/H264/Conformita/FRExt2_Panasonic_C/FRExt2_Panasonic.avc new file mode 100644 index 0000000..d62fff0 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FRExt2_Panasonic_C/FRExt2_Panasonic.avc differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt2_Panasonic_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FRExt2_Panasonic_C/riferimento.md5 new file mode 100644 index 0000000..5b57265 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FRExt2_Panasonic_C/riferimento.md5 @@ -0,0 +1,17 @@ +# FRExt2_Panasonic_rec.yuv 352x288 4:2:0 8 bit, 15 fotogrammi, 2280960 byte +tutto f4f02595e54be89fd9d33cb7907f5cb1 +0 d1030bc5a928a9af93492597ffc981cc +1 a8f58c15a606388f3ba80922dd7a01a3 +2 88421e59964a3ebaedff7b2f2ab641c7 +3 1b05594fa1b25c040771564c966ebe03 +4 f96f1cdc29e3a6038383cb8141e600e5 +5 46a189c2f9ce4e5db1602877e40fd7ca +6 52e46f8ba62ef4949207b1570f3f6756 +7 f6ca84bd558f4a0f7dc280ab71a43afb +8 61a180d0c2269f417e7e1025554305be +9 6a03d603ac0d5a6c0a704a119e3ecab4 +10 fedaea4d1399138c16eef647835dbedd +11 b509ce2e787905dbf0d98cf485c06f57 +12 fc7509384f1f042ed85c8a846b826dbd +13 08d05848ac5d74c6a97cda6845335d4f +14 000bbd8e6155d74df9e382a282155623 diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt3_Panasonic_E/FRExt3_Panasonic.avc b/tests/Febe.Tests/Media/H264/Conformita/FRExt3_Panasonic_E/FRExt3_Panasonic.avc new file mode 100644 index 0000000..be8007d Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FRExt3_Panasonic_E/FRExt3_Panasonic.avc differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt3_Panasonic_E/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FRExt3_Panasonic_E/riferimento.md5 new file mode 100644 index 0000000..8deb8f2 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FRExt3_Panasonic_E/riferimento.md5 @@ -0,0 +1,13 @@ +# FRExt3_Panasonic_rec.yuv 352x288 4:2:0 8 bit, 11 fotogrammi, 1672704 byte +tutto 231e4f3105f75a3602161ec484bbd8e3 +0 417502c2a9e24cceda79c878a1d96afc +1 843107270db6232bd98c488db9e8299f +2 48d6c38beaf08e428b5d5bb88ba3db0c +3 354fdd663e8b9d3f5ccc974b81138cd5 +4 4afe86f7f9f79dfa6141784fba981d50 +5 e529322be91d3831ddf37f89520a6840 +6 7c090c9d62531d05f726a33576542cff +7 a193b76c9639427350b0c77d91e296be +8 858fe407c85c78287f94fbdb055d1804 +9 d1c2cc1c715ef903a54b40e9774e9ab2 +10 be430f34fc21c60b4ab0327971c83314 diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt4_Panasonic_B/FRExt4_Panasonic.avc b/tests/Febe.Tests/Media/H264/Conformita/FRExt4_Panasonic_B/FRExt4_Panasonic.avc new file mode 100644 index 0000000..dbb99b2 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/FRExt4_Panasonic_B/FRExt4_Panasonic.avc differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/FRExt4_Panasonic_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/FRExt4_Panasonic_B/riferimento.md5 new file mode 100644 index 0000000..e68559f --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/FRExt4_Panasonic_B/riferimento.md5 @@ -0,0 +1,12 @@ +# FRExt4_Panasonic_rec.yuv 352x288 4:2:0 8 bit, 10 fotogrammi, 1520640 byte +tutto 73e8c29786302b23808b3025631a9f19 +0 f68e14413c68be6335d08ce788fcba4c +1 82b4f83d9533081d3b084447ecd9818c +2 aa81298fba7cc41fa595aad851fc2b41 +3 d5d52c377e16d6fb1606a84796758b39 +4 01f21dd6fc939d6b430d02d22f43ebb8 +5 92a7416aecf67e874994be6849594dd1 +6 abebe2d244d757e2da2fc9b7f1bac451 +7 8bb2809eeeae64fe9c31c72fd8d4d51f +8 a317a72822e6b4648493d34d6ce1fa4f +9 f2e42dcf63e82596ddbef95761f055fd diff --git a/tests/Febe.Tests/Media/H264/Conformita/HCAFF1_HHI_B/HCAFF1_HHI.264 b/tests/Febe.Tests/Media/H264/Conformita/HCAFF1_HHI_B/HCAFF1_HHI.264 new file mode 100644 index 0000000..a6b9add Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/HCAFF1_HHI_B/HCAFF1_HHI.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/HCAFF1_HHI_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/HCAFF1_HHI_B/riferimento.md5 new file mode 100644 index 0000000..09642ee --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/HCAFF1_HHI_B/riferimento.md5 @@ -0,0 +1,12 @@ +# HCAFF1_HHI.yuv 352x288 4:2:0 8 bit, 10 fotogrammi, 1520640 byte +tutto ededf9476ef00e99b1c61432f69ff330 +0 41a12de325c81e7e7785997d8a2ccabd +1 c2ef71c1612b93958419d6e622c44f6c +2 2b6b21301249ec1cad6d46643127621c +3 d0af063ece9b74a3abe30e393baebfda +4 c1a54f95cd300721244b456e663de7b9 +5 cd9f534479f812ef5bd313d310005c4a +6 66fb08227358e8b3e0141c58958f75c6 +7 7fb61322235a2d4b966ad5e72d9dca1a +8 7cd6009e5aba9a82e91675268064cc40 +9 60c509059478796171b7231608e01d0a diff --git a/tests/Febe.Tests/Media/H264/Conformita/HCAFR1_HHI_C/HCAFR1_HHI.264 b/tests/Febe.Tests/Media/H264/Conformita/HCAFR1_HHI_C/HCAFR1_HHI.264 new file mode 100644 index 0000000..f0cc9c2 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/HCAFR1_HHI_C/HCAFR1_HHI.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/HCAFR1_HHI_C/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/HCAFR1_HHI_C/riferimento.md5 new file mode 100644 index 0000000..a136642 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/HCAFR1_HHI_C/riferimento.md5 @@ -0,0 +1,12 @@ +# HCAFR1_HHI.yuv 352x288 4:2:0 8 bit, 10 fotogrammi, 1520640 byte +tutto a8720257ffe53ce4bb0861e3ae72dbf2 +0 b460beadb33c706cac48e5ed25bf3021 +1 2e4333f4970be7cd32faaabb68693b4b +2 685a3ada3db650ff0df2d52bc99f5e18 +3 9a896793f04828034d3166afd037632e +4 39e43284b17a1303f5b2aa34c972c9d4 +5 3e1b51cbc7aa26693c901f4b65fbda48 +6 35f1ca9e2bcb8dadade752f331dfbee8 +7 88bb1094ec8cdb763b624ac9d6216cce +8 b8120234f922aebda439757ca4311fdb +9 daa0fb5ea64a8824096846066695e3a8 diff --git a/tests/Febe.Tests/Media/H264/Conformita/HCAMFF1_HHI_B/HCAMFF1_HHI.264 b/tests/Febe.Tests/Media/H264/Conformita/HCAMFF1_HHI_B/HCAMFF1_HHI.264 new file mode 100644 index 0000000..58aa2ee Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/HCAMFF1_HHI_B/HCAMFF1_HHI.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/HCAMFF1_HHI_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/HCAMFF1_HHI_B/riferimento.md5 new file mode 100644 index 0000000..190543f --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/HCAMFF1_HHI_B/riferimento.md5 @@ -0,0 +1,12 @@ +# HCAMFF1_HHI.yuv 352x288 4:2:0 8 bit, 10 fotogrammi, 1520640 byte +tutto 2973f5376378cde879649160d4a46a98 +0 aa40dc395d9d931ecd883800bca04ea0 +1 f77cf0c26c91a3e006a383977c037b4a +2 9dca63d79c270f9c29a99c75c63f7876 +3 b7cde122417f5c0c6dae147ac6263687 +4 89961f23c23af77f55f0bb7d79f81c75 +5 d5ae5e4107c362d77532c503c175ac3e +6 46de89a7572dd6f0dc938a96ead60a86 +7 9031acc2129a7ffdbf3b5735e5a23c22 +8 7fc0011c850e108c2005e1c95d90ccd5 +9 adcd76e589bd782885db41047da84583 diff --git a/tests/Febe.Tests/Media/H264/Conformita/HPCAMOLQ_BRCM_B/HPCAMOLQ_BRCM_B.264 b/tests/Febe.Tests/Media/H264/Conformita/HPCAMOLQ_BRCM_B/HPCAMOLQ_BRCM_B.264 new file mode 100644 index 0000000..8927d9d Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/HPCAMOLQ_BRCM_B/HPCAMOLQ_BRCM_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/HPCAMOLQ_BRCM_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/HPCAMOLQ_BRCM_B/riferimento.md5 new file mode 100644 index 0000000..69cab9e --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/HPCAMOLQ_BRCM_B/riferimento.md5 @@ -0,0 +1,103 @@ +# HPCAMOLQ_BRCM_B.YUV 352x288 4:0:0 8 bit, 100 fotogrammi, 15206400 byte +# monocromatico: il file ufficiale porta anche i piani di crominanza 4:2:0, tutti a 128, e l'MD5 li comprende +tutto 7c6f597211ece8ac869f139094a165a8 +0 ea3857d95d0d87aff3dc85fc23454954 +1 bcc8b0480bc39fe642ea111e27d11066 +2 144dfb087446f99c86338b005573eae9 +3 237b4bd8bf7a9f42310915c88774ef21 +4 741ee1ae02adffedccd770b43d30f0da +5 9fc16409cce5206e4f80b18752b36667 +6 05364a76edaf677c264df8b02383c67d +7 85a662d490b5dc292538ca57c44196da +8 d6f460604b1141460aad528b0e529747 +9 1fb7beb632f1c7dc320e98bf6a975488 +10 1f9fb31bf6d1420d279163a9728fdaf0 +11 24f5aa46aec3263afcd389ee8ccdddc1 +12 d4907b270c79ef502189032d5c857ca7 +13 1e29ee8d4b2736c7d5b559ec2138706a +14 8ddac0a0607393c8c9648641cf776d7a +15 14354e4b1fa99d100e2cd19bb53ff8b8 +16 a510ff22cbe1592325f90d58914bf72a +17 372a6d5cb2dccbdad6559eb5e404d27b +18 aae42c3803fd368e1cabef23e027fe1d +19 26b0f35f2ac551eb512294b3d22e4116 +20 6dee4dd05aa3c72d221a2560c98394dd +21 2349ecaca954515ddde1573f42a12504 +22 6d910fd5b0b6df7626b8086b9e8e80e9 +23 12a078c12583de77a86ab76f36119751 +24 58342b6d65cacf81bfc4207feb4ebd31 +25 7b384399ea17d3e1b3bd43113b093f72 +26 657eda1d5031fc86898170d3f6bdbae4 +27 a3dfecc6995d51704b86261add4b79b3 +28 15e239b710a51aec315e8894571357b2 +29 9f04d8582512f3c686651f029eb40090 +30 546773c75597e5716edb925383c3cd04 +31 a500b9b51119c582ec1948cbea93cf9a +32 775acabc711d54cf50190f2fbaa33608 +33 3bb7a2ccb939d8223a7fafb7ae4667ba +34 02a9cdcee8dbbbb28cac96d02767d356 +35 c8ff6a482434111b1e6715865c27f2db +36 36a568cb03e1669bdcdd0c51b064997a +37 c9747c8476498ad5d5b9d0f7b6180dac +38 8a7ef20e7b642fe4b8a61da9def32ada +39 3f244903fe7eec6b1040922657e56b5c +40 72985f00d82d8981f36044dd2a623a58 +41 4f6da115149a4cfe8e455de861ae94d2 +42 313032df8ada9dba6e1c0d79345a187d +43 be0b02779603a88a073aaee7ed4d813c +44 24cba27e8c73b810a77ae2c4c64ab243 +45 80963e175f9cd227bd996d0d883dfe58 +46 30f183f120ac9c64f4248fc1c6fc4498 +47 c187029871bcdd6e1475580fac41ac79 +48 408b4fe3a68a3599100c95d23773b7bb +49 d4154ecf9ff4a3b193851c97ba7e8734 +50 e4ad5f345d6afbcf27e487877349e06b +51 464701ff3d45ec98f6008fee0fbe8d8e +52 2ce2ee13dbfe3e1cd6c1241697bded37 +53 c8a74275f2ddf6b6e5e08e1252df26c0 +54 b7d17ce4df05a9a3e96a32c67ef071fd +55 ecdfcbb2039675155b2ab0b56580bf3c +56 e2d5a6bf04426f543e1723119ad55113 +57 02a04d931904281dbe53db0432131d7a +58 5dcdedc57168e769f22012c4698d8cd0 +59 3a3ac66b8155fd644bfeee3c565c489e +60 fdca4ae1826422a3117975581457b1fe +61 b23dd25ea8090224913da085c8e23ebc +62 08ae38b58f8c760765ae90c333aa5b1e +63 002ec4b015019f2b64b471268e071c5a +64 79bc9e5a4b309bc7647af27969020fc3 +65 b1ced5d4d80f7e2d1a89a645c3968250 +66 4d23ba84cdeac3abd8d1656b1624bf95 +67 a2fed8ee052b3cc7431852ac1afd0c96 +68 2b5260fdcc6cc616305566ed7f00df1e +69 9376f3d13a83670761930d2dc106acb5 +70 20f5b4f41170be0067a45ce032b6c727 +71 9ce5c30c666d9378181983cd31a8ef07 +72 b3bfaa28e7dfbe728ed426853b488f4c +73 2bb762289f99327e384df97975c96a6e +74 9bb5df2cde21ec621d24769888ed7cfb +75 8dd76872f38ab9f6f00e859c18a783b2 +76 96b745151977b2630648cc8f866d42c0 +77 f6551d2ca0d3d16cba002667796910f2 +78 b80e53a9f658d49ea5c0880130f12b73 +79 c32a20aacd4078f62ccfdc21afb42313 +80 ba5941c3d7a3f8ef4eedcd4d9daddaf5 +81 1a9ba4988a10bda6771d7f18288c787b +82 4c7a48b5a4b33a7f9df2f1c24e5a988f +83 f71917ff4a64a0bde2c213ef8d357521 +84 a7572e1bc408601cb963fe299cb769cd +85 ae165315e535d1514236978c5675c73b +86 7e7359c81a6cfb126af95997390ec73e +87 658452a6a2c83529b4e007a51662c9ae +88 2d3faf43e36b360287d048122794a779 +89 4687b8cf25cd215e2ea098a6c5c9fcea +90 ff331fa194240741c106cd74a4adda32 +91 206088a83ab97c58c890b2a4b21d2c7f +92 9ad32f4ad17c5565fb3046504001fe82 +93 87fb36d9cca4e1fcabfed40549909a7b +94 bd3bde10c2b99eff55cd2bbbd611d0d7 +95 e375c6782481131ba5be6175486eba16 +96 a4694dd2f3a1f5cb82e37da9550739bc +97 6aa17a529f0e8bdb29da003297ca00c7 +98 fdb933d42af7d1ddbff0c79e0d27ff34 +99 7ae7a486240ed5e90d8d2ab77efc71c1 diff --git a/tests/Febe.Tests/Media/H264/Conformita/HPCVMOLQ_BRCM_B/HPCVMOLQ_BRCM_B.264 b/tests/Febe.Tests/Media/H264/Conformita/HPCVMOLQ_BRCM_B/HPCVMOLQ_BRCM_B.264 new file mode 100644 index 0000000..131b725 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/HPCVMOLQ_BRCM_B/HPCVMOLQ_BRCM_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/HPCVMOLQ_BRCM_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/HPCVMOLQ_BRCM_B/riferimento.md5 new file mode 100644 index 0000000..b9ebcd0 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/HPCVMOLQ_BRCM_B/riferimento.md5 @@ -0,0 +1,103 @@ +# HPCVMOLQ_BRCM_B.YUV 352x288 4:0:0 8 bit, 100 fotogrammi, 15206400 byte +# monocromatico: il file ufficiale porta anche i piani di crominanza 4:2:0, tutti a 128, e l'MD5 li comprende +tutto 360eac5edfd332e46197deaa578d7b9a +0 cd67a4954224a314edb4a2f331bfc3a1 +1 87d20ad5750184bbcc27700160ed70fc +2 41dd1005a78a82cc4c125ee37248aea1 +3 aab8445c223b97aea5137ccea72c8614 +4 7ff3d599f1100c39b3698063bcc38600 +5 b0ad036b746719620d63840d51ddd7b9 +6 651a1107f3c156872187ed4acebba74a +7 103895d3f3d48faaf5653052cb5a3145 +8 b605afe259bc835a15f429828ff7f51f +9 79a3270ed81b8f975100993890ae9647 +10 db62ae599dbfb08a7e673daf9ea6aa77 +11 282f177eed096599e6fa9f022ec8cad9 +12 64fa74b0a94c520ac532d088da85c8cc +13 25cf8e49199941fe6c361d45fa8b5517 +14 1dfb20d7fa9288ce481044443c6c52ad +15 235a19696f94e921b298162c2c0b1c12 +16 26e7a7f4b37803a425954d51a8f353b1 +17 1573f1e8fb9832336b58d9af3a08dbc5 +18 2c938033e6a9d76cd657ae1283943261 +19 ef3b4a77bab55d2bba2bd2c410841752 +20 54b0184ed604feebe82293bdf9a0645b +21 9930cf40bf64f79e38999112d541db8c +22 09ef8960fd5fee73e21506b86847f067 +23 95ed7f45c88e8499f3f9c3fb379b54f4 +24 bc142a2121e440b0e3a3d1b16049cb5e +25 aca31710875702e63bd3d3a5856a2ef0 +26 3a9ecff08e4a03e67361d887c4ae0f49 +27 a86d9228e373c2a257423eb7ec432c4e +28 7970f1120090f579eba6fb3a46932b23 +29 ba45dc691f8a2cbe92d54eb0e6eea2d9 +30 d8fcc313f7fbe0db2ea19cafcc9d6646 +31 72a13222b6e6d91dfaeefa93b7fb8c48 +32 1fe8bacac294c2cd92ae344037cfbef1 +33 6c7bb5d439765aa827935f0a9c30c191 +34 a23c55a3a18cd25841a94cc1274a88b0 +35 3f85584b23ae0b066feaa9807f7747a6 +36 de965a6e5f2b1d4eceb29fe7d498523a +37 673d30e988d1763462bb8cec5072e380 +38 d2fcf3ff2a5f9864017fef2bb5a05c5d +39 ec46f5e4f819a877d7a61d8acdc1af97 +40 d76f11617d76be19ec70531a1fdae28b +41 1b072118cf99984328af6a13ef96e4ea +42 445eace6d5c4301ed8d009cf31030e05 +43 1ac33d84df6afec6c75a95382dcd9473 +44 a8e3dc125dae933ea7f6afbe74e04a6d +45 67ef0f777b36c383ae95fd0fa5df83e2 +46 17ec81ff421819fb05b18b5f3259ef72 +47 c9b9e688edb5bf91b5de3fd446c5526c +48 86500cced5eb721ba0bcbedbe547702c +49 797fb85261788a77f1a4a856647e279a +50 181620d50d83879682375cce010ca8e2 +51 5001d76625a7183805f575244c316687 +52 4d3378baeda0fadae4c0be4a386ecc9f +53 e7ab755f264702796b8cbcb57d806c31 +54 51c7391d9c36b40225cca64fc6aaa777 +55 3bbc949c3ad2cf6785a2032a721684b7 +56 95b444c09d7ff457e05b29915ab014eb +57 5be439d676f0efcc7a30b7312906f95e +58 1e6f0f1727a503dead421c990d1118ba +59 9042d95706aa05ce4654c75280555c5b +60 1b96f5a0867fe538a23904673299a4b5 +61 b0bca170c2cfb1d42f433c7ab34f4cc5 +62 1d7864fd510681fa73400f632ef3167e +63 4dbe2521dc0aab0379240ada9eae00af +64 0a2a2c1011680742952ed16c39c92e0e +65 9c47d20bcb81bde409ab540da68b4fbe +66 0980fcfa50aa96a255f18726ab63639d +67 537846ad552af92fb665f25fb184a82d +68 dcd7ea42463e20d4a116859a629dd036 +69 8ad529d3c9a8795b8e9806d4cf743c94 +70 369dd5b3cfddbf8fb498b537ef2ea84e +71 94ac66b3ad6bd88ba43f291e128e48dc +72 8be8f2eaf046ff7475b521255a4acdbe +73 b65c9b55b997efc3f246a20e6f005e58 +74 ee44978812881d19722bb98b8f1f2bc6 +75 2c304bae65b232e2d377334293e04d65 +76 1b8f9ab6f0e50bac0c51eb605d5cec54 +77 b430cf08119c05c439a57afe79ed9eb8 +78 53f7e9621d356c4ba57ede7adc39b2da +79 0e9480a63ae7ed82fe4c30350dc5595a +80 cb8f87d367adef49536a201a8542fc3e +81 5ef390cc5c59e46c1a3e6d189d1b6e2d +82 05e926b8029df73bde00db84d2c5309f +83 c1c6a9f312d5cd42da93ae2730783e1e +84 28eef3b8cbb99bd67c5fa6545176f5fd +85 67b0c7cf67759f56999433eae2153ece +86 016f00bb33bc6be3a872dfa322041c97 +87 45fec19d672193b7c6eb5545beaf3b1e +88 ef0854c71567b02a653c8442c991b2ae +89 7b3025ae3dd04fdc6450b0632157b94e +90 8268b2ed751724cf6f6703960fb394d9 +91 2183c0455126e0a056b343e321a268d3 +92 06812a2b314742eeeaf6b5294995a934 +93 5e90a46084b1e1d64a2397a9d6428809 +94 11f95b832a1656689c88778afc679669 +95 3e899bdb9d107bf3b56293a3c1830318 +96 c0fe74962a7d1fa78b47c59201857ca1 +97 1e3ed77c587b8c63f461663d7d5ff568 +98 c347349efa9eab02c5758810d479ec41 +99 96b5e3a2dddf9f4a5759213e88ba2eb7 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR10_SONY_A/Hi422FR10_SONY_B.264 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR10_SONY_A/Hi422FR10_SONY_B.264 new file mode 100644 index 0000000..9dc0f1b Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR10_SONY_A/Hi422FR10_SONY_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR10_SONY_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR10_SONY_A/riferimento.md5 new file mode 100644 index 0000000..ee6b299 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR10_SONY_A/riferimento.md5 @@ -0,0 +1,7 @@ +# Hi422FR10_SONY_B.yuv 352x288 4:2:2 8 bit, 5 fotogrammi, 1013760 byte +tutto b32b7847f791ce22bad747cff08ce398 +0 700c651b7b421466ed739d94120dc285 +1 87fd1ec1d6b497258a3c706a5eced702 +2 4d71f7c504b2d599f39d9104d0ea2c52 +3 82f8878cd8b0a1b086eba3ce9ca6f9d3 +4 92705052098dc49e275584cf44da1220 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR11_SONY_A/Hi422FR11_SONY_B.264 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR11_SONY_A/Hi422FR11_SONY_B.264 new file mode 100644 index 0000000..e1a2704 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR11_SONY_A/Hi422FR11_SONY_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR11_SONY_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR11_SONY_A/riferimento.md5 new file mode 100644 index 0000000..4fede13 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR11_SONY_A/riferimento.md5 @@ -0,0 +1,7 @@ +# Hi422FR11_SONY_B.yuv 352x288 4:2:2 8 bit, 5 fotogrammi, 1013760 byte +tutto f50fb1a31adf9985b864b959d890922b +0 700c651b7b421466ed739d94120dc285 +1 d55be8626a6c1b6d06de517607d16834 +2 cbd851ecf7fc904a945c6baabf11ac06 +3 1afaeb3c290dd5747b5356238b1ddebc +4 6ebeda354a6a72ec37234a0236695978 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR12_SONY_A/Hi422FR12_SONY_B.264 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR12_SONY_A/Hi422FR12_SONY_B.264 new file mode 100644 index 0000000..a197897 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR12_SONY_A/Hi422FR12_SONY_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR12_SONY_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR12_SONY_A/riferimento.md5 new file mode 100644 index 0000000..eb9a1df --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR12_SONY_A/riferimento.md5 @@ -0,0 +1,7 @@ +# Hi422FR12_SONY_B.yuv 352x288 4:2:2 8 bit, 5 fotogrammi, 1013760 byte +tutto 513afd34c94411f91dfecf2dd1880323 +0 7357b47d50df2ea56b1db2bf6c1580fa +1 f76b7b9d5ca5c59b3c0e4d81b1075e39 +2 5d1cff490c5780b2f6fd5e97b4daebc2 +3 4163cbdd44aee44aa7dfd1f1d74f4293 +4 0399a8b8543f72fb390c3eefb12c8130 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR13_SONY_A/Hi422FR13_SONY_B.264 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR13_SONY_A/Hi422FR13_SONY_B.264 new file mode 100644 index 0000000..6806fef Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR13_SONY_A/Hi422FR13_SONY_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR13_SONY_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR13_SONY_A/riferimento.md5 new file mode 100644 index 0000000..6f38151 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR13_SONY_A/riferimento.md5 @@ -0,0 +1,8 @@ +# Hi422FR13_SONY_B.yuv 352x288 4:2:2 10 bit, 5 fotogrammi, 2027520 byte +# oltre gli 8 bit ogni campione è di due byte, little-endian, come nel file ufficiale +tutto 412bad3d2624a83428571d1c7a6d6f92 +0 9cfd071d7d1c977643443a591d0ecdf5 +1 74086dc9d21bae75698e0fa28506a695 +2 f802c3f03dc09b8b9b2119106aa2c36f +3 b2f3f71ae242c34c7958cc8648434de1 +4 ebc03cf06c5fa2bce04670bca1914854 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR14_SONY_A/Hi422FR14_SONY_B.264 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR14_SONY_A/Hi422FR14_SONY_B.264 new file mode 100644 index 0000000..102507f Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR14_SONY_A/Hi422FR14_SONY_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR14_SONY_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR14_SONY_A/riferimento.md5 new file mode 100644 index 0000000..3a0b9ee --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR14_SONY_A/riferimento.md5 @@ -0,0 +1,8 @@ +# Hi422FR14_SONY_B.yuv 352x288 4:2:2 10 bit, 5 fotogrammi, 2027520 byte +# oltre gli 8 bit ogni campione è di due byte, little-endian, come nel file ufficiale +tutto 43913b65400b8af68f65aa2520666030 +0 9cfd071d7d1c977643443a591d0ecdf5 +1 13c2d055330f9cfc43d2a62c81242a18 +2 d61ba99334fe3dfb22cbb6a059aee1ef +3 0dc59ebedef25158b8431ce6e045eda0 +4 532c1e5ba4dbe8d0524aa5a356cff852 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR15_SONY_A/Hi422FR15_SONY_B.264 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR15_SONY_A/Hi422FR15_SONY_B.264 new file mode 100644 index 0000000..0a4e90e Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR15_SONY_A/Hi422FR15_SONY_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Hi422FR15_SONY_A/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR15_SONY_A/riferimento.md5 new file mode 100644 index 0000000..fe27dbd --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Hi422FR15_SONY_A/riferimento.md5 @@ -0,0 +1,8 @@ +# Hi422FR15_SONY_B.yuv 352x288 4:2:2 10 bit, 5 fotogrammi, 2027520 byte +# oltre gli 8 bit ogni campione è di due byte, little-endian, come nel file ufficiale +tutto 234509d38715eeed66b55fa8f03074f8 +0 a54167e66ce0c06d19ef085a8acb2d03 +1 59d3cdcba85f61c9b2c1c59554761390 +2 7ba47452c5f6c87f94681d92a1b40d2d +3 d57e3d30873ae8a7092086c9fef23f59 +4 5d2d9e7b0363f92d382bbe3bd0bf93bd diff --git a/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md new file mode 100644 index 0000000..bc75d8d --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/LEGGIMI.md @@ -0,0 +1,199 @@ +# Flussi di conformità H.264 + +Questi flussi provano il decodificatore H.264 scritto in casa (`src/Febe.Core/Codecs/H264`) e, ricomposti in MP4, +Matroska, AVI, FLV e MPEG dalle prove di `tests/Febe.Tests/Media/Containers`, anche i lettori dei contenitori e lo +scrittore MP4. + +## Provenienza + +Sono flussi della serie di conformità ufficiale **ITU-T H.264.1** («Conformance specification for ITU-T H.264 +advanced video coding»), pubblicata dall'ITU-T con i flussi di bit, i file `readme` dei loro autori e la ricostruzione +di riferimento di ogni flusso, in https://www.itu.int/wftp3/av-arch/jvt-site/draft_conformance/ (cartelle `AVCv1`, +`FRExt`, `Professional_profiles`, `MVC`, `SVC`). Nel repository stanno **solo i flussi e gli MD5** (decisione di +Alberto del 18 novembre 2026): ogni cartella contiene il flusso così com'è (Annex B: `.264`, `.jsv`, `.avc`, `.h264` o +`.jvt`, come l'hanno chiamato gli autori) e i suoi `riferimento*.md5`; mai i `readme` degli autori, le schede degli +strati SVC o le uscite decodificate. Ciò che le prove ne usano (profilo, formato, numero di fotogrammi, che cosa prova +ogni flusso) è nelle tabelle qui sotto. La cartella prende il nome dello zip. + +I flussi aggiunti il 18 novembre 2026 sono stati scaricati quel giorno; di ogni zip si è controllato il CRC-32 con +l'elenco dell'indice `00readme_H.264.1(2010).html` della stessa cartella, o, per gli zip letti a pezzi, il CRC-32 di +ogni file con quello scritto nello zip. I due flussi MVC sono file `.264` sciolti, nella versione del 2011, senza CRC +pubblicato. + +## Che cosa contiene `riferimento.md5` + +La prima riga dice da quale file YUV ufficiale vengono i valori, con larghezza, altezza, crominanza, bit per campione, +numero di fotogrammi e byte; le righe con `#` che seguono dicono che cosa è il riferimento quando serve. Poi `tutto` con +l'MD5 del file intero e una riga per fotogramma, nell'ordine di uscita: il numero del fotogramma e l'MD5 dei suoi +campioni così come stanno nel file ufficiale (Y, poi Cb, poi Cr, ritagliati; per 4:2:0 a 8 bit è l'I420). Oltre gli 8 +bit ogni campione occupa due byte little-endian; il 4:2:2 ha i piani di crominanza larghi la metà e alti quanto la +luminanza; i due flussi monocromatici hanno nel file ufficiale anche due piani di crominanza 4:2:0 tutti a 128, e +l'MD5 li comprende. Nei flussi a campi ogni fotogramma del file ha i suoi due campi intercalati riga per riga. + +I valori sono calcolati una volta dai file YUV ricostruiti ufficiali, che **non sono nel repository** (pesano molto più +dei flussi e non servono: basta il loro MD5). Una prova passa solo se ogni fotogramma decodificato ha esattamente l'MD5 +del riferimento. + +- **SVC**: `riferimento.md5` è lo strato di destinazione, il più alto del flusso (`-L2` o `-L1`, ciò che dà un + decodificatore SVC dal flusso intero); `riferimento-base.md5` è lo strato base `-L0`, che è H.264 puro: è ciò che deve + dare un decodificatore H.264 che salta le unità NAL 14, 15 e 20, e lo si prova già. +- **MVC**: la cartella MVC dell'ITU-T contiene solo i flussi, senza ricostruzione né `readme` (gli zip che l'indice del + 2010 elenca non sono sul server). `riferimento.md5` lo dice e non ha fotogrammi; il riferimento atteso, quando ci sarà, è + quello di tutte le viste. Per ora le prove controllano che tutte le viste si decodifichino (vedi sotto). + +## I flussi verificati + +`H264ConformanceTests.FramesMatchTheReference`: 4:2:0 a 8 bit, poi 4:2:2 a 8 e 10 bit e 4:0:0. A immagini intere, sulla +sequenza «Foreman»: + +| Flusso | Profilo, formato | Che cosa prova | +|---|---|---| +| `BA1_Sony_D` | Baseline, QCIF, 17 fotogrammi | CAVLC, un riferimento, IDR solo all'inizio, deblocking attivo | +| `SVA_BA1_B` | Baseline, QCIF, 17 | CAVLC, POC di tipo 2, fino a 5 riferimenti | +| `BA3_SVA_C` | Extended, QCIF, 33 | CAVLC con slice B, predizione diretta spaziale, 5 riferimenti | +| `BASQP1_Sony_C` | Baseline, QCIF, 4 | 20 slice per immagine con QP diverso per slice | +| `CI_MW_D` | Baseline, QCIF, 100 | CAVLC, IDR ogni 30 fotogrammi, 4 riferimenti | +| `CABA1_SVA_B` | Main, QCIF, 17 | CABAC, slice I | +| `CABA2_SVA_B` | Main, QCIF, 17 | CABAC, slice I e P, 5 riferimenti | +| `CABA3_SVA_B` | Main, QCIF, 33 | CABAC con slice B e predizione diretta temporale | +| `CANL1_SVA_B` | Main, QCIF, 17 | CABAC, POC di tipo 2, deblocking spento | +| `FRExt1_Panasonic_D` | High, CIF, 8 | CAVLC, solo trasformata 8×8, matrici di quantizzazione di sequenza e di immagine, slice B con diretta spaziale, SPS ripetuto | +| `FRExt3_Panasonic_E` | High, CIF, 11 | CABAC, trasformata 8×8 e 4×4 adattiva, matrici di quantizzazione, slice B con diretta temporale | +| `HCAFR1_HHI_C` | High, CIF, 10 | CABAC con inizializzazione adattiva (`cabac_init_idc` 0, 1, 2), trasformata 8×8, matrici predefinite, slice B | + +Immagini interlacciate (campi, PAFF, MBAFF). Ogni fotogramma esce con i due campi intercalati riga per riga; un campo +rimasto senza il suo compagno esce da solo, con le righe dell'altro campo grigie (128). + +| Flusso | Profilo, formato | Che cosa prova | +|---|---|---| +| `CVFI1_SVA_C` | Main, 720×480, 7 | solo campi, CAVLC, slice I e P, 5 riferimenti | +| `FI1_Sony_E` | Main, 192×128, 17 | solo campi, solo slice I, CAVLC | +| `CAFI1_SVA_C` | Main, 720×480, 33 | solo campi, CABAC, slice I, P e B | +| `Sharp_MP_PAFF_1r2` | Main, 720×480, 15 | PAFF (fotogrammi e coppie di campi), CAVLC, POC di tipo 1, diretta spaziale | +| `HCAFF1_HHI_B` | High, CIF, 10 | PAFF, CABAC adattivo, trasformata 8×8, slice B con diretta spaziale | +| `CVMAQP3_Sony_D` | Main, 192×128, 17 | MBAFF, CAVLC, slice B, QP diverso per macroblocco, SEI | +| `FREXT02_JVC_C` | High, CIF, 16 | MBAFF, CAVLC, 8×8 adattiva, `mb_type` 0 con CBP 0 | +| `CAMACI3_Sony_C` | Main, 192×128, 17 | MBAFF, CABAC, predizione intra vincolata | +| `CAMASL3_Sony_B` | Main, 192×128, 17 | MBAFF, CABAC, 4 slice per immagine, diretta spaziale | +| `HCAMFF1_HHI_B` | High, CIF, 10 | MBAFF, CABAC adattivo, trasformata 8×8, slice B | +| `FREXT01_JVC_D` | High, CIF, 16 | MBAFF, CABAC, 8×8 adattiva, `mb_type` 0 con CBP 0 | +| `CAPAMA3_Sand_F` | Main, CIF, 50 (il `readme` dell'ITU-T dice 30) | PAFF e MBAFF insieme, CABAC, diretta temporale | +| `cama1_vtc_c` | Main, 720×480, 4 | primo fotogramma a campi con il campo inferiore per primo, poi MBAFF, CABAC | +| `FRExt2_Panasonic_C` | High, CIF, 15 | campi e MBAFF alternati, CAVLC, matrici con le regole di ripiego, MMCO, riordino, B di riferimento | +| `FRExt4_Panasonic_B` | High, CIF, 10 | campi e MBAFF alternati, CABAC, solo 8×8, matrici con le regole di ripiego | +| `MR6_BT_B` | Extended, 192×128, 60 | campi, CAVLC, POC di tipo 1, MMCO, riordino, numero di slice variabile | +| `MR9_BT_B` | Main, 192×128, 58 | MBAFF e PAFF, CABAC, slice B, POC di tipo 1, MMCO, riordino | + +Strumenti di Baseline ed Extended, QCIF 4:2:0 a 8 bit: + +| Flusso | Profilo, formato | Che cosa prova | +|---|---|---| +| `FM2_SVA_C` | Baseline, 17 | FMO con 3 gruppi di slice di tipo 0, ASO, POC di tipo 1 | +| `FM1_FT_E` | Baseline, 300 | FMO di tipo 1, 2, 3 e 4 che cambiano lungo il flusso (11 PPS), POC di tipo 2, SEI di recupero graduale | +| `FM1_BT_B` | Baseline, 400 | FMO di tutti i tipi da 0 a 6, ASO | +| `sp1_bt_a` | Extended, 400 | slice SP (39 immagini) con QS diverso da QP e deblocking spento, POC di tipo 1 | +| `sp2_bt_b` | Extended, 400 | slice SP con deblocking attivo | + +Nessuno di questi flussi usa la predizione pesata, i salti di `frame_num` o gli I_PCM: quelle parti del decodificatore +non hanno qui un riferimento ufficiale. Le slice SP dei due flussi hanno tutte `sp_for_switch_flag` a 0. + +Per gli strumenti che nessun flusso della serie usa, `H264ExtendedToolsTests` riscrive flussi verificati con +`StreamRewriter`, lasciando intatti i bit dei macroblocchi, e chiede di nuovo il riferimento ufficiale: + +- **partizionamento dei dati**: ogni slice P, B, SP o I non IDR divisa nelle partizioni A, B e C (`BA3_SVA_C`, + `sp1_bt_a`, `FM1_FT_E`, `MR6_BT_B`, `CVMAQP3_Sony_D`, `SVA_BA1_B`); senza B o senza C il flusso si decodifica ancora, + senza il residuo che mancava; +- **slice ridondanti**: dopo ogni immagine una copia ridondante con dati a caso, che il decodificatore deve saltare + (CAVLC, CABAC, campi, MBAFF, FMO, SP, e anche partizionate); +- **ASO**: le slice di ogni immagine in ordine inverso (`BASQP1_Sony_C`, `FM1_FT_E`, `CAMASL3_Sony_B`). + +Le slice SI e `sp_for_switch_flag` a 1 non hanno flussi: le prova un flusso sintetico di +`H264SyntheticStreamTests`, con i valori calcolati a mano dalle equazioni di §8.6.2. + +Formati di High 4:2:2 e High, CIF; oltre gli 8 bit due byte little-endian per campione. + +**4:2:2, 8 e 10 bit** (High 4:2:2), 5 fotogrammi ciascuno: + +| Flusso | Che cosa prova | +|---|---| +| `Hi422FR10_SONY_A` | 8 bit, solo slice I, CABAC, trasformata 8×8, matrici | +| `Hi422FR11_SONY_A` | 8 bit, slice I e P, CABAC, 8×8, matrici | +| `Hi422FR12_SONY_A` | 8 bit, slice I, P e B, CABAC, 8×8, matrici | +| `Hi422FR13_SONY_A` | 10 bit, solo slice I, CABAC, 8×8, matrici | +| `Hi422FR14_SONY_A` | 10 bit, slice I e P, CABAC, 8×8, matrici | +| `Hi422FR15_SONY_A` | 10 bit, slice I, P e B, CABAC, 8×8, matrici | +| `FREXT2_TANDBERG_A` | 8 bit, slice I e P, CAVLC, deblocking attivo | +| `FREXT3_TANDBERG_A` | 8 bit, slice I, B e P, CAVLC | + +**Monocromatico 4:0:0** (High), 100 fotogrammi: `HPCAMOLQ_BRCM_B` (CABAC) e `HPCVMOLQ_BRCM_B` (CAVLC), con +slice B, diretta temporale e matrici di quantizzazione; escono con i due piani di crominanza 4:2:0 al valore medio, +come nel file ufficiale. + +Le parti dei profili High che la serie qui non ha con la ricostruzione (4:4:4, piani di colore separati, codifica senza +perdita con la sua DPCM, profondità da 11 a 14 bit, 10 bit in 4:2:0) le prova `H264FormatTests` con flussi sintetici +di I_PCM e di Intra_16x16 senza perdita, i cui campioni si conoscono esattamente. Il CABAC in 4:4:4 con i piani insieme +non è gestito (mancano i contesti 460–1023) e il decodificatore lo rifiuta. + +**SVC** (Scalable Baseline; lo strato base è Baseline). `H264ConformanceTests.SvcBaseLayerMatchesTheReference`: lo +strato base dei tre flussi qui sotto, con `riferimento-base.md5`, chiesto al decodificatore con +`DecodeEnhancementLayers = false`. In `FramesMatchTheReference` c'è anche lo strato di destinazione di: + +| Flusso | Formato | Che cosa prova | +|---|---|---| +| `SVCBMT-13` | 352×240, 20 fotogrammi | qualità MGS su tre livelli (L0, L1, L2, CAVLC), slice I e P, `adaptive_base_mode_flag`, `adaptive_motion_prediction_flag` e `adaptive_residual_prediction_flag`; strato L2 | + +## I flussi delle parti ancora da fare + +`H264ConformanceTests.FeaturesStillToDo`: la prova è **inconclusiva** con un messaggio che comincia sempre con «da +fare: …» (anche quando manca il riferimento, come per MVC), così la serie resta verde e il vuoto si vede. Nella CI +`.gitea/scripts/riepilogo-prove.sh` conta a parte, come «da fare», solo le inconclusive di `FeaturesStillToDo` il cui +motivo comincia con «da fare: »; ogni altra inconclusiva è una prova saltata, e la CI non ne ammette. Quando uno di questi flussi +coincide con il riferimento la prova **fallisce** apposta, per ricordare di spostarlo fra i flussi verificati. + +**SVC**: per questi due il decodificatore dà lo strato base e dice perché non va oltre +(`EnhancementLayersSkipped`); `SvcLayersNotWrittenYetLeaveTheBaseLayer` controlla che lo strato base esca esatto anche +dal flusso intero. + +| Flusso | Formato | Che cosa prova | +|---|---|---| +| `SVCBST-19` | 320×240 (30) e 640×480 (60) | scalabilità spaziale di rapporto 2 e temporale: P gerarchiche nello strato base, B gerarchiche in CABAC sopra | +| `SVCBCT-1` | 320×240, 150 e 300 | qualità CGS e scalabilità temporale: P gerarchiche nello strato base, B gerarchiche in CABAC sopra | + +Mancano, per questi due: `dependency_id` maggiore di 0 (la predizione fra strati di §G.8.6 con il sovracampionamento +di tessitura, residuo e moto, e per CGS la stessa senza cambio di risoluzione), i contesti CABAC di `base_mode_flag`, +`motion_prediction_flag_l0`/`_l1` e `residual_prediction_flag` (i loro valori iniziali non sono ancora trascritti +dallo standard); le slice B negli strati di qualità sono scritte ma senza un flusso che le verifichi. Non li usa nessuno dei tre flussi, e il decodificatore li +lascia allo strato base: immagini chiave (`store_ref_base_pic_flag`, `use_ref_base_pic_flag`), `scan_idx_start` e +`scan_idx_end` diversi da 0 e 15, `tcoeff_level_prediction_flag`, trasformata 8×8, interlacciato e formati diversi dal +4:2:0 a 8 bit negli strati di qualità. + +**MVC** (Multiview High; la vista base è High, 640×480, 9 fotogrammi): `MVCDS-4` (due viste, `view_id` 0 e 2) e +`MVCNV-3` (tre viste), senza riferimento. `MvcDecodesEveryView` controlla che ogni vista dia 9 fotogrammi della misura +della vista base, che la vista base sia identica a quella che dà il decodificatore con `DecodeAllViews = false` (H.264 +puro) e che le altre viste siano immagini pulite della stessa scena (scarto medio dalla vista base fra 0 e 40, bordi +dei blocchi sotto 1,5 volte la media interna); l'esattezza resta da verificare. + +## Lasciati fuori, e perché + +- **Partizionamento dei dati (A, B, C), slice ridondanti, slice SI**: nessun flusso della cartella li usa. Si sono letti + i flussi di tutti gli zip di `AVCv1` e `FRExt` (tranne `FREH10-1` e `FREH10-2`, High 10, profilo che quegli strumenti + non li ammette): nessuna unità NAL di tipo 2, 3 o 4, nessun PPS con + `redundant_pic_cnt_present_flag`, nessuna slice SI. I soli flussi Extended sono `BA3_SVA_C`, `sp1_bt_a`, `sp2_bt_b` e + `MR6_BT_B`, `MR7_BT_B`, `MR8_BT_B`. Si provano riscrivendo i flussi verificati (vedi sopra). +- **High 10 in 4:2:0**: `FREH10-1` e `FREH10-2` (1920×1088, flussi da 98 e 34 MB) e `PPH10I1`–`PPH10I7` (High 10 Intra) + non hanno la ricostruzione. I 10 bit si provano con `Hi422FR13`–`Hi422FR15`. +- **High 4:2:2 Intra e altri 4:2:2**: `PPH422I1`–`PPH422I7`, `Hi422FR1`–`Hi422FR9` e `Hi422FREXT16`–`Hi422FREXT19` non + hanno la ricostruzione (gli zip portano solo flusso, `readme` e tracce). +- **4:4:4** (High 4:4:4 Intra, High 4:4:4 Predictive, CAVLC 4:4:4 Intra), con `separate_colour_plane_flag` e la + codifica senza perdita (`qpprime_y_zero_transform_bypass_flag`): i soli flussi sono quelli di + `Professional_profiles` (`PPH444*`, `PPCV444*`, i `.bits` del 2008), tutti senza ricostruzione e da 8 a 113 MB + ciascuno. Senza riferimento non si possono verificare, e così peserebbero da soli più di tutto il resto. +- **MVC Stereo High**: nella cartella non c'è; tutti i flussi MVC sono Multiview High. Degli altri (`MVCDS-1`..`3`, + `MVCICT`, `MVCRP`, `MVCNV-1`, `-2`, `-4`, `MVCSPS`) nessuno ha la ricostruzione: se ne sono presi due piccoli. +- **SVC con più strati o Scalable High** (`SVCH*`, `SVCBS-1`..`8`, `SVCBM*`, `SVCBMST*`, gli altri `SVCBST*`): gli + zip vanno da 5 MB a quasi 2 GB per via delle ricostruzioni e delle tracce; i tre scelti coprono spaziale, CGS, MGS + e temporale con flussi piccoli (da 77 a 475 KB). +- **Altri flussi interlacciati** (per esempio `CVPA1_TOSHIBA_B`, `CAMA1_TOSHIBA_B`, `CVMANL1_TOSHIBA_B`, da 1 a 1,5 MB): + le stesse parti sono già nei flussi scelti, più piccoli. La predizione pesata nei campi e in MBAFF + (`CVMP_MOT_FLD_L30_B`, `CAMP_MOT_MBAFF_L30`) resta fuori, come la predizione pesata in genere: va coperta con una tappa + a parte. diff --git a/tests/Febe.Tests/Media/H264/Conformita/MR6_BT_B/MR6_BT_B.h264 b/tests/Febe.Tests/Media/H264/Conformita/MR6_BT_B/MR6_BT_B.h264 new file mode 100644 index 0000000..e4d19b3 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/MR6_BT_B/MR6_BT_B.h264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/MR6_BT_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/MR6_BT_B/riferimento.md5 new file mode 100644 index 0000000..dc0d827 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/MR6_BT_B/riferimento.md5 @@ -0,0 +1,62 @@ +# MR6_BT_B.yuv 192x128 4:2:0 8 bit, 60 fotogrammi, 2211840 byte +tutto d2ef83e72a57df1cc5266a0be646463f +0 8a119ab41fd73c26194da703369ed2f6 +1 abd4f792024af9498b38001e615d9c78 +2 9a1a91f6d5c0177b85cfb88af94241f6 +3 d906a7dc5afb6794ffbf19346e3a99cd +4 3a06da7b4a08fe5fb550c998ec27d587 +5 3025a0c0cf1ac8448b5e66616b26185b +6 b2001a02ab19a016f21b916d16ed9829 +7 1cc5adb266e751385e17fd71570ba040 +8 2abe0edb1b466c4201cc8d2d9c80ba85 +9 4af95b11af17cb95098212246bc24f0e +10 fa46f57ac296f9767ac4e17fe8181a3c +11 f9522b4ca5494c02a1bd0fa252378097 +12 a23d8e9a5c284a0ae22a7e894b5c740a +13 48cebbeecbbc182b3ce113ff572361d2 +14 8ad719a4efd321fcd1b6537f6a16e456 +15 70dd5ad8ea76d12e4c2f1fa035dec406 +16 eaf03082cf6bacc40d82d90b83ad4b29 +17 c1a7556d6335e12b32ba144465641459 +18 d12755a4aece7f8600185aec16980b34 +19 3792b2ce4468702b985094051be8180c +20 efa6cf953432349bc8e2daa572e50bb7 +21 4587607b4adbcdbdfe1e934fc20e490e +22 db05ca1ad872c5b9c3dd2a3e3e4e704f +23 e71e6790da32bb7ad160384eed3bf205 +24 2fe8fe69b797319c5998607da400df8a +25 23f1adc5c7261ce3a1b5d24757351d12 +26 af10067625eab206db687cc27f3c5945 +27 2284b9ea6c18ea1074aab06174fdb3fd +28 426419d7e11d09a259a9602a63f9230b +29 d03d0a704256560a4b8784e374e007c5 +30 12286c4a5792305251e0d5ca7dca70bc +31 83608260e033a15d742fd81cf86edd3b +32 9d44c84f722f336115b1461b4f5c3f78 +33 55779908445c656c16772049df346be5 +34 b58f1990aa57e14b662f61b989f9b96a +35 1a6efb1dac18b0f62267bf22cc30cfba +36 e4eae04c7ddb7f6ee93e504dac536673 +37 ea708048a719154f78cc61b14dc76469 +38 78ac05b5187bea84017bd00eda506820 +39 01f3b61d67aede49deaa0cf8d112d0d2 +40 a8cdac8ebe376eca137c6a4ef3fd1b2e +41 546707622dd17c8ddc9054ee58fa19cd +42 cc23fd5456e978e148824c0fedb00c89 +43 87df1a40f3062b74a2fbd2059c870c52 +44 795d0c49b88f490de936f36bf02e37dc +45 08092f1b401b4dbe32b7f3a63cf64bef +46 5baaba3190c20febe28ac7691fa418ca +47 c5e6d5df4923c3493618642946137a64 +48 eb8c250d4bf5fbb6cc238ff422bc0a52 +49 911fd2c8c6cf36e9a30bcc80be69db7e +50 9fd86fdb8ab91c01e26db8b13a2d7ff4 +51 f3fe86917e18a1d8d60f394c4a362a03 +52 8a119ab41fd73c26194da703369ed2f6 +53 abd4f792024af9498b38001e615d9c78 +54 9a1a91f6d5c0177b85cfb88af94241f6 +55 aad4f12ee0a8d4a80b7a3f88d989b342 +56 30fe875e4ecb8b40cd5edc753d232e15 +57 47cb6cdafb5533fed10e265815a3db16 +58 16ec0e74a2d5c437cd824fa02d815fa2 +59 2a9736d7642884e78095d27d8f093198 diff --git a/tests/Febe.Tests/Media/H264/Conformita/MR9_BT_B/MR9_BT_B.h264 b/tests/Febe.Tests/Media/H264/Conformita/MR9_BT_B/MR9_BT_B.h264 new file mode 100644 index 0000000..80392fa Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/MR9_BT_B/MR9_BT_B.h264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/MR9_BT_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/MR9_BT_B/riferimento.md5 new file mode 100644 index 0000000..b600b4b --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/MR9_BT_B/riferimento.md5 @@ -0,0 +1,60 @@ +# MR9_BT_B.yuv 192x128 4:2:0 8 bit, 58 fotogrammi, 2138112 byte +tutto c1ae4e809894d01cc4f5e6b0bb8df99e +0 0330d7071f03cd2094eeb6a661520093 +1 46706de4d76bb3bfc7e47065e82da638 +2 cb911a7356f97adea6b8f17d06a00ed8 +3 1d9905e089a1e83867cc135fc7fd1e48 +4 ded3fb0b1246508b9a878335c70299a8 +5 96bff87c28deacd508e9f80a58754085 +6 eb0fd15cb315465acbcc4da88f29aafb +7 3991a78a724127856485ef5a1cb7e736 +8 8c696a20531591ef1bd188ad5a606100 +9 0afd05aaa745e2df249a1985249d9b2a +10 ec880d398583af61d3a7907473cfdea4 +11 420f77203c98618123d462e34fbf87b1 +12 603f1bc536634904d75b78d1ff90e146 +13 621eb25254a3f0f4068d08881552dbb8 +14 c3b0a7c247f7203dfbdfd0a05e0442e5 +15 c756d9022d8963def2d9f84a06744fb8 +16 c122a3dd5eac813854a1efb246cc13bf +17 9371a99f493f13cfaf806994a9d7eb2d +18 0bceec0cebe1276163bc1722a3c6bd93 +19 5d71ff6522a7f753bf524323d24cc02f +20 5f4fca1590fc55fd249531413897eb3a +21 4b3d8db98174c36f2f4ce819e32b5ce8 +22 90ffa593a1eac13d37e9407dc03c746f +23 30466f49a85fad0793aad5d321d9e659 +24 0cd0928ad4eaa4293c92b342204f8e4c +25 52304d54d7f0bb9e117adcc01131a5ad +26 7119d898822bfa6b0c29df08b2bc652b +27 e91acde7e2d1e20f2cb100b9e4aad73e +28 3a0ec00b0f454b352a22ca69ba69a93a +29 defa0a2da40a1f91f6f2e005d76e8465 +30 e029eb60ce485e23cf8bd647286c3de3 +31 ed82b8472dfc3238242aa42f512dbed3 +32 5e52b54b75b235f7728302f807ae91b4 +33 304794788e7b718424ad9d03c426e8e5 +34 d362d29c297ec54dd81602d3958144fe +35 a7514ad60d89a376399d4c0fd5f6a15c +36 f88468326a1ab4fc4b9517e48f207d98 +37 d46a3d56e3bbcf470eb293e1b5fc5209 +38 2ac803275a4e16a339dec40f39b6adb0 +39 c9f1929d0a56bdd5e11a3324cffe0c1e +40 09dc1016c52f039130f5d4721f58ac0d +41 fb3b4a4eba4d0054e8bcd6db343e2221 +42 ef7153f4224a136e74df20a572f34447 +43 f2e65350140785a76a459e2935a83beb +44 7d029c32c698f86bc9b4d5b3428123b0 +45 8af51f8b0aef4a6b5bcf9dfe2abff908 +46 fbe4015e8deabb3b0ad0dee2115664ca +47 89eb458c57cd630f0bd5a7ab47bfdbb4 +48 580701a3288d0adc031b0fa43c192820 +49 1969845904e3351a3e5838bf25a05c45 +50 c3a53f17c3057c352869bd8278ccf997 +51 6c79eaf7c5a72c470fad37e83294d0f6 +52 9d09e2b3a2bbc13e6cf004c1c2479e21 +53 453e5804a9ea63779df38599c173a16d +54 8c39f397491665a261f3b7d67cae2436 +55 b2e723e5578bbae0769feeb74e8c6351 +56 ee2ba45de23856c711c41011ab34db17 +57 94d8202049448f0a5d5538ed5bb51052 diff --git a/tests/Febe.Tests/Media/H264/Conformita/MVCDS-4/MVCDS-4.264 b/tests/Febe.Tests/Media/H264/Conformita/MVCDS-4/MVCDS-4.264 new file mode 100644 index 0000000..ce23f53 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/MVCDS-4/MVCDS-4.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/MVCDS-4/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/MVCDS-4/riferimento.md5 new file mode 100644 index 0000000..96567b4 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/MVCDS-4/riferimento.md5 @@ -0,0 +1,2 @@ +# MVCDS-4.264: nessuna ricostruzione ufficiale: la cartella MVC della serie ITU-T contiene solo il flusso +# riferimento atteso, quando ci sarà: tutte le viste, la vista base e poi le altre, nell'ordine di uscita diff --git a/tests/Febe.Tests/Media/H264/Conformita/MVCNV-3/MVCNV-3.264 b/tests/Febe.Tests/Media/H264/Conformita/MVCNV-3/MVCNV-3.264 new file mode 100644 index 0000000..00e7457 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/MVCNV-3/MVCNV-3.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/MVCNV-3/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/MVCNV-3/riferimento.md5 new file mode 100644 index 0000000..1ded9d9 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/MVCNV-3/riferimento.md5 @@ -0,0 +1,2 @@ +# MVCNV-3.264: nessuna ricostruzione ufficiale: la cartella MVC della serie ITU-T contiene solo il flusso +# riferimento atteso, quando ci sarà: tutte le viste, la vista base e poi le altre, nell'ordine di uscita diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVA_BA1_B/SVA_BA1_B.264 b/tests/Febe.Tests/Media/H264/Conformita/SVA_BA1_B/SVA_BA1_B.264 new file mode 100644 index 0000000..8bc3988 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/SVA_BA1_B/SVA_BA1_B.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVA_BA1_B/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVA_BA1_B/riferimento.md5 new file mode 100644 index 0000000..fdd7efd --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVA_BA1_B/riferimento.md5 @@ -0,0 +1,19 @@ +# SVA_BA1_B_rec.yuv 176x144 4:2:0 8 bit, 17 fotogrammi, 646272 byte +tutto dab92aa2145ab44abab2beb2868dd326 +0 f4b78c62fc4e4c8e3ad1b1c9d8b3b7fc +1 d6e4e2884278e6e6b5123c864d31e6da +2 95e687587e8c01c63de9ab626da0aa8d +3 470ca42c33a69b553049eae29eceba6b +4 847b277a3e040cd063c6f84a12ef2fa7 +5 bfa974c51d336b909cbd2a9a2528ce59 +6 66c47f41c757e8f3f699289c59635647 +7 2eb32080bea4ec71241cba602e24cadd +8 03306a95228efea1d2ee7b60b65c1eb4 +9 adefe3fe4cd1407c3f4bab3a5dbed5cb +10 ce58ea99a0bb65ad4e7063104ef1fb18 +11 9dbc055a6939bcf567334ce31fe67f7d +12 f66d8a56cb565d15b0b8786b602413f5 +13 921cdefd3b49730bc2ddd7cba992fd7f +14 26f6da4ba31f677fbf413e3b846dc82a +15 5811e32f49e50934a61c673a5be32287 +16 6b0799522c2808d08ad81d7483e486c2 diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/SVCBCT-1.264 b/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/SVCBCT-1.264 new file mode 100644 index 0000000..55e73ba Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/SVCBCT-1.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/riferimento-base.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/riferimento-base.md5 new file mode 100644 index 0000000..e8d1884 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/riferimento-base.md5 @@ -0,0 +1,153 @@ +# SVCBCT-1-L0.yuv 320x240 4:2:0 8 bit, 150 fotogrammi, 17280000 byte +# strato base (dependency_id 0, quality_id 0, AVC): ciò che dà un decodificatore H.264 che salta le unità NAL 14, 15 e 20 +tutto cd4fe22dbc80483f38f1cf9f6574d4ca +0 a1a8ca927c3e872549f0b74f7b8c82b9 +1 a9c1a691c2dd208ae539ff29d4397fcf +2 163930ae611151dda5c08362fe7db47d +3 e6a5215d94a44a5ed6d9bd85d82d55fc +4 58f794b3fb8af4d4c737dbd545998d2d +5 b769c1b2e7002474037b02fcecdd62c2 +6 620434cebf7c953917b5213a4ab9b9ad +7 e3d86613d3ce22084aa890953f8a5123 +8 bd1ae282c0fb8d4b125c3b4932b3fa66 +9 101f1d7630d4a623818d6cc2dfad4e28 +10 8b999bcf3a2cf550179a2f7d97b69e6f +11 3d5ce0c11f9383f7b42d9f3b939050b9 +12 c5c7d5fe7e4582a350ca99d67e75f5a3 +13 4d1b44a18d02f849b3ae4bba950b90cf +14 6aee93d158d4ab7263ac759997fb1fd7 +15 399d3fc6479e449d2d230357dbe46056 +16 e278533b88045b6502615f7a2b979c44 +17 19d79e0ab803e5aaac6367e80b4291af +18 e9325ca04901b425432d202bd05bf65c +19 db00d734910f4be546ee8b92cd9d056a +20 8fee611eeb870b5ce887699972736bf7 +21 50cdb5b89dd47e78ba1db979272a4177 +22 e5cfd82f91bc4669aa8a72206b578b23 +23 1063c42c2951bd480a84488e8b611a4b +24 4ea1cb9e6df88321257428ecf3b2a483 +25 e709048c7f7f4166bf6631939f655062 +26 9b42424a952f9f82b3635744ef3ccdf3 +27 654fda523b4ac1c30892be555d749b6a +28 04585f2a3310e0a8d20ce382ba315ebd +29 eb892f9d2fd632657104da863691e224 +30 ae8ba87118e4daf04ccb930c27f3fc22 +31 14128911be3aa68866f36a9979470226 +32 75a17a907892ed99dae681939b1dd729 +33 54b43e9a198ee33f157883adf197006c +34 aafa455255589ac37526281f67bd3cd1 +35 8a20bc688b247466b744592df129d313 +36 ef2e19a50a2b19f0683e0bcc39c056a1 +37 3aef8267f106dd5a70644bfbbe78c0c9 +38 05972b581c316b28105efb5d940f86d4 +39 a65675e6d756c0586bed4206303a1a75 +40 9a11ec9d85d871fa2065dc8b40c55569 +41 1a3d1db915bfb11b5cdfbdf0e4d4cb83 +42 e48ab590e364639cfdfd833a05b38e70 +43 eaed9f75104227dfd07d03726c035ee1 +44 4a9d501a4a73df71c5a3fe09285512e4 +45 0a4a828d1d2e74eda474646dcf37f771 +46 b2ab3ca5f5382adad6b35be114c87965 +47 ede618f935d473435a4b21ffd5a8c850 +48 89a36fe78202b908509d60c820535ab2 +49 8d0884cb8f8ecd71c8052ebc991d56e1 +50 00397ea80257305bbffe3aaefb947bae +51 409e7041f214483c2d6a29d6abe51f4a +52 518f468b937f66ee9dc2fc5746fe730e +53 ec63e56f6399f9c5263fff48e9e4991c +54 41c1648c5b0f55e2cdeffe80bbb14532 +55 bf21c00aebc4fb4a97c6cf4b41bc5e04 +56 24d596f8d3c4b3fa3a12b8faf42812dc +57 caa7261a69a8daf714507c348d4b22d4 +58 08be17c30be620d564a5e512cd12dd77 +59 c1ba64b0e61ccbfdd3a5bb545893d257 +60 bcc23b3e86ce67b449d27dab462e0c7f +61 2a4586a326c0173e105499045ce49766 +62 ad7d5da24d51c51739b366c3ad119ebe +63 c7054016bef63a429f734d028ef3536f +64 7bca4209daa26fc42c5a8571933ce3ea +65 b8c6dcb107962f894095a04bd6dd5e46 +66 9c562fa3214f10029fb268df7939eeb0 +67 8b9ea6db32c0ae0cd41ac9a4037bb82d +68 9c9057812ec027f635a34d281a82cd7b +69 b57518d56dbf5149dc0137be044db881 +70 540cfc51c29c6cbd70ff37f624c34e7e +71 a4ae86dca826845219dabd603a30251f +72 83aac1e02e1ce9e3ca77fc83dbf81d78 +73 169f1096f5ff98486f5c5c98307484bb +74 bceec783f08d59145c3f60cd75af3f48 +75 b3ef0d4d0407d57aa98163b4c1a47f98 +76 fd4cd68e3c2780c13d5d55c742ca0b1b +77 05914eaf1a90a8ae2b61191019713165 +78 47bd033c2ab829177b4fa8c7951dc7d7 +79 654fd3f0760e6ff6c20cd714068c3d57 +80 ce2b8211cba7548f30b0b0eea01f1457 +81 b5100e67e7bcf28f952b7546d731372b +82 7b47cb13418a3e604e98bee2b9275707 +83 1b058b991e64809e088eeea995342f5b +84 92ba21ea97262a1efbb4fea58aeb458c +85 2418b37f69f6d27b38d7d9b69fd408e2 +86 d656844365fef933a2a55a8da4548610 +87 5ab18955904ede8b6e1aa61517969465 +88 e83fd978793c70df95409a1eaf2e66f7 +89 591c69d64e8019a3f2c23f89bb1ded6a +90 3cebc7b31457b314ee19b8e32e7c3336 +91 cb671f62ecca4a42c64b16a8063caea0 +92 409cab9f5fb17b15b678ee82fd1a43d3 +93 0cf29030e7285c8fc8f214ecf656a3b6 +94 ab0f43a7958f25b4f152a1eedb002a92 +95 3249fb85d821574da9c9f97b2a9ab5c6 +96 b37461f8519c40841ea3c47a4cc26dc3 +97 5776b724f0ed92ea56f2e6db9fbaa78b +98 2be6e46728a114a7c8817491a14e0b38 +99 ec22ad760a75e42e1d592ddef5638156 +100 075f3013e37e5fa171573487f315999f +101 5c4d7c0018c911765d17287165ca3bad +102 d932882265012f22b1d33ca23ebb5f9e +103 4be796d0ef13a9361853ed78015363dc +104 395f833e1bcb8858d7e8f12007684404 +105 3d6a5049d6088694f2d0bdd807147acb +106 99aff430d662868f6ca38a80efeef4fe +107 f85ce13ed154a07f69990666bd6ab9ae +108 6ce91b162ff9992960d8053efd0b2a33 +109 8903d302e35f63982dfb3cf78d83dd89 +110 bcbbc31ec0f16e6e684de7f7b92ddc57 +111 70b9e69cf7131ae33e71cf3d6fc4dcb8 +112 08dc87eeebe374c6dc1a6c87f336d95d +113 e9d4aa9fce0798cc0074bebdcd1f489e +114 fda4e0fdb07e77b747d26546e249b883 +115 e2770ce078fb342f8d98acaca82b98dd +116 1f14b4167a6cef2d8f02ef884437cd9f +117 127988de27ce29a267b1b2587fb7ffe8 +118 f70340d38ef089cabb79936df0b4d2e6 +119 7dd092a6adcf2c18c0170e0f2c0702e1 +120 9e29f9352c2ef39df19551719b5773ee +121 542e82695c94037fa0f2ebabe5b13103 +122 284c4cd7a66feb02c5f5628202186aec +123 81acd26c775500afa1e916fe37e08107 +124 db105a549c2cd37f694f15871607514c +125 89f5ef16e9af04b10f03501ddef1cfba +126 272a94b2b35f9841db397705e7f5dd37 +127 bb4022e900040fe8882304106645d939 +128 edeb9d4e882b3fa9f49a895583930f5d +129 378a7d065ab0c482921d2f20b0fbca19 +130 65e8f99867076fe50d93c983ffdea135 +131 c33be9ea0be69d7a89cf68a9b13a6c25 +132 2c0b59f70a2202a605c60688d8d33cbf +133 e039e86b756bb28525508a696a6fbf9a +134 0b469375ed41e884a03b6765cb16b52e +135 0971a36cb1a937f8540c9dc46a154cef +136 85144c833c7f8337b31bcf499c36b3e2 +137 cc1a6a17a4d249566cc0f5cb87e66e4d +138 7b63a86849fb43588e2af48c540d563f +139 ed5eebd51d70c6c3a20eea2d454b5f64 +140 43bd84afd3c3175edbdeefb87c03952b +141 ef3c7832ff9ef7444a6581e7c4fae511 +142 c6c63924eace95f0d002966c9dd8de71 +143 44675f9a3ba35d27920c6ad770cac150 +144 de729626e167979bf5264014ac0206a8 +145 af2a6a18da8f983f6a30862513ec6b53 +146 546fcd5e0def5599bf616059162ff6f9 +147 a756e1b69dc6e31d9d5283ef4a03762f +148 a03f4b9351f0365d46d9592a4a291728 +149 e1ecbb12102744fcd209fa1901c3f447 diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/riferimento.md5 new file mode 100644 index 0000000..694105d --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVCBCT-1/riferimento.md5 @@ -0,0 +1,303 @@ +# SVCBCT-1-L1.yuv 320x240 4:2:0 8 bit, 300 fotogrammi, 34560000 byte +# strato di destinazione: L1, il più alto del flusso (tutti gli strati decodificati da un decodificatore SVC) +tutto 3518c010d8383835da64861306bea61c +0 b32f2cd93a36ec11458e60877639a806 +1 fcab3461630164b98d36eb8445723a1a +2 ce0a6c43a16c62d99d56962141e54cad +3 e1266ccbbd2d9ff818f0383a35aff1d7 +4 c632ffa75e8164fa3d4245407ae17420 +5 1a9edd7770764b077648dc64c117c45c +6 deec6ba6855112d96e3b24fe17ad1e14 +7 f68862941a8245d3d36433ef3911ec0c +8 cc9435259faa710eadc15bc6f175853a +9 42bdf152394adb286a367a7d56c1b9e8 +10 a7203ab3ade6382d60b89536259754b8 +11 265c45ca62c64f3e5de1b68d5ff4bd0e +12 1a449651a968fe2e1c36f403b66d4f08 +13 5c2faf987a72d209b45ec3805efbe606 +14 086a163409187a7cd396367531f9648e +15 4eeffe1c69b86fee42daa5ff61dab9a5 +16 fcd631d594ec1cc173be9a5eaf8571a7 +17 7d28d7d6ada13bb899ee3ae7ab5b4c26 +18 20adb74930fddd32bf2d9c328531ca88 +19 f7717c6d9d7585f1d8c770cfe44e4419 +20 44d60db83efdf9e0599c10305f388363 +21 46643322e65ede6f596d7fca25d66fda +22 168cad5dafd852227cff18e6d3048820 +23 6715de857ad78a092a4d55138e8719ab +24 878f031990fed5f20db1d15f750588ab +25 e7d0cf205860e442f111776c9a85f4f9 +26 4f5c552269af8ae7967c78568cd447bb +27 d2b1b36e9b439bb321055171ac4ff6f3 +28 38443361b4aa7bd9723f6f2e8004196e +29 4aa9eacb783b6ddca9577b5ba170e965 +30 1231c3cc743c62cf4511d1ebfecc705d +31 d9cadeb91a64e9d6c09347eb7a82dcfe +32 82de80a0a8cdad16ca565290dc17f979 +33 5c62f92ec2c4f80d03ec59a3e36ad853 +34 55da828f39e64e82585056d52da0c78b +35 021368e0d6d80fe51b39cf92b3a62564 +36 b360a8f05dc3323abd99ea709f76bedf +37 ba562c1eaf40cddcc63a87390155100a +38 50a1b78ff68ead726047118b6f7e3b1b +39 da5937fe34b2b48d4038a081684e36c0 +40 412d0485881275b2a8229821c680532f +41 cd552626e3332dea9fefba7c66c87875 +42 04b5d6fe689410f6ff084d2cb621943e +43 1068acd817a63569e0a83e8f3ee6b4cc +44 fd2abc37fc5b8e00187a245c3dc11a6c +45 9d84dc3365cf98e806b87f39251ccd7e +46 ec4dfb6eb1a24a5ca3f5922f7a1adceb +47 958fbe31142c9b633ba869dcbb2f1a8b +48 95087428d3773edbe29b2f290a6927b6 +49 dff21f28dc3bfe2393d10ae048cc032b +50 342cc02f630fb08c70dcdf6b16d9265b +51 b1aae6b7fbe99978b634828734a11a7b +52 47b5f0f7af57c43b8618ddec7997f996 +53 b5a000cea6deeed7be230d296d3178b4 +54 1427e78c69f7027618a14067ad8edb5e +55 d0f319d419049d611abf1f4f6ced8986 +56 fec5bac230122a2761e624bd95e25e2e +57 5466d61a06045b81c040769afafb60c3 +58 4d3164585d39bce5f252120fc307afcf +59 683645bf80f96224be24a57db9429468 +60 1689a99f10fd7d44ef7014912a92c82a +61 78c2731693c8c9dd8f8ad69bc92d037a +62 9a1b2ef760f91f846c16c9b139338854 +63 a7cf90c7f397321ee191dafc18111af1 +64 48130afa6da4075e27f919cc1a7805b5 +65 47ab0dac9ae566ee632c125b5e02ae36 +66 beb153234cf96c7647f15420d02ece29 +67 8ed1c6d57fbd20bfbe79b29c4b4a76ca +68 2f13c61bc059e70dc308701691fbb261 +69 f637dc13c7861bfd610ef17726d33452 +70 11699076120e2cecec40e5e2123dbd34 +71 71b175d2a9592b54e6654166c5b8f32b +72 2aa888562042f14bb91333b0e501b0b7 +73 a86e4be32f18243a8af815aa3487aa3d +74 bd5ada862275e15cf4806833cd60d17d +75 4e6b6723973eb6c3b2f1e6301a6f7a82 +76 8e7c82e5a9d704bb0dfb289ea1b411dc +77 9b32e7b2db39e0b2ea138625fc3265e0 +78 3866afb893e3e270d8615bcef6eb80b7 +79 8b263f8baffb913133731db2a564db55 +80 d66581b6720e27f08243f43a8d727cfa +81 0efd39b4e8f8657155b8b244e60dad9c +82 093bac30e30d0e1bd2c3a370a799fa21 +83 e0d52214e08517d386d57a7cc93c5577 +84 475a4ff16093da4a73a85fec6ac8326f +85 c3657809f69ca6eea53e1aaffd8bae33 +86 c4dff5b89b4bf03144e136b74135f740 +87 f8697fb3d4780a5035b0436ce9a497c9 +88 53d1fc17c6377e91b3d62130b86ee906 +89 c677970d14823f40d49d83b810de40c4 +90 3f2bf5415f0ee9c08415fbbbb4e399f4 +91 40bd9f8420a0344686d168f757d1aa59 +92 883ef06b790cc7d5c65971917e620851 +93 e8286fd08b616b36fe878a79156767fe +94 2a3aa765ec25fd3e70d9611a4e0094b2 +95 900ba0a1c8acedf1f90f8577f25295c9 +96 bf838eb0e6138daa3549a22731e1a268 +97 c5cd134249879810678c0c0015fc7ba4 +98 831d36ad245ce8837641985b38e3200c +99 263b465caa7ed9fce3e1d822751e0b52 +100 3acbbd1c28ce6aa179178e30b1580bd0 +101 2a0ca572c269ce4d0c1124979ef51bd9 +102 2cbf25261b2574e8fcb9736570a285da +103 8e4936f8e72d0c1547450a15dbe7a4ea +104 7bce0adaac23222bc1fe1f6cbd45984c +105 3d3c840a05d0663a87fab989bcfdf7dc +106 78cbbd8102f71e07b920d6b6e02d4f05 +107 f75cbbdf3bc8a2bb7c93caf564e870d4 +108 49e6ae8dfcb6d3d2beb65e0d58754157 +109 663b1a34a709f7b36fa93ff47b507727 +110 2c3f89094dd7e493ea1082df14fdad7f +111 4a08b45b62b0a1beb799fc9fa3361d1c +112 23cd21f381b51239e9c2b3cc088f1e3f +113 0c43b1aba6293c67203dcf6178d16356 +114 a490025d72f92000fcce4de936474b38 +115 02506bef7803d6fb9e9c35ffaa974031 +116 a3e6e7dfd4887d0abda1d32d13bfc4bb +117 1a9ac7965b30cf15369474f15d1bfd23 +118 bbc6bcc114bbdb7a6824da74764fd2cc +119 a054dd8bba0b529cf903d6d33219a3e9 +120 9af6d3ac2b401d11eca2774991462c9d +121 6b36982ac64662d47bb3ef832b34ff98 +122 9cd5a95261c0b676fa37ef800252607c +123 5b869057601dcf7dcfeec2aca069c59f +124 2594c5392690f79055dec7cb66ea365d +125 a994f11374d4240eefb1b7b9e874cd86 +126 a9957d99144f973cf16383a3670cd02a +127 caaa86eace8f85750c879c332abf7ada +128 fd56c2d1966fe46c8cbdfe35f8233889 +129 318bf25f36393c1c399c91c4b7f143c2 +130 f0a146317b6f335153470a208642c97d +131 56725331785b9f5e4e23acaea2728933 +132 9497a6d6f0bae9cea3ba685a71a768e5 +133 00a6fd7d117343966137114703a4a222 +134 ec7e1212bc942d6a42e83cab252fe92d +135 33d958a7461084867244f71d4a43faf7 +136 6c00b813a52d72d820d918d1c34d04de +137 b7a8ca9ecd5adcca4fc56f75250c436f +138 2f2c2f35d42fd74086e91eb5370b8449 +139 3a5f364ae84dd2e215c6beb3f2aae256 +140 8962332c3a1f2a14324e1af0e54ebd99 +141 28b2f3699bf04607364b8c1ee9bc6182 +142 4d11e480d5859ca6150d95f0fca4cfd9 +143 3a3e7316952c9829ad048994222ea049 +144 ae426ab0447d74085048f2003267f7f9 +145 9c71488d2426b4f225da8477c812529f +146 d3615eb32773d5df04eb194c3b28ab8b +147 a23bbcdee0ae1b1a13ab8b8fa58c6b07 +148 be04ea2afc167bbd15ba878112521366 +149 1b318cf28c604a1781e76c8908d3464c +150 ddadeb081210855a372211d3dd02ba32 +151 d6fbe008e7b4495a525298bcadb03951 +152 217943ececbca36af5e1d62637024f90 +153 66735b7281b5bcd35c37c559e3cf226a +154 9eef867d2f69c6ae853e11018a465a87 +155 e637ef3549f938cc9e747b2108074196 +156 08cbd3135d1cc30d6d968c0b906d3c44 +157 4f1a83ce23904466ce54cfc3b5d2fb8d +158 8a3d0a9b656240210729fee08b70e7b9 +159 2f6afe412efe29d9133049024d292527 +160 457b5c7516eaebff54da96b8be967fb0 +161 cc208360d7b73495a5f5c2afb986373c +162 b4e9cd0ed065436d586475bb995c40aa +163 22020a4928ebfca709298b40dd34d644 +164 9849ae9bde8f06d3db94ba9251da2fae +165 ab92033929d40f6b774e84a66d667264 +166 0f8377e3a973ce094a4c1ae0e3618297 +167 27e9919e8a55a74f35ffc77bd7bf0c56 +168 7a90e519df4bdca1725934a7ce9217df +169 f016371c0cf6e9bc7c2f90048eaf85ca +170 cdfbd4e73629de9c415bf8cf997f8230 +171 6e66eedc93e0c6a832d19970672f6688 +172 431c594fbe4ce16071a4836084343551 +173 c12a3111d38746540857fcbe1f88b3cf +174 8ef64a01cc08b77e9d13ac4035c1f7e3 +175 0026f27493b9b2c48b30c31a318c12f2 +176 3f739d715e70fd187cf4d53fc885919d +177 f1814f5df08af4848870dfbc2238b37e +178 786c940e5a231703cdbe8f07db1483b7 +179 23dd6c9cc75169443d9cf7e918f210dd +180 692a21dc95ace04c88958effc9464280 +181 48650e6994b8d366b65625eb1a35ca9b +182 58233d1a99a36693586b269223832f2b +183 56b38d0244767a0cd12648c395f88907 +184 35e9f539d5f62a15b88635ad3dc0c99a +185 83432452855e3afcde7f37844d8900cc +186 794dbfdefd8432a57358b34e1250a406 +187 f13d746f85f7b343ff2d1dc0390b0af2 +188 c1978962931850b579de70bdb9b69114 +189 c6988203d02511fe64411052db7ba571 +190 5b4125641d1b7b9cf7d3e8fccf174efc +191 938302a6a676db3b2b51c526edc28eb7 +192 b94e265bb1dc61c3a40b9e0ae049bd0c +193 b2127b24c784f0085aae2897162f86f8 +194 460b7c472bc3baaee4f2901deb83db81 +195 a0fe20b6e574b24daf9b3849ea457491 +196 9d8e3fe3e0ae1f6ebb28621909db3e36 +197 c682e7f45b4739aa1d976a4d2a4ff0f3 +198 5e52b7c3141e7d6b29a6e87249eeb07f +199 724512d4953641f233b3c4959c169ca6 +200 a1a367e1a75c4aa89d0dad720141b81f +201 30bfedf8976ab2e5cf657bfcb0025987 +202 984a56a612b9a8a93db3efb92b37ada9 +203 ce74cb65d344e428c84994ee0f636095 +204 e344b50f521836e2a30701666c735618 +205 454e4702fb13184c5585c89e8867157b +206 3773956e36a4f28663976a2ad20159b7 +207 8b0ff4dc7026b3d503532b16074f7041 +208 547caf0926238489b343d7df250cd09f +209 080c98f74dc0f0c8ff8b28eb57180e41 +210 dde48ebbac5cf13193d0b37dc145ad30 +211 b2410b5cf9f5692498aa9e36cb82e18b +212 5c38e63f970e34f254d1a618c865a47e +213 52228c0d12df95c9f7bd60ece5616707 +214 ee2aa4c380f84f866cdcb11efd65c092 +215 e716f12ca45dcb8afac5e2962f637728 +216 f1af5ea52aa04a424c13be61b36d473f +217 3c7a630ad0d0afdbceaf58af9671b398 +218 d247ed16597ef5b37b9b14b21c544049 +219 25ff8ae5a5e9a7a7a3dca4df50d20d6c +220 c19a84316dd3f51575577a48b947c173 +221 67b4003d248c704f5b884a5c293d2403 +222 3ae4316f557487a3cce67af5829ce17b +223 b42f627a546a2b47437d92439f15b74b +224 aae3754a807db110e20b38c6b2e4428d +225 b536a241f48ffe1ec639b928a5c93faa +226 d325ed3d2363d3e2a523241acb641806 +227 f078550529f74095e17bc4846fe60fb8 +228 d9082c781b82cfeba5850798bbc6ffb7 +229 874ab076ad8a649782254e192468e84f +230 1099d84a0d92d0e95e26ffbc6b0d8c15 +231 8fe4ccda713518eb970624127b67d73a +232 6ddbfda602ba2476a40be122fff768b6 +233 45cbc5b815db82dd2fc23e4f2088900e +234 82e7e8072ffc0a8252173725a42210a8 +235 13a6750176519437c91f070e31da8585 +236 faeff8fe5ff7f3f2710c34319064d0d8 +237 27d5848b5a7d854780830ef72742a35d +238 8c681398803c1646bfbd05d33624953e +239 92257a91fd86bd987211f2de4a711119 +240 e78c0fcb91500a49db3cdc7d0c133f81 +241 6f24444b0c4138e5da24bf56129ba59c +242 39da00721b24849dc30a6b905a6b879c +243 23080df4cec5be24f5823156a44a525c +244 8c571a277b7a2ca0ac9e651c4c4b559c +245 e74e850d3aae836c09f49c7806d73ce6 +246 120a39040355170aabf44808caa8c359 +247 10a9c07f77e21f2ca0e1995131d4ec4c +248 09a72322934a7f6cd6a4c0860ca3ab0c +249 35127b7fa36e5e099ee5683be41d58c5 +250 3679903aaf097a498d81869cf94b273e +251 8c7f5bb39169fd9a34399e8e3c762ecd +252 0ae28b4fc7c14279230913d11540db1a +253 7ab36d526cf25eba8f6a7b1f72e68a07 +254 7e5357cd0f0508b304f1a934744ddba8 +255 4a4de7670da32dc547b9776eec8b732e +256 51ae638cdc34e6b9e2fd81dd282af6d2 +257 a50d35e0e76c2b41db5a781bf4e348a1 +258 3614dc01ca3114295d4c24b3882bb333 +259 3202ed3b58d9d73ac9af6cb1be7975d2 +260 561f2f66e7c35b66863f8a0f68a3bfdc +261 52dfdad6eddaa84c4cf7a81d764688e4 +262 994b4fb559617e32a4f7b0ee9dcfecec +263 2704f9df9405105933f5bc1a35227a32 +264 017d288a07b3c8f46a25546b23ab0797 +265 3763db3628985f0613eabc7bde3f58fa +266 dd5a42159208f056b020ceebff50adee +267 4d23d34fed62a9eff3323108dfe7a2a1 +268 cfc2c83395ca66e6d36ce80c9c92ef18 +269 a935db0f26f45059e24a5edada17dcc7 +270 883092b393c9954adf36d8090977f611 +271 a1644b76c93703d6323a04b3eebd7b29 +272 c546e8e3d28e3dfd48bf026affcf3ed7 +273 4cfbb93e2e1c710e09b6d8473a0703a2 +274 c2e5b6e007017211474e80ed16846350 +275 7d1290b31eacc5052c393cf2ddf75eca +276 9c43b7c7c143b694c68382be6ece320a +277 d355d3ccdfd3021f2a71ca6c6c595639 +278 f777f798143ed0cc8574e418d56c1419 +279 f5c8c757f9688a63631ae916ff566c25 +280 5a81c73a3b3e0c9506755383e5f47178 +281 c612c11179d49b9131b66852e926e7c6 +282 411fe6ad1dcee9caec215eb78c83f8ad +283 37918c2de6abf41d331ce0dc29e42cff +284 644b7b927b4bdbd606c2675c9f81ef52 +285 64253e2f5e1d8472a1dfe18b248b91a6 +286 4c68a15080976b185dd6110b54265d81 +287 4f4440e26309385d3a02c7a3f49071a6 +288 121c746c50aaf969a6fe64b60f59de1f +289 5cb50bd7b95ef83b6ba5cab5e59045a5 +290 175d14c33fa62fcf2ac7f73a9a81b780 +291 63a67620c948d2d1e766300e6faf4e43 +292 fd0bca99bfc10cede4d4084d1f817093 +293 a47e0778e66d451222066d5b921c9d05 +294 55937bfbb3cb67bdd36646854a695f61 +295 75f33f4a7dccaf7f90fa53772d470de1 +296 4110912952d4fc188fb5dabfb138f88d +297 c89d9c814588d89e32e597bd025c0afd +298 6a866dbc7c5af7af51b19bc5b67103bf +299 0799c9800fdb77d25f05150bcbea809a diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/SVCBMT-13.264 b/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/SVCBMT-13.264 new file mode 100644 index 0000000..47aca13 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/SVCBMT-13.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/riferimento-base.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/riferimento-base.md5 new file mode 100644 index 0000000..3e6e36c --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/riferimento-base.md5 @@ -0,0 +1,23 @@ +# SVCBMT-13-L0.yuv 352x240 4:2:0 8 bit, 20 fotogrammi, 2534400 byte +# strato base (dependency_id 0, quality_id 0, AVC): ciò che dà un decodificatore H.264 che salta le unità NAL 14, 15 e 20 +tutto c6fef267dff2ebe6d172e5d0285eea5f +0 5e2514d33a9c976e6ef558a4bd8bf887 +1 d8e91f388953c21bc72e8672fd9dabe9 +2 ddf9cf2d8d0ead5892a177e421091928 +3 84ad41f97dc9a351a1398167351c0a4a +4 a8053462c6369d053f89f0de36df08e7 +5 6c87b208b81493f7fd31037a1ef3b558 +6 5173d9c7ee939033d576fdf6a6aa8283 +7 50c1620d80bc7f4546eb4a2ec32e3ad9 +8 46ecf0ef949eecdf0fb00a007ecbf562 +9 5230957a316c201acb6c875d125035cd +10 2acc413f8a384901e62f513eac2054a9 +11 2c61ca0d1626ed6840687a2c432c00dc +12 99655451a7056f0c1031f9c178417f5d +13 860467ed009309d7e10d1967ba2ab618 +14 a398d49ad323e034a546abfffa0b2abd +15 9f6f78596c3d25682e4b3870b2373317 +16 326bbdf9271905e99ca82f3c46df4bcf +17 d7d45ca30d1a6f42e7c3e29e4ef6b863 +18 ec32d2652b331c6799dc55a0260ff294 +19 0d7c9c767caf99d261465700576c5f55 diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/riferimento.md5 new file mode 100644 index 0000000..ed7f046 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVCBMT-13/riferimento.md5 @@ -0,0 +1,23 @@ +# SVCBMT-13-L2.yuv 352x240 4:2:0 8 bit, 20 fotogrammi, 2534400 byte +# strato di destinazione: L2, il più alto del flusso (tutti gli strati decodificati da un decodificatore SVC) +tutto 2cc42817a35d2d7650b73b4b53c99ed9 +0 1d6f94b2513d1405e6ccc8d565df1058 +1 aeff89ccfd757303767503e44d471e91 +2 dbc2ff2aea70dfe1dc7b0159211549ed +3 ad56012197a812f0fef183a7c5052d14 +4 4d4d7e2df3131e59ab6a80e9377594eb +5 11d14f4e390d51cde518abbd8472349a +6 f31192be2967cf4805fa75cf4181e94d +7 6cd5b1dd9932ecf25810a2549cef8d67 +8 8d21ba93fed40edcb39a764aef295d57 +9 bf0daaa2b4b0b6864a5ed9147244c176 +10 e5ae78f66de25b139acdbadb381bd406 +11 036269c04a07ea63dd2ef7e91f0689ad +12 a5768c3f973b56451cfc140f4fcd0b9a +13 9d77e6ad91587cd2ee23c5fe1280306a +14 71fb5c64d372be5c715c7f354444cd04 +15 e951c2f16216cae5426644c50555f72d +16 37bd5faae621d436da4d02c6e2bc938d +17 b5462050aef157c261b934b7cc320e64 +18 e35675c792c0c50f4dc22f854e40f7d2 +19 34dc12da10ace1a534b3e304513de30e diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/SVCBST-19.264 b/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/SVCBST-19.264 new file mode 100644 index 0000000..aa3d409 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/SVCBST-19.264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/riferimento-base.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/riferimento-base.md5 new file mode 100644 index 0000000..a4fe170 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/riferimento-base.md5 @@ -0,0 +1,33 @@ +# SVCBST-19-L0.yuv 320x240 4:2:0 8 bit, 30 fotogrammi, 3456000 byte +# strato base (dependency_id 0, quality_id 0, AVC): ciò che dà un decodificatore H.264 che salta le unità NAL 14, 15 e 20 +tutto 3062f65d01ac9c2360c2345860358def +0 f915af4d1354bb5b34232cf48b26ec27 +1 f78cff23cc4435967750e0bec812f284 +2 b690979b575bf5e775f96d02aaffb8dd +3 6604dcf1b7b3dd5130e7b0517beb2af7 +4 804a17295a1e8ad150892afcf65c50f3 +5 702418ea833b33b4fa15fab58380c8c7 +6 b059b4be6c661a7e9d8ca3e93d7b829b +7 7b348dedd85cc8374a5b1c4563bf4e72 +8 14cf3048449f48c1684a3c2c8e36c5be +9 9406f741e72483a4fad12fd6c332c096 +10 935807f2ddcc568302021d7e4202f9c6 +11 df46ef7efad2f22733733090223497e7 +12 bc8c6c6e9f15b6196015b3b58eb96a08 +13 2bfd50ddccc8b17a3d439faf4f27a60d +14 a9c7fec8ae6522489fea67df9c62c3e6 +15 03601bdbdbf61fa563bf574fbe7e5c89 +16 af9ebab74e5a2b697f8beb5afb869800 +17 23adc7de98e6d8a176c81db89f1a8877 +18 b534c3ec6560fa2719d4d171c382168b +19 ff9ecc719e18599f417b6dbbba973826 +20 c74e6d016f8628a72d79bbac91de3caf +21 c6c732de66b0024a27746bc017eb5845 +22 1b126d77e28d2f4fb16be70526de7932 +23 907979f105660b3cf77073c976c89b03 +24 6b6ba7c54d0fa96c34adaf4e6ae11b5d +25 6c2fb4be2f53638e3b06b361e7498619 +26 36d13b0d605780c972fa9253ea4bac2b +27 ebe75c39b3fcc1615fd0081cee2a6358 +28 609ccb5d7554261aa708085e8e65790b +29 3381701f46ea05df9510e8a587a9bc75 diff --git a/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/riferimento.md5 new file mode 100644 index 0000000..a1cb8fc --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/SVCBST-19/riferimento.md5 @@ -0,0 +1,63 @@ +# SVCBST-19-L1.yuv 640x480 4:2:0 8 bit, 60 fotogrammi, 27648000 byte +# strato di destinazione: L1, il più alto del flusso (tutti gli strati decodificati da un decodificatore SVC) +tutto 8e85fd925bc86abd0c9c6df34655d6bb +0 3a29ab35109e1737bb973918c8b03aad +1 6e5e1c404efbe0228a42f3b202dfefa8 +2 2f8f1e507fbb873a61d4bb8c89937957 +3 017041c820dcff3c593e866a9523c215 +4 0f5908e2b386d9049cff417b03b6c86b +5 5c1ada3e500d3202ccbdba2f5ca65d2f +6 b898e10e398a2555103de3a3dd2f60f4 +7 b34c9f42a6071581e35e48dd9626ae91 +8 7c3fc124c310a5a1702edb20d4d7af15 +9 a4edea025331610ad882ae9f80ab343f +10 a6c215b5971db5ec0e45d59148360f19 +11 94e62dbcdc9ed3c0f8a2ff25788a2e93 +12 765bce67a12ddb6f5a2686a30805620f +13 014b4ad04f32e152d8ba4c56ec26a2b8 +14 c40dc9ff42c1d0f7ded238012bf5bb4b +15 3589650f0fc621ba6c7ea74b21b1e6d5 +16 2b937fd6e5186ea296700578e9c83857 +17 89cd071a0c20161e278b9d1fbb332a2b +18 7d28b3dbf053df9f4f4e7de8ca11bba6 +19 4ed55b3b1551e428c9f1153756e535b1 +20 97db20ca7247a0884d481ae74eef7d7e +21 8d410ec0458d8d509cd895af055223b4 +22 60cfacab27cc66b9c9232a20fa2ce225 +23 ca76504c665b7ea2defc2990a2ba5d40 +24 7e1eec16c492aefe0642ee0db7cf3f20 +25 1f0375be3f43a5c4b4ddcc708788e13e +26 07a9e98b7ad6e0cd44e3fc9a8e9fe39b +27 5d2f7a150d6d728a67f78887240bf052 +28 a7258edcd8690dcaee24cc6e39612c74 +29 20aab166ea0a2289eb77e2ea80f65865 +30 811f8d7bc32e47f4c35cbde2261f74f1 +31 360b5e18b3af56dd0b242acad4ff25d4 +32 e6384d4e1fc1cc938c92a4d0818b7956 +33 85d4c8a487cfbf99db4c41717fb43e85 +34 2049159054f1c117e14a6efa5c989791 +35 064ae91eb16ce0b91231292fa51038a7 +36 929566906138769d86baaf2532e0e0d3 +37 e9c65a7368d2f0a28c77479e944d09e4 +38 09010a99d629304414a30524428757fe +39 3638d48fa98c9ddb1c5018c7c4c5bbcd +40 2417b9c13a86557036546b437f809474 +41 13ea9d43249f8692eb9b6c0ea7341c67 +42 83b00a62e734108ca19125170574db55 +43 39a362b718fccb9fc565ecd95f1abc8c +44 6329a5385b1ba53311f4aa4f7990a611 +45 f0bf72dcc847c072c207d34347eaa611 +46 c062f97cbfdd7937619be4ae977ff8f7 +47 8887d4b6c6f5f0eae881bbb3de2eedda +48 98f2ee0af395ced2d4e41b6daef778cb +49 09587c0ba8abf4914a6fc6c295833779 +50 ba22ef8c2e021d41f6ed09192af4b796 +51 39b6940792b37f1a08718431af47665f +52 f1123c21666e48f3317858bb5f1f87fe +53 64c09885a69cefb2d2eac7a61591ab75 +54 9071a54911c761c7e6b9bd38e5343ca5 +55 84d8e1012eec7f38e28cf14c19627642 +56 3c986ea2923f2ac02aac95a21d0c8893 +57 da1652d1daa386e3c83fb14c66cfee3a +58 58f506ef5e4e3008ea5ccf743ff3f1de +59 a99e5fda83877c12a24edbb727d3d8d0 diff --git a/tests/Febe.Tests/Media/H264/Conformita/Sharp_MP_PAFF_1r2/Sharp_MP_PAFF_1r2.jvt b/tests/Febe.Tests/Media/H264/Conformita/Sharp_MP_PAFF_1r2/Sharp_MP_PAFF_1r2.jvt new file mode 100644 index 0000000..091831f Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/Sharp_MP_PAFF_1r2/Sharp_MP_PAFF_1r2.jvt differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/Sharp_MP_PAFF_1r2/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/Sharp_MP_PAFF_1r2/riferimento.md5 new file mode 100644 index 0000000..1db6400 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/Sharp_MP_PAFF_1r2/riferimento.md5 @@ -0,0 +1,17 @@ +# Sharp_MP_PAFF_1r2_rec.yuv 720x480 4:2:0 8 bit, 15 fotogrammi, 7776000 byte +tutto e31b7df5a2e5dde2b5c8ede9d3aec16d +0 ed42136006cad79d70ae1ede0ff3a817 +1 1ec169c249dcd6ee26fcc41b42766f7f +2 a439f4c7a5f9d659df2650bb783e2ec1 +3 f282e13bf1af312a47052ee5a9138245 +4 cb99d1d639432cd45e2bb1c29d44b4ac +5 e84e2d47f43c8ebc32af275cda97386c +6 93859f516edfcacbf2f8a78c862b5597 +7 2f3d775d672b3c6ffd26dcf19fd069e6 +8 350eedf3c760984aaf4c8780d263a755 +9 e36f82ef959f4afdc60ac73da5437006 +10 ddceb3a2665de92982ed0268421f8cbc +11 ffd0535672cf3f20ebab0282a6a83f90 +12 d98bc34f3801523ed1aa778d4026cdba +13 32667a5216f0e4087903de217834505f +14 92905168c66b16c80fd5e60df9f64fe3 diff --git a/tests/Febe.Tests/Media/H264/Conformita/cama1_vtc_c/cama1_vtc_c.avc b/tests/Febe.Tests/Media/H264/Conformita/cama1_vtc_c/cama1_vtc_c.avc new file mode 100644 index 0000000..3635dc9 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/cama1_vtc_c/cama1_vtc_c.avc differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/cama1_vtc_c/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/cama1_vtc_c/riferimento.md5 new file mode 100644 index 0000000..7eb3392 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/cama1_vtc_c/riferimento.md5 @@ -0,0 +1,6 @@ +# cama1_vtc_c_recon.yuv 720x480 4:2:0 8 bit, 4 fotogrammi, 2073600 byte +tutto 9e3e565497977759d97d169cd13b842a +0 b55dd548f0843e513906412be54e9640 +1 d774f974bd1ec5eb3ab3aa6cecd94817 +2 c3f47a4f53972c0ddcd391145b7a2cf3 +3 46dc88f9730e7c1dbf06dc5a52fc5792 diff --git a/tests/Febe.Tests/Media/H264/Conformita/sp1_bt_a/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/sp1_bt_a/riferimento.md5 new file mode 100644 index 0000000..d152c02 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/sp1_bt_a/riferimento.md5 @@ -0,0 +1,402 @@ +# sp1_bt_a.yuv 176x144 4:2:0 8 bit, 400 fotogrammi, 15206400 byte +tutto ca0b3580f448cc1e07f81a4756273b59 +0 1fdac852bf37e58cd7fcac827c4465e2 +1 c30a05ad45c5164fbce03d62f28a7097 +2 173e929536b25d8dd375f9edb5df975e +3 262a928f6e1207d43bdb042011b1df21 +4 2b3b51176e8e81bb0439f629c1644176 +5 82ae076eba8f3a9075f8418b2f952bbe +6 6b8b5b64a2c24a2496a4bde8565ebc94 +7 2fd5f983139d1c5bca831915aedde5e3 +8 dd4e895d4325c17a57bce5b6a9b2bcf5 +9 5a0f59a2d2babc972f7442416ab008e6 +10 3dd2caf2a9dd539a22752b1c7fb9732a +11 d9000b7776249c5b0d717005242504e6 +12 68d8c523d6d2e4de20e659c11553312b +13 e667c65161c37b639e15267ea6638b95 +14 3d939c13383c7fea4044bf0e0db5e87f +15 7e0bd069ae58fdb2d718d36363357c01 +16 8e6d17e9509afccf74a9fec74c116420 +17 547ab2f74b587a578e69004b83a4940e +18 80b9135ccd4edd59e2180ecc65914495 +19 1a6627853e107f20ffd6c0ea90a727ab +20 aca82ff4a17749f042bb31d673b1eb79 +21 44f7c0631f321e7560d35db233b4c400 +22 ebf1955ba73283fd1e5aba19fede394d +23 45e9472a39d2ff23a6dd6ecdc51ce332 +24 670dfca3b0ac72eae3c507ab4a314b1c +25 106615d43386ea5e0bb83660a3f90b8f +26 033f6c83cc3bc14d88b6dcd0aaba483c +27 2ea2143e74043d01fec669478786bf7e +28 0a6b284796b958198d8582060d95add0 +29 45ea7dc8d26555ba7ec09f7546408b18 +30 30f120e05d1a0de08e75872130b620e8 +31 43c44213a0d20ac6e768799ad6ce642d +32 ce7b11e44d872ca3e8ffac471d0a3418 +33 d617934a5d034991197411312b4e46e6 +34 8c88cbbf4412a56107e8062df758c7e8 +35 3418dbe751dfd640580d84500e49e379 +36 436212ef122445aef29546ed012ccbd7 +37 ff0f12b222882c1d663473a562f81c1b +38 281da509b73ba29ae19a271d4684cf3d +39 bb350eecc99f9545c2fce0114569f0d7 +40 df9aeb91d4639e373de59de6576d577e +41 4b0259e48b1a0a2ad2452cadef810ad2 +42 0c975697200607aa9b42ff2584130455 +43 5e7a745b6a8ee1cca2abfa7dabb59eda +44 b40671d1f5f207512c671c430d475681 +45 3e4bd2ab335ac9ea4134ba9252990a90 +46 ff33f32638b09d347f3c8fbff07b6fd8 +47 3c302fffc45c0bb5c790db4f5f5861d6 +48 3c253ccbe8a43683da091bcb7cdb81d0 +49 1cc2e34776e58d807182c90c7d3d34d0 +50 9dd268667e95fe02016bad55f907b76f +51 5c3195ca87011befe3de9f28f648bc68 +52 b68be38d06e7f1085829c9e45200e239 +53 867dd248ec4e71866e6c4a116abe29b1 +54 8b8cde67126ca1980ac40f3840b76aa1 +55 d7c63ec09116a86499cc878611f99a09 +56 b899a1988e31ce442a799bc0e937f11e +57 535898fd628116402828bc7e13612dc4 +58 d217d0311797fc70eb18fd58736a84db +59 ddca7aa16d757118fef515e409d9d361 +60 0e12125b0276622c247b72dcfff365ac +61 ec1ed1b0d4d5bee0e2b3ea9176d737b6 +62 2c290bd0d46ef435f13f82f34eca9ebe +63 dc51e2ae7ff785985ed41425a77f5979 +64 9beac1a667819b3cd516c10f994808bb +65 672a22f89a881b626f39353b798c75b5 +66 1bc06105f3cd1f6405451cd32ab41a69 +67 ba27284f86224dae86fbf4705995a5f7 +68 e97bc7caa34b239ae7e311cbbaa0a351 +69 abb0ef181cdd7454dd24f25f68649e2d +70 4cc1ced8e8486a33f2dc4527a65974db +71 0be19f7fd8b00ddde522f35fba320a0f +72 dd48794a0763cf819cb63d5a649f1737 +73 6cc7ccb8a83dacc542dfb4ce407c4fe7 +74 ce87aebe2d173d89199e05bb466c8729 +75 bd03041cbd5a42e088d6703e5ef6de50 +76 a26ce8e23845fa3db4866d842eb85468 +77 2f8645dd57b878c684dfc29090e2ee7e +78 f5f83446ee5f877c233ce41fc8d2230f +79 c2a3599d0954ae6f89dc984a41b4db8b +80 7b76b938329eac4b89e28b9332e5480d +81 cb42c44fe14eed00a4c1aae9d62a320b +82 cb3ea3216dc7f67ddb274b9f10ca8aec +83 5587ca0cdfea8c41c65e76e96ee3977d +84 b63de12866b414327cc77b2f201d037d +85 a9896a0c0e0a4bcebe7b19676664e37f +86 f85ad57b84b162bc4bea0f81dc455e94 +87 5b7e977b61a6853a83c11ed5da9ac711 +88 8349d89771de24fdfdfb5016340392b4 +89 cbd5b32cc180f923e6a5f53813373aff +90 454ae787ea9e5c245821fbe130459287 +91 908a70a479e2e51236ec01a9f0129319 +92 966803f390acc745147b0ae338a9d10b +93 52023480ec0194a2b6664211188844c3 +94 5291ec81a35580363db89765df8569a5 +95 3e6d159da8588d45fbb1dc1fd0d0053d +96 8a9cfd6b45433800d13f1ab6c5650a32 +97 43789300df888c6cf33c24b5928f0984 +98 c183d313811b60d822fbb2428f437c14 +99 1b90c4fed97d579fa7afde2d2ea5f3d5 +100 d8a1d38902be46f0c254352f180b9e0d +101 dbbf70ee02ff5a1dc7808e3716db4f38 +102 84c8008072a80ca6d8f2a991d8926cb7 +103 c5c4f8b4cd762b2b1ea4ad5f026dd86c +104 547be56cb33660413e782678129f3cf7 +105 a9e3faeb7690a779ce8a9104405ab877 +106 7d85aae1367e0170a9ec406bd7999ab2 +107 f48d187628fd6b4fe93900df706cc769 +108 2aefedff4c1253d4e3aef6bc1f387ef7 +109 9e12dd2d345960a7ffaf21d816b8c078 +110 86fa3c6b0d8525f6c158a22d716cc6f0 +111 5d79bdc0826ccc937cb5cfec5dfe2798 +112 b6fda3eab80a1019c65cbe9e732d0ec5 +113 fd42a296fa27e2c33abea387281a3e5e +114 cb6a746c241d4dce8928f63e6310ccf2 +115 45c59ed18ce4fdc7982a857b85543256 +116 067f8757fcfa322775d22d70c206bc58 +117 a07bb4d1d13cd9a083c46918a8198ca2 +118 895a7a417585bf93f600112075df518b +119 f3513a0018130a8f65c3ab3618f90c72 +120 fbdcdeaab774b5e0063404051caab838 +121 44bd7bd78d7dc04c724e0344a537a761 +122 9d8b1fd3d9a297ffcd78160a58b26e2e +123 2617267c03071309ef78d052e16e9ae7 +124 41efc69d5fe7444eae2ec3c840d4fc82 +125 f1660c5e335fba06e93158b52111dc89 +126 b9dac5345e6aa84f73ac81a85e3d58d0 +127 d87c3e881d101bdd72e4be7f3a8537ef +128 7d285e2df5f06d520982f38fa796206f +129 7eba3277d13d8c8ee923f62acdab46de +130 11312b76d189ecd14aa99534a4f29b9e +131 72f67306b22b8cf2f5842a3a44f624ae +132 75cb348deaf1d984474e233b708299b5 +133 66193df78c9c18a284c7ebfb9d06075b +134 9852f1ada52bcf64efaa1158e1d30635 +135 3a59675d848a0abbd45db16cb36fefdf +136 dc2f8b9f2ac515d94b3a55a8e110624f +137 b816b8be0b1030c6b0751b7cd7aea11c +138 a27b6e3ec754022ab9b85c92da260978 +139 7752a6ad88f130aacb9b24c08a82032e +140 88216b308efb15f89dde26085a6845a2 +141 bb8559e7c01382dc53fd88d77adfa58a +142 6a05b012dc5abfb3bad3269d492a60d4 +143 e8be9e66b47934a1888ac38c3603b107 +144 433f63398f6f122765352ec60ac2468a +145 089f96adc92e9730082677c9a039044f +146 6ba7e5ec3e9bfc720cfb8886f78e6c70 +147 77818eed7dbdea908cf78aaa6001b6d5 +148 6fb239625f2efcc84fef447843b0381e +149 4631da57fac45129964aae17d72eae85 +150 1627710b7c98ff28fd110548868e458a +151 5414f9cf1c589460d89d234f722663ca +152 3ec0ed10a7daff395a999228550e0b76 +153 3218714803deadd7b487717971238418 +154 9a5353ec08ffabb5c04f7a7a8169ff78 +155 08815d994dc6b7c10d3501a82e0bad1b +156 679049bd808b0230d7ccb7690fbf6d3b +157 9b3b3fc21c55f04d0916829da4cc365d +158 49dce5145a073d77a291a5e171f97c5e +159 dafd8e51ccb9bd49725dfe29d70884c4 +160 c7fa3e80ea6f6cf6043db0aee3fe2dcb +161 e2fd8ffe7b4a4abda537f71807e490b1 +162 8a60dc56f378677e08470686caa89d55 +163 2b27b09a2e7ac23a7a7e14718590cf21 +164 3bc79930c442da825be335aac86bd13f +165 c2f569b15c2c0f4a38c67b4d035c9b36 +166 c737b6ed4fa58141137216589de85f8c +167 7ffd974af1f492980f5c5912d766014f +168 55bd806b29a152f55978056717a2243a +169 c6cd96b89998f47c38b422408c65181a +170 dc6d66c8857c1e74caed5a3807717780 +171 206bc854a059974f0fc506b3b6894f76 +172 18f9404186a22df88bcab5aed60d5ce2 +173 2c485537370579e07bbcff5d63b7d143 +174 7488d63a00e4fc851fa28cc9522c668d +175 93a09fd8568d3d5ce10c9642c328c698 +176 92b848fd62d2adda32fe86a273ae18ff +177 064fd92c43dbb8420e7e51f08188f4aa +178 c85ddfe9567fac528d7253bff5a2c9a9 +179 ac55ee1e5e6aee2d073b0211eba3221d +180 a471e2a853c310cd7e158eba2dd07770 +181 d3827181e727db8545067367ee5a1f00 +182 d59736dcaff966e887ad50b2b0bf0c22 +183 e42a4b10a718126e1a01d86adbbeeaa4 +184 de6ad0bda711812696ce5d2d098a3962 +185 4a18ec663c7a5ad09204f23492d2d3e9 +186 10fa5bea1a593292a84a8b77c48193b5 +187 4de20a72cf0a47f66abdd9f962b62e79 +188 388d454c8c6b74fcd13da0ff63734c99 +189 d5fc9126c2a756c9f37d5c25b574c149 +190 3d93fa8aa42d6b1d569321f1c34311db +191 1e4e101a766aa4cd4c19706652e9c8a3 +192 c7bdc9a7d32a9f617f68b2babf6bbcd1 +193 a114d6cefdb33a70563146c7975bdf75 +194 ed14d86298579a8f14153738e48ffad3 +195 c812e4da02f8ca9a711cc19019d842b2 +196 55746082ab3a3677a2fd408547d57485 +197 110ef29aff92c27b1e3c2b6581f26d1f +198 1e23bf0ab4da6b184f9d70f05074d6f7 +199 7a101adaa262129e50a3066412825796 +200 6407d5113c18c4d84a74916c8275fd66 +201 e12a40d611dfec7fab4203841fb0e3f6 +202 426c11011a3941e498b28a199fc1f0c0 +203 40ec335a55d959e50016d01b4e9c7b17 +204 07668a0ab8b55ef5cf797136f082999e +205 e14d5be23331b9ec26afc9071cfea0b6 +206 6f2b50748b856a4e04f90bf1a29c6ce5 +207 1a02d0c5457d986bcbbfe8eec0f59c18 +208 7cf2ba6346dc837fcbe0b4475860b1ed +209 bfed8eb5392c95acc4dde3ccd82e5305 +210 4f89ad2ce140175d14a76a1213251619 +211 6bf78696ee9f473d17032bc396e823af +212 1c98f5bb98de8f54821f9b6647b952a3 +213 cf36e7645638ffb3321ff0defda4563b +214 428eca56f6d60308861f93ff560ebe8e +215 0a9be030d4e9b5a0a049ce4b6d481e7c +216 5bedcff5d579cf47998d9c4947641f5d +217 d565c155ffd860e6f495bb6bdd03d714 +218 4f20f22865a82afe96c1784cb3e47b4d +219 1802f02b4e5333e0788d14934696171c +220 91b125c8e6fc5f3606005664812c6aa7 +221 fa6d3f563de5e47d8b42bd241727b9a0 +222 9834783a91c02b6908ba4b3aa7f2ee56 +223 a72d51195fbbaf54b336a33aea6e0c8b +224 25f6f5696c89c37f0bebf94bdbc077c8 +225 ae0abd2f470a5a7b343d3c00bdb66463 +226 c20eb8f8dba64b480510280b0152aeb2 +227 0c5e4bec9f7fa994003f298837a508ae +228 460ede22b3f2537f78eb940fd328d23d +229 713030852613ac2a1f433e919df66e8c +230 7e44191285a80942bc82a593aeb2cff5 +231 afb3c5292ec2b15962fa6fc7cf84228d +232 ef9f10924b3525c9063d271ee796d33d +233 2f401db7f99117807c81b847bb22ad3e +234 f4596bc048afa6bfecfd22dad78dedd2 +235 13f5ce361191ab7671e34895da2fb545 +236 fe3681ac2888b44803c18f53bcfe49a3 +237 9d8a57c2a97592dd8e9360c3c03350d7 +238 d11be1616221c53d4a2d0356ba5b9afe +239 9804061d3b33312895c4d29a87c26753 +240 a5cdf474ea602f8dc4630df50aec23c7 +241 a85b7dcf3d023a279ba9ae08793f8177 +242 69c059f2ad2b443f97d870e5259c10bf +243 ded8404da1253d961e37122b8a29e6fb +244 aab0255ae080e98678709d4f055acfa9 +245 e052ede90c46262c914c00ea63a132e5 +246 63492da35cce9617f86154eb5d52ead0 +247 50c32643d014f2f68e47717c0eb64ded +248 64e18a47185268e739696fa3f2a5bc99 +249 082debd78b3c03e2e8f1cc9b266bc880 +250 1f0ef82e9970cfd520a7f3a91f9abf2e +251 07ee6cfbacd74f79046061a6f1df7a29 +252 606fd76ba20e9f392e8f1f759a8c2b5e +253 23dd3fa69a2b5fca4a49c827d3121cd2 +254 ae7a9bbcc76bb31356a3d046a26e16e0 +255 9b8ba2e0fba1e781a7a3494de8bf735a +256 6d14f46ebba6824f180aa47122292969 +257 fba2e5809cd9b78fd439245c7f74b3a4 +258 53bfffda70744cd364df2fdb08d923c5 +259 b68e3a07986a8ac0a63a7f44ad59b43c +260 dceb34935d8403be69fe373c875f7b19 +261 fc380c89dc0ec7af680dc7ff18f01b05 +262 e9aa5fc6add345e951c4679a3272cbe1 +263 9bf5d672590a874a4f8e38ac638459ab +264 c15029c86e317f829777df2f5ee78458 +265 ab76a96467f472841681e77c279108e6 +266 db664d38e19490b60bcd156ecea51f2f +267 e377fe777305d23b66cbdd78f831f747 +268 c19babbc957094e5fd0516262d85c2c6 +269 4ab009a6a10503a586bb72b2ece74a8f +270 5dc41626b1ee53b92690b014dab377fb +271 fd5f5e8ceede09d2cc4fba4a7ff84932 +272 c22b8c4704a6e95eb4fcab1317d9882c +273 1378df4c8694791848820d793109f725 +274 e07687fd80f2ad9975bf2c293da9f686 +275 928541af885ba0ed7d24020950439a66 +276 19b0e8f121fd429e65172ccc2647914d +277 d5fd237dee2d0ba89161a57c49b011c4 +278 9d964081da8d1697973ccd0204e07ae2 +279 82c228db80e18ad18c29faa04d78d6b0 +280 2f5b49144f3f828d1f730245aa8aedfa +281 f356e02c8ea07f530a706be3bd54233a +282 7c0833efe451930e9dee778c81fd7d25 +283 c3a8fede630e89a0b2da27f5cc69b628 +284 2ee77bdace12701619ad1078c083583b +285 eeed5cf25404a463cda3d0db12fc465c +286 7346cddebb4352c97a41540576c6bcf4 +287 6b717917cded4ace5c0ab9e39d4a8160 +288 ebc4ab8dab87db2837b961335152ee84 +289 3e7aada0012794f8c683d74f5bdba0ba +290 81d75d507069df96ca26a56c86a22a29 +291 97f27fe753f2413e495967314d39ea58 +292 24d02f5c3333b0c49b4bfd5920fe60f2 +293 caaf835d83141ba41cdf9c9934545a30 +294 8d67b59b26fa7c1a0bed96a6c05b05d8 +295 a496d9231ec00a131a9ef523d9b4c98e +296 58fc8204d5102fe3d2b6153770014941 +297 71692d9e7875d7ec27727b918e1084a1 +298 1c0bdce4c888c55989bad83479ef6a47 +299 773e2bc8f4705803d3e1c4d9fa8bb150 +300 fc250ddc42e71f64a7aa5a47abba309a +301 291ee3022d4863310cfe6db552a97910 +302 8cadff05a8149b393bcb2eeecc2e81c5 +303 20d1c32e2e05c4ea1bb7c7a62d58d90a +304 93ebdb9792ef5067333b7bc72953518f +305 5ec6040ca04d84553399c30c6307c23a +306 3c587632a7f6a1e6562c22fe187903f1 +307 afcc941a2f7ca5744149756456f61bba +308 10ecb961c23ff577712e799044f571fb +309 e6f2524e5b13ea7efc48a90e10821d9a +310 3c7edc2e976f13218694a3a714a823fe +311 ca666ed1d763c1e24f63a8747bf527cc +312 07a7b59bf57e11fdaa09b1e0b3077a0e +313 f206ca4914ec068453f4c5e62bc3fbec +314 5497341dea78b8e9cf6931761b1e1d5d +315 04ff7a4307c1fa0638fb4e4acc17add5 +316 c37a12342879d933954b6e77d3f1c50c +317 1a95736264f5627f08633976e8554d19 +318 ba1af11eee6e76a83133cb8a5a2b53dd +319 5cbcd89ed5e56579ff7ad6003f0f40fd +320 a33d7447bf39ac309911b08ff04e2e25 +321 11e6996e4fdc399047ed919459a49734 +322 a3661cadb47325f4dae325d485f17749 +323 e536ae39a9a6a8f8a4a5d291e5556bcd +324 a38dd347549a5acd2a293332a24cb526 +325 16945082339367f92f49082c792e8772 +326 822c87261868294565a1bb04b00e6698 +327 e472d81271facc1d17c1ee1cf70e490d +328 c0c987a1a680cccf725eb32a56cc7e45 +329 7e7ef42578dd492b049c0dda83f7cdd1 +330 0bdfacd4d718bfb2c1bea29809ff0222 +331 6af18f18b728285a76fd4db2fdbfbcaa +332 219920362fdfdd06e2ab6182fe6e2cff +333 84d1eccb5440eaee54907fa53e541669 +334 bb6452c20deebcc8e60770db67e1bcaf +335 0966e921585c4eb06340eeef3fecfc36 +336 819a0af8dec781bb7d5b3ff16b2bf2d1 +337 d8b068fdc104acba1f351b33cb16df53 +338 4e67a82776e3fdf6eccc3d15f5c8acf4 +339 b231871b1ba6256da68fff1f7ee72bff +340 bf1944e90aeb00224fe850441430bf25 +341 3b192418c2f2df5a06ccf9bfb53569a9 +342 1a6992c81ad108be28b590f6ed0d1db3 +343 8d029ac327dfe850fa0c7f3be9e17e9b +344 0eac27fc0739191801d40f8563ac4a6a +345 9cc137f6d07b7fc29ae49239d95e05ff +346 199228f275bb5c911539e7e4d1cf2734 +347 7638b8f00c6877cdab6ff93460d3d704 +348 99978e4d5e12f4f0027045ce93c64c07 +349 48c85cf364636b23f65b7980b0bc8321 +350 f198f5a9bf502017252409bc4529403b +351 2264c41c1969c629a9af16f68a57950b +352 dc11d8fda3d2a2aba70793a58f5e6d86 +353 6eb99db5df824c83134d0177d6ba591c +354 bcf2371c1108f979bfcb72186cd01faa +355 dfe003773358f66cc5ef2c2ec54a227b +356 3d158a02d5eee69caaef647bf4c2869e +357 77f54f6e3dbe3f371af3d9aca842a961 +358 400ad6a15468cd6b243d3713f21b5f0b +359 95ee61ab5be43ca68da94b04ca33aa3f +360 16a0429459d8a4bdd40ad84d67e05f14 +361 ef4c2b2ff5b553c12483a7a18dc8cc75 +362 18e2371a8f78c85865f5c1fdac6a5618 +363 45912a00ce8e51a7700d2c33ce155a35 +364 cf822f1c62095b8978138e8d67c61d71 +365 6d09d373eb24770e31f3a98ffe6a1650 +366 7676b5d848cde19f741275e52d8241bc +367 b5cf1c197ef19f8c659fbf41ff6ae9d0 +368 cac2cc04ed4a1fc3f57e8f28c952c486 +369 781fd6719dcb147ddb5153b00fe32bb3 +370 20a7211d84bfa48d80d51b33242a74da +371 e4ccc5e1a074e901df623a8645c8a143 +372 821672b8b5731ad47242e999c0e7cabb +373 52eddb3445847a0f4757c1d6f33a78d4 +374 63ba454d1471b09b4e97dcb7edd98433 +375 de99fd1cd557f917821a8311e1f1f032 +376 7026fd07afb0876549dd98be398a5710 +377 1455c2c2384cc790444bbe25117a2134 +378 e9641a32f72a43bda537860fd133567d +379 393d5a0cbfd070c70364ed064f01d517 +380 dc4332eade8234a5a854709cf5899aee +381 2a208ebaa2379d8a1193bd35e3939297 +382 17c8bf19bd4a33e9f48c1d73b138f62f +383 79be6bfa54ad90a548455502d53097c4 +384 b96f152ed6b7f98057c4fa2f9af5ce8e +385 615763c12f5abad8fbb624eb41447593 +386 5ef99f87f56e405720c894f99dbbf4cc +387 c4d71f1be23eafd70763e20bc675ced6 +388 efb7688ab7ae28bf9f430547d9a44a78 +389 0776eaf6d93d86d17e1f7405943adb24 +390 ea28b7cc849f0f7657ea7efbcedb0dc1 +391 e981864d6bd5243f03523c14f3678a76 +392 d1ebaa23d8e165c7dea7ccc59edf0249 +393 ab5a08bf9c02be449aa0210ef01622ce +394 ee45a030870dedcb705b66fed4aec964 +395 88cb433a59b7bcabdba130c36970d1d4 +396 b1c0bbbf1da4b92716a87b74944f02c5 +397 0c5e54c2bee8ef8ce2e1d1dce6376a56 +398 e17c95473a3277f2f269b620381d68bd +399 d27112a690375edf8696c04376b0b37d diff --git a/tests/Febe.Tests/Media/H264/Conformita/sp1_bt_a/sp1_bt_a.h264 b/tests/Febe.Tests/Media/H264/Conformita/sp1_bt_a/sp1_bt_a.h264 new file mode 100644 index 0000000..dc76699 Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/sp1_bt_a/sp1_bt_a.h264 differ diff --git a/tests/Febe.Tests/Media/H264/Conformita/sp2_bt_b/riferimento.md5 b/tests/Febe.Tests/Media/H264/Conformita/sp2_bt_b/riferimento.md5 new file mode 100644 index 0000000..8e67570 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/Conformita/sp2_bt_b/riferimento.md5 @@ -0,0 +1,402 @@ +# sp2_bt_b.yuv 176x144 4:2:0 8 bit, 400 fotogrammi, 15206400 byte +tutto 77fef826070d3d17174529b16765bb24 +0 6cda07ad5c6e657e324fa07bec857073 +1 92692ec1d9bd6cd05e8d94e120897889 +2 94a7db8e3a1fd2597d4fe8dcbb940849 +3 7cf222dbf0df6ba4069856dcd07be435 +4 4305b2328318406cc803841ddeaf0809 +5 2ac1c304bd22200cea0836983d42cac0 +6 6b6754a3e0eced0e7234e54a1db365b6 +7 279982cab8f1547e3f9132e0b252efa0 +8 8b8b749e2ddbc377f24646694c3343c9 +9 bd95dad0749d7977c1028d9b88982d92 +10 42cc9f3be0d70e77d66b42d822df1f48 +11 5caa7f6ff698ac4e955ae7f8dcd8b8c9 +12 8f50bdc4cfc0b7832b8a08700910b3e4 +13 7c3cbd84ac6ccc54b1747ddfeb8a4de8 +14 2077ec8fd3fec1c25b3aa456a0364114 +15 8fabb386575ba31a10d1bf9241e174d2 +16 c265a6242a113954f7ebe67fa75e2985 +17 09e3f37aaa644a0ed7d1917636893608 +18 ee6e904bff28b26098a7e378c9589a69 +19 cb89dcc1e4b05a689d59aa2d4ee1e45a +20 5634c4393e66b12fd9bc12806d1133cd +21 4371cbf2b1ec122dd1ceadfef1f5fd9e +22 2271d46ac2bf8de542b4148a4f013b73 +23 eaaf4cf61cde8ea34321c5bb8ab3cef5 +24 cd36f1e08ca99f4460694c6b4e3af305 +25 3cadd16b2f101f98e07ef0c5f05a8215 +26 7b3b4e45f711d3be938b8c66a9027f30 +27 d0c4c3de3f2d5d73fd4edc337221e249 +28 1228e8630e487587796a433efb3ab483 +29 48b0408737c910e6bee14b0e4a5d6819 +30 998fd1fb6c6d054adccb3265b6a6ecb7 +31 55c7eed702ef66e1ad073b0df3317ec1 +32 f01b14758327540e6c4eb39e8759b8f2 +33 a01d15f7285170b02a565bfb002be74c +34 c89b367ba7dff5b9b5dca0f47a4756dc +35 6db9640a97c28f3b3141050b9d4c9681 +36 6a31acb305a8f34a710c9215cad307b5 +37 78bd9b4af86c2034c395d5e6040e8a57 +38 7d4cc3919e54581a6cfd5b65aa53c058 +39 f6f9b89f9c2d2aa9075fe40ffeeb6ad0 +40 9f8a420f68e08773de03bc735076a19c +41 3d1f9c9c06b04ef10e6a86a7ab20d9f9 +42 e052ee6bbc97995e915b02ee02064953 +43 edd8d1c7ae4faf9dcacdc9389ad290cb +44 a4dd0f7d12c038385e8c0a32740cda4b +45 6827d4ebb0cef24c78259e0887122a07 +46 87d62bccfd329da3bfd6ea900e29ac04 +47 39d166cf9cd726bd79f07f2732363bf3 +48 467eb8f9812ad301417835fba3920e07 +49 6b255f752485291e4d512ead9bf49cf0 +50 9e2407314f76d3d78c33ecec19852158 +51 2b85a29be0cc3226944d2b8c9f94cc97 +52 e3e47460009c028f03664fb7eb5d5c37 +53 63ddebb1aa78756ecf12b773376d3d78 +54 e90426df4580fc9db864ccb7454d4037 +55 cb5e08deabc2c5683a08e06607060fac +56 f36d5ad4c368b2a78d87a8ca1ea95300 +57 fa1e9206c859bb1ab9f581d94af668ac +58 4fe1006ba9469cfb83d8b13a009e930b +59 0dd7a77511fc898a9fb3c8da92e8b372 +60 3e80b85067afeb073c37646adc4e9ef6 +61 3562efeaa77018fd39cef344d045c922 +62 ca477add548d576f7357524c8f9db806 +63 c12cc3fc9306daa536e4224c370ea515 +64 72f6911153eddeb82e70cad2478c7805 +65 029b70687b79a10d61d8806788f5ccc9 +66 d50cf9782312827c2ee41dc2f6e80a41 +67 20288482dbf9af3bda51752fc7f2aa65 +68 c6edab3a8938b2a8ce21dabf8e2e2c48 +69 bc966c91c6ea316cc83f0ebf227fee1d +70 7052b02a3a7f77489ccecd816f588779 +71 e5f510d23e158ee0c5bf6e329f259f49 +72 c9cf6a7905c5c9299a280a14eba6d464 +73 831f8a7169aeee5e9fcf573aae92d2d1 +74 8d1ef16f3453a8de676bbd625bf855ac +75 0969809a2823ed8e3fd6b87fac708602 +76 3a38a23a2e1df34eec90336b6903818a +77 bd3bf38e5df820f843e876133d7c87ea +78 8fa66a62089282bf26b294b8803ea67e +79 37152aacb25c16a1091588a4d6eb8f1d +80 7a119a4620b3384edff46648538be34c +81 146db81799b4e3967663ce503af88170 +82 3fa2e29213f2003a5c472a704cfa1456 +83 e79fed429decc6cfbfa245b1ee1ec741 +84 1adddd3f75196c49b70fe820165f09e6 +85 5ac7c6e0489497f996405c4f2474d0cc +86 b3e381b7c96d01cbcce6bee5ce1b503e +87 06695029fe57791b28495c11eb5ea70c +88 5923fe76575bf973cfe78c6bed5b8042 +89 547446535bec4cff44981edb7537ecbf +90 27ce160ec547b6de03eb5df859f523c4 +91 2f9f18cc2c9b778fe72863af14fad252 +92 852602617d146fccbcaadcacc2c01b66 +93 77fa9be840b1745296cb980ff10a8549 +94 ae59137fe4236ddfdf592c3090707552 +95 6eadfb952c5c71c7a5346d1f7e225246 +96 f373b72c56b5ebfc3d1f03378f21114f +97 6998e278914f6a6ade55ab023f73a98f +98 01f20247e8f3804ae39b74955823dfd7 +99 f61f0b7633980e7c333c895a32121601 +100 a5f297bf92bf508cb419cd62eb58da0a +101 bf808f8f91d3fceb9b87f464325194cd +102 b4bf592a51eb0a0dd7ea85164bda1f43 +103 b5348c4a7b467fb0b7817b3e56b04e21 +104 62dc34a2fd81cfcc300504e57acb5b52 +105 233a2215ca0b983fa52d309dff50c424 +106 d73669d9fc4138ba6428e844e6ae6244 +107 b8258e7076936e8a9aa2dbb33c919d7b +108 3c161fb2608fa483421f1c08215b902a +109 5ce846cbf61fc4a45bc96b351cd8d8d8 +110 e1443024a0775112760830f896e41f69 +111 22da2d5b561a9e0f9fd432b4250618a1 +112 6b736de2247182a872b6def296dc736c +113 411de67a408cc9d0b83ced97682dac57 +114 a0c5b800ed3d2672ebe24eee57ec05e0 +115 94ee0128cb3838d08e8f0f0f8c8672df +116 7a660dd339fca68ae009f6ebaf8f1a3d +117 b5de95618b1aa3a63d9b7f4de334b3b7 +118 91165f826668d7924871ee7a21908858 +119 1d6d0f665b15ff18b132956080ca7d4b +120 59022388f8e1faa9f1ccd44c8192095d +121 cb383f34434373e2ce03f54f38763a24 +122 68f7576adb0990f7b412eeb8a71f1b51 +123 eab0747228bb0665b9790357bb132a49 +124 58cf44f35cb3a10ee88df0f66117e3c2 +125 e0c738eba168619a42c1c724cfe190e9 +126 fd77991453f9b64f9807965c28113908 +127 7b161e97f5b2a4bc701ca657017d5c33 +128 ff56435332fdbf43bdad490a23b48a02 +129 612b90445cfe9fb165f2fcd6fe29710e +130 fc1dbba8d066ce81e21a9be673e8ca35 +131 7b409bd47614597cc4b7f4948ded0090 +132 38cb637f4f00a6396040bf471c243510 +133 b5a1371db1facfb86f4301485815e57b +134 097a01ce4eb14392a56dd9259b836a04 +135 67f34e94f6d2ad6d8f3e5a82ab968576 +136 ba1643337132227263a5ad9334d7bc1a +137 0366481dcffb217047a5b2a00502ddb1 +138 4929be24dcd77ab337e916d1258ef89f +139 69dab8a125e276e7703244a282f1e7d3 +140 eaf3bba661047b35dc04077cd94d6a59 +141 e137edc71b75bd63932ff4c859ef87a7 +142 7cf3548e9c0575225d52c751e280b10b +143 d44e92323f378abd7bdd931137358537 +144 903b5a73bcd1ee5fe6c8eaf777d14f61 +145 67fc481264eae41874058c3701111760 +146 a9a23429c34ab598ccff837a3ee927bf +147 e2c25f133aaa59ebed901fe929d7ec48 +148 2c78b6b46fb4d00f519963409acc7619 +149 4da4d965c999e0a08970036c0189011d +150 9791f06014c4a2661710fadfd00250df +151 f83b1b28e917c16e6929c1646774103d +152 6ac92bb6064f7cf2a00ace0ca176535c +153 482777e2bfb7bfe7cfb2c12412828a3e +154 c266943a63f37ea0d8ebd6f41f3385bf +155 af29af79d01621ac648b8815acc1d85c +156 79ffd8818ad3be1bd071fee632c2063f +157 1aa6eef8fa99de90e06d0e29e27b6875 +158 832fae63e360a03e7f14571fa3ec7482 +159 be039529b03f496623e36e9fd40e5b65 +160 54a86d8ba4aaa7b18a35a2f4494ea157 +161 b03e8be6fb9b68a41a5fa51223c93dd5 +162 87f3af98ed6b7d73859100bb5db2f147 +163 e29f22ea65ccb4979464a18a89f50d0c +164 b30654bbb461a4e5c3613a136a09f7a8 +165 b9827befeb64f15814fbae9450541653 +166 eb65a312db1f80b1eb527c02f12ade4b +167 86d3ccf5734ac9f74809a2e3c35bc8bb +168 3f41a8ec066b6bf43df4a123cca1ad56 +169 8190df3579db4bd70aa32f6c136798b5 +170 1ec47a8abd664ef31934a6acd630f6db +171 1a4313621a938fe6fd399a0d311f2697 +172 ca5e3283147c974b33aabd1bac887a57 +173 994a23c7db0e1199d97ace4c1aa85287 +174 bf1294a924b29ec50a7f29e50b89b8f3 +175 2a30d58b88e40e63800474c9303b4e38 +176 12e6a061ade25a621b96fea8f042292e +177 6b9d6e8b539bdf5e7993ac1812adf13e +178 ace2bab52062358bc9896273c0759f32 +179 5de28b076f169bd5275befacb36b01bf +180 6c0b54638e9ef4c90f7fd6289f514e07 +181 44b73ec5484b7f7ec8f73f6e714780d1 +182 fa93284b22d65ad94b2c4675a1325e5e +183 b677c79c8d6b82e6cdfdce6d5b69f7e7 +184 4ea881af4faa75b5891bf019966b1af1 +185 e92aed03a7a71fa8d840474ab0e75bfd +186 06d84e36355498583f923285e66c43d4 +187 f2fb86d85247a744886be3b31f14a017 +188 f54278f9597d1288525dbaf12a4604ef +189 9ef7bc2c6253ade0bbcc6de200afc25e +190 be915604ce9fe40ee604837e9cbc1f9a +191 31a2d3e4e5f97e792d4de1a247cb2f32 +192 f28d76526316408075f05873a7deb19d +193 d93aeba41d4dba68e1431d37dab9580f +194 b691bc48292dde4fbdbec233df323552 +195 03e9cfca8e4e50840f75683ebedb37c6 +196 ee5eec60f7da5f7bf4369df98cdf4b84 +197 fae3b067418ac5c0765f944d6fcd8f23 +198 2e3fa0913d4e1c34cd6f5e452b65f486 +199 8c38d5baa8992d8bc1bfde1af6c03315 +200 67aff2492cf028f98b96c4814e29fb91 +201 b3a5af6badb66a0bb8543f9879e17990 +202 375dda5d2c0dbd9214b4da65e3020e84 +203 3f79ba7e5931385db8e7d30de3f01c29 +204 8107c74f24f493ade2f9bb86dbb58d45 +205 4d0f33de93ef5001902d465cdc6462ff +206 eebca963630cffa6ccae3dbc098bc3ab +207 0588e31951ad84dbc9f87103889a28a1 +208 20a520d8f642464979f7b3540d11bef6 +209 fbe519a8d230e8033ab71e15e7b36807 +210 d891138e70b87d10050770d885f590f1 +211 eded53c770050a109d4af601f4850735 +212 ca1bc51a13f03f1be38bfe9e66ebd58d +213 668bfdb00b5963600f0ff9c9f88ec72e +214 d4c823ac72ade27a9b84871816a3c876 +215 10d7df61f3c6b8babf8114cdea6e6f20 +216 a7165b9edf91b4711f3b17e0ef58b089 +217 8c63832b391f049028bec81ee536cfe3 +218 f0e0d70994d13616e12ab0a5daa17e6b +219 a919729e847c678698733940a142af49 +220 de748ae31997c95121100bb998ad9e53 +221 543be7f33e51252e37fa6eff18e2e8a0 +222 47f17ae3bbd377f2d0ecb406d99c0d35 +223 4d964cdc10e35a2da01cc17e9a3eab56 +224 167936639b7b3ca3c538eb7d69504b86 +225 fa0c83a1dc334d281cc01b0fef54ca76 +226 859feabad4d0fff505629b65e3abe7ff +227 2bd734ae9dc5d5a8f96641f85909205e +228 993582c3011db58d413fbb13ae2b73a1 +229 d47b78153bfbe613daf3eb2f23f49771 +230 37b0d281e73103e7b74e4b409750d4f2 +231 033256e98f9b1778add71dc780f7aad3 +232 cba4b43eb00db6a1fde1dfcdf3df73bc +233 e4a1f12c828ab9af0020a3c396c3141b +234 9055ebe0f89315ce85294443c0422b2c +235 1ddd2a898bcf730b20eba74f9e252259 +236 00c49cb7603e6c1d88715c7721e37cc1 +237 9a55641f99cbf0bab4f60af45565c9bb +238 852f7503bce3643d378e26b800ad4d74 +239 05ce1afe85c8bc8ee4ffb097a754a348 +240 e33e1550025a3260f05cb5c07059bfdd +241 df43ac05d7619df47e468b48e308e7f3 +242 8b1f00dfe641ab05ae9b4ec6941dcf6c +243 9b31872a9167b27f3fa6eea5025b7c6b +244 c576cfbc6b62750fb029e525a0c2333e +245 2640fe8f44e4bc96eb8b96adbec4435d +246 3b8aac360332bd50c8bb171c2392b860 +247 4f9b0cd7d2d8ef814d7216763f0fb2c4 +248 078c68254f3bb8fc403f2b3c1dc29f54 +249 d71664500aaedbad7fb4fcc9f3375f2d +250 ea3c1ccebd4cd4ff9457b4d6b8dc5efa +251 c1a763743d644989719d69f3190ec75f +252 ed712c6ad8727f5108c2fb53cf3faa14 +253 565da6c75b8c7a8f4bcc3baaf12879bf +254 551ed1a3fb026f47e9f64560414507f3 +255 579935a9ed7fbafd5274794b7bd619f5 +256 c9d8758b35d49be1f99fca9ef2b7b70a +257 1314f68b584f89340c2667298bd6dede +258 7cf13f6585e2e3cfc93125c020a99692 +259 c0904810d9ebd2d247d6b1baa28f405d +260 c058c07e172b89ba806230e378993fa4 +261 821e92c72ded2a649e9837252fe2c551 +262 80de8965523219006ced6990dfd2ba3f +263 c56b3a94c15f4e1fc49ebb34bfdae127 +264 695be17c5a7246bf5984ff8932e40107 +265 3e1cf444efc993fd4f63e482a250a831 +266 acedf44189e2b51a13d1c1fa52822c99 +267 c6990f354f235db4088fc04437509521 +268 edadf41b1963e3dd76180d9845ebfa94 +269 bbd72e394abe33d36f1757a4f4891450 +270 fa0882f013b3b5d8815deda8cff92b74 +271 18dc313d3f793882ee1fcb596f39f33f +272 a0bc2290c5d05724330a5c2e43226171 +273 e0918d5b6d96934cbde56e0d2c9da01b +274 a0f87215efc4aa1d86f569ecde0c533f +275 a4f589009f382082a18008c6ac7bb555 +276 ccb5035a4182732b52e82a94e84ea044 +277 32337b2e2ed1dd48dbb75090107a6a11 +278 0e6aa6bc7af7cfdf59f931b97628fae9 +279 2bd292a5658f5e24a9f09d1f52d5f5a9 +280 c450cf8f6947f50deda170cc5c90f769 +281 cae6bb0c054f6dbcb3c29aaa528506af +282 34d0742e6010f1c67706a614bf540d23 +283 58dbe04ce3324c84804b2bc2930edb4d +284 02d0a2ffba53c89ebc613d807df37644 +285 458a83af687c01a2f3e89065f7988364 +286 ec62ed2bdd074b048de2e154b4fb6324 +287 14f4e6f657507f0019b03e4ca22fb935 +288 512b0d5ddd9812609976cbb7e5ce74b0 +289 72c3e751b8deb3ba16688bda83015b34 +290 5bbdac229fa562781e94a931267ac2d5 +291 9361f1cd5d64813a51833840a2e30119 +292 5cc7e143536f4b21e06a43a99095c792 +293 cab007ec080af8e23c4eef9d2c14c9c9 +294 5e266117bdb4c36ed49f845214e55502 +295 80e4322186cb040e4c28f0eaee4627a3 +296 5c1b6d5783a7d5068f5b81e95b88b7fd +297 6e09dd24d2ff4f64d3d2bbcdbe0a7726 +298 ac6d8b0f5d19ee30b597b278d3c2f737 +299 f5d53c710bcfc3bf7305f96dfbbe7022 +300 91164963135eeb9c742ebade125ba43b +301 bf326df8ed971b3922f2bdb2309a7ee6 +302 ea27952d3fcdcabb4060cf3d81a79e2d +303 8047265e81af7aea8c4518d638434ccc +304 cc4bcc377d450d8ff1412e7627415202 +305 92a5f2b081db7e778529e17dc1bf2c3b +306 67c371ed6582f425b3b7f955cc702639 +307 d60e046670a75664b8671f753fc732f3 +308 2f6abb8e2b66dbbebebbc56d2f5b081d +309 5586cb9e90261165f6d9b46ecaf351b7 +310 da31d96fa8684da3f4f06f4051bb9251 +311 c5bbd783cb15b0c3a5d5ad73f7088b85 +312 18622719060e0392018967d08d56fbf8 +313 21450a458a27463efd8e560aa3b2b1ab +314 35590aee87b6847565835955b12a587f +315 6ec2cb63e439531717bc6abe18729ca6 +316 0d4992d6b21c73ebad7eaeb51c33e320 +317 8ffec9095eb151f278f7ae61dabd9b0e +318 3a926d4e078725320c443bed1e32a43e +319 4ec48bb92ed67bee25e1fd9c79a036e5 +320 34c1e2c30ae66a3b7cb37f8d8e450ea6 +321 f61ce86964d27bcb63524f66941a5a66 +322 60c562700ff0c7f9ccf371c038d628dd +323 1431007994c6e30833d273190446f2b7 +324 18f2892f4f71849433870dc997405a1d +325 25f4efd5434b4797cc0c66ffc1bc8043 +326 cfbfdce7670c79a461935b2357c5d797 +327 070eaee0b9c463ce79f57f1b33d37977 +328 dd0c84f30358a8178dd5984d24548ce4 +329 042f307e6c26f208b39d3af74b18c533 +330 e9eac4a564505eb1c2317268d7210cea +331 84fca3a870a0527f37ceefa7f695d9c9 +332 5554d5823d7101684729a332e6d7d32e +333 af3b7c78506b065d7bb0e01a1a2400cf +334 32d3ee6dbf9049040baf78d255c7f843 +335 2dafbca54df9cb1934c189efce81bb74 +336 2f696439e80031d0ffffbb85a5f6ac8a +337 668e86c4ee37b5498b7bc274b57209de +338 68978cc8fa96cf977810170dc6c45d82 +339 cd24a263a6d23509d0804b9d05fd6ee8 +340 d82834863d4093281478d258676b62cb +341 718794ca92b2daa671eafe114c3d4036 +342 6db0b105b2c7d89c3c5af539522d77f7 +343 3a207b8ea281011b34a10c951dcf611f +344 591ef6aede22264f45c2f2991961009b +345 f2ac71715f4e6b2c48fedfe27ee810e9 +346 8425e528d75c3b4c7e8abb69cf22808f +347 3155548fdc16e74cc99094b9bef044a1 +348 f38c207fbe6c8f6d8d8a97a6f90921bd +349 ba431ea771c20e59e4dea04b8ae800af +350 64f514fec788722db9f73041e10df304 +351 9624311248695cf9bfe4231fa2be7e8b +352 1b1e1075eff7f427cfecabe0f732bcf4 +353 ff8b5aed1ca68a5beee05c81a05c5f91 +354 56ea4816ea6dc935fc054272f452d3fa +355 6d64b16cccf5ebe20e720ef35ac27d75 +356 98f6e5c405ac6a08b183356a577aad3b +357 b629a9546fef76760cb99b26c1713693 +358 eb98c71b37fec1998bfec3de1a3fdfaa +359 c16f548b8b32e8660c827e763fcac36f +360 4bc15ba9951e11b6321151f2a30940e6 +361 b07433081d17690d159f648a2a1bcc3e +362 96d11d26fa44fabef63dcc8a22be46a3 +363 9adbdb1053910fb3fdc83e40fe048ab3 +364 faf1fcf919f085259a221148137c0a0b +365 7176f493ee15417faec92f11da874a4d +366 b9504ac56d595027850d383df40483e2 +367 71c946126e82db30670b1d934cc0d191 +368 cc740c64172e72a7c40f8d2d1965f2f3 +369 07881ee2d16df3ec9805b82505e498e2 +370 f41eb690fdcb1cc2de5d4d28c1a01fd2 +371 93ad833d623f894941923da644da97f0 +372 3893adf950f2027252ea42112b749dbc +373 480f6bf637a4ddd75736a23db897c7c4 +374 ea7c9495a47d480c100d60941922fe69 +375 7bfaf0d9453e6c6de1f1b2e0a5dd9898 +376 a32d58996604d6b5b3c6cb7d9adcfaa0 +377 5f62f898f1703f78ec7617559730bdfb +378 12b0a0c8e812ec5e474806b803097de6 +379 f8e3cd88d45c1458b182d7c584c71156 +380 4d9dbcfa2103bfd35f528fe8af913f74 +381 172e828e80458294e0fc7664b1170059 +382 118f66d349ec1d4a73394fb36a176530 +383 84a64c91cb639d9dd59ead7ab0ecda66 +384 8a66016425af12a84eda52cb19d2916a +385 86e655a0b0e1626527950dfa319c6c99 +386 5acee122c6b66157284c9d606c1f80ab +387 6a7687f98a4a4a9128493b9bed3b3ac7 +388 139b020c9be28bc788676bfc2957691c +389 e9da3dd443dd07cab0c3b8e40629c7e1 +390 e8b7cb749fe29763105b90bed8714863 +391 f1bc67ea6c6cb4bcec1d19e0b9ae3ac4 +392 c5f9326c70ef7e532f8660d13695c794 +393 1df983c1d3e03b183d426e63cf7f7573 +394 ef5e7f6b9bc9e168c4297425869d1410 +395 85e1b2e46478b285c688feaa39059d10 +396 aef12361dc54c6a1ec33827beb8cba65 +397 449b734ccfba9a5e1935c26c3baf6973 +398 12002f7502fd04fda15ec739b0fa093f +399 04c049766df5f93ca82497366945117b diff --git a/tests/Febe.Tests/Media/H264/Conformita/sp2_bt_b/sp2_bt_b.h264 b/tests/Febe.Tests/Media/H264/Conformita/sp2_bt_b/sp2_bt_b.h264 new file mode 100644 index 0000000..7d6948e Binary files /dev/null and b/tests/Febe.Tests/Media/H264/Conformita/sp2_bt_b/sp2_bt_b.h264 differ diff --git a/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs new file mode 100644 index 0000000..12c9e4a --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264ConformanceTests.cs @@ -0,0 +1,354 @@ +using System.Security.Cryptography; +using System.Text.RegularExpressions; +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The decoder against streams of the ITU-T H.264.1 conformance suite: every output frame, in output order, must have the +/// MD5 of the corresponding frame of the official reconstruction (see Conformita/LEGGIMI.md). The verified streams include +/// interlaced video — field pictures, PAFF, MBAFF, both together — with memory management operations, long-term +/// references and POC type 1 on fields (MR6_BT_B, MR9_BT_B), slice groups of every map type with slices in any order +/// (FM1_BT_B, FM1_FT_E, FM2_SVA_C), SP slices (sp1_bt_a, sp2_bt_b; sp2 with the deblocking filter on), 4:2:2 at 8 and 10 +/// bits with CABAC and CAVLC (Hi422FR10–15_SONY_A, FREXT2/3_TANDBERG_A) and monochrome 4:0:0 (HPCAMOLQ_BRCM_B, +/// HPCVMOLQ_BRCM_B). None of them +/// uses weighted prediction, gaps in frame_num, I_PCM, SI slices, sp_for_switch_flag, data partitioning or redundant +/// slices: data partitioning, redundant slices and other slice orders are checked on conformance streams rewritten by +/// (), SI slices and the rest by +/// , without an official reference. SVC: the target layer of SVCBMT-13 (MGS quality +/// refinement) is verified, the base layer of every SVC stream too. The streams of the parts the decoder does not handle +/// yet (SVC spatial and CGS) or that have no official reconstruction (MVC) are in : they +/// are inconclusive until the feature is written, and fail as soon as one of them matches its reference without having +/// been moved among the verified ones. +/// +[TestClass] +public sealed class H264ConformanceTests +{ + [TestMethod] + [DataRow("BA1_Sony_D")] + [DataRow("SVA_BA1_B")] + [DataRow("BA3_SVA_C")] + [DataRow("BASQP1_Sony_C")] + [DataRow("CI_MW_D")] + [DataRow("CABA1_SVA_B")] + [DataRow("CABA2_SVA_B")] + [DataRow("CABA3_SVA_B")] + [DataRow("CANL1_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("FRExt3_Panasonic_E")] + [DataRow("HCAFR1_HHI_C")] + [DataRow("CVFI1_SVA_C")] + [DataRow("FI1_Sony_E")] + [DataRow("CAFI1_SVA_C")] + [DataRow("Sharp_MP_PAFF_1r2")] + [DataRow("HCAFF1_HHI_B")] + [DataRow("CVMAQP3_Sony_D")] + [DataRow("FREXT02_JVC_C")] + [DataRow("CAMACI3_Sony_C")] + [DataRow("CAMASL3_Sony_B")] + [DataRow("HCAMFF1_HHI_B")] + [DataRow("FREXT01_JVC_D")] + [DataRow("CAPAMA3_Sand_F")] + [DataRow("cama1_vtc_c")] + [DataRow("FRExt2_Panasonic_C")] + [DataRow("FRExt4_Panasonic_B")] + [DataRow("MR6_BT_B")] + [DataRow("MR9_BT_B")] + [DataRow("FM2_SVA_C")] + [DataRow("FM1_FT_E")] + [DataRow("FM1_BT_B")] + [DataRow("sp1_bt_a")] + [DataRow("sp2_bt_b")] + [DataRow("Hi422FR10_SONY_A")] + [DataRow("Hi422FR11_SONY_A")] + [DataRow("Hi422FR12_SONY_A")] + [DataRow("Hi422FR13_SONY_A")] + [DataRow("Hi422FR14_SONY_A")] + [DataRow("Hi422FR15_SONY_A")] + [DataRow("FREXT2_TANDBERG_A")] + [DataRow("FREXT3_TANDBERG_A")] + [DataRow("HPCAMOLQ_BRCM_B")] + [DataRow("HPCVMOLQ_BRCM_B")] + [DataRow("SVCBMT-13")] + public void FramesMatchTheReference(string name) => AssertMatches(name, "riferimento.md5"); + + [TestMethod] + [DataRow("SVCBMT-13")] + [DataRow("SVCBST-19")] + [DataRow("SVCBCT-1")] + public void SvcBaseLayerMatchesTheReference(string name) + { + // The base layer of an SVC stream is plain H.264: a decoder that skips NAL units 14, 15 and 20 (prefix, subset + // SPS, slice extension) must give exactly the official reconstruction of layer L0. + AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), "riferimento-base.md5", enhancementLayers: false); + } + + [TestMethod] + [DataRow("SVCBST-19")] + [DataRow("SVCBCT-1")] + public void SvcLayersNotWrittenYetLeaveTheBaseLayer(string name) + { + // Spatial scalability and CGS are not written yet: the decoder says so and gives the base layer, exactly. + var data = File.ReadAllBytes(StreamFile(Folder(name))); + var frames = new List(); + var decoder = new H264Decoder(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(data); + + Assert.IsNotNull(decoder.EnhancementLayersSkipped); + CollectionAssert.AreEqual(ReadReference(Path.Combine(Folder(name), "riferimento-base.md5"), out _), OutputOrder(frames).Select(Md5).ToList()); + } + + [TestMethod] + [DataRow("MVCDS-4", 2)] + [DataRow("MVCNV-3", 3)] + public void MvcDecodesEveryView(string name, int views) + { + // Without an official reconstruction: every view decodes, with as many frames as the base view and its size; the + // base view is the same as the one a plain H.264 decoder gives, and the others are pictures of the same scene + // (close to the base view, the difference being the parallax) without the block edges a wrong prediction leaves. + var data = File.ReadAllBytes(StreamFile(Folder(name))); + var all = new List(); + var decoder = new H264Decoder(); + decoder.FrameDecoded += all.Add; + decoder.DecodeAnnexB(data); + + var baseOnly = new List(); + var plain = new H264Decoder { DecodeAllViews = false }; + plain.FrameDecoded += baseOnly.Add; + plain.DecodeAnnexB(data); + + var byView = all.GroupBy(f => f.ViewId).OrderBy(g => g.Key == baseOnly[0].ViewId ? -1 : g.Key).Select(g => OutputOrder(g.ToList())).ToList(); + Assert.AreEqual(views, byView.Count, $"{name}: viste"); + Assert.AreEqual(9, baseOnly.Count, $"{name}: fotogrammi della vista base"); + CollectionAssert.AreEqual(OutputOrder(baseOnly).Select(Md5).ToList(), byView[0].Select(Md5).ToList(), $"{name}: vista base"); + foreach (var view in byView.Skip(1)) + { + Assert.AreEqual(baseOnly.Count, view.Count, $"{name}: fotogrammi della vista {view[0].ViewId}"); + for (var i = 0; i < view.Count; i++) + { + var other = view[i]; + var reference = byView[0][i]; + Assert.AreEqual((reference.Width, reference.Height, reference.Poc), (other.Width, other.Height, other.Poc), $"{name}: vista {other.ViewId}, fotogramma {i}"); + long sum = 0; + for (var k = 0; k < other.Y.Length; k++) + { + sum += Math.Abs(other.Y[k] - reference.Y[k]); + } + + var mean = (double)sum / other.Y.Length; + Assert.IsTrue(mean is > 0 and < 40, $"{name}: vista {other.ViewId}, fotogramma {i}: scarto medio {mean:F1} dalla vista base"); + var edges = Blockiness(other); + Assert.IsTrue(edges < 1.5, $"{name}: vista {other.ViewId}, fotogramma {i}: bordi dei blocchi {edges:F2}"); + } + } + } + + [TestMethod] + [DataRow("SVCBST-19", "SVC, scalabilità spaziale e temporale (strato L1, 640×480)")] + [DataRow("SVCBCT-1", "SVC, qualità CGS e scalabilità temporale (strato L1)")] + [DataRow("MVCDS-4", "MVC, due viste")] + [DataRow("MVCNV-3", "MVC, tre viste")] + public void FeaturesStillToDo(string name, string feature) + { + var folder = Folder(name); + var expected = ReadReference(Path.Combine(folder, "riferimento.md5"), out var declared); + Assert.AreEqual(declared, expected.Count, $"{name}: riferimento.md5 non ha tutti i fotogrammi dichiarati"); + + List actual; + string? skipped; + try + { + actual = Decode(StreamFile(folder), out skipped); + } + catch (H264Exception ex) + { + Assert.Inconclusive($"da fare: {feature} ({ex.Message})"); + return; + } + + if (expected.Count == 0) + { + // The CI counts as «da fare» only messages that start with it (.gitea/scripts/riepilogo-prove.sh): any other + // inconclusive result is a skipped test, and the CI allows none. + Assert.Inconclusive($"da fare: {feature}, confronto bit per bit; manca la ricostruzione ufficiale (oggi escono {actual.Count} fotogrammi di tutte le viste, vedi {nameof(MvcDecodesEveryView)})"); + } + + if (skipped is not null) + { + Assert.Inconclusive($"da fare: {feature}; non ancora scritto: {skipped} (oggi esce lo strato base, {actual.Count} fotogrammi)"); + } + + var same = 0; + for (var i = 0; i < Math.Min(actual.Count, expected.Count); i++) + { + same += actual[i] == expected[i] ? 1 : 0; + } + + if (same == expected.Count && actual.Count == expected.Count) + { + Assert.Fail($"{name} ora coincide con il riferimento: spostalo fra i flussi di {nameof(FramesMatchTheReference)}."); + } + + Assert.Inconclusive($"da fare: {feature}; oggi {same} fotogrammi su {expected.Count} coincidono ({actual.Count} decodificati)"); + } + + [TestMethod] + [DataRow("CABA3_SVA_B")] + [DataRow("CANL1_SVA_B")] + [DataRow("FRExt1_Panasonic_D")] + [DataRow("FRExt3_Panasonic_E")] + [DataRow("HCAFR1_HHI_C")] + [DataRow("CAFI1_SVA_C")] + [DataRow("Sharp_MP_PAFF_1r2")] + [DataRow("CAPAMA3_Sand_F")] + [DataRow("cama1_vtc_c")] + [DataRow("HCAMFF1_HHI_B")] + [DataRow("MR9_BT_B")] + public void PicturesLeftOutDoNotChangeTheOthers(string name) + { + // Pictures nobody refers to and nobody wants are not reconstructed (only their headers count): every frame + // handed out must still be the one of the full decoding, in the same place of the output order. + var data = File.ReadAllBytes(StreamFile(Folder(name))); + var all = new List(); + var full = new H264Decoder(); + full.FrameDecoded += all.Add; + full.DecodeAnnexB(data); + + var some = new List(); + var partial = new H264Decoder { Wanted = index => index % 3 == 2 }; + partial.FrameDecoded += some.Add; + partial.DecodeAnnexB(data); + + Assert.AreEqual(full.FramesDecoded, partial.FramesDecoded); + CollectionAssert.AreEqual(all.Where(f => f.DecodeIndex % 3 == 2).Select(f => f.DecodeIndex).ToArray(), some.Select(f => f.DecodeIndex).ToArray()); + foreach (var frame in some) + { + var expected = all.Single(f => f.DecodeIndex == frame.DecodeIndex); + Assert.AreEqual((expected.Poc, expected.Period), (frame.Poc, frame.Period), $"{name}: ordine del fotogramma {frame.DecodeIndex}"); + CollectionAssert.AreEqual(expected.ToPlanar(), frame.ToPlanar(), $"{name}: fotogramma {frame.DecodeIndex}"); + } + } + + /// The folder of a conformance stream. + internal static string Folder(string name) => Path.Combine(AppContext.BaseDirectory, "Media", "H264", "Conformita", name); + + /// The Annex B stream of a folder, whatever extension its authors gave it. + internal static string StreamFile(string folder) => + Directory.EnumerateFiles(folder).Single(f => Path.GetExtension(f).ToLowerInvariant() is ".264" or ".jsv" or ".avc" or ".h264" or ".jvt"); + + private static void AssertMatches(string name, string reference) => + AssertStreamMatches(name, File.ReadAllBytes(StreamFile(Folder(name))), reference); + + /// + /// (the conformance stream , possibly rewritten) must give every frame + /// of the official reconstruction. + /// + internal static void AssertStreamMatches(string name, byte[] stream, string reference = "riferimento.md5", bool enhancementLayers = true) + { + var folder = Folder(name); + var expected = ReadReference(Path.Combine(folder, reference), out var declared); + Assert.AreEqual(declared, expected.Count, $"{name}: {reference} non ha tutti i fotogrammi dichiarati"); + + var frames = new List(); + var decoder = new H264Decoder { DecodeEnhancementLayers = enhancementLayers }; + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + + var ordered = OutputOrder(frames); + var actual = ordered.Select(Md5).ToList(); + for (var i = 0; i < Math.Min(actual.Count, expected.Count); i++) + { + if (actual[i] != expected[i]) + { + var f = ordered[i]; + Assert.Fail($"{name}: il fotogramma {i} (decodifica {f.DecodeIndex}, POC {f.Poc}, {f.Width}×{f.Height}) è diverso dal riferimento."); + } + } + + Assert.AreEqual(expected.Count, actual.Count, $"{name}: numero di fotogrammi"); + } + + /// The frame MD5s of a riferimento.md5, in output order. + internal static List ReferenceFrames(string name) => ReadReference(Path.Combine(Folder(name), "riferimento.md5"), out _); + + /// The MD5 of each frame of a stream, in output order. + internal static List FrameMd5s(byte[] stream) + { + var frames = new List(); + var decoder = new H264Decoder(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + return OutputOrder(frames).Select(Md5).ToList(); + } + + private static List Decode(string stream, out string? skipped) + { + var frames = new List(); + var decoder = new H264Decoder(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(File.ReadAllBytes(stream)); + skipped = decoder.EnhancementLayersSkipped; + return OutputOrder(frames).Select(Md5).ToList(); + } + + private static List OutputOrder(List frames) => + frames.OrderBy(f => f.Period).ThenBy(f => f.Poc).ThenBy(f => f.DecodeIndex).ToList(); + + /// The mean luma step across 8-sample block edges over the mean step inside the blocks (about 1 for a clean picture). + private static double Blockiness(H264Frame frame) + { + long edge = 0, inside = 0, edges = 0, insides = 0; + for (var y = 0; y < frame.Height; y++) + { + for (var x = 1; x < frame.Width; x++) + { + var step = Math.Abs(frame.Y[(y * frame.Width) + x] - frame.Y[(y * frame.Width) + x - 1]); + if ((x & 7) == 0) + { + edge += step; + edges++; + } + else + { + inside += step; + insides++; + } + } + } + + return ((double)edge / edges) / Math.Max(0.01, (double)inside / insides); + } + + private static string Md5(H264Frame frame) => Convert.ToHexStringLower(MD5.HashData(frame.ToPlanar())); + + /// + /// The frame MD5s of a riferimento.md5, in output order, and the number of frames its first line declares (0 when + /// the file only says that there is no official reconstruction). + /// + private static List ReadReference(string path, out int declared) + { + var frames = new List(); + declared = 0; + foreach (var line in File.ReadAllLines(path)) + { + if (frames.Count == 0 && declared == 0 && line.StartsWith('#')) + { + var count = Regex.Match(line, @" (\d+) fotogrammi,"); + if (count.Success) + { + declared = int.Parse(count.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture); + } + } + + var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 2 && int.TryParse(parts[0], out var index)) + { + Assert.AreEqual(frames.Count, index, "riferimento.md5 fuori ordine"); + frames.Add(parts[1]); + } + } + + return frames; + } +} diff --git a/tests/Febe.Tests/Media/H264/H264ExtendedToolsTests.cs b/tests/Febe.Tests/Media/H264/H264ExtendedToolsTests.cs new file mode 100644 index 0000000..6e48d24 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264ExtendedToolsTests.cs @@ -0,0 +1,111 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// +/// Tools of the Baseline and Extended profiles that no stream of the ITU-T series uses — slice data partitioning, +/// redundant slices — and slices in another order than the one of the series, on conformance streams rewritten by +/// : the macroblocks keep their bits, so every frame must still be the official one. +/// +[TestClass] +public sealed class H264ExtendedToolsTests +{ + [TestMethod] + [DataRow("BA3_SVA_C")] // Extended, B slices + [DataRow("sp1_bt_a")] // SP slices + [DataRow("FM1_FT_E")] // slice groups of types 1–4 + [DataRow("MR6_BT_B")] // Extended, field pictures + [DataRow("CVMAQP3_Sony_D")] // MBAFF + [DataRow("SVA_BA1_B")] // non-IDR I slices: residual in partition B only + public void DataPartitionsGiveTheOfficialFrames(string name) + { + var stream = StreamRewriter.Partition(Original(name)); + var types = NalTypes(stream); + Assert.IsFalse(types.Contains(1), "restano slice non partizionate"); + Assert.IsTrue(types.Contains(2), "manca la partizione A"); + Assert.IsTrue(types.Contains(3) || types.Contains(4), "mancano le partizioni B e C"); + H264ConformanceTests.AssertStreamMatches(name, stream); + } + + [TestMethod] + [DataRow(false, true)] + [DataRow(true, false)] + [DataRow(false, false)] + public void MissingPartitionsLeaveTheirResidualOut(bool keepB, bool keepC) + { + // Without partition B or C a slice still decodes, without the residual of its intra or inter macroblocks: every + // picture comes out, and the IDR picture (never partitioned) is still the official one. + var name = "BA3_SVA_C"; + var complete = H264ConformanceTests.FrameMd5s(StreamRewriter.Partition(Original(name))); + var partial = H264ConformanceTests.FrameMd5s(StreamRewriter.Partition(Original(name), keepB, keepC)); + var expected = H264ConformanceTests.ReferenceFrames(name); + Assert.HasCount(expected.Count, partial); + Assert.AreEqual(expected[0], partial[0], "l'immagine IDR"); + Assert.IsTrue(partial.Where((md5, i) => md5 != complete[i]).Any(), "togliere una partizione cambia qualcosa"); + } + + [TestMethod] + [DataRow("BA3_SVA_C", 4101)] // CAVLC + [DataRow("CABA3_SVA_B", 4102)] // CABAC + [DataRow("MR6_BT_B", 4103)] // fields, POC type 1 + [DataRow("CAPAMA3_Sand_F", 4104)] // CABAC, MBAFF and fields + [DataRow("FM1_FT_E", 4105)] // slice groups, several PPS + [DataRow("sp1_bt_a", 4106)] // SP slices + public void RedundantSlicesAreSkipped(string name, int seed) + { + var stream = StreamRewriter.AddRedundantSlices(Original(name), seed); + Assert.IsGreaterThan(Original(name).Length, stream.Length); + H264ConformanceTests.AssertStreamMatches(name, stream); + } + + [TestMethod] + public void RedundantSlicesAreSkippedAlsoWhenPartitioned() + { + // The redundant slices become partitions A (header and random bits) with slice_id and redundant_pic_cnt. + var name = "BA3_SVA_C"; + H264ConformanceTests.AssertStreamMatches(name, StreamRewriter.Partition(StreamRewriter.AddRedundantSlices(Original(name), 4107))); + } + + [TestMethod] + [DataRow("BASQP1_Sony_C")] // twenty slices per picture + [DataRow("FM1_FT_E")] // slice groups + [DataRow("CAMASL3_Sony_B")] // CABAC, MBAFF, four slices per picture + public void SlicesInReverseOrderGiveTheOfficialFrames(string name) + { + var original = Original(name); + var stream = StreamRewriter.ReverseSlices(original); + CollectionAssert.AreNotEqual(original, stream, "il flusso ha più slice per immagine"); + H264ConformanceTests.AssertStreamMatches(name, stream); + } + + [TestMethod] + [DataRow("FM1_FT_E")] // several slices per picture: the stray partitions have a slice_id of their own + [DataRow("BASQP1_Sony_C")] // twenty slices per picture + [DataRow("BA3_SVA_C")] // one slice per picture: the stray partitions come after both B and C of the slice before + public void PartitionsBAndCWithoutTheirPartitionAAreIgnored(string name) + { + // A lost partition A leaves its B and C right after the partitions of the slice before, which is still waiting + // to be decoded: they must change nothing, as if the whole slice had been lost, and above all not the residual + // of the waiting slice. + var partitioned = StreamRewriter.Partition(Original(name)); + var strays = StreamRewriter.DropPartitionsA(partitioned, alsoBAndC: false, out var dropped); + var lost = StreamRewriter.DropPartitionsA(partitioned, alsoBAndC: true, out var droppedWhole); + Assert.AreEqual(dropped, droppedWhole); + Assert.IsGreaterThanOrEqualTo(5, dropped, "slice senza partizione A"); + Assert.IsGreaterThan(StreamRewriter.Units(lost).Count, StreamRewriter.Units(strays).Count, "restano le partizioni B e C"); + CollectionAssert.AreEqual(H264ConformanceTests.FrameMd5s(lost), H264ConformanceTests.FrameMd5s(strays)); + } + + [TestMethod] + [DataRow("FM1_FT_E", 4201)] + [DataRow("sp2_bt_b", 4202)] + [DataRow("BA3_SVA_C", 4203)] + public void DamagedPartitionedStreamsGiveFramesOrAnH264Exception(string name, int seed) + { + H264RobustnessTests.AssertDamagedCopiesDecode(name, StreamRewriter.Partition(Original(name)), seed, trials: 30); + } + + private static byte[] Original(string name) => File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))); + + private static HashSet NalTypes(byte[] stream) => StreamRewriter.Units(stream).Select(u => u[0] & 0x1F).ToHashSet(); +} diff --git a/tests/Febe.Tests/Media/H264/H264FormatTests.cs b/tests/Febe.Tests/Media/H264/H264FormatTests.cs new file mode 100644 index 0000000..1adc91b --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264FormatTests.cs @@ -0,0 +1,179 @@ +using Febe.Core.Codecs.H264; +using static Febe.Tests.Codecs.H264.SyntheticStreams; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The formats of the High profiles on tiny streams written by , where the conformance +/// streams in the repository have no reference: every chroma format at every bit depth, the colour planes of 4:4:4 +/// coded separately, lossless macroblocks with their DPCM, the CABAC of 4:4:4 that is refused. +/// +[TestClass] +public sealed class H264FormatTests +{ + [TestMethod] + [DataRow(0, 8, 8)] + [DataRow(0, 12, 9)] + [DataRow(1, 10, 10)] + [DataRow(1, 8, 10)] + [DataRow(2, 12, 9)] + [DataRow(3, 14, 14)] + [DataRow(3, 9, 8)] + public void PcmSamplesKeepTheirFormatAndBitDepth(int chromaFormat, int bitDepthLuma, int bitDepthChroma) + { + // Two I_PCM macroblocks side by side: every sample is written as it is, at its bit depth. + var h = new HighSettings(chromaFormat, bitDepthLuma, bitDepthChroma, WidthInMbs: 2); + int luma = (1 << bitDepthLuma) - 3, cb = (1 << (bitDepthChroma - 1)) - 7, cr = (1 << bitDepthChroma) - 2; + var frames = Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => + { + Pcm(b, h, luma, cb, cr); + Pcm(b, h, luma, cb, cr); + })]); + + Assert.HasCount(1, frames); + var f = frames[0]; + Assert.AreEqual(32, f.Width); + Assert.AreEqual(16, f.Height); + Assert.AreEqual(chromaFormat, f.ChromaFormat); + Assert.AreEqual(bitDepthLuma, f.BitDepthLuma); + + // Monochrome comes out with 4:2:0 chroma at the middle value, at the luma bit depth (as the official reconstructions + // of HPCAMOLQ_BRCM_B and HPCVMOLQ_BRCM_B hold it). + var depthC = chromaFormat == 0 ? bitDepthLuma : bitDepthChroma; + Assert.AreEqual(depthC, f.BitDepthChroma); + var bytes = Math.Max(bitDepthLuma, depthC) > 8 ? 2 : 1; + Assert.HasCount(32 * 16 * bytes, f.Y); + var (cw, ch) = chromaFormat switch + { + 3 => (32, 16), + 2 => (16, 16), + _ => (16, 8), + }; + Assert.AreEqual(cw, f.ChromaWidth); + Assert.AreEqual(ch, f.ChromaHeight); + Assert.HasCount(cw * ch * bytes, f.Cb); + Assert.HasCount(cw * ch * bytes, f.Cr); + for (var i = 0; i < 32 * 16; i++) + { + Assert.AreEqual(luma, f.LumaAt(i), $"luma {i}"); + } + + int expectedCb = chromaFormat == 0 ? 1 << (depthC - 1) : cb, expectedCr = chromaFormat == 0 ? 1 << (depthC - 1) : cr; + for (var i = 0; i < cw * ch; i++) + { + Assert.AreEqual(expectedCb, f.ChromaAt(f.Cb, i), $"Cb {i}"); + Assert.AreEqual(expectedCr, f.ChromaAt(f.Cr, i), $"Cr {i}"); + } + } + + [TestMethod] + [DataRow(8)] + [DataRow(10)] + public void SeparateColourPlanesMakeOneFrame(int bitDepth) + { + // separate_colour_plane_flag: three slices of the same IDR picture, one per colour_plane_id, each a monochrome + // picture of I_PCM macroblocks at the luma bit depth. + var h = new HighSettings(3, bitDepth, bitDepth, SeparatePlanes: true, WidthInMbs: 2); + int[] values = [11 << (bitDepth - 8), 22 << (bitDepth - 8), 33 << (bitDepth - 8)]; + var stream = new List([.. HighSps(h), .. HighPps(h)]); + for (var plane = 0; plane < 3; plane++) + { + var v = values[plane]; + stream.AddRange(HighIdr(h, b => + { + Pcm(b, h, v, 0, 0); + Pcm(b, h, v, 0, 0); + }, plane)); + } + + var frames = Decode([.. stream]); + Assert.HasCount(1, frames); + var f = frames[0]; + Assert.AreEqual(3, f.ChromaFormat); + Assert.AreEqual(bitDepth, f.BitDepthChroma); + Assert.AreEqual(32, f.ChromaWidth); + for (var i = 0; i < 32 * 16; i++) + { + Assert.AreEqual(values[0], f.LumaAt(i), $"Y {i}"); + Assert.AreEqual(values[1], f.ChromaAt(f.Cb, i), $"Cb {i}"); + Assert.AreEqual(values[2], f.ChromaAt(f.Cr, i), $"Cr {i}"); + } + } + + [TestMethod] + [DataRow(0, 8, 1)] + [DataRow(0, 8, 0)] + [DataRow(0, 8, 2)] + [DataRow(0, 10, 1)] + [DataRow(1, 8, 0)] + [DataRow(2, 10, 1)] + [DataRow(3, 8, 1)] + [DataRow(3, 8, 0)] + [DataRow(3, 12, 2)] + public void ALosslessMacroblockAccumulatesItsResidual(int chromaFormat, int bitDepth, int mode) + { + // An I_PCM macroblock, then an Intra_16x16 one predicted from it at QP′Y 0 with qpprime_y_zero_transform_bypass_flag: + // lossless (§8.5.15). Its only residual is a DC level on the first 4×4 block of each luma-like plane, taken as + // it is (no transform, no scaling) and accumulated along the prediction: horizontal (mode 1) adds it to the whole + // first row, vertical (mode 0, the I_PCM macroblock above) to the whole first column, DC (mode 2) only to the + // first sample. + var vertical = mode == 0; + var h = new HighSettings(chromaFormat, bitDepth, bitDepth, Lossless: true, WidthInMbs: vertical ? 1 : 2, HeightInMbs: vertical ? 2 : 1); + var shift = bitDepth - 8; + int[] pcm = [100 << shift, 60 << shift, 180 << shift]; + int[] dc = [1, 2, -1]; + var frames = Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => + { + Pcm(b, h, pcm[0], pcm[1], pcm[2]); + Intra16x16Dc(b, h, mode, dc); + })]); + + Assert.HasCount(1, frames); + var f = frames[0]; + var planes = chromaFormat == 3 ? 3 : 1; + for (var p = 0; p < planes; p++) + { + var plane = p == 0 ? f.Y : p == 1 ? f.Cb : f.Cr; + for (var y = 0; y < 16; y++) + { + for (var x = 0; x < 16; x++) + { + var touched = mode == 1 ? y == 0 : mode == 0 ? x == 0 : x == 0 && y == 0; + var expected = pcm[p] + (touched ? dc[p] : 0); + var index = vertical ? ((16 + y) * 16) + x : (y * 32) + 16 + x; + var actual = p == 0 ? f.LumaAt(index) : f.ChromaAt(plane, index); + Assert.AreEqual(expected, actual, $"piano {p}, ({x}, {y})"); + } + } + } + + if (chromaFormat is 1 or 2) + { + // Chroma: DC prediction from the I_PCM chroma, no residual. + for (var i = 0; i < f.ChromaWidth * f.ChromaHeight; i++) + { + Assert.AreEqual(pcm[1], f.ChromaAt(f.Cb, i), $"Cb {i}"); + Assert.AreEqual(pcm[2], f.ChromaAt(f.Cr, i), $"Cr {i}"); + } + } + } + + [TestMethod] + public void CabacIn444IsRefusedUntilItsContextsAreWritten() + { + // The residual of Cb and Cr of 4:4:4 with CABAC needs the contexts 460–1023: not transcribed yet, so the slice is + // refused rather than decoded wrong. + var h = new HighSettings(3, Cabac: true); + Assert.ThrowsExactly(() => Decode([.. HighSps(h), .. HighPps(h), .. HighIdr(h, b => b.Bits(0, 8))])); + } + + private static List Decode(byte[] stream) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + decoder.Flush(); + return frames; + } +} diff --git a/tests/Febe.Tests/Media/H264/H264MultiviewLimitsTests.cs b/tests/Febe.Tests/Media/H264/H264MultiviewLimitsTests.cs new file mode 100644 index 0000000..307c293 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264MultiviewLimitsTests.cs @@ -0,0 +1,124 @@ +using Febe.Core.Codecs.H264; +using static Febe.Tests.Codecs.H264.SyntheticStreams; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The decoders of the non-base views of an MVC stream (Annex H): what a damaged subset SPS may make them allocate, and +/// the filter, which holds for every view. +/// +[TestClass] +public sealed class H264MultiviewLimitsTests +{ + [TestMethod] + public void TheViewsOfAStreamShareOneBoundForTheirBuffers() + { + // A subset SPS may list up to 1,024 views, and each view has a decoder and frame stores of its own: together they + // stay within H264Decoder.MaxAllViewsMbs, here sixteen reference frames of 1920×1088 per view. + var s = new SequenceSettings(WidthInMbs: 120, HeightInMbs: 68, MaxNumRefFrames: 16); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeUnit(MvcSubsetSps(s, views: 64)[4..]); + decoder.DecodeUnit(Pps()[4..]); + + // Views the subset SPS does not list are refused, and leave nothing behind that would count against the bound. + for (var id = 100; id < 140; id++) + { + var absent = Assert.ThrowsExactly(() => decoder.DecodeUnit(ViewIdr(s, id)[4..])); + StringAssert.Contains(absent.Message, "Vista assente"); + } + + var perView = (s.MaxNumRefFrames + 1L) * s.WidthInMbs * s.HeightInMbs; + var allowed = (int)(H264Decoder.MaxAllViewsMbs / perView) - 1; // besides the base view + Assert.AreEqual(9, allowed); + for (var id = 1; id <= allowed; id++) + { + decoder.DecodeUnit(ViewIdr(s, id)[4..]); + } + + var refused = Assert.ThrowsExactly(() => decoder.DecodeUnit(ViewIdr(s, allowed + 1)[4..])); + StringAssert.Contains(refused.Message, "Troppe viste"); + + // The views kept still decode: one frame each, grey (Intra_16x16 DC with nothing around gives 128). + decoder.Flush(); + CollectionAssert.AreEqual(Enumerable.Range(1, allowed).ToArray(), frames.Select(f => f.ViewId).ToArray()); + foreach (var frame in frames) + { + Assert.IsTrue(frame.Y.All(v => v == 128), $"vista {frame.ViewId}"); + } + } + + [TestMethod] + public void ExtensionUnitsCutShortGiveNothingOrAnH264Exception() + { + // NAL units 14, 15 and 20 whose header is read byte by byte (svc_extension_flag, view_id, dependency_id), from one + // byte to a few, SVC and MVC, after an MVC subset SPS and a PPS or without them. + var s = new SequenceSettings(WidthInMbs: 2, HeightInMbs: 2); + foreach (var withParameters in new[] { false, true }) + { + foreach (var type in new[] { 14, 15, 20 }) + { + for (var length = 1; length <= 8; length++) + { + foreach (var second in new byte[] { 0x00, 0x40, 0x80, 0xC0, 0xFF }) + { + var decoder = new H264Decoder(); + decoder.FrameDecoded += _ => { }; + var unit = new byte[length]; + unit[0] = (byte)(0x60 | type); + for (var i = 1; i < length; i++) + { + unit[i] = i == 1 ? second : (byte)(0x35 * i); + } + + try + { + if (withParameters) + { + decoder.DecodeUnit(MvcSubsetSps(s, views: 2)[4..]); + decoder.DecodeUnit(Pps()[4..]); + } + + decoder.DecodeUnit(unit); + decoder.Flush(); + } + catch (H264Exception) + { + } + } + } + } + } + } + + [TestMethod] + [DataRow("MVCDS-4")] + [DataRow("MVCNV-3")] + public void WantedHoldsForEveryView(string name) + { + // The filter of the root decoder applies to the decoders of the other views too, each with its own decoding + // index; the frames handed out are those of the full decoding, and the view components the views after them + // refer to are still reconstructed. + var data = File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))); + var all = new List(); + var full = new H264Decoder(); + full.FrameDecoded += all.Add; + full.DecodeAnnexB(data); + + var some = new List(); + var partial = new H264Decoder { Wanted = index => index % 3 == 2 }; + partial.FrameDecoded += some.Add; + partial.DecodeAnnexB(data); + + Assert.IsGreaterThan(1, all.Select(f => f.ViewId).Distinct().Count(), "più viste"); + CollectionAssert.AreEqual( + all.Where(f => f.DecodeIndex % 3 == 2).Select(f => (f.ViewId, f.DecodeIndex)).ToArray(), + some.Select(f => (f.ViewId, f.DecodeIndex)).ToArray()); + foreach (var frame in some) + { + var expected = all.Single(f => f.ViewId == frame.ViewId && f.DecodeIndex == frame.DecodeIndex); + CollectionAssert.AreEqual(expected.ToPlanar(), frame.ToPlanar(), $"{name}: vista {frame.ViewId}, fotogramma {frame.DecodeIndex}"); + } + } +} diff --git a/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs new file mode 100644 index 0000000..187f95d --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264RobustnessTests.cs @@ -0,0 +1,142 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// +/// Damaged H.264 streams: the decoder reads bytes of any file the library holds, so whatever they are it must end with +/// frames or an , and a damaged parameter set must never make it allocate huge pictures. +/// +[TestClass] +public sealed class H264RobustnessTests +{ + [TestMethod] + [DataRow("BA1_Sony_D", 2641)] + [DataRow("SVA_BA1_B", 2642)] + [DataRow("BA3_SVA_C", 2643)] + [DataRow("BASQP1_Sony_C", 2644)] + [DataRow("CI_MW_D", 2645)] + [DataRow("CABA1_SVA_B", 2646)] + [DataRow("CABA2_SVA_B", 2647)] + [DataRow("CABA3_SVA_B", 2648)] + [DataRow("CANL1_SVA_B", 2649)] + [DataRow("FRExt1_Panasonic_D", 2650)] + [DataRow("FRExt3_Panasonic_E", 2651)] + [DataRow("HCAFR1_HHI_C", 2652)] + [DataRow("FI1_Sony_E", 2653)] + [DataRow("CVMAQP3_Sony_D", 2654)] + [DataRow("CAMACI3_Sony_C", 2655)] + [DataRow("CAMASL3_Sony_B", 2656)] + [DataRow("MR6_BT_B", 2657)] + [DataRow("MR9_BT_B", 2658)] + [DataRow("CAPAMA3_Sand_F", 2659)] + [DataRow("FM2_SVA_C", 2660)] + [DataRow("FM1_FT_E", 2661)] + [DataRow("FM1_BT_B", 2662)] + [DataRow("sp1_bt_a", 2663)] + [DataRow("sp2_bt_b", 2664)] + public void DamagedStreamsGiveFramesOrAnH264Exception(string name, int seed) => + AssertDamagedCopiesDecode(name, File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))), seed, trials: 60); + + /// + /// The same for the formats of the High profiles beyond 4:2:0 at 8 bits (samples of two bytes, 4:2:2 and 4:0:0 + /// layouts) and for the extensions, whose NAL units 14, 15 and 20 have headers of their own and whose layers or + /// views have arrays and decoders of their own; fewer copies each, since these streams are larger or decode twice. + /// + [TestMethod] + [DataRow("Hi422FR12_SONY_A", 2665)] // 4:2:2, 8 bit, slice B + [DataRow("Hi422FR13_SONY_A", 2666)] // 4:2:2, 10 bit: two bytes per sample + [DataRow("Hi422FR15_SONY_A", 2667)] // 4:2:2, 10 bit, slices P and B + [DataRow("FREXT2_TANDBERG_A", 2668)] // 4:2:2, CAVLC + [DataRow("HPCAMOLQ_BRCM_B", 2669)] // 4:0:0, CABAC + [DataRow("HPCVMOLQ_BRCM_B", 2670)] // 4:0:0, CAVLC + [DataRow("SVCBMT-13", 2671)] // SVC: MGS quality layers, NAL units 14 and 20 + [DataRow("SVCBST-19", 2672)] // SVC: spatial layer left to the base + [DataRow("SVCBCT-1", 2673)] // SVC: CGS layer left to the base + [DataRow("MVCDS-4", 2674)] // MVC: two views, subset SPS, NAL units 14, 15 and 20 + [DataRow("MVCNV-3", 2675)] // MVC: three views, inter-view prediction + public void DamagedStreamsOfOtherFormatsAndExtensionsGiveFramesOrAnH264Exception(string name, int seed) => + AssertDamagedCopiesDecode(name, File.ReadAllBytes(H264ConformanceTests.StreamFile(H264ConformanceTests.Folder(name))), seed, trials: 20); + + /// + /// Copies of with a few bytes changed (and some cut short), from a fixed seed: each must give + /// frames or an , never another exception. + /// + internal static void AssertDamagedCopiesDecode(string name, byte[] data, int seed, int trials) + { + var random = new Random(seed); + for (var trial = 0; trial < trials; trial++) + { + var copy = (byte[])data.Clone(); + var changes = 1 + random.Next(20); + for (var k = 0; k < changes; k++) + { + var p = random.Next(copy.Length); + copy[p] = random.Next(3) switch + { + 0 => (byte)random.Next(256), + 1 => (byte)(copy[p] ^ (1 << random.Next(8))), + _ => 0xFF, + }; + } + + if (random.Next(4) == 0) + { + copy = copy[..random.Next(copy.Length)]; + } + + try + { + var decoder = new H264Decoder(); + decoder.FrameDecoded += _ => { }; + decoder.DecodeAnnexB(copy); + } + catch (H264Exception) + { + } + catch (Exception ex) + { + Assert.Fail($"{name}, variante {trial} del seme {seed}: {ex.GetType().Name} {ex.Message}\n{ex.StackTrace}"); + } + } + } + + [TestMethod] + public void APictureLargerThanEveryLevelIsRefusedBeforeItIsAllocated() + { + // 1024 × 1024 macroblocks (16384 × 16384): what ue(v) allows, a hundred times what level 6.2 does. A PPS and the + // start of an IDR slice follow, so a decoder without the bound would really allocate its pictures. + var huge = new SyntheticStreams.SequenceSettings(WidthInMbs: 1024, HeightInMbs: 1024); + byte[] stream = [.. SyntheticStreams.Sps(huge), .. SyntheticStreams.Pps(), .. SyntheticStreams.Idr(huge, 100, macroblocks: 1)]; + var before = GC.GetAllocatedBytesForCurrentThread(); + var error = Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(stream)); + StringAssert.Contains(error.Message, "livello"); + Assert.IsLessThan(1024L * 1024, GC.GetAllocatedBytesForCurrentThread() - before); + + // The largest frame of level 6.2 is still accepted. + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272))); + } + + [TestMethod] + public void MoreReferenceFramesThanTheLargestBufferAreRefused() + { + // 8192 × 4352 with sixteen reference frames would be 1.4 GB of pictures; level 6.2 holds five of that size. + var error = Assert.ThrowsExactly(() => + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 16)))); + StringAssert.Contains(error.Message, "riferimento"); + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 512, HeightInMbs: 272, MaxNumRefFrames: 5))); + new H264Decoder().DecodeAnnexB(SyntheticStreams.Sps(new(WidthInMbs: 120, HeightInMbs: 68, MaxNumRefFrames: 16))); + } + + [TestMethod] + public void ACropThatLeavesNoPictureIsRefused() + { + // 176 × 144 (11 × 9 macroblocks): crop units are two samples in 4:2:0 frames. + new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (4, 4, 2, 2))); + Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (44, 44, 0, 0)))); + Assert.ThrowsExactly(() => new H264Decoder().DecodeAnnexB(Sps(11, 9, crop: (0, 0, 8192, 0)))); + } + + /// A Baseline SPS of the given size and crop. + private static byte[] Sps(int widthInMbs, int heightInMbs, (int, int, int, int) crop) => + SyntheticStreams.Sps(new(WidthInMbs: widthInMbs, HeightInMbs: heightInMbs, Crop: crop)); +} \ No newline at end of file diff --git a/tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs b/tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs new file mode 100644 index 0000000..5153ee1 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264SyntheticStreamTests.cs @@ -0,0 +1,138 @@ +using Febe.Core.Codecs.H264; +using static Febe.Tests.Codecs.H264.SyntheticStreams; + +namespace Febe.Tests.Codecs.H264; + +/// +/// The decoder on tiny streams written by : the parts of the standard no conformance stream in +/// the repository exercises. +/// +[TestClass] +public sealed class H264SyntheticStreamTests +{ + [TestMethod] + [DataRow(16)] + [DataRow(2)] + public void AGapInFrameNumKeepsTheWrapInThePictureOrder(int maxNumRefFrames) + { + // POC type 2, MaxFrameNum 16: references 0..14, then frame_num 3. Frames 15, 0, 1 and 2 are missing (§8.2.5.2): + // the wrap at 0 is among them, so the frame after the gap has FrameNumOffset 16 and POC 2 × (16 + 3) (§8.2.1.3). + // With two reference frames, 15 and 0 are counted without becoming references. + var s = new SequenceSettings(MaxNumRefFrames: maxNumRefFrames, GapsAllowed: true); + var stream = new List([.. Sps(s), .. Pps(), .. Idr(s, 100)]); + for (var n = 1; n <= 14; n++) + { + stream.AddRange(SkippedP(s, n)); + } + + stream.AddRange(SkippedP(s, 3)); + var frames = Decode([.. stream]); + + Assert.HasCount(16, frames); + for (var n = 0; n <= 14; n++) + { + Assert.AreEqual(2 * n, frames[n].Poc, $"fotogramma {n}"); + } + + Assert.AreEqual(2 * (16 + 3), frames[15].Poc, "il fotogramma dopo il salto"); + } + + [TestMethod] + public void ARedundantPictureIsSkipped() + { + // The primary IDR picture (luma 100) and a redundant copy (redundant_pic_cnt 1) whose slice also starts at + // macroblock 0: one frame, the primary one. + var s = new SequenceSettings(); + byte[] stream = [.. Sps(s), .. Pps(redundantPicCntPresent: true), .. Idr(s, 100, redundantPicCnt: 0), .. Idr(s, 200, redundantPicCnt: 1)]; + var frames = Decode(stream); + Assert.HasCount(1, frames); + Assert.IsTrue(frames[0].Y.All(v => v == 100), "il fotogramma è quello primario"); + } + + [TestMethod] + [DataRow(0, 127, 49, 128)] + [DataRow(12, 130, 52, 126)] + public void AnSiPictureIsRebuiltInQs(int qsDelta, int first, int third, int chroma) + { + // Three macroblocks: SI, I_PCM (luma 50), SI; the SI ones without residual, every block predicted in DC mode. Each + // 4×4 block of an SI macroblock is its prediction transformed, quantised in QS and decoded in QS (§8.6.2), so a + // flat block of 128 comes back as 127 with QS 26 (DC 2048 → level 39 → 8112 → 127) and as 130 with QS 38; next to + // the I_PCM samples (50) the blocks give 49 and 52. Chroma: the DC of the four blocks through the 2×2 transform + // (8192 → level 79 with QSc 26, 28 with QSc 35), back to 128 and 126. Worked out by hand from the equations. + var s = new SequenceSettings(WidthInMbs: 3); + var frames = Decode([.. Sps(s), .. Pps(), .. SiIdr(s, qsDelta, pcm: [1], pcmLuma: 50)]); + Assert.HasCount(1, frames); + var f = frames[0]; + for (var y = 0; y < 16; y++) + { + for (var x = 0; x < 48; x++) + { + var expected = x < 16 ? first : x < 32 ? 50 : third; + Assert.AreEqual(expected, f.Y[(y * 48) + x], $"luma ({x}, {y})"); + } + } + + for (var i = 0; i < f.Cb.Length; i++) + { + var x = i % 24; + var expected = x is >= 8 and < 16 ? 128 : chroma; + Assert.AreEqual(expected, f.Cb[i], $"Cb {i}"); + Assert.AreEqual(expected, f.Cr[i], $"Cr {i}"); + } + } + + [TestMethod] + public void APSliceWithNothingToPredictFromIsRefused() + { + // Decoding that starts at a P picture (an AVI without index, read from a sample that is not a key frame): the + // decoder refuses it instead of predicting the picture from itself. + var s = new SequenceSettings(); + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + Assert.ThrowsExactly(() => decoder.DecodeAnnexB([.. Sps(s), .. Pps(), .. SkippedP(s, 1)])); + Assert.IsEmpty(frames); + } + + [TestMethod] + public void AnUnwantedPictureNobodyRefersToIsNotDecoded() + { + // The second picture is not a reference and its slice data is broken (a skip run past the picture): decoding it + // fails, so a decoder that skips it as unwanted shows it was never reconstructed. + var s = new SequenceSettings(PocType: 0); + byte[] broken = [.. SkippedP(s with { WidthInMbs = 2 }, 1, reference: false)]; // a run of 2 in a 1-macroblock picture + byte[] stream = [.. Sps(s), .. Pps(), .. Idr(s, 100), .. broken, .. SkippedP(s, 1, pocLsb: 4)]; + Assert.ThrowsExactly(() => Decode(stream)); + + var decoder = new H264Decoder { Wanted = index => index != 1 }; + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + Assert.AreEqual(3, decoder.FramesDecoded); + CollectionAssert.AreEqual(new long[] { 0, 2 }, frames.Select(f => f.DecodeIndex).ToArray()); + Assert.AreEqual(4, frames[1].Poc, "il fotogramma dopo quello saltato ha il suo ordine"); + Assert.IsTrue(frames[1].Y.All(v => v == 100)); + } + + [TestMethod] + public void TheStartOfDecodingIsRecognised() + { + var s = new SequenceSettings(); + Assert.AreEqual(H264AccessPoint.Idr, H264Decoder.AccessPoint([.. Sps(s), .. Pps(), .. Idr(s, 100)], 0)); + Assert.AreEqual(H264AccessPoint.None, H264Decoder.AccessPoint([.. Sps(s), .. Pps(), .. SkippedP(s, 1)], 0)); + Assert.AreEqual(H264AccessPoint.None, H264Decoder.AccessPoint([], 0)); + + // Length-prefixed (MP4): the same IDR picture without its start code. + var idr = Idr(s, 100)[4..]; + Assert.AreEqual(H264AccessPoint.Idr, H264Decoder.AccessPoint([0, 0, (byte)(idr.Length >> 8), (byte)idr.Length, .. idr], 4)); + } + + private static List Decode(byte[] stream) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(stream); + return frames; + } +} diff --git a/tests/Febe.Tests/Media/H264/H264TablesTests.cs b/tests/Febe.Tests/Media/H264/H264TablesTests.cs new file mode 100644 index 0000000..32ae67d --- /dev/null +++ b/tests/Febe.Tests/Media/H264/H264TablesTests.cs @@ -0,0 +1,94 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// The constant tables of the decoder: shape checks and a few values taken from the text of the standard. +[TestClass] +public sealed class H264TablesTests +{ + [TestMethod] + public void VariableLengthCodesArePrefixFree() + { + foreach (var (name, codes) in CavlcTables.AllCodeTables()) + { + var present = codes.Where(c => c is not null).Select(c => c!).ToList(); + for (var i = 0; i < present.Count; i++) + { + for (var j = 0; j < present.Count; j++) + { + if (i != j) + { + Assert.IsFalse(present[j].StartsWith(present[i], StringComparison.Ordinal), $"{name}: {present[i]} è prefisso di {present[j]}"); + } + } + } + } + } + + [TestMethod] + public void DeblockingTablesCoverEveryIndex() + { + Assert.AreEqual(52, H264Tables.Alpha.Length); + Assert.AreEqual(52, H264Tables.Beta.Length); + Assert.AreEqual(52 * 3, H264Tables.Tc0.Length); + Assert.AreEqual(25, H264Tables.Tc0[(51 * 3) + 2]); + Assert.AreEqual(52, H264Tables.ChromaQp.Length); + Assert.AreEqual(39, H264Tables.ChromaQp[51]); + } + + [TestMethod] + public void CodedBlockPatternTablesArePermutations() + { + CollectionAssert.AreEquivalent(Enumerable.Range(0, 48).ToArray(), H264Tables.CbpIntra.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 48).ToArray(), H264Tables.CbpInter.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.CbpIntraNoChroma.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.CbpInterNoChroma.Select(b => (int)b).ToArray()); + } + + [TestMethod] + public void ScansArePermutations() + { + CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.ZigZag4x4.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), H264Tables.ZigZag8x8.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 16).ToArray(), H264Tables.FieldScan4x4.Select(b => (int)b).ToArray()); + CollectionAssert.AreEquivalent(Enumerable.Range(0, 64).ToArray(), H264Tables.FieldScan8x8.Select(b => (int)b).ToArray()); + } + + [TestMethod] + public void FieldScansGoDownBeforeAcross() + { + // Field scans (Tables 8-13 and 8-14) favour vertical frequencies: the first coefficients after DC are the ones + // below it. + CollectionAssert.AreEqual(new byte[] { 0, 4, 1, 8, 12, 5 }, H264Tables.FieldScan4x4[..6]); + CollectionAssert.AreEqual(new byte[] { 0, 8, 16, 1, 9, 24, 32, 17 }, H264Tables.FieldScan8x8[..8]); + Assert.AreEqual(63, H264Tables.FieldScan8x8[63]); + } + + [TestMethod] + public void FieldSignificanceContextsOf8x8BlocksMatchTheStandard() + { + // Table 9-43, ctxIdxInc of significant_coeff_flag for field coded 8×8 blocks: 63 values from 0 to 14. + var table = H264Tables.SignificantContext8x8Field; + Assert.AreEqual(63, table.Length); + Assert.AreEqual(0, table[0]); + Assert.AreEqual(14, table.Max()); + Assert.AreEqual(14, table[62]); + Assert.AreEqual(H264Tables.SignificantContext8x8.Length, table.Length); + } + + [TestMethod] + [DataRow(-1, 402, -17, 120)] + [DataRow(0, 11, 23, 33)] + [DataRow(1, 417, 17, -10)] // once taken from the field table by mistake + [DataRow(1, 426, -5, 71)] + [DataRow(1, 178, 102, -94)] + [DataRow(2, 435, -10, 79)] + [DataRow(2, 165, -22, 127)] + public void ContextInitialisationMatchesTheStandard(int idc, int ctx, int m, int n) + { + var table = idc < 0 ? CabacTables.InitI : CabacTables.InitPB[idc]; + Assert.AreEqual(CabacTables.ContextCount * 2, table.Length); + Assert.AreEqual(m, table[ctx * 2]); + Assert.AreEqual(n, table[(ctx * 2) + 1]); + } +} diff --git a/tests/Febe.Tests/Media/H264/StreamRewriter.cs b/tests/Febe.Tests/Media/H264/StreamRewriter.cs new file mode 100644 index 0000000..b02e24f --- /dev/null +++ b/tests/Febe.Tests/Media/H264/StreamRewriter.cs @@ -0,0 +1,448 @@ +using Febe.Core.Codecs.H264; + +namespace Febe.Tests.Codecs.H264; + +/// +/// Conformance streams rewritten with the tools of the Extended and Baseline profiles that no stream of the ITU-T series +/// uses: the same pictures split into data partitions, with redundant slices, with the slices of each picture in another +/// order. The macroblocks and their bits do not change, so the official reconstruction stays the expected result. +/// +internal static class StreamRewriter +{ + /// + /// Every non-IDR slice (NAL unit 1) as partitions A, B and C (§7.3.2.8–§7.3.2.10): the decoder reads the original + /// stream and says where the residual of each macroblock lies; A keeps the header and everything else, B the residual + /// of the intra macroblocks, C that of the inter ones. A partition with nothing in it is left out, as are those that + /// and drop. Only CAVLC without constrained intra prediction and + /// without I_PCM: with them the bits would not stay the same (§9.2.1, pcm_alignment_zero_bit). + /// + internal static byte[] Partition(byte[] stream, bool keepB = true, bool keepC = true) + { + var decoder = new H264Decoder(); + var residual = new List<(int Start, int End, bool Intra, bool Pcm)>(); + decoder.ResidualRead = (start, end, intra, pcm) => residual.Add((start, end, intra, pcm)); + var sequences = new Dictionary(); + var pictures = new Dictionary(); + var output = new List(); + var sliceId = 0; + foreach (var unit in Units(stream)) + { + var nal = NalUnits.Parse(unit); + Remember(nal, sequences, pictures); + residual.Clear(); + decoder.DecodeUnit(unit); + if (nal.Type != 1) + { + output.Add(unit); + continue; + } + + var reader = nal.Reader(); + var header = SliceHeader.Parse(reader, nal, sequences, pictures, out _, out var pps); + if (pps.Cabac || pps.ConstrainedIntraPred || residual.Exists(r => r.Pcm)) + { + throw new InvalidOperationException("Flusso non adatto: CABAC, predizione intra vincolata o I_PCM."); + } + + // slice_id: 0 for the first slice of each picture, then one more per slice (the streams are in order). + sliceId = header.FirstMb == 0 ? 0 : sliceId + 1; + var a = new BitWriter(); + a.Copy(nal.Rbsp, 8, reader.Position); + a.Ue((uint)sliceId); + var b = PartitionStart(sliceId, pps, header); + var c = PartitionStart(sliceId, pps, header); + var position = reader.Position; + foreach (var (start, end, intra, _) in residual) + { + a.Copy(nal.Rbsp, position, start); + (intra ? b : c).Copy(nal.Rbsp, start, end); + position = end; + } + + a.Copy(nal.Rbsp, position, StopBit(nal)); + var refIdc = (byte)(nal.RefIdc << 5); + output.Add(Unit((byte)(refIdc | 2), a)); + if (keepB && residual.Exists(r => r.Intra)) + { + output.Add(Unit((byte)(refIdc | 3), b)); + } + + if (keepC && residual.Exists(r => !r.Intra)) + { + output.Add(Unit((byte)(refIdc | 4), c)); + } + } + + return Join(output); + } + + /// + /// A partitioned stream () with the partition A of some slices lost: of every other slice + /// whose partitions B or C come right after those of the slice before, when that slice is still waiting for nothing + /// a decoder could take them for (a slice_id of its own, or the slice before already has both B and C). With + /// the whole slice is lost instead, its B and C with it. is the + /// number of slices that lost their partition A. + /// + internal static byte[] DropPartitionsA(byte[] partitioned, bool alsoBAndC, out int dropped) + { + var units = Units(partitioned); + var output = new List(); + dropped = 0; + var candidates = 0; + (int Start, int End)? previous = null; + var i = 0; + while (i < units.Count) + { + if ((units[i][0] & 0x1F) != 2) + { + output.Add(units[i]); + previous = null; + i++; + continue; + } + + var end = i + 1; + while (end < units.Count && (units[end][0] & 0x1F) is 3 or 4) + { + end++; + } + + var drop = false; + if (previous is { } before && end > i + 1 && end - i - 1 <= 2) + { + var full = before.End - before.Start == 3; + var id = SliceIdOf(units[i + 1]); + var beforeId = before.End > before.Start + 1 ? SliceIdOf(units[before.Start + 1]) : id; + drop = (full || id != beforeId) && candidates++ % 2 == 0; + } + + if (drop) + { + dropped++; + if (!alsoBAndC) + { + output.AddRange(units.GetRange(i + 1, end - i - 1)); + } + } + else + { + output.AddRange(units.GetRange(i, end - i)); + } + + // A slice that lost its partition A is no slice the next one can follow: the decoder still waits for the + // one before it. + previous = drop ? null : (i, end); + i = end; + } + + return Join(output); + } + + /// slice_id, the first syntax element of a partition B or C. + private static int SliceIdOf(byte[] unit) => NalUnits.Parse(unit).Reader().ReadUe(Sps.MaxFrameMbs - 1); + + /// + /// The same stream with redundant_pic_cnt_present_flag set in every PPS (§7.3.2.2) and, after the slices of each + /// picture, a redundant copy of them (redundant_pic_cnt 1) whose header is the primary one and whose data are random + /// bits: a decoder that decodes a redundant slice cannot give the official reconstruction. + /// + internal static byte[] AddRedundantSlices(byte[] stream, int seed) + { + var random = new Random(seed); + var sequences = new Dictionary(); + var pictures = new Dictionary(); + var output = new List(); + var redundant = new List(); + foreach (var unit in Units(stream)) + { + var nal = NalUnits.Parse(unit); + var slice = nal.Type is 1 or 5; + var header = slice ? SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _) : null; + if (!slice || header!.FirstMb == 0) + { + output.AddRange(redundant); + redundant.Clear(); + } + + if (nal.Type == 8) + { + Remember(nal, sequences, pictures); + output.Add(SetRedundantFlag(nal)); + continue; + } + + Remember(nal, sequences, pictures); + if (!slice) + { + output.Add(unit); + continue; + } + + var reader = nal.Reader(); + SliceHeader.Parse(reader, nal, sequences, pictures, out var sps, out var pps); + var headerEnd = reader.Position; + var insert = RedundantPicCntPosition(nal, sps, pps); + output.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 0, null)); + var garbage = new byte[16 + random.Next(48)]; + random.NextBytes(garbage); + redundant.Add(WithRedundantPicCnt(nal, insert, headerEnd, pps.Cabac, 1, garbage)); + } + + output.AddRange(redundant); + return Join(output); + } + + /// + /// The slices of each picture in reverse order (arbitrary slice order, §7.4.3: Baseline and Extended). A picture ends + /// at a NAL unit that is not a slice or at a slice whose header differs as in §7.4.1.2.4: the source may already send + /// its slices out of order. + /// + internal static byte[] ReverseSlices(byte[] stream) + { + var sequences = new Dictionary(); + var pictures = new Dictionary(); + var output = new List(); + var picture = new List(); + var current = ""; + foreach (var unit in Units(stream)) + { + var nal = NalUnits.Parse(unit); + Remember(nal, sequences, pictures); + var slice = nal.Type is 1 or 5; + var key = ""; + if (slice) + { + var h = SliceHeader.Parse(nal.Reader(), nal, sequences, pictures, out _, out _); + key = $"{h.FrameNum} {h.PpsId} {h.Structure} {nal.RefIdc == 0} {nal.Type} {h.IdrPicId} {h.PocLsb} {h.DeltaPocBottom} {h.DeltaPoc0} {h.DeltaPoc1}"; + } + + if (!slice || key != current) + { + current = key; + picture.Reverse(); + output.AddRange(picture); + picture.Clear(); + } + + if (slice) + { + picture.Add(unit); + } + else + { + output.Add(unit); + } + } + + picture.Reverse(); + output.AddRange(picture); + return Join(output); + } + + /// The NAL units of an Annex B stream, each with its header and without start code. + internal static List Units(byte[] stream) + { + var units = new List(); + var position = 0; + while (NalUnits.NextAnnexB(stream, ref position, out var range)) + { + units.Add(stream[range]); + } + + return units; + } + + internal static byte[] Join(IEnumerable units) + { + var output = new List(); + foreach (var unit in units) + { + output.AddRange((byte[])[0, 0, 0, 1]); + output.AddRange(unit); + } + + return [.. output]; + } + + private static void Remember(NalUnit nal, Dictionary sequences, Dictionary pictures) + { + if (nal.Type == 7) + { + var sps = Sps.Parse(nal.Reader()); + sequences[sps.Id] = sps; + } + else if (nal.Type == 8) + { + var pps = Pps.Parse(nal.Reader(), sequences); + pictures[pps.Id] = pps; + } + } + + /// slice_id, then redundant_pic_cnt when the PPS has it (§7.3.2.10). + private static BitWriter PartitionStart(int sliceId, Pps pps, SliceHeader header) + { + var bits = new BitWriter(); + bits.Ue((uint)sliceId); + if (pps.RedundantPicCntPresent) + { + bits.Ue((uint)header.RedundantPicCnt); + } + + return bits; + } + + private static byte[] Unit(byte header, BitWriter bits) + { + bits.Trailing(); + return [header, .. bits.ToArray()]; + } + + /// The position of the rbsp_stop_one_bit: the last bit set of the payload. + private static int StopBit(NalUnit nal) + { + var last = nal.Length - 1; + while (nal.Rbsp[last] == 0) + { + last--; + } + + return (last * 8) + 7 - System.Numerics.BitOperations.TrailingZeroCount(nal.Rbsp[last]); + } + + /// Where redundant_pic_cnt goes in a slice header: after the picture order count fields (§7.3.3). + private static int RedundantPicCntPosition(NalUnit nal, Sps sps, Pps pps) + { + var r = nal.Reader(); + r.ReadUe(); // first_mb_in_slice + r.ReadUe(); // slice_type + r.ReadUe(); // pic_parameter_set_id + r.Read(sps.Log2MaxFrameNum); + var field = false; + if (!sps.FrameMbsOnly && (field = r.ReadFlag())) + { + r.ReadFlag(); // bottom_field_flag + } + + if (nal.Type == 5) + { + r.ReadUe(); // idr_pic_id + } + + if (sps.PocType == 0) + { + r.Read(sps.Log2MaxPocLsb); + if (pps.BottomFieldPicOrderInFramePresent && !field) + { + r.ReadSe(); + } + } + else if (sps.PocType == 1 && !sps.DeltaPicOrderAlwaysZero) + { + r.ReadSe(); + if (pps.BottomFieldPicOrderInFramePresent && !field) + { + r.ReadSe(); + } + } + + return r.Position; + } + + /// + /// The slice with redundant_pic_cnt inserted at ; with its slice + /// data are those bytes instead of the original ones (CABAC data start again at a byte, after cabac_alignment_one_bit). + /// + private static byte[] WithRedundantPicCnt(NalUnit nal, int insert, int headerEnd, bool cabac, int count, byte[]? garbage) + { + var bits = new BitWriter(); + bits.Copy(nal.Rbsp, 8, insert); + bits.Ue((uint)count); + bits.Copy(nal.Rbsp, insert, headerEnd); + if (cabac) + { + bits.AlignWithOnes(); + if (garbage is null) + { + bits.Copy(nal.Rbsp, (headerEnd + 7) / 8 * 8, nal.Length * 8); + return [nal.Rbsp[0], .. bits.ToArray()]; + } + } + + if (garbage is null) + { + bits.Copy(nal.Rbsp, headerEnd, StopBit(nal)); + } + else + { + bits.Copy(garbage, 0, garbage.Length * 8); + } + + bits.Trailing(); + return [nal.Rbsp[0], .. bits.ToArray()]; + } + + /// The PPS with redundant_pic_cnt_present_flag set: the fields before it read again (§7.3.2.2). + private static byte[] SetRedundantFlag(NalUnit nal) + { + var r = nal.Reader(); + r.ReadUe(); // pic_parameter_set_id + r.ReadUe(); // seq_parameter_set_id + r.ReadFlag(); // entropy_coding_mode_flag + r.ReadFlag(); // bottom_field_pic_order_in_frame_present_flag + var groups = (int)r.ReadUe() + 1; + if (groups > 1) + { + var type = r.ReadUe(); + switch (type) + { + case 0: + for (var i = 0; i < groups; i++) + { + r.ReadUe(); + } + + break; + case 2: + for (var i = 0; i < 2 * (groups - 1); i++) + { + r.ReadUe(); + } + + break; + case 3 or 4 or 5: + r.ReadFlag(); + r.ReadUe(); + break; + case 6: + { + var size = (int)r.ReadUe() + 1; + var bitsPerId = 32 - System.Numerics.BitOperations.LeadingZeroCount((uint)(groups - 1)); + r.Skip(size * bitsPerId); + break; + } + } + } + + r.ReadUe(); // num_ref_idx_l0_default_active_minus1 + r.ReadUe(); // num_ref_idx_l1_default_active_minus1 + r.ReadFlag(); // weighted_pred_flag + r.Read(2); // weighted_bipred_idc + r.ReadSe(); // pic_init_qp_minus26 + r.ReadSe(); // pic_init_qs_minus26 + r.ReadSe(); // chroma_qp_index_offset + r.ReadFlag(); // deblocking_filter_control_present_flag + r.ReadFlag(); // constrained_intra_pred_flag + var flag = r.Position; + if (r.ReadFlag()) + { + throw new InvalidOperationException("Il PPS ha già redundant_pic_cnt_present_flag."); + } + + var bits = new BitWriter(); + bits.Copy(nal.Rbsp, 8, flag); + bits.Bits(1, 1); + bits.Copy(nal.Rbsp, flag + 1, StopBit(nal)); + bits.Trailing(); + return [nal.Rbsp[0], .. bits.ToArray()]; + } +} diff --git a/tests/Febe.Tests/Media/H264/SyntheticStreams.cs b/tests/Febe.Tests/Media/H264/SyntheticStreams.cs new file mode 100644 index 0000000..d4123a5 --- /dev/null +++ b/tests/Febe.Tests/Media/H264/SyntheticStreams.cs @@ -0,0 +1,474 @@ +namespace Febe.Tests.Codecs.H264; + +/// +/// Tiny H.264 streams written bit by bit from the syntax of the standard (§7.3): Baseline parameter sets, IDR pictures +/// made of I_PCM macroblocks (their samples are written as they are, so every pixel is known) and P pictures made only +/// of skipped macroblocks. They reach the parts of the decoder the conformance streams in the repository do not: gaps in +/// frame_num, redundant pictures, slices without references, huge parameter sets. +/// +internal static class SyntheticStreams +{ + /// Settings of the sequence parameter set. + internal sealed record SequenceSettings( + int WidthInMbs = 1, + int HeightInMbs = 1, + int PocType = 2, + int Log2MaxFrameNum = 4, + int MaxNumRefFrames = 1, + bool GapsAllowed = false, + (int Left, int Right, int Top, int Bottom)? Crop = null); + + /// A sequence parameter set NAL unit with its start code (§7.3.2.1.1). + internal static byte[] Sps(SequenceSettings s) + { + var bits = new BitWriter(); + bits.Bits(66, 8); // profile_idc: Baseline + bits.Bits(0, 8); // constraint flags + bits.Bits(30, 8); // level_idc + bits.Ue(0); // seq_parameter_set_id + bits.Ue((uint)s.Log2MaxFrameNum - 4); + bits.Ue((uint)s.PocType); + if (s.PocType == 0) + { + bits.Ue(4); // log2_max_pic_order_cnt_lsb_minus4 + } + + bits.Ue((uint)s.MaxNumRefFrames); + bits.Bits(s.GapsAllowed ? 1u : 0u, 1); + bits.Ue((uint)s.WidthInMbs - 1); + bits.Ue((uint)s.HeightInMbs - 1); + bits.Bits(1, 1); // frame_mbs_only_flag + bits.Bits(1, 1); // direct_8x8_inference_flag + bits.Bits(s.Crop is null ? 0u : 1u, 1); + if (s.Crop is { } c) + { + bits.Ue((uint)c.Left); + bits.Ue((uint)c.Right); + bits.Ue((uint)c.Top); + bits.Ue((uint)c.Bottom); + } + + bits.Bits(0, 1); // vui_parameters_present_flag + return Nal(0x67, bits); + } + + /// A Baseline picture parameter set (CAVLC, one slice group, deblocking control present, §7.3.2.2). + internal static byte[] Pps(bool redundantPicCntPresent = false) + { + var bits = new BitWriter(); + bits.Ue(0); // pic_parameter_set_id + bits.Ue(0); // seq_parameter_set_id + bits.Bits(0, 1); // entropy_coding_mode_flag: CAVLC + bits.Bits(0, 1); // bottom_field_pic_order_in_frame_present_flag + bits.Ue(0); // num_slice_groups_minus1 + bits.Ue(0); // num_ref_idx_l0_default_active_minus1 + bits.Ue(0); // num_ref_idx_l1_default_active_minus1 + bits.Bits(0, 1); // weighted_pred_flag + bits.Bits(0, 2); // weighted_bipred_idc + bits.Se(0); // pic_init_qp_minus26 + bits.Se(0); // pic_init_qs_minus26 + bits.Se(0); // chroma_qp_index_offset + bits.Bits(1, 1); // deblocking_filter_control_present_flag + bits.Bits(0, 1); // constrained_intra_pred_flag + bits.Bits(redundantPicCntPresent ? 1u : 0u, 1); + return Nal(0x68, bits); + } + + /// + /// An IDR picture of I_PCM macroblocks whose luma samples are all (chroma 128), as one slice. + /// + internal static byte[] Idr(SequenceSettings s, byte luma, int idrPicId = 0, int? redundantPicCnt = null, int macroblocks = -1) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(7); // slice_type: I (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + bits.Bits(0, s.Log2MaxFrameNum); // frame_num + bits.Ue((uint)idrPicId); + if (s.PocType == 0) + { + bits.Bits(0, 8); // pic_order_cnt_lsb + } + + if (redundantPicCnt is { } r) + { + bits.Ue((uint)r); + } + + bits.Bits(0, 1); // no_output_of_prior_pics_flag + bits.Bits(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + var count = macroblocks < 0 ? s.WidthInMbs * s.HeightInMbs : macroblocks; + for (var m = 0; m < count; m++) + { + bits.Ue(25); // mb_type: I_PCM + bits.Align(); // pcm_alignment_zero_bit + for (var i = 0; i < 256; i++) + { + bits.Bits(luma, 8); + } + + for (var i = 0; i < 128; i++) + { + bits.Bits(128, 8); + } + } + + return Nal(0x65, bits); + } + + /// A P picture whose macroblocks are all skipped (a copy of the newest reference), as one slice. + /// The sequence. + /// frame_num. + /// False for nal_ref_idc 0. + /// pic_order_cnt_lsb with POC type 0 (default: twice frame_num). + internal static byte[] SkippedP(SequenceSettings s, int frameNum, bool reference = true, int? pocLsb = null) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(5); // slice_type: P (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + bits.Bits((uint)frameNum, s.Log2MaxFrameNum); + if (s.PocType == 0) + { + bits.Bits((uint)(pocLsb ?? (2 * frameNum)) & 0xFF, 8); // pic_order_cnt_lsb + } + + bits.Bits(0, 1); // num_ref_idx_active_override_flag + bits.Bits(0, 1); // ref_pic_list_modification_flag_l0 + if (reference) + { + bits.Bits(0, 1); // adaptive_ref_pic_marking_mode_flag + } + + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + bits.Ue((uint)(s.WidthInMbs * s.HeightInMbs)); // mb_skip_run: the whole picture + return Nal(reference ? (byte)0x41 : (byte)0x01, bits); + } + + /// + /// An IDR picture of one SI slice (§7.3.3, §7.3.5) with QS = 26 + : every macroblock is an SI + /// macroblock without residual (Intra_4x4, every block with the predicted mode, chroma DC), except those listed in + /// , which are I_PCM (mb_type 26 in an SI slice) with luma and chroma 128. + /// + internal static byte[] SiIdr(SequenceSettings s, int qsDelta, int[] pcm, byte pcmLuma) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(9); // slice_type: SI (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + bits.Bits(0, s.Log2MaxFrameNum); // frame_num + bits.Ue(0); // idr_pic_id + if (s.PocType == 0) + { + bits.Bits(0, 8); // pic_order_cnt_lsb + } + + bits.Bits(0, 1); // no_output_of_prior_pics_flag + bits.Bits(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Se(qsDelta); // slice_qs_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + for (var m = 0; m < s.WidthInMbs * s.HeightInMbs; m++) + { + if (Array.IndexOf(pcm, m) >= 0) + { + bits.Ue(26); // mb_type: I_PCM (25 + 1 in an SI slice) + bits.Align(); // pcm_alignment_zero_bit + for (var i = 0; i < 256; i++) + { + bits.Bits(pcmLuma, 8); + } + + for (var i = 0; i < 128; i++) + { + bits.Bits(128, 8); + } + + continue; + } + + bits.Ue(0); // mb_type: SI + for (var i = 0; i < 16; i++) + { + bits.Bits(1, 1); // prev_intra4x4_pred_mode_flag + } + + bits.Ue(0); // intra_chroma_pred_mode: DC + bits.Ue(3); // coded_block_pattern: codeNum 3 is 0 for intra prediction modes (table 9-4) + } + + return Nal(0x65, bits); + } + + /// + /// Settings of a High 4:4:4 Predictive sequence (profile_idc 244): chroma format, bit depths, separate colour planes, + /// lossless macroblocks (qpprime_y_zero_transform_bypass_flag, with the slices at QP′Y 0), CABAC. + /// + internal sealed record HighSettings( + int ChromaFormat = 1, + int BitDepthLuma = 8, + int BitDepthChroma = 8, + bool SeparatePlanes = false, + bool Lossless = false, + int WidthInMbs = 1, + int HeightInMbs = 1, + bool Cabac = false) + { + /// ChromaArrayType: no chroma syntax for monochrome and separate planes. + internal int ChromaArrayType => SeparatePlanes ? 0 : ChromaFormat; + + /// Chroma samples of each component in a macroblock. + internal int ChromaSamples => ChromaArrayType switch + { + 0 => 0, + 1 => 64, + 2 => 128, + _ => 256, + }; + } + + /// The sequence parameter set of (§7.3.2.1.1), POC type 2, no VUI. + internal static byte[] HighSps(HighSettings h) + { + var bits = new BitWriter(); + bits.Bits(244, 8); // profile_idc: High 4:4:4 Predictive + bits.Bits(0, 8); // constraint flags + bits.Bits(30, 8); // level_idc + bits.Ue(0); // seq_parameter_set_id + bits.Ue((uint)h.ChromaFormat); + if (h.ChromaFormat == 3) + { + bits.Bits(h.SeparatePlanes ? 1u : 0u, 1); + } + + bits.Ue((uint)h.BitDepthLuma - 8); + bits.Ue((uint)h.BitDepthChroma - 8); + bits.Bits(h.Lossless ? 1u : 0u, 1); // qpprime_y_zero_transform_bypass_flag + bits.Bits(0, 1); // seq_scaling_matrix_present_flag + bits.Ue(0); // log2_max_frame_num_minus4 + bits.Ue(2); // pic_order_cnt_type + bits.Ue(1); // max_num_ref_frames + bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag + bits.Ue((uint)h.WidthInMbs - 1); + bits.Ue((uint)h.HeightInMbs - 1); + bits.Bits(1, 1); // frame_mbs_only_flag + bits.Bits(1, 1); // direct_8x8_inference_flag + bits.Bits(0, 1); // frame_cropping_flag + bits.Bits(0, 1); // vui_parameters_present_flag + return Nal(0x67, bits); + } + + /// The picture parameter set of : QP′Y 0 (QPY −QpBdOffsetY) when lossless, else 26. + internal static byte[] HighPps(HighSettings h) + { + var bits = new BitWriter(); + bits.Ue(0); // pic_parameter_set_id + bits.Ue(0); // seq_parameter_set_id + bits.Bits(h.Cabac ? 1u : 0u, 1); // entropy_coding_mode_flag + bits.Bits(0, 1); // bottom_field_pic_order_in_frame_present_flag + bits.Ue(0); // num_slice_groups_minus1 + bits.Ue(0); // num_ref_idx_l0_default_active_minus1 + bits.Ue(0); // num_ref_idx_l1_default_active_minus1 + bits.Bits(0, 1); // weighted_pred_flag + bits.Bits(0, 2); // weighted_bipred_idc + bits.Se(h.Lossless ? -26 - (6 * (h.BitDepthLuma - 8)) : 0); // pic_init_qp_minus26 + bits.Se(0); // pic_init_qs_minus26 + bits.Se(0); // chroma_qp_index_offset + bits.Bits(1, 1); // deblocking_filter_control_present_flag + bits.Bits(0, 1); // constrained_intra_pred_flag + bits.Bits(0, 1); // redundant_pic_cnt_present_flag + return Nal(0x68, bits); + } + + /// + /// One I slice of an IDR picture of (for separate planes, the slice of ), + /// deblocking off, its macroblocks written by . + /// + internal static byte[] HighIdr(HighSettings h, Action macroblocks, int colourPlane = 0) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(7); // slice_type: I (all slices of the picture) + bits.Ue(0); // pic_parameter_set_id + if (h.SeparatePlanes) + { + bits.Bits((uint)colourPlane, 2); + } + + bits.Bits(0, 4); // frame_num + bits.Ue(0); // idr_pic_id + bits.Bits(0, 1); // no_output_of_prior_pics_flag + bits.Bits(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + macroblocks(bits); + return Nal(0x65, bits); + } + + /// + /// An I_PCM macroblock (CAVLC): its luma samples all , then (with chroma syntax) Cb and Cr all + /// and , at the bit depths of . + /// + internal static void Pcm(BitWriter bits, HighSettings h, int luma, int cb, int cr) + { + bits.Ue(25); // mb_type: I_PCM + bits.Align(); // pcm_alignment_zero_bit + for (var i = 0; i < 256; i++) + { + bits.Bits((uint)luma, h.BitDepthLuma); + } + + for (var c = 0; c < 2; c++) + { + for (var i = 0; i < h.ChromaSamples; i++) + { + bits.Bits((uint)(c == 0 ? cb : cr), h.BitDepthChroma); + } + } + } + + /// + /// An Intra_16x16 macroblock (CAVLC) without AC residual, prediction mode (0 vertical, + /// 1 horizontal, 2 DC; chroma DC if the chroma has syntax), and in each luma-like plane (Y; Cb and Cr too in 4:4:4) one + /// DC level of on the first block. The neighbour it predicts from must be I_PCM: its blocks + /// count 16 coefficients, so nC is 16 and coeff_token the 6-bit code of §9.2.1. + /// + internal static void Intra16x16Dc(BitWriter bits, HighSettings h, int mode, int[] dc) + { + bits.Ue((uint)(1 + mode)); // mb_type: I_16x16__0_0 + if (h.ChromaArrayType is 1 or 2) + { + bits.Ue(0); // intra_chroma_pred_mode: DC + } + + bits.Se(0); // mb_qp_delta + var planes = h.ChromaArrayType == 3 ? 3 : 1; + for (var p = 0; p < planes; p++) + { + var level = dc[p]; + if (level == 0) + { + bits.Bits(0b000011, 6); // coeff_token: TotalCoeff 0 + continue; + } + + if (Math.Abs(level) == 1) + { + bits.Bits(0b000001, 6); // coeff_token: TotalCoeff 1, TrailingOnes 1 + bits.Bits(level < 0 ? 1u : 0u, 1); // trailing_ones_sign_flag + } + else + { + // coeff_token: TotalCoeff 1, TrailingOnes 0; level_prefix with suffixLength 0, the first level after + // fewer than three trailing ones counting from 2 (levelCode = 2 |level| − 4, + 1 when negative). + bits.Bits(0b000000, 6); + var levelCode = (2 * Math.Abs(level)) - 4 + (level < 0 ? 1 : 0); + if (levelCode >= 14) + { + throw new ArgumentOutOfRangeException(nameof(dc), "Livello troppo grande per questo flusso di prova."); + } + + bits.Bits(1, levelCode + 1); // level_prefix: levelCode zeros then a one + } + + bits.Bits(1, 1); // total_zeros: 0 + } + + // No chroma residual: the mb_type says coded_block_pattern chroma 0. + } + + /// + /// A subset sequence parameter set (NAL unit 15, §7.3.2.1.3) of the Multiview High profile: the sequence of + /// in 8-bit 4:2:0, then seq_parameter_set_mvc_extension() (§H.7.3.2.1.4) with + /// views, view_id 0 to views − 1, none of them referring to another. + /// + internal static byte[] MvcSubsetSps(SequenceSettings s, int views) + { + var bits = new BitWriter(); + bits.Bits(118, 8); // profile_idc: Multiview High + bits.Bits(0, 8); // constraint flags + bits.Bits(51, 8); // level_idc + bits.Ue(0); // seq_parameter_set_id + bits.Ue(1); // chroma_format_idc: 4:2:0 + bits.Ue(0); // bit_depth_luma_minus8 + bits.Ue(0); // bit_depth_chroma_minus8 + bits.Bits(0, 1); // qpprime_y_zero_transform_bypass_flag + bits.Bits(0, 1); // seq_scaling_matrix_present_flag + bits.Ue((uint)s.Log2MaxFrameNum - 4); + bits.Ue(2); // pic_order_cnt_type + bits.Ue((uint)s.MaxNumRefFrames); + bits.Bits(0, 1); // gaps_in_frame_num_value_allowed_flag + bits.Ue((uint)s.WidthInMbs - 1); + bits.Ue((uint)s.HeightInMbs - 1); + bits.Bits(1, 1); // frame_mbs_only_flag + bits.Bits(1, 1); // direct_8x8_inference_flag + bits.Bits(0, 1); // frame_cropping_flag + bits.Bits(0, 1); // vui_parameters_present_flag + bits.Bits(1, 1); // bit_equal_to_one + bits.Ue((uint)views - 1); // num_views_minus1 + for (var i = 0; i < views; i++) + { + bits.Ue((uint)i); // view_id + } + + for (var pass = 0; pass < 2; pass++) + { + for (var i = 1; i < views; i++) + { + bits.Ue(0); // num_anchor_refs_l0 (then num_non_anchor_refs_l0) + bits.Ue(0); // num_anchor_refs_l1 (then num_non_anchor_refs_l1) + } + } + + bits.Ue(0); // num_level_values_signalled_minus1 + bits.Bits(51, 8); // level_idc + bits.Ue(0); // num_applicable_ops_minus1 + bits.Bits(0, 3); // applicable_op_temporal_id + bits.Ue(0); // applicable_op_num_target_views_minus1 + bits.Ue(0); // applicable_op_target_view_id + bits.Ue((uint)views - 1); // applicable_op_num_views_minus1 + bits.Bits(0, 1); // mvc_vui_parameters_present_flag + bits.Bits(0, 1); // additional_extension2_flag + return Nal(0x6F, bits); + } + + /// + /// An IDR view component of view (NAL unit 20 with the MVC header, §H.7.3.1.1), as one I + /// slice whose macroblocks are all Intra_16x16 DC without residual: one byte each. + /// + internal static byte[] ViewIdr(SequenceSettings s, int viewId) + { + var bits = new BitWriter(); + bits.Ue(0); // first_mb_in_slice + bits.Ue(7); // slice_type: I + bits.Ue(0); // pic_parameter_set_id + bits.Bits(0, s.Log2MaxFrameNum); // frame_num + bits.Ue(0); // idr_pic_id + bits.Bits(0, 1); // no_output_of_prior_pics_flag + bits.Bits(0, 1); // long_term_reference_flag + bits.Se(0); // slice_qp_delta + bits.Ue(1); // disable_deblocking_filter_idc: off + for (var m = 0; m < s.WidthInMbs * s.HeightInMbs; m++) + { + bits.Ue(3); // mb_type: I_16x16_2_0_0 (DC, no coded block) + bits.Ue(0); // intra_chroma_pred_mode: DC + bits.Se(0); // mb_qp_delta + bits.Bits(1, 1); // coeff_token of Intra16x16DCLevel, nC 0: TotalCoeff 0 + } + + bits.Bits(1, 1); // rbsp_stop_one_bit + + // nal_unit_header_mvc_extension(), outside emulation prevention: svc_extension_flag 0, non_idr_flag 0, + // priority_id 1, view_id, temporal_id 0, anchor_pic_flag 1, inter_view_flag 1, reserved_one_bit. + return [0, 0, 0, 1, 0x74, 0x01, (byte)(viewId >> 2), (byte)(((viewId & 3) << 6) | 0x07), .. bits.ToArray()]; + } + + private static byte[] Nal(byte header, BitWriter bits) + { + bits.Bits(1, 1); // rbsp_stop_one_bit + return [0, 0, 0, 1, header, .. bits.ToArray()]; + } +} diff --git a/tests/Febe.Tests/Packaging/PipelineTests.Riepilogo.cs b/tests/Febe.Tests/Packaging/PipelineTests.Riepilogo.cs new file mode 100644 index 0000000..1a5f395 --- /dev/null +++ b/tests/Febe.Tests/Packaging/PipelineTests.Riepilogo.cs @@ -0,0 +1,88 @@ +using System.Security; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Packaging; + +/// +/// The summary of the test results (.gitea/scripts/riepilogo-prove.sh), run on .trx files written here: the CI allows no +/// skipped test, and the only inconclusive results that do not count as skipped are the «da fare» ones of +/// H264ConformanceTests.FeaturesStillToDo, whose reason starts with «da fare: » right after the frame MSTest puts around +/// it (in English or in Italian). +/// +public sealed partial class PipelineTests +{ + private const string FeaturesStillToDo = "FeaturesStillToDo (\"SVCBST-19\",\"SVC, scalabilità spaziale\")"; + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task OnlyTheToDoConformanceStreamsMaySkipInTheCi() + { + var bash = RequireBash(); + + // The frames of MSTest, old and new, English and Italian: all «da fare», none skipped. + var toDo = await RunSummaryAsync(bash, + ("Passed", "AnythingElse", null), + ("NotExecuted", FeaturesStillToDo, "Assert.Inconclusive. da fare: SVC, scalabilità spaziale"), + ("NotExecuted", FeaturesStillToDo, "Assert.Inconclusive failed. da fare: MVC, due viste, confronto bit per bit"), + ("NotExecuted", FeaturesStillToDo, "Assert.Inconclusive non riuscito. da fare: MVC, tre viste"), + ("Inconclusive", FeaturesStillToDo, "Assert.Inconclusive. da fare: SVC & ")); + Assert.AreEqual(0, toDo.Code, toDo.Report); + StringAssert.Contains(toDo.Output, "totale 5 · superate 1 · fallite 0 · saltate 0 · da fare 4", toDo.Report); + StringAssert.Contains(toDo.Output, " - da fare: SVC & ", toDo.Report); + + // Anything else inconclusive is a skipped test, and turns the verification red: another reason in + // FeaturesStillToDo, «da fare: » not at the start of the reason, the same reason in another test. + (string Name, string Message)[] skipped = + [ + (FeaturesStillToDo, "Assert.Inconclusive. da verificare: MVC, due viste"), + (FeaturesStillToDo, "Assert.Inconclusive. Manca Chromium; da fare: installarlo"), + ("ChromiumStartsInTheSandbox", "Assert.Inconclusive. da fare: niente"), + ("FeaturesStillToDoLater", "Assert.Inconclusive. da fare: niente"), + ]; + foreach (var (name, message) in skipped) + { + var run = await RunSummaryAsync(bash, ("Passed", "AnythingElse", null), ("NotExecuted", name, message)); + Assert.AreEqual(1, run.Code, $"{name}: {message}\n{run.Report}"); + StringAssert.Contains(run.Output, "totale 2 · superate 1 · fallite 0 · saltate 1 · da fare 0", run.Report); + StringAssert.Contains(run.Errors, "Prove saltate: 1, più delle 0 ammesse.", run.Report); + } + + // The H.264 conformance tests write no other inconclusive reason: every Assert.Inconclusive there starts with it. + var source = Read(Repository.PathOf("tests", "Febe.Tests", "Media", "H264", "H264ConformanceTests.cs")); + var reasons = System.Text.RegularExpressions.Regex.Matches(source, @"Assert\.Inconclusive\(\$?""(?[^""]*)"""); + Assert.IsGreaterThanOrEqualTo(3, reasons.Count); + foreach (System.Text.RegularExpressions.Match reason in reasons) + { + StringAssert.StartsWith(reason.Groups["reason"].Value, "da fare: ", reason.Value); + } + } + + /// riepilogo-prove.sh with no skipped test allowed, on one .trx file of the given results. + private async Task<(int Code, string Output, string Errors, string Report)> RunSummaryAsync(string bash, params (string Outcome, string Name, string? Message)[] results) + { + using var folder = new TempFolder("febe-riepilogo"); + var trx = new System.Text.StringBuilder("\n\n \n"); + var id = 0; + foreach (var (outcome, name, message) in results) + { + trx.Append($" "); + if (message is not null) + { + trx.Append($"\n \n \n {SecurityElement.Escape(message)}\n \n \n "); + } + + trx.Append("\n"); + id++; + } + + trx.Append(" \n\n"); + await File.WriteAllTextAsync(folder.Combine("prove.trx"), trx.ToString(), TestContext.CancellationToken); + var run = await RunProcessAsync(bash, ["--noprofile", "--norc", ".gitea/scripts/riepilogo-prove.sh", folder.Path.Replace('\\', '/'), "0"], start => + { + start.Environment.Remove("GITHUB_STEP_SUMMARY"); + start.Environment.Remove("PROVE_SALTATE_AMMESSE"); + }); + return (run.Code, run.Output, run.Errors, $"codice {run.Code}\n{run.Output}\n{run.Errors}"); + } +} diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs index e4e4b87..60a42a7 100644 --- a/tests/Febe.Tests/Packaging/PipelineTests.cs +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -69,11 +69,19 @@ public sealed partial class PipelineTests StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\""); var environment = Script("ambiente-prove.sh"); - foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" }) + foreach (var package in new[] { "chromium", "xvfb", "nsis", "locales" }) { StringAssert.Contains(environment, package); } + // Videos are read and decoded in house: no ffmpeg in the CI, nor in the image (Alberto, 18 November 2026). + var image = Code(Read(Repository.PathOf("docker", "Dockerfile"))); + foreach (var program in new[] { "ffmpeg", "ffprobe" }) + { + Assert.IsFalse(environment.Contains(program, StringComparison.Ordinal), $"{program} non serve più alle prove"); + Assert.IsFalse(image.Contains(program, StringComparison.Ordinal), $"{program} non va nell'immagine"); + } + // tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project. foreach (var name in new[] { "verifica.yml", "rilascio.yml" }) { diff --git a/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs b/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs index 94132c9..7551a61 100644 --- a/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs +++ b/tests/Febe.Tests/Server/SessionKeyOptionsTests.cs @@ -225,40 +225,6 @@ public sealed class SessionKeyOptionsTests Assert.IsFalse(display.Environment.Keys.Any(ChildProcessEnvironment.IsSecret)); } - [TestMethod] - [DoNotParallelize] - public void FfmpegAndFfprobeStartWithoutThePasswordOrTheKeyOfFebesEnvironment() - { - // Febe's own environment holds both (as in Docker): ffprobe and ffmpeg must not inherit them (spec §13.2). - using var folder = new TempFolder("figli"); - var tool = folder.Combine("strumento-di-prova"); - File.WriteAllText(tool, string.Empty); - var before = ChildProcessEnvironment.SecretVariables.Select(n => (Name: n, Value: Environment.GetEnvironmentVariable(n))).ToList(); - try - { - foreach (var name in ChildProcessEnvironment.SecretVariables) - { - Environment.SetEnvironmentVariable(name, "valore-di-prova"); - } - - Assert.IsTrue(new System.Diagnostics.ProcessStartInfo("x").Environment.Keys.Any(ChildProcessEnvironment.IsSecret), "The parent holds them."); - var probe = Febe.Core.Import.FfprobeVideoMetadataProbe.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4"); - var frame = VideoFrameExtractor.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4", "1"); - foreach (var info in new[] { probe, frame }) - { - Assert.IsFalse(info.Environment.Keys.Any(ChildProcessEnvironment.IsSecret), info.FileName); - CollectionAssert.Contains(info.ArgumentList.ToArray(), "video-di-prova.mp4"); - } - } - finally - { - foreach (var (name, value) in before) - { - Environment.SetEnvironmentVariable(name, value); - } - } - } - private static Func Env(params (string Name, string Value)[] values) { var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);