C2–C3: contenitori e decodificatore H.264 in casa, ffmpeg esce (#58) #63

Merged
Alby96 merged 16 commits from funzione/decoder-h264 into main 2026-11-26 13:58:37 +01:00
183 changed files with 25150 additions and 486 deletions

No files matched your search

+1 -4
View File
@@ -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$'
+27 -10
View File
@@ -6,7 +6,10 @@
# .gitea/scripts/riepilogo-prove.sh <cartella dei .trx> [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
+3 -2
View File
@@ -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-<versione>-ci.<numero>.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
+2 -3
View File
@@ -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 \
+17
View File
@@ -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 |
+4 -4
View File
@@ -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
+2 -2
View File
@@ -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
+8 -5
View File
@@ -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-<versione>-ci.<numero>.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-<commit>`. Alla fine si toglie
+2 -2
View File
@@ -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-<versione>-ci.<numero>.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-<commit>` |
@@ -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.
+2 -2
View File
@@ -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,
@@ -0,0 +1,438 @@
using System.Buffers.Binary;
using System.Globalization;
using System.Text;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// 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 (<c>WM/EncodingTime</c> 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.
/// </summary>
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);
/// <summary>Bytes of an object header: its GUID and its 64-bit size.</summary>
private const int ObjectHeader = 24;
/// <summary>Header objects looked at, in all: a real header has a few dozen.</summary>
private const int MaxObjects = 4096;
/// <summary>The largest header object read into memory; the extended content description may hold a cover picture, cut here.</summary>
private const int MaxObjectBytes = 4 * 1024 * 1024;
/// <summary>True when the stream starts with the GUID of the ASF header object.</summary>
public static bool Looks(ReadOnlySpan<byte> start) => start.Length >= 16 && new Guid(start[..16]) == HeaderObject;
/// <summary>
/// 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.
/// </summary>
public static bool IsAudioOnly(ReadOnlySpan<byte> 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;
}
/// <summary>Reads a seekable stream from its start.</summary>
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<byte> 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<byte> 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();
}
/// <summary>The objects in <paramref name="data"/>, one after the other, up to its end or the first damaged one.</summary>
private static void Objects(ReadOnlySpan<byte> 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<byte> 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<byte> 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);
}
}
/// <summary>
/// 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.
/// </summary>
private static void ExtendedStreamProperties(ReadOnlySpan<byte> 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<byte> 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;
}
}
/// <summary>Name and value pairs (§3.11); only <c>WM/EncodingTime</c> is used, for the date.</summary>
private static void ExtendedContentDescription(ReadOnlySpan<byte> 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;
}
}
/// <summary>True when a null-terminated UTF-16LE name is <paramref name="expected"/>.</summary>
private static bool IsName(ReadOnlySpan<byte> 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);
}
/// <summary>A FILETIME (100-nanosecond units from 1601, UTC) from 1995 to a day past now; null otherwise.</summary>
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,
};
}
}
}
@@ -0,0 +1,395 @@
using System.Buffers.Binary;
using System.Globalization;
using System.Text;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// Reader of RIFF AVI files (the Microsoft AVI RIFF format, with the OpenDML extension of RIFF <c>AVIX</c> parts),
/// written from the format description: the main header, the first video and audio streams and the chunks of the
/// <c>movi</c> lists in file order. Key frames come from the <c>idx1</c> index when there is one.
/// </summary>
public static class AviReader
{
private const int MaxSamples = IsoBmffReader.MaxSamples;
private const int MaxHeaderBytes = 16 * 1024 * 1024;
/// <summary>True when the stream starts like an AVI file.</summary>
public static bool Looks(ReadOnlySpan<byte> start) =>
start.Length >= 12 && start[..4].SequenceEqual("RIFF"u8) && start.Slice(8, 4).SequenceEqual("AVI "u8);
/// <summary>Reads a seekable stream from its start.</summary>
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<byte> 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<byte> 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<byte> 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
}
}
/// <summary>The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».</summary>
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<MediaSample>(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<MediaSample>(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 };
}
/// <summary>Chunks of the video stream flagged as key frames in idx1 (by position among them); null without an index.</summary>
private HashSet<int>? KeyFrames()
{
if (Index is null || VideoStream < 0)
{
return null;
}
var keys = new HashSet<int>();
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
}
}
}
@@ -0,0 +1,22 @@
namespace Febe.Core.Codecs.Containers;
/// <summary>A big-endian bit reader over the few bytes of a codec header; past the end it gives zeros.</summary>
internal ref struct BitReader(ReadOnlySpan<byte> data, int position)
{
private readonly ReadOnlySpan<byte> data = data;
private int position = position;
/// <summary>The next <paramref name="count"/> bits (at most 31) as an unsigned number.</summary>
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;
}
}
@@ -0,0 +1,100 @@
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// 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.
/// </summary>
public static class ContainerReader
{
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
public const int MaxSampleSize = 64 * 1024 * 1024;
/// <summary>The format of a file from its first bytes; null when it is none of those read here.</summary>
public static ContainerFormat? Detect(ReadOnlySpan<byte> 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;
}
/// <summary>
/// Reads a seekable stream; null when its format is not recognised. Damaged files raise
/// <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/> when truncated); <paramref name="ct"/> is
/// checked between the top-level boxes, elements and fragments.
/// </summary>
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
Span<byte> 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,
};
}
/// <summary>Reads a file (read-only, shared); null when its format is not recognised.</summary>
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);
}
/// <summary>Opens a file for reading without blocking other readers or writers.</summary>
public static FileStream OpenRead(string path) =>
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, FileOptions.RandomAccess);
/// <summary>The bytes of a sample, read into <paramref name="buffer"/> (grown when needed).</summary>
public static ReadOnlySpan<byte> 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);
}
}
@@ -0,0 +1,751 @@
using System.Buffers.Binary;
using System.Text;
using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// Reader of FLV files, written from the Adobe Flash Video File Format Specification (version 10.1, annex E): the header,
/// the <c>onMetaData</c> 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.
/// </summary>
public static class FlvReader
{
private const int MaxSamples = IsoBmffReader.MaxSamples;
/// <summary>The largest script tag read: metadata with a keyframe index of a long video stays far below.</summary>
private const int MaxScriptBytes = 4 * 1024 * 1024;
/// <summary>The largest AVC sequence header or AAC configuration read.</summary>
private const int MaxConfigurationBytes = 64 * 1024;
/// <summary>For the metadata alone, the tags looked at from the start (and their bytes) before giving up on the rest.</summary>
private const int HeadTags = 4096;
private const long HeadBytes = 32L * 1024 * 1024;
/// <summary>Audio without a single video tag that, at the start of a file, proves it has no video.</summary>
public const int AudioProofMilliseconds = 5000;
/// <summary>Tags looked at back from the end of the file for its last time.</summary>
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];
/// <summary>True when the stream starts like an FLV file: «FLV», version 1 and a header of at least nine bytes.</summary>
public static bool Looks(ReadOnlySpan<byte> start) =>
start.Length >= 9 && start[..3].SequenceEqual("FLV"u8) && start[3] == 1 && BinaryPrimitives.ReadUInt32BigEndian(start[5..]) >= 9;
/// <summary>
/// True only when the first bytes of a file prove an FLV without video: the header says audio and no video, the tags
/// in <paramref name="head"/> hold at least one whole audio tag and no video tag, and they reach far enough to rule
/// video out — the exact end of <paramref name="head"/> (it is the whole file), <see cref="AudioProofMilliseconds"/>
/// of audio, or <see cref="HeadTags"/> 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.
/// </summary>
public static bool IsAudioOnly(ReadOnlySpan<byte> 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);
}
/// <summary>Reads a seekable stream from its start.</summary>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(stream);
var length = stream.Length;
Span<byte> 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();
}
/// <summary>True when a script tag starts with the AMF0 string «onMetaData»: other script tags (cue points) are not read.</summary>
private static bool IsMetadata(Stream stream, long body)
{
Span<byte> start = stackalloc byte[13];
stream.Position = body;
stream.ReadExactly(start);
return start[..3].SequenceEqual((ReadOnlySpan<byte>)[2, 0, 10]) && start[3..].SequenceEqual("onMetaData"u8);
}
private static void Audio(Stream stream, long body, int size, long time, ReadOnlySpan<byte> 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<byte> 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));
}
}
/// <summary>The time of the last audio or video tag, walking back from the end with the PreviousTagSize fields.</summary>
/// <summary>
/// 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.
/// </summary>
private static long? EndTime(Stream stream, long firstTag)
{
Span<byte> 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;
}
/// <summary>
/// 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.
/// </summary>
private static (int Width, int Height) SorensonSize(ReadOnlySpan<byte> 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),
};
}
/// <summary>Sample rate and channels of an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1); null when damaged.</summary>
internal static (int Rate, int Channels)? AacRateAndChannels(ReadOnlySpan<byte> 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 });
}
/// <summary>Reads the onMetaData script tag; true when it was one (another script tag leaves the next to be read).</summary>
private static bool Script(ReadOnlySpan<byte> 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;
}
/// <summary>The properties of an AMF0 object up to its end marker; only the top level is kept.</summary>
private static bool Properties(ReadOnlySpan<byte> 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
}
/// <summary>One AMF0 value (Action Message Format AMF0, §2); false when the data is not AMF0 or runs out.</summary>
private static bool Value(ReadOnlySpan<byte> data, ref int p, int depth, Metadata? metadata, ReadOnlySpan<byte> 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<byte> 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<byte> data, ref int p, int count)
{
p += count;
return p <= data.Length;
}
private static bool ShortString(ReadOnlySpan<byte> data, ref int p, out ReadOnlySpan<byte> 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;
}
/// <summary>The onMetaData properties Febe uses.</summary>
private sealed class Metadata(DateTimeOffset now)
{
internal double? Duration;
internal double? Width;
internal double? Height;
internal DateTimeOffset? Created;
internal void Number(ReadOnlySpan<byte> 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<byte> name, ReadOnlySpan<byte> 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<byte> 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<MediaSample> Samples = [];
/// <summary>For the metadata alone: the script, the video codec (with its sequence header for H.264) and the audio are known.</summary>
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 };
}
}
}
@@ -0,0 +1,978 @@
using System.Buffers.Binary;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// 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 (<c>moof</c>) of fragmented
/// files. Only boxes are read into memory; media data is never loaded here.
/// </summary>
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;
/// <summary>Samples of one track at most (about 18 hours at 30 frames per second; 40 bytes each in memory).</summary>
internal const int MaxSamples = 2_000_000;
/// <summary>True when the stream starts like an ISO media file (an <c>ftyp</c>, <c>moov</c>, <c>mdat</c>... box).</summary>
public static bool Looks(ReadOnlySpan<byte> 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));
/// <summary>Reads a seekable stream from its start.</summary>
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">
/// 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).
/// </param>
/// <param name="ct">Checked between the top-level boxes (each fragment of a fragmented file).</param>
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<byte> 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;
}
/// <summary>Child boxes of the box body data[start..start+count]: type, body start and body length.</summary>
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<byte> 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<MediaSample> Samples = [];
internal long FragmentTime = -1;
}
private sealed class Movie(bool samples, long fileLength)
{
/// <summary>The <c>trex</c> defaults of each track: sample duration, size and flags.</summary>
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
private readonly List<Track> tracks = [];
private DateTimeOffset? created;
private long timescale;
private long duration;
/// <summary>True when the movie has an <c>mvex</c> box: its samples are in fragments.</summary>
internal bool Fragmented;
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
internal long FragmentDuration;
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
internal bool NeedsFragmentsForDuration =>
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
internal void ParseMvhd(ReadOnlySpan<byte> 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<byte> 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));
}
}
}
}
}
/// <summary>The DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1 descriptors).</summary>
private static byte[]? EsdsConfig(ReadOnlySpan<byte> 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<MediaSample>(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;
}
/// <summary>Adds the samples of one movie fragment (ISO/IEC 14496-12 §8.8).</summary>
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;
}
}
}
}
/// <summary>The total duration of the <paramref name="count"/> samples of a trun, from their fields after the header.</summary>
private static long RunDuration(ReadOnlySpan<byte> 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 };
}
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
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;
}
}
}
@@ -0,0 +1,766 @@
using System.Buffers.Binary;
using System.Text;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>True when the stream starts with an EBML header.</summary>
public static bool Looks(ReadOnlySpan<byte> start) => start.Length >= 4 && BinaryPrimitives.ReadUInt32BigEndian(start) == EbmlId;
/// <summary>Reads a seekable stream from its start.</summary>
/// <param name="stream">The file.</param>
/// <param name="now">Current time: later creation times are ignored.</param>
/// <param name="samples">False to stop before the first cluster.</param>
/// <param name="ct">Checked between the top-level elements.</param>
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<byte> 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<long> 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<MediaSample> Samples = [];
}
private sealed class State
{
internal long TimecodeScale = 1_000_000;
internal double DurationTicks;
internal DateTimeOffset? Created;
internal TrackEntry? Video;
internal TrackEntry? Audio;
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
private long unit;
internal bool HasSamples => Video?.Samples.Count > 0 || Audio?.Samples.Count > 0;
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>TimecodeScale (nanoseconds of a tick of the block times); the default for a damaged value.</summary>
private long Scale => TimecodeScale > 0 ? TimecodeScale : 1_000_000;
/// <summary>Units of <see cref="UnitNanoseconds"/> in a tick (at least 1, should Info come after the first block).</summary>
private long Factor => Math.Max(1, Scale / UnitNanoseconds);
/// <summary>A time in TimecodeScale ticks as a time in units of <see cref="UnitNanoseconds"/>.</summary>
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 };
}
}
/// <summary>EBML primitives over the stream.</summary>
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<byte> 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;
}
}
}
@@ -0,0 +1,161 @@
namespace Febe.Core.Codecs.Containers;
/// <summary>The container formats Febe reads without external programs.</summary>
public enum ContainerFormat
{
/// <summary>ISO base media file format: MP4, MOV, 3GP, M4V (also fragmented).</summary>
IsoBmff,
/// <summary>Matroska and WebM.</summary>
Matroska,
/// <summary>RIFF AVI (also OpenDML).</summary>
Avi,
/// <summary>Advanced Systems Format: WMV, WMA and ASF files (metadata only).</summary>
Asf,
/// <summary>Flash Video (FLV).</summary>
Flv,
/// <summary>MPEG program stream (ISO/IEC 11172-1 and 13818-1): MPG, MPEG, VOB (metadata only).</summary>
MpegPs,
}
/// <summary>Video codecs recognised in a container; only <see cref="H264"/> can be decoded.</summary>
public enum VideoCodec
{
Unknown,
H264,
Hevc,
Vp8,
Vp9,
Av1,
Mpeg4Part2,
Mjpeg,
/// <summary>MPEG-1 video (ISO/IEC 11172-2).</summary>
Mpeg1,
/// <summary>MPEG-2 video (ITU-T H.262).</summary>
Mpeg2,
/// <summary>Windows Media Video 7 and 8 (WMV1, WMV2).</summary>
Wmv,
/// <summary>Windows Media Video 9 and VC-1 (WMV3, WMVA, WVC1).</summary>
Vc1,
/// <summary>H.263 and its Sorenson Spark variant of FLV.</summary>
H263,
/// <summary>On2 VP6 of FLV.</summary>
Vp6,
}
/// <summary>Audio codecs recognised in a container.</summary>
public enum AudioCodec
{
Unknown,
Aac,
Mp3,
Opus,
Vorbis,
Pcm,
/// <summary>MPEG audio layer I or II.</summary>
Mp2,
/// <summary>AC-3 (Dolby Digital).</summary>
Ac3,
/// <summary>Windows Media Audio (all versions).</summary>
Wma,
}
/// <summary>
/// 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 <see cref="MediaTrack.Timescale"/>. Samples are listed in decoding order.
/// </summary>
public readonly record struct MediaSample(long Offset, int Size, long DecodeTime, long PresentationTime, bool Key);
/// <summary>A track of a container.</summary>
public abstract class MediaTrack
{
/// <summary>Ticks per second of the sample times.</summary>
public long Timescale { get; init; } = 1000;
/// <summary>Duration of the track in <see cref="Timescale"/> units; 0 when unknown.</summary>
public long Duration { get; init; }
/// <summary>Samples in decoding order (empty when the container was read for its metadata only).</summary>
public IReadOnlyList<MediaSample> Samples { get; init; } = [];
/// <summary>The four-character code or codec identifier of the container, for messages.</summary>
public string CodecTag { get; init; } = string.Empty;
/// <summary>Time in seconds of a value in track units.</summary>
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
}
/// <summary>The video track of a container.</summary>
public sealed class VideoTrack : MediaTrack
{
public VideoCodec Codec { get; init; }
/// <summary>Coded width in pixels (before rotation).</summary>
public int Width { get; init; }
/// <summary>Coded height in pixels (before rotation).</summary>
public int Height { get; init; }
/// <summary>Clockwise rotation to apply when showing the frames: 0, 90, 180 or 270.</summary>
public int Rotation { get; init; }
/// <summary>The AVCDecoderConfigurationRecord (<c>avcC</c>) of an H.264 track stored with length prefixes.</summary>
public byte[]? AvcConfiguration { get; init; }
/// <summary>True when the samples are an Annex B byte stream (start codes), as in AVI.</summary>
public bool AnnexB { get; init; }
/// <summary>Width as shown (rotation applied).</summary>
public int DisplayWidth => Rotation % 180 == 0 ? Width : Height;
/// <summary>Height as shown (rotation applied).</summary>
public int DisplayHeight => Rotation % 180 == 0 ? Height : Width;
}
/// <summary>The audio track of a container.</summary>
public sealed class AudioTrack : MediaTrack
{
public AudioCodec Codec { get; init; }
public int SampleRate { get; init; }
public int Channels { get; init; }
/// <summary>The AudioSpecificConfig of an AAC track.</summary>
public byte[]? AacConfiguration { get; init; }
}
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
public sealed class MediaContainer
{
public ContainerFormat Format { get; init; }
/// <summary>Creation time written in the container, when plausible.</summary>
public DateTimeOffset? CreatedAt { get; init; }
/// <summary>Duration of the whole presentation.</summary>
public TimeSpan? Duration { get; init; }
/// <summary>The title written in the container (ASF content description), when there is one.</summary>
public string? Title { get; init; }
public VideoTrack? Video { get; init; }
public AudioTrack? Audio { get; init; }
}
/// <summary>A container that cannot be read: damaged, truncated or of a shape Febe does not handle.</summary>
public sealed class ContainerException(string message) : Exception(message);
@@ -0,0 +1,647 @@
using System.Buffers.Binary;
using System.Text;
namespace Febe.Core.Codecs.Containers;
/// <summary>A sample to write: its size, its times in track units, whether it is a sync sample.</summary>
public readonly record struct Mp4OutputSample(int Size, long DecodeTime, long PresentationTime, bool Key);
/// <summary>A track to write: H.264 video (with its <c>avcC</c>) or AAC audio (with its AudioSpecificConfig).</summary>
public sealed class Mp4OutputTrack
{
public required bool IsVideo { get; init; }
public required long Timescale { get; init; }
public required IReadOnlyList<Mp4OutputSample> Samples { get; init; }
/// <summary>Writes the bytes of sample <c>i</c> (exactly its <see cref="Mp4OutputSample.Size"/>) into the stream.</summary>
public required Action<int, Stream> WriteSample { get; init; }
public int Width { get; init; }
public int Height { get; init; }
/// <summary>Clockwise rotation written in the track matrix: 0, 90, 180 or 270.</summary>
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; }
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
public long LastSampleDuration { get; init; }
}
/// <summary>
/// Writer of MP4 files (ISO/IEC 14496-12 and 14496-14/15), written from the standards: <c>ftyp</c>, then the
/// <c>moov</c> box (so the file plays while it downloads), then one <c>mdat</c> with the tracks interleaved about every
/// half second.
/// </summary>
public static class Mp4Writer
{
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
private const int MovieTimescale = 1000;
/// <summary>Writes the tracks into <paramref name="output"/> (from its current position).</summary>
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> 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<byte> 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.");
}
}
}
}
/// <summary>Times of a track as the boxes need them.</summary>
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<Mp4OutputTrack> 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<Mp4OutputTrack> 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<int>();
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<long>();
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<byte> 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;
}
/// <summary>A box being built in memory.</summary>
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<byte> b = stackalloc byte[2];
BinaryPrimitives.WriteUInt16BigEndian(b, v);
body.Write(b);
}
internal void U32(uint v)
{
Span<byte> b = stackalloc byte[4];
BinaryPrimitives.WriteUInt32BigEndian(b, v);
body.Write(b);
}
internal void U64(ulong v)
{
Span<byte> 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<byte> 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;
}
}
}
@@ -0,0 +1,696 @@
using System.Buffers;
using System.Buffers.Binary;
using System.Globalization;
using Febe.Core.Codecs.H264;
namespace Febe.Core.Codecs.Containers;
/// <summary>
/// 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.
/// </summary>
public static class MpegPsReader
{
/// <summary>Bytes read from the start of the file.</summary>
private const int HeadWindow = 2 * 1024 * 1024;
/// <summary>Bytes read from the end of the file, for the last time.</summary>
private const int TailWindow = 1024 * 1024;
/// <summary>Bytes of the video stream gathered to find its headers.</summary>
private const int MaxVideoProbe = 1024 * 1024;
/// <summary>Presentation times are 33-bit numbers of a 90 kHz clock.</summary>
private const long TimeWrap = 1L << 33;
private const int ClockRate = 90_000;
/// <summary>Ticks of 90 kHz per frame for each frame_rate_code of MPEG-1 and MPEG-2 video (0 = forbidden or reserved).</summary>
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];
/// <summary>True when the stream starts with an MPEG-1 or MPEG-2 pack header.</summary>
public static bool Looks(ReadOnlySpan<byte> start) =>
start.Length >= 5 && start[0] == 0 && start[1] == 0 && start[2] == 1 && start[3] == 0xBA
&& ((start[4] & 0xC0) == 0x40 || (start[4] & 0xF0) == 0x20);
/// <summary>Reads a seekable stream: its first megabytes and its last.</summary>
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<byte>.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<byte>.Shared.Return(buffer);
state.Release();
}
return state.Build();
}
/// <summary>The packs and packets of a window of the file; anything else is skipped up to the next start code.</summary>
private static void Scan(ReadOnlySpan<byte> data, State state, bool head, CancellationToken ct)
{
ReadOnlySpan<byte> 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;
}
}
/// <summary>A PES packet of an audio or video stream: its presentation time and, at the start of the file, its payload.</summary>
private static void Packet(int id, ReadOnlySpan<byte> 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);
}
}
/// <summary>
/// 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.
/// </summary>
private static bool PesHeader(ReadOnlySpan<byte> 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;
}
/// <summary>A 33-bit time in five bytes with three marker bits (PTS, DTS, SCR of MPEG-1); -1 when a marker is wrong.</summary>
private static long Timestamp(ReadOnlySpan<byte> 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);
}
/// <summary>The base of the system clock reference of an MPEG-2 pack header (§2.5.3.4); -1 when a marker is wrong.</summary>
private static long Scr(ReadOnlySpan<byte> 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);
}
/// <summary>The stream types of the program stream map (§2.5.4), by elementary stream ID.</summary>
private static void StreamMap(ReadOnlySpan<byte> 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)..]);
}
}
/// <summary>Codec, sample rate and channels of the first payload of the audio stream.</summary>
private static void Audio(int id, ReadOnlySpan<byte> 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;
}
}
/// <summary>Sample rate and channels of an AC-3 sync frame (ATSC A/52 §5.3): fscod, acmod and lfeon.</summary>
private static void Ac3(ReadOnlySpan<byte> data, State state)
{
var sync = data.IndexOf((ReadOnlySpan<byte>)[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;
/// <summary>Gathers the start of the video stream and looks at it now and then, until its headers are found.</summary>
internal void AddVideo(ReadOnlySpan<byte> payload)
{
if (VideoDone || payload.IsEmpty)
{
return;
}
probe ??= ArrayPool<byte>.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);
}
}
/// <summary>
/// Codec and size from what was gathered; with <paramref name="final"/> nothing more will come, and with
/// <paramref name="whole"/> the stream ends there.
/// </summary>
internal void FinishVideo(bool final, bool whole)
{
if (VideoDone || VideoId < 0)
{
return;
}
var data = probe is null ? ReadOnlySpan<byte>.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;
}
}
/// <summary>The sequence header of MPEG-1 or MPEG-2 video and, for MPEG-2, its sequence extension right after it.</summary>
private bool MpegVideo(ReadOnlySpan<byte> data, byte type, bool final)
{
ReadOnlySpan<byte> sequence = [0, 0, 1, 0xB3];
ReadOnlySpan<byte> 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<byte>.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 };
}
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
/// <summary>Ticks from the earliest time at the start to the latest at the end; null without two times.</summary>
internal long? Elapsed()
{
if (reference < 0)
{
return null;
}
var last = tailLast != long.MinValue ? tailLast : headLast;
return last > headFirst ? last - headFirst : null;
}
}
}
+169
View File
@@ -0,0 +1,169 @@
using System.Buffers.Binary;
using System.Numerics;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>The next bits of the slice data, from the most significant bit.</summary>
private ulong window;
/// <summary>Valid bits at the top of <see cref="window"/>.</summary>
private int bits;
/// <summary>The next byte of <see cref="data"/> to load into the window.</summary>
private int next;
/// <summary>Initialises the context variables (§9.3.1.1).</summary>
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;
}
}
}
/// <summary>Initialises the decoding engine at the current, byte-aligned position (§9.3.1.2).</summary>
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;
}
/// <summary>The next <paramref name="count"/> bits (1 to 32) of the slice data.</summary>
private int Take(int count)
{
if (bits < count)
{
Refill();
}
var value = (int)(window >> (64 - count));
window <<= count;
bits -= count;
return value;
}
/// <summary>
/// Loads four bytes below the valid bits. Past the payload the buffer holds zero padding (see
/// <see cref="RbspReader"/>); a damaged slice that reads beyond the padding fails as the bit reader would.
/// </summary>
private void Refill()
{
while (bits <= 32)
{
window |= (ulong)BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(next, 4)) << (32 - bits);
next += 4;
bits += 32;
}
}
}
+248
View File
@@ -0,0 +1,248 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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.
/// </summary>
internal static class CabacTables
{
/// <summary>Number of context variables kept by the decoder.</summary>
internal const int ContextCount = 460;
/// <summary>rangeTabLPS[pStateIdx * 4 + qCodIRangeIdx] (table 9-44).</summary>
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,
];
/// <summary>transIdxLPS (table 9-45).</summary>
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,
];
/// <summary>(m, n) pairs for I slices, [ctxIdx * 2].</summary>
internal static readonly sbyte[] InitI = I;
/// <summary>(m, n) pairs for P and B slices by cabac_init_idc, [idc][ctxIdx * 2].</summary>
internal static readonly sbyte[][] InitPB = [P0, P1, P2];
}
+255
View File
@@ -0,0 +1,255 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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.
/// </summary>
internal static class CavlcTables
{
/// <summary>coeff_token for 0 ≤ nC &lt; 2, indexed [TotalCoeff * 4 + TrailingOnes].</summary>
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",
];
/// <summary>coeff_token for 2 ≤ nC &lt; 4.</summary>
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",
];
/// <summary>coeff_token for 4 ≤ nC &lt; 8.</summary>
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",
];
/// <summary>coeff_token for the chroma DC of 4:2:0 (nC = −1).</summary>
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",
];
/// <summary>coeff_token for the chroma DC of 4:2:2 (nC = −2, eight coefficients).</summary>
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",
];
/// <summary>total_zeros of 4×4 blocks, indexed [TotalCoeff − 1][total_zeros].</summary>
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"],
];
/// <summary>total_zeros of the 4:2:0 chroma DC, indexed [TotalCoeff − 1][total_zeros].</summary>
private static readonly string[][] TotalZerosChromaDc =
[
["1", "01", "001", "000"],
["1", "01", "00"],
["1", "0"],
];
/// <summary>total_zeros of the 4:2:2 chroma DC (table 9-9 (b)), indexed [TotalCoeff − 1][total_zeros].</summary>
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"],
];
/// <summary>run_before, indexed [Min(zerosLeft, 7) − 1][run_before].</summary>
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"],
];
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>All the code tables, for the self-checks of the tests (prefix-free, complete where the standard is).</summary>
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]);
}
}
/// <summary>
/// A 65536-entry table: for the next 16 bits of the stream, (code length &lt;&lt; 8) | value; zero when no code
/// matches.
/// </summary>
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)];
}
}
@@ -0,0 +1,632 @@
using static Febe.Core.Codecs.H264.Samples;
namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder
{
/// <summary>The luma-like plane the deblocking filter is working on: Y, or one colour plane coded separately.</summary>
private byte[] deblockLuma = [];
/// <summary>
/// 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.
/// </summary>
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<ushort>(picture);
}
else
{
DeblockPicture<byte>(picture);
}
}
private void DeblockPicture<T>(Picture picture)
where T : unmanaged
{
if (curStructure != 0)
{
DeblockRows<T>(picture, 2, curStructure - 1);
}
else if (activeSps!.MbAdaptiveFrameField)
{
DeblockPairs<T>(picture);
}
else
{
DeblockRows<T>(picture, 1, 0);
}
}
/// <summary>A frame (<paramref name="rowStep"/> 1) or the field of <paramref name="parity"/> (<paramref name="rowStep"/> 2).</summary>
private void DeblockRows<T>(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<byte> 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<T>(picture, m - 1, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
InnerEdges<T>(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<T>(picture, up, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
InnerEdges<T>(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
}
}
/// <summary>
/// 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).
/// </summary>
private void DeblockPairs<T>(Picture picture)
where T : unmanaged
{
var w = widthInMbs;
int width = picture.Width, cwidth = picture.ChromaWidth;
Span<byte> bs = stackalloc byte[4];
Span<byte> rowBs = stackalloc byte[16];
Span<int> 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<T>(picture, leftTop + (bottom * w), m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
else
{
MixedLeftEdge<T>(picture, m, leftTop, isField, bottom != 0, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, rowBs, rowMb);
}
}
InnerEdges<T>(picture, m, true, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
// Top edge.
if (!isField && bottom == 1)
{
MbEdge<T>(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<T>(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<T>(picture, pm, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
}
}
InnerEdges<T>(picture, m, false, lumaOrigin, stride, chromaOrigin, cstride, alphaOffset, betaOffset, bs);
}
}
}
}
/// <summary>
/// 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.
/// </summary>
private void MixedLeftEdge<T>(
Picture picture, int m, int leftTop, bool isField, bool bottom, int lumaOrigin, int stride, int chromaOrigin, int cstride,
int alphaOffset, int betaOffset, Span<byte> rowBs, Span<int> 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<T>(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<T>(picture.Cb);
var cr = Plane<T>(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);
}
}
}
}
/// <summary>A macroblock edge between <paramref name="pm"/> (left or above) and <paramref name="qm"/>, luma and chroma.</summary>
private void MbEdge<T>(
Picture picture, int pm, int qm, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span<byte> 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<T>(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<T>(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);
}
}
/// <summary>
/// The internal edges of macroblock <paramref name="m"/> 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.
/// </summary>
private void InnerEdges<T>(
Picture picture, int m, bool vertical, int lumaOrigin, int stride, int chromaOrigin, int cstride, int alphaOffset, int betaOffset, Span<byte> 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<T>(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<T>(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);
}
}
}
}
/// <summary>
/// α, β 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.
/// </summary>
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;
}
/// <summary>
/// The <paramref name="count"/> 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.
/// </summary>
private static void Edge<T>(Span<T> plane, int origin, int along, int across, ReadOnlySpan<byte> 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);
}
}
}
/// <summary>
/// bS of the edge between 4×4 luma blocks <paramref name="pb"/> of <paramref name="pm"/> and <paramref name="qb"/> of
/// <paramref name="qm"/> (§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.
/// </summary>
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;
}
/// <summary>The picture (frame, or field of a frame store) a block refers to in a list; empty when the list is not used.</summary>
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;
/// <summary>
/// The transform block holding the 4×4 luma block <paramref name="blk"/> has coefficients; in 4:4:4 (not coded as
/// separate planes) those of the Cb and Cr blocks at the same place count too.
/// </summary>
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;
}
/// <summary>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 <paramref name="bdShift"/>.</summary>
private static void FilterLuma<T>(Span<T> 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<T>(Clip(p0 + delta, max));
s[o] = Make<T>(Clip(q0 - delta, max));
if (ap)
{
s[o - (2 * step)] = Make<T>(p1 + Math.Clamp((p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1, -tc0, tc0));
}
if (aq)
{
s[o + step] = Make<T>(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<T>((p2 + (2 * p1) + (2 * p0) + (2 * q0) + q1 + 4) >> 3);
s[o - (2 * step)] = Make<T>((p2 + p1 + p0 + q0 + 2) >> 2);
s[o - (3 * step)] = Make<T>(((2 * p3) + (3 * p2) + p1 + p0 + q0 + 4) >> 3);
}
else
{
s[o - step] = Make<T>(((2 * p1) + p0 + q1 + 2) >> 2);
}
if (aq && strong)
{
var q3 = Get(s[o + (3 * step)]);
s[o] = Make<T>((p1 + (2 * p0) + (2 * q0) + (2 * q1) + q2 + 4) >> 3);
s[o + step] = Make<T>((p0 + q0 + q1 + q2 + 2) >> 2);
s[o + (2 * step)] = Make<T>(((2 * q3) + (3 * q2) + q1 + q0 + p0 + 4) >> 3);
}
else
{
s[o] = Make<T>(((2 * q1) + q0 + p1 + 2) >> 2);
}
}
/// <summary>The filter of the chroma edges of 4:2:0 and 4:2:2 (chromaStyleFilteringFlag).</summary>
private static void FilterChroma<T>(Span<T> 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<T>(Clip(p0 + delta, max));
s[o] = Make<T>(Clip(q0 - delta, max));
return;
}
s[o - step] = Make<T>(((2 * p1) + p0 + q1 + 2) >> 2);
s[o] = Make<T>(((2 * q1) + q0 + p1 + 2) >> 2);
}
}
@@ -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;
}
}
}
/// <summary>mb_type of an I slice (ctxIdxOffset 3).</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// residual_block() of category <paramref name="cat"/> (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 <paramref name="output"/>; returns the number of non-zero ones.
/// </summary>
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<int> 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<int> 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;
}
/// <summary>
/// §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).
/// </summary>
private bool HiddenByPartitioning(int n) => partitioned && pps.ConstrainedIntraPred && !IsIntra(n) && IsIntra(mb);
/// <summary>nC of a luma 4×4 block (raster index) from the blocks to its left and above (§9.2.1).</summary>
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;
}
/// <summary>nC of a chroma AC block of 4:2:0 or 4:2:2 (blocks in raster order, two per row).</summary>
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<bool> 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;
}
/// <summary>condTermFlagN of coded_block_flag (§9.3.3.1.1.9) for the block to the left or above.</summary>
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;
}
}
}
}
@@ -0,0 +1,721 @@
namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder
{
private int weightMode;
/// <summary>Implicit weights w0 of the slice by (refIdxL0, refIdxL1): frames, or the fields of a field picture.</summary>
private int[] implicitW0 = [];
/// <summary>MBAFF: implicit weights of the field macroblocks, by parity of the macroblock.</summary>
private int[][] implicitField = [[], []];
/// <summary>
/// The neighbouring 4×4 luma block covering (<paramref name="xN"/>, <paramref name="yN"/>) 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, <see cref="blkDone"/>).
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// Luma motion vector prediction (§8.4.1.3). <paramref name="directional"/>: 0 none, 1/2 the upper/lower 16×8
/// partition, 3/4 the left/right 8×16 partition.
/// </summary>
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);
/// <summary>Direct prediction (§8.4.1.2) of the sub-macroblocks <paramref name="first"/> to <paramref name="end"/> − 1.</summary>
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;
}
/// <summary>
/// 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).
/// </summary>
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;
}
/// <summary>For a field macroblock of an MBAFF frame its parity (its references are fields of the frame lists), else −1.</summary>
private int MbFieldOf => mbaff && mbField ? mbY & 1 : -1;
/// <summary>
/// The entry of a list for a reference index: as built, or (<paramref name="fieldOf"/> ≥ 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.
/// </summary>
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);
}
/// <summary>A reference picture of the current macroblock; a substitute when the stream refers to a missing one.</summary>
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);
}
}
}
/// <summary>Implicit weights (§8.4.2.3.1) for every pair of indices, with the order counts of frames or of fields.</summary>
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);
}
}
}
}
/// <summary>
/// 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.
/// </summary>
/// <summary>
/// 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.
/// </summary>
private void MotionCompensate(int px, int py, int w, int h)
{
if (wide)
{
MotionCompensate<ushort>(px, py, w, h);
}
else
{
MotionCompensate<byte>(px, py, w, h);
}
}
private void MotionCompensate<T>(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<T> a = stackalloc T[256];
Span<T> 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<T>(Samples.Plane<T>(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<T>(Samples.Plane<T>(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<T>(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<T>(Samples.Plane<T>(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<T>(Samples.Plane<T>(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<T>(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));
}
}
}
/// <summary>
/// The weighted sample prediction (§8.4.2.3) of component <paramref name="comp"/> (0 luma, 1 Cb, 2 Cr): the offsets
/// are in units of 8-bit samples, scaled to <paramref name="bitDepth"/>.
/// </summary>
private void Combine<T>(Span<T> a, ReadOnlySpan<T> 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);
}
}
}
@@ -0,0 +1,319 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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).
/// </summary>
public sealed partial class H264Decoder
{
/// <summary>Subset sequence parameter sets (NAL unit 15) of the root decoder; the view decoders use them as their SPSs.</summary>
private readonly Dictionary<int, Sps> subsetSequences = [];
/// <summary>The decoder of the base view, for the decoder of another view; null for the root decoder itself.</summary>
private readonly H264Decoder? root;
/// <summary>The decoders of the non-base views (root decoder only), in the order they appeared.</summary>
private readonly List<H264Decoder> viewDecoders = [];
/// <summary>view_id of the view this decoder decodes.</summary>
private int viewId;
/// <summary>Root decoder: access units started so far (one per picture of the base view).</summary>
private long accessUnit;
/// <summary>The frame store of the view component of the latest access unit, its access unit and its inter_view_flag.</summary>
private Picture? auPicture;
private long auPictureUnit = -1;
private bool auPictureInterView;
/// <summary>The view component being decoded is an anchor picture (anchor_pic_flag): it uses the anchor references.</summary>
private bool anchorPicture;
/// <summary>inter_view_flag of the view component whose slices come next (from its prefix or extension header).</summary>
private bool pendingInterView = true;
/// <summary>A subset SPS with the multiview extension was read: the stream is MVC.</summary>
private bool multiview;
/// <summary>
/// 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.
/// </summary>
internal const long MaxAllViewsMbs = 2L * Sps.MaxDpbMbs;
public H264Decoder()
{
}
/// <summary>The decoder of a non-base view: it shares the parameter sets of the root decoder.</summary>
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.
}
/// <summary>
/// Whether the non-base views of an MVC stream are decoded too (the default), each frame carrying its
/// <see cref="H264Frame.ViewId"/>; false keeps only the base view, which is plain H.264, and skips the rest.
/// </summary>
public bool DecodeAllViews { get; set; } = true;
/// <summary>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.</summary>
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;
}
/// <summary>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.</summary>
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);
}
/// <summary>
/// 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 <see cref="MaxAllViewsMbs"/>: each view holds at most max_num_ref_frames reference frames
/// and the picture being decoded.
/// </summary>
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);
}
/// <summary>
/// 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 (<paramref name="register"/>) also has the root decoder keep this decoder.
/// </summary>
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);
}
/// <summary>Finishes the pictures of the other views (at the end of an access unit, or before the next base view one).</summary>
private void FinishViews()
{
foreach (var decoder in viewDecoders)
{
decoder.FinishPicture();
}
}
/// <summary>Flushes the decoders of the other views.</summary>
private void FlushViews()
{
foreach (var decoder in viewDecoders)
{
decoder.Flush();
}
}
/// <summary>Records the frame store of the view component starting now, for the views that refer to it.</summary>
private void NoteViewComponent(Picture picture)
{
if (root is null)
{
accessUnit++;
}
auPicture = picture;
auPictureUnit = (root ?? this).accessUnit;
auPictureInterView = pendingInterView;
}
/// <summary>
/// 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 <see cref="Wanted"/> says.
/// </summary>
private bool NeededByOtherViews => (root ?? this) is { multiview: true, DecodeAllViews: true } && pendingInterView;
/// <summary>The view_ids of the inter-view references of list <paramref name="list"/> of the current view component.</summary>
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];
}
/// <summary>
/// The view component of view <paramref name="id"/> 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.
/// </summary>
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);
}
/// <summary>Whether some inter-view reference of the current view component is there.</summary>
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;
}
/// <summary>§H.8.2.1: the inter-view references of the list, in the order of the SPS, after the temporal ones.</summary>
private void AppendInterView(List<RefEntry> list, int index)
{
foreach (var id in InterViewRefs(index))
{
var entry = InterViewPicture(id);
if (entry.Pic is not null)
{
list.Add(entry);
}
}
}
/// <summary>
/// The inter-view reference picked by modification_of_pic_nums_idc 4 (subtract) or 5 (add) with
/// abs_diff_view_idx_minus1 <paramref name="value"/> (§H.8.2.2.3); <paramref name="pred"/> is picViewIdxPred.
/// </summary>
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;
}
}
@@ -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.
/// <summary>A partition A is waiting for its partitions B and C.</summary>
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;
/// <summary>The slice being decoded is partitioned: the residual comes from <see cref="intraResidual"/> and <see cref="interResidual"/>.</summary>
private bool partitioned;
/// <summary>Partition B of the slice being decoded, null when it is missing.</summary>
private RbspReader? intraResidual;
/// <summary>Partition C of the slice being decoded, null when it is missing.</summary>
private RbspReader? interResidual;
/// <summary>
/// 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.
/// </summary>
internal Action<int, int, bool, bool>? ResidualRead { get; set; }
/// <summary>Partition A (§7.3.2.9): the slice header and slice_id, kept until partitions B and C have arrived.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
/// <summary>Decodes the slice of the partitions received; a missing B or C leaves the residual it carries at zero.</summary>
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;
}
}
/// <summary>A copy of the RBSP of a partition, which must outlive the shared buffer of the stream.</summary>
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 };
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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).
/// </remarks>
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;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,245 @@
namespace Febe.Core.Codecs.H264;
public sealed partial class H264Decoder
{
/// <summary>The picture has more than one slice group (FMO): a slice walks the macroblocks of its group only.</summary>
private bool fmo;
/// <summary>The slice group of each map unit (mapUnitToSliceGroupMap, §8.2.2.1–§8.2.2.7).</summary>
private int[] mapUnitGroup = [];
/// <summary>The slice group of each macroblock address of the picture (mbToSliceGroupMap, §8.2.2.8).</summary>
private byte[] mbGroup = [];
/// <summary>NextMbAddress (§8.2.2): the next address of the same slice group, the picture size after the last one.</summary>
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;
/// <summary>The address after <paramref name="addr"/> in the slice (§7.3.4).</summary>
private int NextAddress(int addr) => fmo ? nextMb[addr] : addr + 1;
/// <summary>
/// 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.
/// </summary>
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<int> 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;
}
/// <summary>mapUnitToSliceGroupMap for the map type of the PPS (§8.2.2.1–§8.2.2.7).</summary>
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;
}
}
/// <summary>Box-out (§8.2.2.4): group 0 grows as a spiral from the centre, clockwise or counter-clockwise.</summary>
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;
}
}
}
}
@@ -0,0 +1,569 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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,
/// <see cref="EnhancementLayersSkipped"/> 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.
/// </summary>
public sealed partial class H264Decoder
{
private const int CoefPerMb = 512;
/// <summary>A subset SPS with the scalable extension was read: the stream is SVC.</summary>
private bool scalable;
/// <summary>The enhancement layers of the stream use something not written yet: from then on only the base layer.</summary>
private string? svcUnsupported;
/// <summary>DQId of the highest layer decoded into the current picture (0 the base layer).</summary>
private int picDqId;
/// <summary>A layer of the current picture could not be decoded: the layers above it are skipped.</summary>
private bool picSvcStopped;
/// <summary>The refinement slice being decoded, null for an AVC slice.</summary>
private SvcSliceFields? svcSlice;
/// <summary>The macroblock being decoded is an ordinary one of a refinement slice (base_mode_flag 0).</summary>
private bool svcOwnMb;
/// <summary>motion_prediction_flag_lX of the macroblock, by list and 8×8 block.</summary>
private readonly bool[] svcMotionPred = new bool[8];
/// <summary>The residual of the macroblock was cleared and read (else it is that of a skipped macroblock: none).</summary>
private bool mbResidualSet;
/// <summary>Intra_16x16 prediction mode of the macroblock being decoded.</summary>
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 = [];
/// <summary>The macroblock being decoded is a base_mode intra refinement.</summary>
private bool mbRefinedIntra;
private bool[] baseIntraRefined = [];
/// <summary>
/// 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.
/// </summary>
public bool DecodeEnhancementLayers { get; set; } = true;
/// <summary>Why the enhancement layers of the stream are not decoded (null when they are, or the stream has none).</summary>
public string? EnhancementLayersSkipped => svcUnsupported;
/// <summary>The per-macroblock data of the layers is kept while the base layer is decoded.</summary>
private bool RecordLayers => scalable && DecodeEnhancementLayers && svcUnsupported is null && root is null;
/// <summary>The SVC prefix NAL unit (§G.7.3.2.12.1) before a base layer slice: key pictures are not handled.</summary>
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;
}
/// <summary>A slice of an enhancement layer (NAL unit 20 with the SVC header): decoded over the current picture.</summary>
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;
}
}
/// <summary>Makes room for the per-macroblock data of the layers.</summary>
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];
}
/// <summary>The coefficients and Intra_16x16 mode of the macroblock just decoded, for the layer above it.</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>The layer decoded so far becomes the reference layer of the one starting (§G.8.1.5).</summary>
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;
/// <summary>A macroblock of a refinement slice (macroblock_layer_in_scalable_extension(), §G.7.3.6).</summary>
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;
}
}
/// <summary>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.</summary>
private void DecodeScalableSkip()
{
DecodeSkip();
var s = svcSlice!;
var residualPrediction = !s.AdaptiveResidualPrediction && s.DefaultResidualPrediction;
ClearResidual();
if (residualPrediction)
{
AddBaseCoefficients();
if (wide)
{
AddInterResidual<ushort>();
}
else
{
AddInterResidual<byte>();
}
}
}
/// <summary>
/// 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.
/// </summary>
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<byte>();
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<ushort>();
}
else
{
AddInterResidual<byte>();
}
}
/// <summary>Refinement (§G.8.5): the scaled coefficients of the layer below are added to those of this one.</summary>
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;
}
}
}
/// <summary>
/// motion_prediction_flag_l0 and _l1 of an ordinary inter macroblock of a refinement slice (§G.7.3.6.1), for the
/// partitions <paramref name="parts"/> (8×8 blocks of each), read or inferred.
/// </summary>
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;
}
}
}
}
}
}
/// <summary>Whether the motion of the 8×8 block <paramref name="b8"/> is predicted from the layer below.</summary>
private bool MotionFromBase(int list, int b8) => svcOwnMb && svcMotionPred[(list * 4) + b8];
/// <summary>The reference index of the layer below for an 8×8 block (0 where it has none).</summary>
private int BaseRefIdx(int list, int b8) => Math.Max(0, (int)baseRefIdx[(((list * mbCount) + mb) * 4) + b8]);
/// <summary>The motion vector of the layer below for a 4×4 block (raster index).</summary>
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]);
}
/// <summary>residual_prediction_flag of an ordinary inter macroblock of a refinement slice, read or inferred.</summary>
private bool ReadResidualPredictionFlag()
{
var s = svcSlice!;
return s.AdaptiveResidualPrediction ? rd.ReadFlag() : s.DefaultResidualPrediction;
}
/// <summary>A slice with slice_skip_flag: every macroblock as base_mode_flag 1 with the residual of the layer below.</summary>
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();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
using System.Buffers.Binary;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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).
/// </summary>
public static class H264StreamInfo
{
/// <summary>The picture size of an SPS NAL unit (header byte included); false when it is not an SPS or is damaged.</summary>
public static bool TryPictureSize(ReadOnlySpan<byte> nal, out int width, out int height)
{
width = height = 0;
if (nal.Length < 4 || (nal[0] & 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;
}
}
/// <summary>
/// The picture size of the first SPS of an AVCDecoderConfigurationRecord (ISO/IEC 14496-15 §5.3.3.1), as FLV and MP4
/// carry it.
/// </summary>
public static bool TryPictureSizeFromConfiguration(ReadOnlySpan<byte> 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);
}
/// <summary>
/// The picture size of the first whole SPS of an Annex B byte stream; an SPS that the end of
/// <paramref name="stream"/> cuts counts only when <paramref name="complete"/> says nothing follows.
/// </summary>
public static bool TryPictureSizeFromAnnexB(ReadOnlySpan<byte> stream, bool complete, out int width, out int height)
{
width = height = 0;
ReadOnlySpan<byte> startCode = [0, 0, 1];
var found = stream.IndexOf(startCode);
while (found >= 0)
{
var start = found + 3;
var next = stream[start..].IndexOf(startCode);
if (next < 0 && !complete)
{
return false; // the last unit may be cut short
}
var end = next < 0 ? stream.Length : start + next;
var nal = stream[start..end];
while (nal.Length > 0 && nal[^1] == 0)
{
nal = nal[..^1]; // the zero byte of a four-byte start code belongs to the next unit
}
if (nal.Length > 0 && (nal[0] & 0x1F) == 7 && TryPictureSize(nal, out width, out height))
{
return true;
}
found = next < 0 ? -1 : end;
}
return false;
}
}
+178
View File
@@ -0,0 +1,178 @@
namespace Febe.Core.Codecs.H264;
/// <summary>Fixed tables of ITU-T H.264 other than the variable-length codes and the CABAC contexts.</summary>
internal static class H264Tables
{
/// <summary>Zig-zag scan of 4×4 frame blocks: scan index → raster position (row * 4 + column).</summary>
internal static readonly byte[] ZigZag4x4 = BuildZigZag(4);
/// <summary>Zig-zag scan of 8×8 frame blocks: scan index → raster position (row * 8 + column).</summary>
internal static readonly byte[] ZigZag8x8 = BuildZigZag(8);
/// <summary>Field scan of 4×4 blocks (table 8-13): scan index → raster position (row * 4 + column).</summary>
internal static readonly byte[] FieldScan4x4 = [0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15];
/// <summary>Field scan of 8×8 blocks (table 8-14): scan index → raster position (row * 8 + column).</summary>
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,
];
/// <summary>luma4x4BlkIdx → raster index of the 4×4 block in the macroblock ((y / 4) * 4 + x / 4).</summary>
internal static readonly byte[] BlockToRaster = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15];
/// <summary>Raster index of a 4×4 block → luma4x4BlkIdx.</summary>
internal static readonly byte[] RasterToBlock = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15];
/// <summary>coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum (table 9-4, 4:2:0 and 4:2:2).</summary>
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,
];
/// <summary>coded_block_pattern of inter macroblocks from codeNum (table 9-4).</summary>
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,
];
/// <summary>coded_block_pattern of Intra_4x4 and Intra_8x8 macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3).</summary>
internal static readonly byte[] CbpIntraNoChroma = [15, 0, 7, 11, 13, 14, 3, 5, 10, 12, 1, 2, 4, 8, 6, 9];
/// <summary>coded_block_pattern of inter macroblocks from codeNum without chroma syntax (table 9-4, ChromaArrayType 0 and 3).</summary>
internal static readonly byte[] CbpInterNoChroma = [0, 1, 2, 4, 8, 3, 5, 10, 12, 15, 7, 11, 13, 14, 6, 9];
/// <summary>normAdjust4x4 values v[m][0..2] (equation 8-315).</summary>
internal static readonly byte[,] NormAdjust4x4 =
{
{ 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 },
};
/// <summary>normAdjust8x8 values v[m][0..5] (equation 8-318).</summary>
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 },
};
/// <summary>Default_4x4_Intra in zig-zag order (table 7-3).</summary>
internal static readonly byte[] Default4x4Intra = [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42];
/// <summary>Default_4x4_Inter in zig-zag order (table 7-3).</summary>
internal static readonly byte[] Default4x4Inter = [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34];
/// <summary>Default_8x8_Intra in zig-zag order (table 7-4).</summary>
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,
];
/// <summary>Default_8x8_Inter in zig-zag order (table 7-4).</summary>
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,
];
/// <summary>QPc from qPI (table 8-15), for qPI 0..51.</summary>
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,
];
/// <summary>α′ of the deblocking filter (table 8-16), by indexA.</summary>
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,
];
/// <summary>β′ of the deblocking filter (table 8-16), by indexB.</summary>
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,
];
/// <summary>tC0′ of the deblocking filter (table 8-17), [indexA * 3 + bS − 1].</summary>
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,
];
/// <summary>ctxIdxInc of significant_coeff_flag for 8×8 frame blocks (table 9-43), by levelListIdx.</summary>
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,
];
/// <summary>ctxIdxInc of significant_coeff_flag for 8×8 field blocks (table 9-43), by levelListIdx.</summary>
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,
];
/// <summary>ctxIdxInc of last_significant_coeff_flag for 8×8 blocks (table 9-43), by levelListIdx.</summary>
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;
}
}
@@ -0,0 +1,240 @@
using static Febe.Core.Codecs.H264.Samples;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// Fractional sample interpolation (§8.4.2.2) and weighted sample prediction (§8.4.2.3), at any bit depth (<c>max</c> is
/// 2^BitDepth − 1). The luma interpolation serves also the Cb and Cr planes of 4:4:4.
/// </summary>
internal static class InterPrediction
{
/// <summary>
/// Luma prediction of a <paramref name="w"/> × <paramref name="h"/> block whose top-left corner, in quarter
/// samples, is (<paramref name="qx"/>, <paramref name="qy"/>), from the <paramref name="pw"/> × <paramref name="ph"/>
/// picture whose row y starts at <paramref name="origin"/> + y × <paramref name="stride"/> (a frame, or one field of a
/// frame store). Samples outside the picture repeat the edge.
/// </summary>
internal static void Luma<T>(ReadOnlySpan<T> plane, int origin, int stride, int pw, int ph, int qx, int qy, int w, int h, Span<T> 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<int> 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<T>(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<int> bh = stackalloc int[17 * 16];
Span<int> vh = stackalloc int[16 * 17];
Span<int> 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<int> 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<T>(value);
}
}
}
/// <summary>
/// Chroma prediction (4:2:0 and 4:2:2) of a <paramref name="w"/> × <paramref name="h"/> block whose corner, in eighths
/// of a chroma sample, is (<paramref name="ex"/>, <paramref name="ey"/>), from a plane view as for <see cref="Luma"/>.
/// </summary>
internal static void Chroma<T>(ReadOnlySpan<T> plane, int origin, int stride, int pw, int ph, int ex, int ey, int w, int h, Span<T> 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<T>(((wA * Get(plane[y0 + x0])) + (wB * Get(plane[y0 + x1])) + (wC * Get(plane[y1 + x0])) + (wD * Get(plane[y1 + x1])) + 32) >> 6);
}
}
}
/// <summary>Default bi-prediction average (equation 8-273), into <paramref name="a"/>.</summary>
internal static void Average<T>(Span<T> a, ReadOnlySpan<T> b)
where T : unmanaged
{
for (var i = 0; i < a.Length; i++)
{
a[i] = Make<T>((Get(a[i]) + Get(b[i]) + 1) >> 1);
}
}
/// <summary>Weighted prediction from one list (equation 8-270); <paramref name="offset"/> is already scaled to the bit depth.</summary>
internal static void WeightOne<T>(Span<T> 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<T>(Clip(v + offset, max));
}
}
/// <summary>Weighted bi-prediction (equation 8-272), into <paramref name="a"/>; the offsets are already scaled to the bit depth.</summary>
internal static void WeightTwo<T>(Span<T> a, ReadOnlySpan<T> 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<T>(Clip(v, max));
}
}
}
@@ -0,0 +1,519 @@
using static Febe.Core.Codecs.H264.Samples;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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 &lt;&lt; (BitDepth − 1).
/// </summary>
internal static class IntraPrediction
{
/// <summary>Intra_4x4 (§8.3.1.2) of the block at <paramref name="o"/>.</summary>
internal static void Predict4x4<T>(Span<T> 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<int> t = stackalloc int[8];
Span<int> 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>(t[x]);
}
}
break;
case 1: // Horizontal
for (var y = 0; y < 4; y++)
{
p.Slice(o + (y * stride), 4).Fill(Make<T>(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<T>(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<int> 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<T>(Directional(e, 4, mode, x, y, 4));
}
}
break;
}
}
}
/// <summary>
/// Modes 4–8 of Intra_4x4 and Intra_8x8 on an edge array where p[−1, y] is at <c>c − 1 − y</c>, p[−1, −1] at
/// <c>c</c> and p[x, −1] at <c>c + 1 + x</c> (<paramref name="c"/> = block size).
/// </summary>
private static int Directional(ReadOnlySpan<int> 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);
}
}
}
/// <summary>p[i, −1] of the edge array, i ≥ −1.</summary>
private static int T(ReadOnlySpan<int> e, int c, int i) => e[c + 1 + i];
/// <summary>p[−1, i] of the edge array, i ≥ −1.</summary>
private static int L(ReadOnlySpan<int> e, int c, int i) => e[c - 1 - i];
/// <summary>Intra_8x8 with the reference sample filtering of §8.3.2.2.1.</summary>
internal static void Predict8x8<T>(Span<T> 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<int> t = stackalloc int[16];
Span<int> 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<int> ft = stackalloc int[16];
Span<int> 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<T>(ft[x]);
}
}
break;
case 1:
for (var y = 0; y < 8; y++)
{
p.Slice(o + (y * stride), 8).Fill(Make<T>(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<T>(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<int> 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<T>(Directional(e, 8, mode, x, y, 8));
}
}
break;
}
}
}
/// <summary>Intra_16x16 (§8.3.3).</summary>
internal static void Predict16x16<T>(Span<T> 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;
}
}
/// <summary>
/// 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 <paramref name="leftRows"/> 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.
/// </summary>
internal static void PredictChroma<T>(Span<T> 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;
}
}
/// <summary>
/// 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.
/// </summary>
private static void Plane<T>(Span<T> 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<T>(Clip(v >> 5, max));
}
}
}
private static void Fill<T>(Span<T> p, int o, int stride, int w, int h, int value)
where T : unmanaged
{
var sample = Make<T>(value);
for (var y = 0; y < h; y++)
{
p.Slice(o + (y * stride), w).Fill(sample);
}
}
}
+728
View File
@@ -0,0 +1,728 @@
namespace Febe.Core.Codecs.H264;
/// <summary>A sequence parameter set (§7.3.2.1.1), with the fields Febe uses.</summary>
internal sealed class Sps
{
/// <summary>MaxFS of level 6.2 (table A-1), in macroblocks: 8192×4320 fits.</summary>
internal const int MaxFrameMbs = 139_264;
/// <summary>MaxDpbMbs of level 6.2 (table A-1): the largest decoded picture buffer of any level, in macroblocks.</summary>
internal const int MaxDpbMbs = 696_320;
internal int ProfileIdc;
internal int LevelIdc;
internal int Id;
internal int ChromaFormatIdc = 1;
/// <summary>separate_colour_plane_flag: the three colour planes of 4:4:4 are coded as three monochrome pictures.</summary>
internal bool SeparateColourPlane;
internal int BitDepthLuma = 8;
internal int BitDepthChroma = 8;
/// <summary>qpprime_y_zero_transform_bypass_flag: macroblocks with QP′Y 0 are lossless (§8.5.15).</summary>
internal bool TransformBypass;
/// <summary>ChromaArrayType (§7.4.2.1.1): chroma_format_idc, or 0 when the colour planes are separate.</summary>
internal int ChromaArrayType => SeparateColourPlane ? 0 : ChromaFormatIdc;
/// <summary>SubWidthC (Table 6-1): 2 for 4:2:0 and 4:2:2, 1 for 4:4:4.</summary>
internal int SubWidthC => ChromaFormatIdc == 3 ? 1 : 2;
/// <summary>SubHeightC (Table 6-1): 2 for 4:2:0, 1 for 4:2:2 and 4:4:4.</summary>
internal int SubHeightC => ChromaFormatIdc == 1 ? 2 : 1;
/// <summary>QpBdOffsetY = 6 × bit_depth_luma_minus8.</summary>
internal int QpBdOffsetY => 6 * (BitDepthLuma - 8);
/// <summary>QpBdOffsetC = 6 × bit_depth_chroma_minus8.</summary>
internal int QpBdOffsetC => 6 * (BitDepthChroma - 8);
/// <summary>Scaling lists 0–5 (4×4) and 6–11 (8×8) in zig-zag order, after the fall-back rule A.</summary>
internal byte[][] ScalingLists = ScalingMatrix.Flat();
/// <summary>seq_scaling_matrix_present_flag: chooses fall-back rule B (instead of A) for the PPS lists.</summary>
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;
/// <summary>VUI colour description: matrix_coefficients (2 = unspecified) and video_full_range_flag.</summary>
internal int MatrixCoefficients = 2;
internal bool FullRange;
internal int MaxFrameNum => 1 << Log2MaxFrameNum;
/// <summary>CropUnitX of §7.4.2.1.1: 1 without chroma (or in 4:4:4), else SubWidthC.</summary>
internal int CropUnitX => ChromaArrayType == 0 ? 1 : SubWidthC;
/// <summary>CropUnitY of §7.4.2.1.1, doubled when the frames may be coded as fields.</summary>
internal int CropUnitY => (ChromaArrayType == 0 ? 1 : SubHeightC) * (FrameMbsOnly ? 1 : 2);
internal int HeightInMbs => (2 - (FrameMbsOnly ? 1 : 0)) * HeightInMapUnits;
/// <summary>The multiview extension of a subset SPS (profiles 118, 128 and 134), null otherwise.</summary>
internal MvcExtension? Mvc;
/// <summary>The scalable extension of a subset SPS (profiles 83 and 86), null otherwise.</summary>
internal SvcExtension? Svc;
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>The VUI after the colour description (§E.1.1), read only to reach what follows it in a subset SPS.</summary>
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();
}
}
}
/// <summary>hrd_parameters() (§E.1.2), skipped.</summary>
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);
}
/// <summary>The start of the VUI (§E.1.1), up to the colour description; the rest is not needed.</summary>
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);
}
}
}
}
/// <summary>
/// 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.
/// </summary>
internal sealed class MvcExtension
{
/// <summary>view_id of each view, by view order index (VOIdx).</summary>
internal int[] ViewIds = [];
/// <summary>anchor_ref_lX[VOIdx][j] by list X: the view_id of each inter-view reference of an anchor view component.</summary>
internal int[][][] AnchorRefs = [[], []];
/// <summary>non_anchor_ref_lX[VOIdx][j] by list X.</summary>
internal int[][][] NonAnchorRefs = [[], []];
/// <summary>The view order index of a view, −1 when the sequence does not have it.</summary>
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;
}
}
/// <summary>seq_parameter_set_svc_extension() (§G.7.3.2.1.4).</summary>
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;
}
}
/// <summary>A picture parameter set (§7.3.2.2).</summary>
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;
/// <summary>26 + pic_init_qs_minus26: the starting QS of SP and SI slices.</summary>
internal int PicInitQs;
/// <summary>num_slice_groups_minus1 + 1: more than one is FMO (§8.2.2).</summary>
internal int NumSliceGroups = 1;
internal int SliceGroupMapType;
/// <summary>run_length_minus1 + 1 of each slice group (map type 0).</summary>
internal int[] RunLength = [];
/// <summary>top_left and bottom_right of the rectangles of the slice groups but the last (map type 2).</summary>
internal int[] TopLeft = [];
internal int[] BottomRight = [];
internal bool SliceGroupChangeDirection;
/// <summary>slice_group_change_rate_minus1 + 1 (map types 3–5).</summary>
internal int SliceGroupChangeRate;
/// <summary>slice_group_id of each map unit (map type 6).</summary>
internal byte[] SliceGroupIds = [];
internal int ChromaQpIndexOffset;
internal int SecondChromaQpIndexOffset;
internal bool DeblockingFilterControlPresent;
internal bool ConstrainedIntraPred;
internal bool RedundantPicCntPresent;
internal bool Transform8x8Mode;
/// <summary>The scaling lists of the picture, null when the PPS has none (those of the SPS apply).</summary>
internal byte[][]? ScalingLists;
/// <param name="r">The RBSP after the NAL unit header.</param>
/// <param name="sequences">The SPSs read so far.</param>
/// <param name="subsetSequences">The subset SPSs read so far: a PPS of the enhancement layers or views may refer to one.</param>
internal static Pps Parse(RbspReader r, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Sps>? 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;
}
/// <summary>The slice group map of §7.3.2.2 (num_slice_groups_minus1 above 0), checked against the picture later.</summary>
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;
}
}
}
}
/// <summary>Scaling lists (§7.3.2.1.1.1, tables 7-2 to 7-4) and the scale factors derived from them (§8.5.9).</summary>
internal static class ScalingMatrix
{
/// <summary>Twelve flat lists (Flat_4x4_16 and Flat_8x8_16).</summary>
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;
}
/// <summary>
/// Parses <paramref name="count"/> lists and applies the fall-back rules: rule A (from the defaults) for the SPS,
/// rule B (from the lists of the SPS, <paramref name="sequenceLists"/>) for the PPS. Lists that are not
/// transmitted at all (8×8 without transform_8x8_mode) keep the SPS ones, or flat.
/// </summary>
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;
}
/// <summary>Reads one list; true when it says «use the default matrix».</summary>
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,
};
/// <summary>Fall-back rule A (<paramref name="sequenceLists"/> null) or B.</summary>
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],
};
/// <summary>
/// LevelScale4x4[m][i] for the six 4×4 lists (raster positions): <c>result[list][m * 16 + pos]</c>.
/// </summary>
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;
}
/// <summary>LevelScale8x8 for the 8×8 lists 6–11 (raster positions): <c>result[list − 6][m * 64 + pos]</c>.</summary>
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;
}
}
+257
View File
@@ -0,0 +1,257 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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 (<see cref="MbField"/>) keep their motion vectors in
/// field units and refer to fields (<see cref="RefPar"/>). 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
/// <see cref="SelectPlane"/> chooses the one the properties show.
/// </remarks>
internal sealed class Picture
{
private readonly MotionPlane[] motion;
private MotionPlane selected;
/// <param name="widthInMbs">Width in macroblocks.</param>
/// <param name="heightInMbs">Height in macroblocks.</param>
/// <param name="chromaFormat">chroma_format_idc: 0 monochrome (no chroma planes), 1 4:2:0, 2 4:2:2, 3 4:4:4.</param>
/// <param name="bytesPerSample">1 up to 8 bits, 2 above.</param>
/// <param name="colourPlanes">3 when the colour planes are coded separately, else 1.</param>
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; }
/// <summary>chroma_format_idc of the samples (3 also for separate colour planes).</summary>
internal int ChromaFormat { get; }
internal int BytesPerSample { get; }
/// <summary>Width of the Cb and Cr planes in samples (0 for monochrome).</summary>
internal int ChromaWidth { get; }
/// <summary>Height of the Cb and Cr planes in samples (0 for monochrome).</summary>
internal int ChromaHeight { get; }
internal byte[] Y { get; }
internal byte[] Cb { get; }
internal byte[] Cr { get; }
/// <summary>Motion vectors: [((list * mbs + mb) * 16 + raster 4×4 block) * 2 + component], quarter samples.</summary>
internal short[] Mv => selected.Mv;
/// <summary>Reference indices: [(list * mbs + mb) * 4 + 8×8 block]; −1 when the list is not used.</summary>
internal sbyte[] RefIdx => selected.RefIdx;
/// <summary>The frame store each 8×8 block refers to, by list (same index as <see cref="RefIdx"/>).</summary>
internal Picture?[] RefPic => selected.RefPic;
/// <summary>The field of <see cref="RefPic"/> referred to: 0 top, 1 bottom, −1 the frame (same index as <see cref="RefIdx"/>).</summary>
internal sbyte[] RefPar => selected.RefPar;
internal bool[] MbIntra => selected.MbIntra;
/// <summary>Field macroblocks: those of field pictures and the field pairs of MBAFF frames.</summary>
internal bool[] MbField => selected.MbField;
/// <summary>The plane of colour component <paramref name="k"/> (0 Y, 1 Cb, 2 Cr).</summary>
internal byte[] Plane(int k) => k == 0 ? Y : k == 1 ? Cb : Cr;
/// <summary>Shows the motion data of colour plane <paramref name="k"/> (only one exists unless the planes are separate).</summary>
internal void SelectPlane(int k) => selected = motion[Math.Min(k, motion.Length - 1)];
/// <summary>A store taken from the pool: no block refers to any picture yet.</summary>
internal void ClearReferences()
{
foreach (var m in motion)
{
Array.Clear(m.RefPic);
}
}
/// <summary>A frame inferred for a gap in frame_num: all its macroblocks count as intra frame macroblocks.</summary>
internal void MarkAsGap()
{
foreach (var m in motion)
{
Array.Fill(m.MbIntra, true);
Array.Clear(m.MbField);
}
}
internal int MbCount => WidthInMbs * HeightInMbs;
/// <summary>TopFieldOrderCnt and BottomFieldOrderCnt (§8.2.1) of the fields decoded so far.</summary>
internal int TopPoc;
internal int BottomPoc;
/// <summary>The fields decoded so far: 1 top, 2 bottom, 3 both (a frame or a field pair).</summary>
internal int Decoded;
/// <summary>Coded as two field pictures (else as a frame, progressive or MBAFF).</summary>
internal bool CodedAsFields;
internal int FrameNum;
internal int FrameNumWrap;
internal int LongTermFrameIdx;
/// <summary>Fields used for short-term reference: 1 top, 2 bottom, 3 both (the frame).</summary>
internal int ShortMask;
/// <summary>Fields used for long-term reference, as <see cref="ShortMask"/>.</summary>
internal int LongMask;
/// <summary>A frame inferred for a gap in frame_num (§8.2.5.2): never output, its samples are not meaningful.</summary>
internal bool NonExisting;
/// <summary>Some field of the frame was not reconstructed (nobody refers to it, nobody wants it): it is not handed out.</summary>
internal bool Skipped;
/// <summary>In the decoded picture buffer.</summary>
internal bool InDpb;
/// <summary>Decoding order of the frame in the stream.</summary>
internal long DecodeIndex;
/// <summary>Counts IDR pictures (and memory_management_control_operation 5): output order restarts with each.</summary>
internal int Period;
internal bool IsReference => (ShortMask | LongMask) != 0;
/// <summary>A short-term reference frame: both fields marked (§8.2.4.1, frames and complementary pairs).</summary>
internal bool ShortTerm => ShortMask == 3;
/// <summary>A long-term reference frame.</summary>
internal bool LongTerm => LongMask == 3;
internal int PicNum => FrameNumWrap;
internal int LongTermPicNum => LongTermFrameIdx;
/// <summary>PicOrderCnt of the frame (§8.2.1): the smaller of the fields decoded.</summary>
internal int Poc => Decoded switch
{
1 => TopPoc,
2 => BottomPoc,
_ => Math.Min(TopPoc, BottomPoc),
};
/// <summary>PicOrderCnt of a field (0 top, 1 bottom) or of the frame (−1).</summary>
internal int PocOf(int parity) => parity < 0 ? Poc : parity == 0 ? TopPoc : BottomPoc;
/// <summary>Whether the field (0 top, 1 bottom) or the frame (−1) is a long-term reference.</summary>
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;
/// <summary>The motion data of the macroblocks of one colour plane.</summary>
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];
}
}
/// <summary>
/// A reference picture of a list: a frame (<see cref="Parity"/> −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 (<see cref="InterView"/>), which is marked
/// "used for inter-view reference" only: neither a short-term nor a long-term reference of the current view.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="Width">Luma width after cropping.</param>
/// <param name="Height">Luma height after cropping.</param>
/// <param name="Y">Luma, <paramref name="Width"/> × <paramref name="Height"/> samples.</param>
/// <param name="Cb">Blue-difference chroma, <see cref="ChromaWidth"/> × <see cref="ChromaHeight"/> samples.</param>
/// <param name="Cr">Red-difference chroma, same size as <paramref name="Cb"/>.</param>
/// <param name="Poc">Picture order count: frames are shown by increasing value within a <paramref name="Period"/>.</param>
/// <param name="Period">Increases at each IDR picture.</param>
/// <param name="DecodeIndex">Position of the frame in decoding order (0 for the first).</param>
/// <param name="MatrixCoefficients">matrix_coefficients of the VUI (1 = BT.709, 5 and 6 = BT.601, 2 = unspecified).</param>
/// <param name="FullRange">video_full_range_flag of the VUI.</param>
/// <param name="ChromaFormat">chroma_format_idc: 0 monochrome, 1 4:2:0, 2 4:2:2, 3 4:4:4.</param>
/// <param name="BitDepthLuma">Bits of each luma sample, 8 to 14.</param>
/// <param name="BitDepthChroma">Bits of each chroma sample, 8 to 14.</param>
/// <param name="ViewId">view_id of the view of an MVC stream the frame belongs to (that of the base view, usually 0, otherwise).</param>
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)
{
/// <summary>Width of <see cref="Cb"/> and <see cref="Cr"/> in samples.</summary>
public int ChromaWidth => ChromaFormat == 3 ? Width : (Width + 1) / 2;
/// <summary>Height of <see cref="Cb"/> and <see cref="Cr"/> in samples.</summary>
public int ChromaHeight => ChromaFormat is 2 or 3 ? Height : (Height + 1) / 2;
/// <summary>Bytes of every sample of the three planes: 2 when either bit depth is above 8, else 1.</summary>
public int BytesPerSample => BitDepthLuma > 8 || BitDepthChroma > 8 ? 2 : 1;
/// <summary>Luma sample <paramref name="index"/> (row × Width + column), whatever the bit depth.</summary>
public int LumaAt(int index) => BytesPerSample == 2 ? Y[2 * index] | (Y[(2 * index) + 1] << 8) : Y[index];
/// <summary>Sample <paramref name="index"/> of a chroma plane (row × ChromaWidth + column), whatever the bit depth.</summary>
public int ChromaAt(byte[] plane, int index) => BytesPerSample == 2 ? plane[2 * index] | (plane[(2 * index) + 1] << 8) : plane[index];
/// <summary>The frame as one planar buffer (Y, then Cb, then Cr), as the official reconstruction files lay it out.</summary>
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;
}
}
+298
View File
@@ -0,0 +1,298 @@
using System.Buffers.Binary;
namespace Febe.Core.Codecs.H264;
/// <summary>A malformed or unsupported H.264 stream.</summary>
public sealed class H264Exception(string message) : Exception(message);
/// <summary>
/// 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 <see cref="BitsLeft"/>.
/// </summary>
internal sealed class RbspReader
{
private readonly byte[] data;
private readonly int length;
private readonly int stopBit;
private int position;
/// <param name="data">The payload, followed by at least sixteen bytes of padding.</param>
/// <param name="length">Bytes of payload.</param>
/// <param name="startByte">First byte to read (after the NAL unit header).</param>
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;
/// <summary>more_rbsp_data(): true while bits remain before the stop bit.</summary>
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;
/// <summary>ue(v): Exp-Golomb code (§9.1).</summary>
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));
}
/// <summary>se(v): signed Exp-Golomb code (§9.1.1).</summary>
internal int ReadSe()
{
var code = ReadUe();
var magnitude = (int)((code + 1) >> 1);
return (code & 1) != 0 ? magnitude : -magnitude;
}
/// <summary>A ue(v) value that must not exceed <paramref name="max"/>.</summary>
internal int ReadUe(int max)
{
var value = ReadUe();
if (value > (uint)max)
{
throw new H264Exception("Valore fuori dall'intervallo ammesso.");
}
return (int)value;
}
}
/// <summary>
/// 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 <see cref="Rbsp"/>[1..3]: the emulation prevention bytes are removed only after them.
/// </summary>
internal readonly record struct NalUnit(int Type, int RefIdc, byte[] Rbsp, int Length)
{
/// <summary>Bytes of the NAL unit header: 4 for the extension units, else 1.</summary>
internal int HeaderLength => HasExtensionHeader(Type) && Length >= 4 ? 4 : 1;
/// <summary>svc_extension_flag of an extension unit: 1 for SVC (Annex G), 0 for MVC (Annex H).</summary>
internal bool IsSvc => (Rbsp[1] & 0x80) != 0;
/// <summary>A reader positioned after the header.</summary>
internal RbspReader Reader() => new(Rbsp, Length, HeaderLength);
/// <summary>NAL unit types whose header has the three extension bytes.</summary>
internal static bool HasExtensionHeader(int type) => type is 14 or 20 or 21;
}
/// <summary>
/// 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.
/// </summary>
internal static class NalUnits
{
/// <summary>Bytes of zero padding a buffer keeps past the payload (see <see cref="RbspReader"/>).</summary>
internal const int Padding = 16;
/// <summary>Removes the emulation prevention bytes (0x000003 → 0x0000) of one NAL unit (§7.4.1) into a new buffer.</summary>
internal static NalUnit Parse(ReadOnlySpan<byte> nal)
{
byte[]? buffer = null;
return Unescape(nal, ref buffer);
}
/// <summary>
/// Removes the emulation prevention bytes of one NAL unit into <paramref name="buffer"/>, grown when needed; the
/// unit is valid until the buffer is used again.
/// </summary>
internal static NalUnit Unescape(ReadOnlySpan<byte> 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<byte> 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);
}
/// <summary>
/// The next NAL unit of an Annex B byte stream (start codes 0x000001 or 0x00000001) from <paramref name="position"/>,
/// which moves past it; false when there is none left.
/// </summary>
internal static bool NextAnnexB(ReadOnlySpan<byte> stream, ref int position, out Range unit)
{
ReadOnlySpan<byte> 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;
}
/// <summary>
/// The next NAL unit of a sample whose units are each prefixed by a big-endian length, from
/// <paramref name="position"/>; false at the end or at a damaged length (what was read stands).
/// </summary>
internal static bool NextLengthPrefixed(ReadOnlySpan<byte> 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;
}
/// <summary>The NAL units of an Annex B byte stream, each in its own buffer (for tools and tests).</summary>
internal static List<NalUnit> SplitAnnexB(ReadOnlySpan<byte> stream)
{
var units = new List<NalUnit>();
var position = 0;
while (NextAnnexB(stream, ref position, out var unit))
{
units.Add(Parse(stream[unit]));
}
return units;
}
/// <summary>The NAL units of a length-prefixed sample, each in its own buffer (for tools and tests).</summary>
internal static List<NalUnit> SplitLengthPrefixed(ReadOnlySpan<byte> sample, int lengthSize)
{
var units = new List<NalUnit>();
var position = 0;
while (NextLengthPrefixed(sample, lengthSize, ref position, out var unit))
{
units.Add(Parse(sample[unit]));
}
return units;
}
}
+43
View File
@@ -0,0 +1,43 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// The two sample types of the decoder: <see cref="byte"/> for 8-bit video, <see cref="ushort"/> 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.
/// </summary>
internal static class Samples
{
/// <summary>The value of a sample.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int Get<T>(T sample)
where T : unmanaged =>
typeof(T) == typeof(byte) ? Unsafe.As<T, byte>(ref sample) : Unsafe.As<T, ushort>(ref sample);
/// <summary>A sample of value <paramref name="value"/>, already within the range of the bit depth.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static T Make<T>(int value)
where T : unmanaged
{
if (typeof(T) == typeof(byte))
{
var b = (byte)value;
return Unsafe.As<byte, T>(ref b);
}
var u = (ushort)value;
return Unsafe.As<ushort, T>(ref u);
}
/// <summary>A plane stored as bytes, seen as samples of type <typeparamref name="T"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static Span<T> Plane<T>(byte[] plane)
where T : unmanaged => MemoryMarshal.Cast<byte, T>(plane.AsSpan());
/// <summary>Clip1 of §5.7: <paramref name="value"/> within 0..<paramref name="max"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int Clip(int value, int max) => value < 0 ? 0 : value > max ? max : value;
}
+687
View File
@@ -0,0 +1,687 @@
namespace Febe.Core.Codecs.H264;
/// <summary>Slice types (slice_type modulo 5).</summary>
internal enum SliceType
{
P = 0,
B = 1,
I = 2,
SP = 3,
SI = 4,
}
/// <summary>nal_unit_header_svc_extension() (§G.7.3.1.1): where the NAL unit sits among the layers of an SVC stream.</summary>
internal readonly record struct SvcNalHeader(
bool Idr, int PriorityId, bool NoInterLayerPred, int DependencyId, int QualityId, int TemporalId, bool UseRefBasePic,
bool Discardable, bool Output)
{
/// <summary>DQId = (dependency_id &lt;&lt; 4) + quality_id.</summary>
internal int DqId => (DependencyId << 4) + QualityId;
/// <summary>The extension header of a NAL unit 14 or 20 with svc_extension_flag 1.</summary>
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);
}
}
/// <summary>The fields of slice_header_in_scalable_extension() that a slice of AVC does not have.</summary>
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;
}
/// <summary>A slice header (§7.3.3), with the reference list modifications, weights and marking it carries.</summary>
internal sealed class SliceHeader
{
internal int FirstMb;
internal SliceType Type;
internal int PpsId;
/// <summary>colour_plane_id: the colour plane (0 Y, 1 Cb, 2 Cr) of a slice when the planes are coded separately.</summary>
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;
/// <summary>redundant_pic_cnt: 0 for the primary coded picture, above 0 for a redundant one.</summary>
internal int RedundantPicCnt;
internal bool DirectSpatialMvPred;
internal int NumRefIdxActiveL0;
internal int NumRefIdxActiveL1;
/// <summary>ref_pic_list_modification: (modification_of_pic_nums_idc, value) per list.</summary>
internal List<(int Idc, int Value)>[] Modifications = [[], []];
internal int LumaLog2WeightDenom;
internal int ChromaLog2WeightDenom;
/// <summary>Explicit weights [list][refIdx * 3 + component] and offsets; null when there is no pred_weight_table.</summary>
internal int[][]? Weights;
internal int[][]? Offsets;
internal bool NoOutputOfPriorPics;
internal bool LongTermReference;
internal bool AdaptiveMarking;
/// <summary>memory_management_control_operation entries: (operation, value 1, value 2).</summary>
internal List<(int Op, int A, int B)> Mmco = [];
internal int CabacInitIdc;
internal int QpDelta;
internal int DisableDeblocking;
internal int AlphaOffset;
internal int BetaOffset;
/// <summary>sp_for_switch_flag of an SP slice: its P macroblocks decode as those of a switching picture (§8.6.1).</summary>
internal bool SpForSwitch;
/// <summary>QS_Y of an SP or SI slice: pic_init_qs_minus26 + 26 + slice_qs_delta.</summary>
internal int Qs;
/// <summary>slice_group_change_cycle (map types 3–5 of FMO).</summary>
internal int SliceGroupChangeCycle;
/// <summary>The scalable part of slice_header_in_scalable_extension() (§G.7.3.3.4), for a slice of NAL unit 20 of SVC.</summary>
internal SvcSliceFields? Svc;
internal bool IsIntra => Type is SliceType.I or SliceType.SI;
/// <summary>A P or SP slice: both are parsed and predicted alike (an SP slice differs in the reconstruction).</summary>
internal bool IsP => Type is SliceType.P or SliceType.SP;
/// <summary>An SP or SI slice: switching pictures (§8.6).</summary>
internal bool IsSwitching => Type is SliceType.SP or SliceType.SI;
internal bool IsB => Type == SliceType.B;
/// <summary>0 frame, 1 top field, 2 bottom field.</summary>
internal int Structure => !FieldPic ? 0 : BottomField ? 2 : 1;
/// <summary>
/// slice_header() of a NAL unit 1, 5 or (<paramref name="multiview"/>) 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
/// <paramref name="nal"/> stands for the view component, with type 5 when it is IDR.
/// </summary>
internal static SliceHeader Parse(RbspReader r, NalUnit nal, IReadOnlyDictionary<int, Sps> sequences, IReadOnlyDictionary<int, Pps> 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;
}
/// <summary>ref_pic_list_modification() (§7.3.3.1), or ref_pic_list_mvc_modification() (§H.7.3.3.1.1).</summary>
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.");
}
/// <summary>
/// slice_header_in_scalable_extension() (§G.7.3.3.4) of a slice of NAL unit 20 with the SVC header
/// <paramref name="ext"/>; <paramref name="baseHeader"/> 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).
/// </summary>
internal static SliceHeader ParseScalable(RbspReader r, NalUnit nal, SvcNalHeader ext, IReadOnlyDictionary<int, Sps> subsetSequences, IReadOnlyDictionary<int, Pps> 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;
}
/// <summary>dec_ref_pic_marking() (§7.3.3.3) of an IDR picture or not.</summary>
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));
}
}
/// <summary>dec_ref_base_pic_marking() (§G.7.3.3.5), skipped: base representations are not kept.</summary>
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] ??= [];
}
}
@@ -0,0 +1,161 @@
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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.
/// </summary>
internal static class SwitchingTransform
{
/// <summary>Quantisation factors (the inverse of normAdjust4x4) by QS % 6 and class of position (0 even-even, 1 odd-odd, 2 others).</summary>
private static readonly int[,] Quant =
{
{ 13107, 5243, 8066 }, { 11916, 4660, 7490 }, { 10082, 4194, 6554 }, { 9362, 3647, 5825 }, { 8192, 3355, 5243 }, { 7282, 2893, 4559 },
};
/// <summary>A<sub>ij</sub> of §8.6.1 by class of position.</summary>
private static readonly int[] Norm = [16, 25, 20];
/// <summary>The class of each raster position of a 4×4 block (0 even row and column, 1 both odd, 2 the others).</summary>
private static readonly byte[] Class = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1];
/// <summary>
/// A luma 4×4 block: the prediction at <paramref name="o"/> is replaced by the reconstruction from it and the levels
/// (raster order, not scaled). <paramref name="levelInQs"/> 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).
/// </summary>
internal static void Luma4x4(byte[] plane, int o, int stride, ReadOnlySpan<int> levels, int qp, int qs, bool levelInQs)
{
Span<int> 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);
}
/// <summary>
/// One chroma component (four 4×4 blocks): <paramref name="ac"/> holds the AC levels of the four blocks (block × 16
/// + raster position; position 0 is ignored), <paramref name="dc"/> the four DC levels in the order they are parsed.
/// </summary>
internal static void Chroma(byte[] plane, int o, int stride, ReadOnlySpan<int> ac, ReadOnlySpan<int> dc, int qpc, int qsc, bool levelInQs)
{
Span<int> 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<int> 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);
}
}
/// <summary>
/// The level in QS of one coefficient from the transformed prediction <paramref name="predicted"/> 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.
/// </summary>
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);
/// <summary>The forward 4×4 core transform of the samples at <paramref name="o"/> (§8.6.1, c<sup>p</sup>), raster order.</summary>
private static void Forward(byte[] plane, int o, int stride, Span<int> 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);
}
}
/// <summary>The inverse 4×4 transform of scaled coefficients (§8.5.12), stored at <paramref name="o"/> in place of the prediction.</summary>
private static void Store4x4(Span<int> 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);
}
+178
View File
@@ -0,0 +1,178 @@
using static Febe.Core.Codecs.H264.Samples;
namespace Febe.Core.Codecs.H264;
/// <summary>
/// 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 (<c>max</c> is 2^BitDepth − 1).
/// </summary>
internal static class Transform
{
/// <summary>Inverse 4×4 transform of scaled coefficients (raster order), added to the 4×4 block at <paramref name="o"/>.</summary>
internal static void Add4x4<T>(Span<int> d, Span<T> 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);
}
}
/// <summary>Inverse 8×8 transform (§8.5.13), added to the 8×8 block at <paramref name="o"/>.</summary>
internal static void Add8x8<T>(Span<int> d, Span<T> plane, int o, int stride, int max)
where T : unmanaged
{
Span<int> tmp = stackalloc int[8];
for (var i = 0; i < 8; i++)
{
var row = d.Slice(i * 8, 8);
Butterfly8(row, row);
}
Span<int> 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);
}
}
}
/// <summary>
/// The residual of a lossless block (TransformBypassModeFlag, §8.5.15): <paramref name="r"/> holds the
/// <paramref name="w"/> × <paramref name="h"/> coefficients in raster order, which are the residual itself; under an
/// intra prediction that is horizontal (<paramref name="dpcm"/> 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.
/// </summary>
internal static void AddBypass<T>(Span<int> r, int w, int h, int dpcm, Span<T> 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<T>(Clip(Get(row[x]) + r[(y * w) + x], max));
}
}
}
private static void Butterfly8(ReadOnlySpan<int> d, Span<int> 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;
}
/// <summary>Inverse 4×4 Hadamard transform of the Intra_16x16 DC coefficients (§8.5.10), in place, raster order.</summary>
internal static void Hadamard4x4(Span<int> 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;
}
}
/// <summary>
/// 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 <see cref="Hadamard4x4"/> and B = [1 1; 1 −1]; in place.
/// </summary>
internal static void ChromaDc422(Span<int> 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<T>(Span<T> plane, int index, int residual, int max)
where T : unmanaged
{
plane[index] = Make<T>(Clip(Get(plane[index]) + ((residual + 32) >> 6), max));
}
}
+4 -2
View File
@@ -18,7 +18,8 @@ internal sealed record ContentFacts(
/// <summary>
/// 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, <c>mvhd</c> for MP4/MOV, ffprobe as an extra for the rest).
/// photos, date from the metadata (EXIF for photos, <c>mvhd</c> for MP4/MOV, the in-house container readers for WebM, Matroska, AVI,
/// WMV/ASF, FLV and MPEG program streams).
/// </summary>
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)
{
+1 -1
View File
@@ -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);
}
+7 -3
View File
@@ -33,10 +33,14 @@ public sealed record ImportEnvironment
/// </summary>
public PerceptualHashIndex? HashIndex { get; init; }
/// <summary>ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
public VideoFrameExtractor? Frames { get; init; }
/// <summary>The in-house frame decoder, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
public VideoFrameDecoder? Frames { get; init; }
/// <summary>ffprobe, an optional extra for videos the hand-written reader does not cover.</summary>
/// <summary>
/// Reader of the metadata of videos the MP4 header reader does not cover (WebM/Matroska, AVI, WMV/ASF, FLV and MPEG
/// program streams: see <see cref="IVideoMetadataProbe"/>). Null: the in-house <see cref="ContainerVideoMetadataProbe"/>
/// on the clock of this environment.
/// </summary>
public IVideoMetadataProbe? VideoProbe { get; init; }
/// <summary>«Imposta la data del file a quella di pubblicazione» (library setting).</summary>
+14 -5
View File
@@ -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
+5 -3
View File
@@ -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
/// <summary>
/// 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.
/// </summary>
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)
+29 -164
View File
@@ -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;
/// <summary>Metadata of a video read by an external tool.</summary>
/// <summary>Metadata of a video read from its container.</summary>
public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
/// <summary>
/// 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»).
/// </summary>
/// <summary>Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI, WMV/ASF, FLV, MPEG program stream).</summary>
public interface IVideoMetadataProbe
{
/// <summary>Metadata of a video file, read-only; null when the tool cannot read it.</summary>
/// <summary>Metadata of a video file, read-only; null when it cannot be read.</summary>
Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default);
}
/// <summary>
/// <see cref="IVideoMetadataProbe"/> with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is
/// parsed with <see cref="JsonDocument"/>; error output is never logged (it may contain paths).
/// <see cref="IVideoMetadataProbe"/> written in house on the container readers of <see cref="ContainerReader"/>: no
/// external program. Only the headers are read (no sample tables), so it is quick also on long videos.
/// </summary>
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;
/// <summary>Full path of ffprobe.</summary>
public string Executable { get; }
/// <summary>Finds ffprobe on the PATH (or at <paramref name="explicitPath"/>); null when it is not available.</summary>
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();
/// <summary>
/// The start of ffprobe for <paramref name="path"/>: its arguments, and the environment of Febe without
/// <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, 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.
/// </summary>
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<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
public Task<VideoMetadata?> 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);
}
/// <summary>The metadata of <paramref name="path"/>; null when the file is unreadable or of another format.</summary>
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;
}
/// <summary>Parses the JSON printed by ffprobe.</summary>
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;
}
}
+3 -3
View File
@@ -14,7 +14,7 @@ public sealed record RebuildOptions
/// </summary>
public IReadOnlyList<string> ExtraAccountFolders { get; init; } = [];
/// <summary>Create missing thumbnails (photos; videos with ffmpeg when available).</summary>
/// <summary>Create missing thumbnails (photos; H.264 videos with the in-house frame decoder).</summary>
public bool CreateThumbnails { get; init; } = true;
/// <summary>Files hashed in parallel.</summary>
@@ -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);
+1 -1
View File
@@ -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
/// <c>Dati/miniature</c>, 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 (<see cref="VideoFrameExtractor"/>); without either, the interface shows the neutral tile
/// frame (<see cref="VideoFrameDecoder"/>); without either, the interface shows the neutral tile
/// (<see cref="NeutralVideoTile"/>).
/// </summary>
public sealed class ThumbnailStore
+664
View File
@@ -0,0 +1,664 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264;
namespace Febe.Core.Library;
/// <summary>A decoded video frame in 8-bit RGB, rows top to bottom, three bytes per pixel (red, green, blue).</summary>
public sealed record VideoImage(int Width, int Height, byte[] Rgb)
{
/// <summary>The image as an uncompressed 24-bit BMP file (Windows bitmap, rows bottom to top).</summary>
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;
}
}
/// <summary>
/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole
/// video. <see cref="Difference"/> 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.
/// </summary>
public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference);
/// <summary>
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
/// the container readers of <see cref="ContainerReader"/> and the H.264 decoder written in house
/// (<see cref="H264Decoder"/>). Videos in other codecs (HEVC, VP9, AV1, ...) give no frame: the interface shows the
/// neutral tile.
/// </summary>
public sealed class VideoFrameDecoder
{
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
public const double StillThreshold = 3.0;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
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;
/// <summary>A decoder with the default budget and run length.</summary>
public VideoFrameDecoder()
: this(DefaultBudget, DefaultMaxRun)
{
}
/// <param name="budget">The longest one call may take (zero: no time at all).</param>
/// <param name="maxRun">
/// 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.
/// </param>
internal VideoFrameDecoder(TimeSpan budget, int maxRun)
{
this.budget = budget;
this.maxRun = maxRun;
}
/// <summary>The shared instance: it keeps no state between calls.</summary>
public static VideoFrameDecoder Instance { get; } = new();
/// <summary>
/// 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.
/// </summary>
public Task<byte[]?> ExtractImageAsync(string videoPath, CancellationToken ct = default) =>
ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 2 * ThumbnailStore.LongSide, ct);
/// <summary>
/// A frame of the video at <paramref name="at"/> (the first frame when the video is shorter), as a BMP image whose
/// long side is at most <paramref name="maxLongSide"/> pixels (0: full size); null when it cannot be decoded.
/// </summary>
public async Task<byte[]?> ExtractImageAsync(string videoPath, TimeSpan at, int maxLongSide, CancellationToken ct = default)
{
var image = await DecodeFrameAsync(videoPath, at, maxLongSide, ct).ConfigureAwait(false);
return image?.ToBmp();
}
/// <summary>A frame of the video at <paramref name="at"/> in RGB; null when it cannot be decoded.</summary>
public Task<VideoImage?> 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);
}
/// <summary>
/// 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).
/// </summary>
public Task<VideoStillness?> AnalyseStillnessAsync(string videoPath, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct);
}
/// <summary>Runs <paramref name="work"/> for at most the budget: past it the result is null, as for an unreadable file.</summary>
private T? WithinBudget<T>(Func<CancellationToken, T?> 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<int>();
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;
/// <summary>The H.264 video track of a container with its samples; null for other codecs or without video.</summary>
private static VideoTrack? Open(Stream stream)
{
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
var container = ContainerReader.Read(stream, AnyDate, samples: true);
return container?.Video is { Codec: VideoCodec.H264, Samples.Count: > 0 } video
&& (video.AnnexB || video.AvcConfiguration is not null)
? video
: null;
}
/// <summary>The sample shown at <paramref name="at"/> from the start; the first shown one when the video is shorter.</summary>
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<MediaSample> 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<int>();
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];
}
/// <summary>
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
/// </summary>
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
{
private readonly Dictionary<int, H264Frame> found = [];
private readonly HashSet<int> wanted = [];
private readonly int[] keys = KeyIndices(video);
private readonly Dictionary<int, H264AccessPoint> accessPoints = [];
private byte[] buffer = new byte[64 * 1024];
/// <summary>The sample being decoded: the picture it finishes is that sample's frame.</summary>
private int current;
/// <summary>
/// The sample where decoding for <paramref name="index"/> starts. A container without an index (an AVI cut short,
/// or OpenDML past its first gigabyte) flags every sample as key, and starting from a P or B frame there would give
/// a corrupt picture, or none: so the samples flagged as key are looked at, from the nearest one back. The nearest
/// IDR picture is taken when it is within the run limit (the frame comes out exact); otherwise the nearest
/// picture of I slices (close, though pictures after it may refer to earlier ones); otherwise the IDR picture
/// further back, or the first sample.
/// </summary>
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<int, H264Frame> 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;
}
}
/// <summary>
/// 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).
/// </summary>
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<ushort> y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(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<ushort> cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cb) : default;
ReadOnlySpan<ushort> cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cr) : default;
var chromaShift = frame.BitDepthChroma - 8;
var middle = 1 << (frame.BitDepthChroma - 1);
var chromaCounts = new int[GridSize * GridSize];
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;
}
/// <summary>
/// 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 <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide)
{
var (kr, kb) = frame.MatrixCoefficients switch
{
1 => (0.2126, 0.0722),
4 => (0.30, 0.11),
5 or 6 => (0.299, 0.114),
7 => (0.212, 0.087),
9 or 10 => (0.2627, 0.0593),
_ => frame.Height >= 720 ? (0.2126, 0.0722) : (0.299, 0.114),
};
var kg = 1 - kr - kb;
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<ushort> y16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Y) : default;
ReadOnlySpan<ushort> cb16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cb) : default;
ReadOnlySpan<ushort> cr16 = wide ? System.Runtime.InteropServices.MemoryMarshal.Cast<byte, ushort>(frame.Cr) : default;
var area = factor * factor;
for (var oy = 0; oy < height; oy++)
{
for (var ox = 0; ox < width; ox++)
{
int r = 0, g = 0, b = 0;
for (var dy = 0; dy < factor; dy++)
{
var y = (oy * factor) + dy;
var lumaRow = y * frame.Width;
var chromaRow = (y >> shiftY) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var ci = chromaRow + (x >> shiftX);
int l, u, v;
if (wide)
{
l = (y16[lumaRow + x] - yOffset) * cy;
u = cb16[ci] - middle;
v = cr16[ci] - middle;
}
else
{
l = (frame.Y[lumaRow + x] - yOffset) * cy;
u = frame.Cb[ci] - middle;
v = frame.Cr[ci] - middle;
}
r += Clip((l + (crR * v) + Half) >> Shift);
g += Clip((l - (cbG * u) - (crG * v) + Half) >> Shift);
b += Clip((l + (cbB * u) + Half) >> Shift);
}
}
var o = ((oy * width) + ox) * 3;
rgb[o] = (byte)(r / area);
rgb[o + 1] = (byte)(g / area);
rgb[o + 2] = (byte)(b / area);
}
}
return Rotate(new VideoImage(width, height, rgb), rotation);
}
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);
}
}
@@ -1,131 +0,0 @@
using System.Diagnostics;
using Febe.Core.Security;
namespace Febe.Core.Library;
/// <summary>
/// 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.
/// </summary>
public sealed class VideoFrameExtractor
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
private VideoFrameExtractor(string executable) => Executable = executable;
/// <summary>Full path of ffmpeg.</summary>
public string Executable { get; }
/// <summary>Finds ffmpeg on the PATH (or at <paramref name="explicitPath"/>); null when it is not available.</summary>
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;
}
/// <summary>
/// A JPEG frame of the video, taken one second in (or the first frame of shorter videos); null when ffmpeg cannot
/// read the file.
/// </summary>
public async Task<byte[]?> 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;
}
/// <summary>
/// The start of ffmpeg for one frame of <paramref name="videoPath"/> at <paramref name="seek"/> seconds: its
/// arguments, and the environment of Febe without <c>FEBE_PASSWORD</c> and <c>FEBE_CHIAVE_SESSIONE</c>, removed last
/// (spec §13.2).
/// </summary>
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<byte[]?> 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;
}
}
@@ -3,7 +3,7 @@ using System.Diagnostics;
namespace Febe.Core.Security;
/// <summary>
/// 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.
/// </summary>
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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`.
+1 -1
View File
@@ -200,7 +200,7 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
var progress = new SyncProgress<RebuildProgress>(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"));
+1
View File
@@ -19,6 +19,7 @@
</ItemGroup>
<ItemGroup>
<None Include="campioni\**\*" CopyToOutputDirectory="PreserveNewest" />
<None Include="Media\H264\Conformita\**\*" CopyToOutputDirectory="PreserveNewest" />
<!-- Immagini di riferimento dei codec di casa (Imaging/Riferimenti/LEGGIMI.md). -->
<None Include="Imaging\Riferimenti\**\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
+17 -15
View File
@@ -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.");
}
+19 -33
View File
@@ -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]
@@ -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();
}
/// <summary>Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing.</summary>
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;
}
/// <summary>
/// A real H.264 MP4 (a conformance stream, 176×144, muxed by the in-house writer) with the given creation time.
/// </summary>
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);
}
/// <summary>A real H.264 WebM-style Matroska file (the same stream) with the given creation time.</summary>
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);
}
/// <summary>Width and height of <see cref="RealMp4"/> and <see cref="RealWebm"/>.</summary>
public static (int Width, int Height) RealVideoSize => (176, 144);
/// <summary>The PNG encoding of a generated scene.</summary>
public static byte[] Png(int scene, int width = 400, int height = 300)
@@ -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) =>
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<byte>();
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<byte>();
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<string> DecodeAll(byte[] file, VideoTrack video)
{
using var stream = new MemoryStream(file);
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
var lengthSize = video.AnnexB ? 0 : decoder.ConfigureAvcC(video.AvcConfiguration);
var buffer = Array.Empty<byte>();
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;
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
[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<byte>)[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<string> DecodeAll(byte[] file, VideoTrack video)
{
using var stream = new MemoryStream(file);
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
var lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
var buffer = Array.Empty<byte>();
foreach (var sample in video.Samples)
{
decoder.DecodeSample(ContainerReader.ReadSample(stream, sample, ref buffer), lengthSize);
}
decoder.Flush();
return ElementaryStream.Md5InOutputOrder(frames);
}
}
@@ -0,0 +1,570 @@
using System.Buffers.Binary;
using System.Text;
namespace Febe.Tests.Codecs.Containers;
/// <summary>What a test ASF file holds.</summary>
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; }
/// <summary>The video stream properties sit in an extended stream properties object of the header extension.</summary>
public bool VideoInExtension { get; init; }
}
/// <summary>What a test MPEG program stream holds.</summary>
internal sealed record PsOptions
{
/// <summary>«mpeg2», «mpeg1» or «h264» (then <see cref="Stream"/> gives the pictures).</summary>
public string Video { get; init; } = "mpeg2";
public int Width { get; init; } = 720;
public int Height { get; init; } = 576;
public int Frames { get; init; } = 50;
/// <summary>Bytes of slice data per picture: large values make a file longer than the windows the reader looks at.</summary>
public int PictureBytes { get; init; } = 1500;
public bool Mpeg1System { get; init; }
public bool StreamMap { get; init; }
/// <summary>«mp2», «ac3» or null.</summary>
public string? Audio { get; init; } = "mp2";
public long FirstPts { get; init; } = 90_000;
public ElementaryStream? Stream { get; init; }
public int Seed { get; init; } = 7301;
}
/// <summary>
/// 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.
/// </summary>
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 -----
/// <summary>An ASF file: header object with the objects of <paramref name="o"/>, then a data object of filler packets.</summary>
public static byte[] Asf(AsfOptions o)
{
var random = new Random(4101);
var children = new List<byte[]>();
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<byte[]> { 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<byte[]>();
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<byte>();
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 -----
/// <summary>
/// An FLV file of an H.264 stream at 30 frames per second: onMetaData (unless <paramref name="metadata"/> is false),
/// the AVC sequence header, one tag per access unit with its composition time and, with <paramref name="audio"/>, an
/// AAC sequence header and AAC tags between the frames.
/// </summary>
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<byte[]>
{
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();
}
/// <summary>An FLV with one script tag of the given AMF0 body and one H.263 video tag.</summary>
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();
}
/// <summary>An FLV of Sorenson H.263 tags whose picture headers give the size (code 0, 1 or a fixed size code).</summary>
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();
}
/// <summary>An FLV whose video tags use the enhanced header with <paramref name="fourCc"/>, or only audio tags.</summary>
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();
}
/// <summary>
/// An FLV whose header says audio and no video, opened by an onMetaData tag of about <paramref name="metadataBytes"/>
/// bytes (a keyframe index), then MP3 tags every 26 ms for <paramref name="seconds"/>, and from
/// <paramref name="videoFromMs"/> on (when given) H.263 video tags among them every 40 ms.
/// </summary>
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<double> 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 -----
/// <summary>
/// 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 <see cref="PsOptions.Stream"/>.
/// </summary>
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<byte>();
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]);
}
/// <summary>A 33-bit time in five bytes with a four-bit prefix and three marker bits.</summary>
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;
}
/// <summary>Writes bits from the most significant one, as the codec headers want them.</summary>
private sealed class BitWriterForTests
{
private readonly List<byte> 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];
}
}
@@ -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;
/// <summary>
/// Truncated and garbled videos: the container readers, the metadata probe and the frame decoder must survive every one
/// of them with a <see cref="ContainerException"/> (or <see cref="EndOfStreamException"/>), a null result or a frame,
/// and must never allocate much more than the file holds, whatever its damaged headers claim.
/// </summary>
[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<ContainerException>(() => 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<byte> { 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<byte> 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<ContainerException>(() => 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<byte>();
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),
};
}
/// <summary>A copy with a few bytes changed: mostly in the first kilobytes, where the headers are.</summary>
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<byte> pattern)
{
var index = data.AsSpan().IndexOf(pattern);
Assert.IsGreaterThanOrEqualTo(0, index);
return index;
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class ElementaryStream
{
private ElementaryStream(string name, List<List<byte[]>> 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; }
/// <summary>The NAL units (without start codes) of each access unit, in decoding order.</summary>
public List<List<byte[]>> Units { get; }
/// <summary>Position of each access unit in presentation order.</summary>
public int[] Rank { get; }
/// <summary>True for access units with an IDR picture.</summary>
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"));
/// <summary>The official per-frame MD5 values, in output order.</summary>
public static List<string> 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();
/// <summary>MD5 values of frames in output order.</summary>
public static List<string> Md5InOutputOrder(IEnumerable<H264Frame> 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<byte[]>>();
List<byte[]>? 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<H264Frame>();
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<byte> { 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);
}
/// <summary>The same stream with only its first access unit, repeated: a video of a still picture.</summary>
public ElementaryStream FirstPictureRepeated(int times)
{
var units = Enumerable.Repeat(Units[0], times).ToList();
return new ElementaryStream(Name + "-fermo", units, [.. Enumerable.Range(0, times)], [.. Enumerable.Repeat(true, times)], AvcC, Width, Height);
}
/// <summary>
/// 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.
/// </summary>
public ElementaryStream WithParameterSetsEverywhere()
{
var sets = Units[0].Where(n => (n[0] & 0x1F) is 7 or 8).ToList();
var units = Units.Select(u => u.Any(n => (n[0] & 0x1F) == 7) ? u : [.. sets, .. u]).ToList();
return new ElementaryStream(Name + "-parametri", units, Rank, Key, AvcC, Width, Height);
}
/// <summary>An access unit with 4-byte length prefixes (MP4, Matroska).</summary>
public byte[] LengthPrefixed(int index)
{
using var output = new MemoryStream();
Span<byte> length = stackalloc byte[4];
foreach (var nal in Units[index])
{
BinaryPrimitives.WriteInt32BigEndian(length, nal.Length);
output.Write(length);
output.Write(nal);
}
return output.ToArray();
}
/// <summary>An access unit with start codes (AVI).</summary>
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<byte[]> 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<byte[]>();
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;
}
}
/// <summary>Builders of test videos in the three containers, from an <see cref="ElementaryStream"/>.</summary>
internal static class TestVideos
{
/// <summary>Ticks per frame at timescale 30000: 30 frames per second.</summary>
public const int FrameTicks = 1000;
public const int Timescale = 30000;
/// <summary>An MP4 written with <see cref="Mp4Writer"/>; with <paramref name="audio"/>, also an AAC track of silence-shaped samples.</summary>
public static byte[] Mp4(ElementaryStream es, DateTimeOffset? created = null, int rotation = 0, bool audio = false)
{
var samples = new List<Mp4OutputSample>();
var data = new List<byte[]>();
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<Mp4OutputTrack>
{
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();
}
/// <summary>
/// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).
/// With <paramref name="defaults"/> the sample durations come from <c>trex</c>, each fragment has two runs that
/// both give their <c>data_offset</c> from the start of the moof, and an <c>mehd</c> box tells the duration.
/// </summary>
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<byte>();
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<byte[]> { 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();
}
/// <summary>
/// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of
/// <paramref name="timecodeScale"/> nanoseconds (milliseconds by default).
/// </summary>
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<byte[]> { 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<byte[]> { 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];
}
/// <summary>
/// An AVI file with one H.264 stream in Annex B form, an idx1 index (unless <paramref name="index"/> is false, as in a
/// recording cut short) and, when given, an IDIT date. The stream header says <paramref name="rate"/> /
/// <paramref name="scale"/> frames per second and <paramref name="length"/> frames (default: the stream's).
/// </summary>
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<byte>();
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<byte>();
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<byte>();
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<byte[]> { 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<byte[]>();
var idx = new List<byte>();
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<byte[]> { 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;
}
}
@@ -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;
/// <summary>The frame decoder that replaces ffmpeg for thumbnails, and the recognition of videos of a still picture.</summary>
[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<OperationCanceledException>(() => 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")));
}
/// <summary>The frame decoded at position <paramref name="index"/>, straight from the stream.</summary>
private static H264Frame DecodedFrame(ElementaryStream es, int index) => ShownFrame(es, es.Rank[index]);
/// <summary>The frame shown at position <paramref name="rank"/>, decoded straight from the stream.</summary>
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name));
var index = Array.IndexOf(es.Rank, rank);
return frames.Single(f => f.DecodeIndex == index);
}
}
+92
View File
@@ -0,0 +1,92 @@
namespace Febe.Tests.Codecs.H264;
/// <summary>The bits of an RBSP written one by one (§7.2): fixed-length fields, Exp-Golomb codes, bits copied from another RBSP.</summary>
internal sealed class BitWriter
{
private readonly List<bool> bits = [];
/// <summary>Bits written so far.</summary>
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));
/// <summary>Zero bits up to the next byte.</summary>
public void Align()
{
while (bits.Count % 8 != 0)
{
bits.Add(false);
}
}
/// <summary>One bits up to the next byte (cabac_alignment_one_bit).</summary>
public void AlignWithOnes()
{
while (bits.Count % 8 != 0)
{
bits.Add(true);
}
}
/// <summary>Bits <paramref name="from"/> (included) to <paramref name="to"/> (excluded) of <paramref name="data"/>, most significant first.</summary>
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);
}
}
/// <summary>rbsp_trailing_bits(): the stop bit and zeros up to the byte.</summary>
public void Trailing()
{
bits.Add(true);
Align();
}
/// <summary>The bytes, padded with zeros to the byte, with emulation prevention (§7.4.1).</summary>
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<byte>(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];
}
}
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more