WIP: contenitori, sonda dei metadati, fotogrammi e scrittore MP4 in casa; via ffmpeg e ffprobe (#58)

Lettori ISO BMFF (anche frammentato), Matroska/WebM e AVI; ContainerVideoMetadataProbe è la sonda predefinita; VideoFrameDecoder (H.264 in casa, BMP ruotato, riconoscimento dei video fermi) sostituisce VideoFrameExtractor; Mp4Writer con moov in testa. Tolti ffmpeg e ffprobe da Dockerfile, CI, script e prove. WIP perché la corsa completa di tests/Febe.Tests non era finita al momento del commit e l'ultima correzione (data qualsiasi nella lettura dei campioni) non è stata ricompilata né riprovata: la compilazione durante la corsa fallisce per DLL bloccate dalle prove in esecuzione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 12:32:33 +01:00
1 parent 697de97ec3
commit 6ffcb1bb18
39 files changed
+4235 -469

No files matched your search

+1 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché # 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 # 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 # 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). # (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 \ $sudo apt-get install -y -qq --no-install-recommends \
chromium chromium-l10n \ chromium chromium-l10n \
xvfb \ xvfb \
ffmpeg \
nsis zip \ nsis zip \
locales tzdata libicu76 ca-certificates \ locales tzdata libicu76 ca-certificates \
fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \
@@ -27,8 +26,6 @@ $sudo locale-gen > /dev/null
echo "== Strumenti delle prove" echo "== Strumenti delle prove"
chromium --version chromium --version
command -v Xvfb command -v Xvfb
ffmpeg -version | head -n 1 || true
ffprobe -version | head -n 1 || true
echo "makensis $(makensis -VERSION)" echo "makensis $(makensis -VERSION)"
echo "node $(node --version)" echo "node $(node --version)"
locale -a | grep -i '^it_IT\.utf8$' locale -a | grep -i '^it_IT\.utf8$'
+2 -2
View File
@@ -6,7 +6,7 @@
# .gitea/scripts/riepilogo-prove.sh <cartella dei .trx> [saltate ammesse] # .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 # 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.
set -euo pipefail set -euo pipefail
cartella="${1:?Indica la cartella con i file .trx.}" cartella="${1:?Indica la cartella con i file .trx.}"
@@ -96,7 +96,7 @@ if (( fallite_totali > 0 )); then
esito=1 esito=1
fi fi
if (( saltate_totali > ammesse )); then 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 esito=1
fi fi
+2 -2
View File
@@ -4,7 +4,7 @@
# soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); # 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 # 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 # (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.
# Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di # 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; # questa esecuzione, scritto nel registro per rifare un errore;
# installatore Febe-Setup-<versione>-ci.<numero>.exe e lo zip portabile, artefatti per 14 giorni; # installatore Febe-Setup-<versione>-ci.<numero>.exe e lo zip portabile, artefatti per 14 giorni;
@@ -108,7 +108,7 @@ jobs:
echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)." 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\"" 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 run: bash .gitea/scripts/ambiente-prove.sh
- uses: actions/setup-dotnet@v4 - 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 # 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); # 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; # 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. # (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. # 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.source="https://gitea.encke-hake.ts.net/Alby96/Febe" \
org.opencontainers.image.url="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 # 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. # 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 # 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 \ && apt-get install -y --no-install-recommends \
chromium chromium-l10n \ chromium chromium-l10n \
xvfb \ xvfb \
ffmpeg \
libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \ libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \
fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \
ca-certificates tzdata locales \ ca-certificates tzdata locales \
+1
View File
@@ -420,3 +420,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-17 | Il messaggio di «Ho finito» per una copia con valori mancanti conta solo i valori della pagina e i `doc_id` che un'operazione configurata manda (`SessionCapturePlan.NeededValues`, `NeededDocIds`; gli altri si leggono lo stesso e il registro li nomina a parte) e dice com'è: la copia ha sostituito quella di prima, le richieste che li usano non partono e alla prima Febe si ferma come disconnessione. Dopo un rifiuto il messaggio dice di riaprire il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premere di nuovo «Ho finito». La copia incompleta sostituisce comunque quella salvata | Il messaggio prometteva che quelle operazioni «restano al browser», ma il codice le ferma come disconnessione (§6.0, mai un ritorno alle pagine); e «Ho finito» chiude sempre il permesso di guida, quindi un secondo «Ho finito» da solo non copia nulla. Tenere una copia più vecchia ma completa potrebbe tenere i cookie di un altro accesso (regola 7) | | 2026-11-17 | Il messaggio di «Ho finito» per una copia con valori mancanti conta solo i valori della pagina e i `doc_id` che un'operazione configurata manda (`SessionCapturePlan.NeededValues`, `NeededDocIds`; gli altri si leggono lo stesso e il registro li nomina a parte) e dice com'è: la copia ha sostituito quella di prima, le richieste che li usano non partono e alla prima Febe si ferma come disconnessione. Dopo un rifiuto il messaggio dice di riaprire il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premere di nuovo «Ho finito». La copia incompleta sostituisce comunque quella salvata | Il messaggio prometteva che quelle operazioni «restano al browser», ma il codice le ferma come disconnessione (§6.0, mai un ritorno alle pagine); e «Ho finito» chiude sempre il permesso di guida, quindi un secondo «Ho finito» da solo non copia nulla. Tenere una copia più vecchia ma completa potrebbe tenere i cookie di un altro accesso (regola 7) |
| 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano | | 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano |
| 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» | | 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» |
| 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) |
+3 -2
View File
@@ -11,7 +11,7 @@ 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. - 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. - Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET.
- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati), ICU, caratteri di sistema con le emoji - `chromium` e `chromium-l10n`, `xvfb`, ICU, caratteri di sistema con le emoji
(`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. (`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata.
- `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per - `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per
scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium. scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium.
@@ -71,7 +71,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` | | `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 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. 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 ## Porte
+2 -2
View File
@@ -29,8 +29,8 @@ succede: la copia si accende solo quando ci sono richieste configurate.
non accetta sessioni incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori. non accetta sessioni 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 - 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. l'accesso. «Scollega» la cancella.
- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser, Xvfb, - Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser e
ffmpeg): il browser esegue il codice del sito, e non deve poterle leggere. Xvfb): il browser esegue il codice del sito, e non deve poterle leggere.
## Docker: l'interfaccia non va esposta su Internet ## Docker: l'interfaccia non va esposta su Internet
+1 -1
View File
@@ -198,7 +198,7 @@ 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 - `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in
tutta la storia (gitleaks); tutta la storia (gitleaks);
- `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in - `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, Xvfb, ffmpeg, NSIS e Node veri: nessuna prova si salta; un contenitore Debian con Chromium, Xvfb, NSIS e Node veri: nessuna prova si salta;
- `installatore`: `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile, fra gli artefatti per 14 giorni; - `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 - `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 scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-<commit>`. Alla fine si toglie
+1 -1
View File
@@ -87,7 +87,7 @@ Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri proget
| Lavoro | Quando | Che cosa garantisce | | 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`) | | `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`) con Chromium della distribuzione, Xvfb, ffmpeg, NSIS, Node e la lingua italiana: 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`) con Chromium della distribuzione, Xvfb, NSIS, Node e la lingua italiana: 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) |
| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni | | `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup-<versione>-ci.<numero>.exe` 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>` | | `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>` |
+2 -2
View File
@@ -250,8 +250,8 @@ public sealed class FebeApp : IAsyncDisposable
Clock = Clock, Clock = Clock,
Thumbnails = thumbnails, Thumbnails = thumbnails,
HashIndex = hashes, HashIndex = hashes,
Frames = VideoFrameExtractor.TryCreate(), Frames = VideoFrameDecoder.Instance,
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), VideoProbe = new ContainerVideoMetadataProbe(Clock),
SetFileTimeToPublication = settings.SetFileTimeToPublication, SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot),
DataFolder = data.Root, DataFolder = data.Root,
@@ -0,0 +1,385 @@
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 = 20_000_000;
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)
{
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)
{
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 id = Encoding.Latin1.GetString(header[..4]);
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 (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 if (state.InMovi)
{
AddChunk(id, body, (int)size, state);
}
else
{
switch (id)
{
case "avih" when size >= 40:
{
var data = Read(stream, body, (int)size);
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, (int)size);
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:
state.Index = Read(stream, body, (int)Math.Min(size, MaxHeaderBytes * 8L));
break;
}
}
position = next;
}
}
private static byte[] Read(Stream stream, long offset, int count)
{
if (count > MaxHeaderBytes * 8)
{
throw new ContainerException("Intestazione AVI troppo grande.");
}
var data = new byte[count];
stream.Position = offset;
stream.ReadExactly(data);
return data;
}
private static void AddChunk(string id, long body, int size, State state)
{
if (id.Length != 4 || !char.IsAsciiDigit(id[0]) || !char.IsAsciiDigit(id[1]))
{
return; // JUNK, ix## indexes and the like
}
var stream = (id[0] - '0') * 10 + (id[1] - '0');
if (state.Chunks.Count >= MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
if (stream == state.VideoStream && (id[2..] is "dc" or "db"))
{
state.Chunks.Add((body, size));
}
else if (stream == state.AudioStream && id[2..] == "wb")
{
state.AudioChunks.Add((body, size));
}
}
/// <summary>The IDIT date, as many cameras write it: «Mon Mar 04 05:06:07 2021».</summary>
private 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;
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 = frames * frameTicks,
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,
};
}
TimeSpan? duration = video is { Duration: > 0 } ? TimeSpan.FromSeconds(video.Seconds(video.Duration)) : 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,70 @@
namespace Febe.Core.Codecs.Containers;
/// <summary>Recognises the container of a video by its first bytes and reads it with the matching reader.</summary>
public static class ContainerReader
{
/// <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;
}
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).
/// </summary>
public static MediaContainer? Read(Stream stream, DateTimeOffset now, bool samples = true)
{
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),
ContainerFormat.Avi => AviReader.Read(stream, now, samples),
ContainerFormat.IsoBmff => IsoBmffReader.Read(stream, now, samples),
_ => 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)
{
using var stream = OpenRead(path);
return Read(stream, now, samples);
}
/// <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 (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,842 @@
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;
private const int MaxSamples = 20_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, no fragments).</param>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
{
ArgumentNullException.ThrowIfNull(stream);
var length = stream.Length;
long position = 0;
Span<byte> header = stackalloc byte[16];
Movie? movie = null;
var fragments = new List<(long Start, byte[] Body)>();
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
{
stream.Position = position;
stream.ReadExactly(header[..8]);
long size = BinaryPrimitives.ReadUInt32BigEndian(header);
var headerSize = 8;
if (size == 1)
{
stream.ReadExactly(header.Slice(8, 8));
size = (long)BinaryPrimitives.ReadUInt64BigEndian(header.Slice(8, 8));
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 = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples);
if (!samples)
{
break;
}
}
else if (samples && type.SequenceEqual("moof"u8))
{
fragments.Add((position, ReadBody(stream, position + headerSize, size - headerSize)));
}
position += size;
}
if (movie is null)
{
throw new ContainerException("Manca il box moov.");
}
foreach (var (start, body) in fragments)
{
movie.AddFragment(start, body);
}
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)
{
var movie = new Movie(samples);
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":
movie.ParseTrak(moov, start, count);
break;
case "mvex":
foreach (var (t, s, c) in Children(moov, start, count))
{
if (t == "trex" && c >= 24)
{
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)));
}
}
break;
}
}
}
catch (ArgumentOutOfRangeException)
{
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)
{
internal readonly Dictionary<uint, (uint Description, uint Duration, uint Size)> TrackDefaults = [];
private readonly List<Track> tracks = [];
private DateTimeOffset? created;
private long timescale;
private long duration;
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))
{
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;
}
BuildSamples(track, stts, ctts, stsc, stsz, stz2, stco, co64, stss);
}
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
{
var flags = body[p + 2];
p += 3;
if ((flags & 0x80) != 0)
{
p += 2;
}
if ((flags & 0x40) != 0)
{
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 static 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.");
}
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)));
var keys = stss is null ? null : new HashSet<int>();
if (stss is not null)
{
var n = BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(4));
for (var i = 0; i < n; i++)
{
keys!.Add((int)BinaryPrimitives.ReadUInt32BigEndian(stss.AsSpan(8 + (i * 4))) - 1);
}
}
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.Contains(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 (ArgumentOutOfRangeException)
{
// A damaged fragment: the samples read so far stand.
}
}
private void AddTrackFragment(long moofStart, byte[] data, int start, int count)
{
Track? track = null;
long baseOffset = 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.Duration, d.Size, 0);
}
var p = 8;
if ((flags & 0x1) != 0)
{
baseOffset = (long)BinaryPrimitives.ReadUInt64BigEndian(body[p..]);
p += 8;
}
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)BinaryPrimitives.ReadUInt64BigEndian(body[4..]) : 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..]);
if (n < 0 || track.Samples.Count + n > MaxSamples)
{
throw new ContainerException("Troppi campioni.");
}
var p = 8;
var offset = baseOffset;
if ((flags & 0x1) != 0)
{
offset += BinaryPrimitives.ReadInt32BigEndian(body[p..]);
p += 4;
}
uint? firstFlags = null;
if ((flags & 0x4) != 0)
{
firstFlags = BinaryPrimitives.ReadUInt32BigEndian(body[p..]);
p += 4;
}
var dts = decodeTime ?? Math.Max(0, track.FragmentTime);
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)size, dts, dts + ct - track.EditOffset, key));
offset += size;
dts += duration;
}
track.FragmentTime = dts;
decodeTime = dts;
baseOffset = offset; // a later trun of the same traf continues the data
break;
}
}
}
}
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,
};
}
TimeSpan? total = timescale > 0 && duration > 0 ? TimeSpan.FromSeconds((double)duration / timescale) : null;
if (total is null && v is { Duration: > 0 })
{
total = TimeSpan.FromSeconds(v.Seconds(v.Duration));
}
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a };
}
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,678 @@
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 = 20_000_000;
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>
public static MediaContainer Read(Stream stream, DateTimeOffset now, bool samples = true)
{
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 = end;
(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)
{
var elementStart = stream.Position;
if (segmentEnd - elementStart < 2)
{
break;
}
(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;
}
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:
state.DurationTicks = reader.Float(size);
break;
case 0x4461:
{
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;
}
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 = entryEnd;
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 = clusterTime + relative;
var lacing = (flags >> 1) & 3;
var dataStart = stream.Position;
if (lacing == 0)
{
target.Samples.Add(new MediaSample(dataStart, (int)(end - dataStart), time, time, key));
return;
}
var frames = stream.ReadByte() + 1;
var sizes = new 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 && state.TimecodeScale > 0 ? target.DefaultDuration / state.TimecodeScale : 0;
for (var i = 0; i < frames; i++)
{
if (sizes[i] < 0 || offset + sizes[i] > end)
{
throw new ContainerException("Blocco Matroska danneggiato.");
}
var t = time + (i * frameDuration);
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;
internal MediaContainer Build()
{
var timescale = Math.Max(1, 1_000_000_000L / Math.Max(1, TimecodeScale));
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 = (long)DurationTicks,
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 = (long)DurationTicks,
Samples = a.Samples,
};
}
TimeSpan? duration = DurationTicks > 0 ? TimeSpan.FromSeconds(DurationTicks * TimecodeScale / 1e9) : 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.");
}
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.");
}
stream.Position += size;
}
private int ReadByteOrThrow()
{
var b = stream.ReadByte();
return b < 0 ? throw new ContainerException("File Matroska troncato.") : b;
}
}
}
@@ -0,0 +1,122 @@
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>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>Audio codecs recognised in a container.</summary>
public enum AudioCodec
{
Unknown,
Aac,
Mp3,
Opus,
Vorbis,
Pcm,
}
/// <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; }
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,643 @@
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;
for (var i = 1; i <= samples.Count; i++)
{
if (i == samples.Count || samples[i].DecodeTime - samples[first].DecodeTime >= limit || i - first >= 1024)
{
list.Add((t, first, i - first, (double)(samples[first].DecodeTime - samples[0].DecodeTime) / track.Timescale));
first = i;
}
}
}
list.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : a.Track.CompareTo(b.Track));
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;
}
}
}
+3 -2
View File
@@ -18,7 +18,7 @@ internal sealed record ContentFacts(
/// <summary> /// <summary>
/// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for /// 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 and AVI).
/// </summary> /// </summary>
internal static class ContentAnalysis internal static class ContentAnalysis
{ {
@@ -123,8 +123,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); var extra = await probe.ProbeAsync(fullPath, ct).ConfigureAwait(false);
if (extra is not null) if (extra is not null)
{ {
+1 -1
View File
@@ -688,7 +688,7 @@ public sealed class ImportCopier(ImportEnvironment env)
return null; 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); return frame is null ? null : new MemoryStream(frame, writable: false);
} }
+6 -3
View File
@@ -33,10 +33,13 @@ public sealed record ImportEnvironment
/// </summary> /// </summary>
public PerceptualHashIndex? HashIndex { get; init; } public PerceptualHashIndex? HashIndex { get; init; }
/// <summary>ffmpeg, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary> /// <summary>The in-house frame decoder, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
public VideoFrameExtractor? Frames { get; init; } 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). Null: the in-house
/// <see cref="ContainerVideoMetadataProbe"/> on the clock of this environment.
/// </summary>
public IVideoMetadataProbe? VideoProbe { get; init; } public IVideoMetadataProbe? VideoProbe { get; init; }
/// <summary>«Imposta la data del file a quella di pubblicazione» (library setting).</summary> /// <summary>«Imposta la data del file a quella di pubblicazione» (library setting).</summary>
+4 -4
View File
@@ -21,8 +21,8 @@ var import = new ImportService(new ImportEnvironment
Clock = clock, Clock = clock,
Thumbnails = new ThumbnailStore(data.Thumbnails), Thumbnails = new ThumbnailStore(data.Thumbnails),
HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta
Frames = VideoFrameExtractor.TryCreate(), // miniature dei video importati, se c'è ffmpeg Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 importati, decodificate in casa
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), // facoltativo VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska e AVI (null: la stessa, predefinita)
SetFileTimeToPublication = settings.SetFileTimeToPublication, SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder, Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder,
DataFolder = data.Root, DataFolder = data.Root,
@@ -68,8 +68,8 @@ video), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, i
probabile, tipo probabile e titolo della raccolta. 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 - **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 `DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; i lettori di
solo come aggiunta per gli altri video), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora contenitori scritti in casa per WebM, Matroska e AVI), 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`). 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, - **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 taggati, anni...) o solo file, è un account; altrimenti ogni sottocartella di primo livello è un'unità da associare a
+27 -166
View File
@@ -1,192 +1,53 @@
using System.Diagnostics; using Febe.Core.Abstractions;
using System.Globalization; using Febe.Core.Codecs.Containers;
using System.Text.Json;
using Febe.Core.Security;
namespace Febe.Core.Import; 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); public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
/// <summary> /// <summary>Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI).</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>
public interface IVideoMetadataProbe 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); Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default);
} }
/// <summary> /// <summary>
/// <see cref="IVideoMetadataProbe"/> with ffprobe, when installed (in Docker it comes with ffmpeg, §11). The output is /// <see cref="IVideoMetadataProbe"/> written in house on the container readers of <see cref="ContainerReader"/>: no
/// parsed with <see cref="JsonDocument"/>; error output is never logged (it may contain paths). /// external program. Only the headers are read (no sample tables), so it is quick also on long videos.
/// </summary> /// </summary>
public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe public sealed class ContainerVideoMetadataProbe(IClock? clock = null) : IVideoMetadataProbe
{ {
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20); private readonly IClock _clock = clock ?? new SystemClock();
private FfprobeVideoMetadataProbe(string executable) => Executable = executable; public Task<VideoMetadata?> ProbeAsync(string path, CancellationToken ct = default)
/// <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;
}
/// <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).
/// </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)
{ {
ArgumentException.ThrowIfNullOrWhiteSpace(path); ArgumentException.ThrowIfNullOrWhiteSpace(path);
using var process = new Process { StartInfo = BuildStartInfo(path) }; ct.ThrowIfCancellationRequested();
return Task.FromResult(Probe(path, _clock.Now));
}
/// <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)
{
try try
{ {
if (!process.Start()) if (ContainerReader.ReadFile(path, now, samples: false) is not { } container)
{ {
return null; 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 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> /// </summary>
public IReadOnlyList<string> ExtraAccountFolders { get; init; } = []; 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; public bool CreateThumbnails { get; init; } = true;
/// <summary>Files hashed in parallel.</summary> /// <summary>Files hashed in parallel.</summary>
@@ -80,7 +80,7 @@ public sealed class LibraryRebuilder(
LibraryLayout layout, LibraryLayout layout,
IClock clock, IClock clock,
ThumbnailStore? thumbnails = null, ThumbnailStore? thumbnails = null,
VideoFrameExtractor? frames = null, VideoFrameDecoder? frames = null,
PerceptualHashIndex? hashIndex = null) PerceptualHashIndex? hashIndex = null)
{ {
private const int BatchSize = 200; private const int BatchSize = 200;
@@ -468,7 +468,7 @@ public sealed class LibraryRebuilder(
} }
else if (isVideo && createThumbnails && thumbnails is not null && !thumbnail && frames is not null) 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) if (frame is not null)
{ {
using var stream = new MemoryStream(frame); using var stream = new MemoryStream(frame);
+1 -1
View File
@@ -6,7 +6,7 @@ namespace Febe.Core.Library;
/// Thumbnails of the library (spec §8.4): 480 pixels on the long side, JPEG, generated once and kept under /// 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 /// <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 /// 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"/>). /// (<see cref="NeutralVideoTile"/>).
/// </summary> /// </summary>
public sealed class ThumbnailStore public sealed class ThumbnailStore
+492
View File
@@ -0,0 +1,492 @@
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;
private const int GridSize = 32;
private const int SampledPositions = 6;
private const int MaxSequentialSamples = 2000;
private const int MaxRunPerTarget = 300;
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <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; null when the file cannot be read or decoded.
/// </summary>
public Task<byte[]?> ExtractImageAsync(string videoPath, CancellationToken ct = default) =>
ExtractImageAsync(videoPath, TimeSpan.FromSeconds(1), 0, 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(() => DecodeFrame(videoPath, at, maxLongSide, 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(() => AnalyseStillness(videoPath, ct), ct);
}
private static VideoImage? DecodeFrame(string path, TimeSpan at, int maxLongSide, CancellationToken ct)
{
try
{
using var stream = ContainerReader.OpenRead(path);
if (Open(stream) is not { } video)
{
return null;
}
var target = SampleAt(video, at);
var frames = new Decoding(stream, video).Decode([target], ct);
if (!frames.TryGetValue(target, out var frame) && target != 0)
{
frames = new Decoding(stream, video).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 static VideoStillness? AnalyseStillness(string path, CancellationToken ct)
{
try
{
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 keys = KeyIndices(video);
var targets = new SortedSet<int>();
for (var i = 0; i < SampledPositions; i++)
{
var time = first + ((last - first) * i / (SampledPositions - 1));
var index = Closest(samples, time);
// Far from its key frame in a long video: the key frame stands for it, so the work stays bounded.
var key = KeyBefore(keys, index);
if (index - key > MaxRunPerTarget && samples.Count > MaxSequentialSamples)
{
index = key;
}
targets.Add(index);
}
if (targets.Count < 2)
{
return null;
}
var frames = new Decoding(stream, video).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];
}
private static int KeyBefore(int[] keys, int index)
{
var found = Array.BinarySearch(keys, index);
return found >= 0 ? keys[found] : keys[Math.Max(0, ~found - 1)];
}
/// <summary>Decodes chosen samples, each from the key frame before it, reusing a run when the targets share it.</summary>
private sealed class Decoding(Stream stream, VideoTrack video)
{
private readonly Dictionary<int, H264Frame> found = [];
private readonly HashSet<int> wanted = [];
private byte[] buffer = new byte[64 * 1024];
internal Dictionary<int, H264Frame> Decode(int[] targets, CancellationToken ct)
{
foreach (var t in targets)
{
wanted.Add(t);
}
var keys = KeyIndices(video);
H264Decoder? decoder = null;
var next = 0;
var lengthSize = 4;
foreach (var target in targets)
{
var key = KeyBefore(keys, target);
if (decoder is null || next > target || key >= next)
{
decoder = new H264Decoder();
var runStart = key;
decoder.Wanted = index => wanted.Contains(runStart + (int)index);
decoder.FrameDecoded += frame => found.TryAdd(runStart + (int)frame.DecodeIndex, frame);
if (!video.AnnexB)
{
lengthSize = decoder.ConfigureAvcC(video.AvcConfiguration);
}
next = key;
}
try
{
for (; next <= target; next++)
{
ct.ThrowIfCancellationRequested();
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 IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
decoder = null; // this run is damaged: the next target starts again from its own key frame
}
}
return found;
}
}
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
private static double[] Grid(H264Frame frame)
{
var grid = new double[GridSize * GridSize * 2];
var counts = new int[GridSize * GridSize];
for (var y = 0; y < frame.Height; y++)
{
var gy = y * GridSize / frame.Height;
var row = frame.Y.AsSpan(y * frame.Width, frame.Width);
for (var x = 0; x < row.Length; x++)
{
var cell = (gy * GridSize) + (x * GridSize / frame.Width);
grid[cell] += row[x];
counts[cell]++;
}
}
var cw = (frame.Width + 1) / 2;
var ch = (frame.Height + 1) / 2;
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;
grid[(GridSize * GridSize) + cell] += (Math.Abs(frame.Cb[i] - 128) + Math.Abs(frame.Cr[i] - 128)) / 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 or BT.601 coefficients as the stream says (unspecified: BT.709 from 720 lines up), limited
/// or full range, reduced by an integer factor to fit <paramref name="maxLongSide"/>, then rotated clockwise.
/// </summary>
internal static VideoImage ToImage(H264Frame frame, int rotation, int maxLongSide)
{
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;
var yScale = frame.FullRange ? 1.0 : 255.0 / 219.0;
var cScale = frame.FullRange ? 1.0 : 255.0 / 224.0;
var yOffset = frame.FullRange ? 0 : 16;
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.Width + 1) / 2;
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 >> 1) * cw;
for (var dx = 0; dx < factor; dx++)
{
var x = (ox * factor) + dx;
var l = (frame.Y[lumaRow + x] - yOffset) * cy;
var u = frame.Cb[chromaRow + (x >> 1)] - 128;
var v = frame.Cr[chromaRow + (x >> 1)] - 128;
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; namespace Febe.Core.Security;
/// <summary> /// <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 /// 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. /// parent; Chromium runs the site's code, so a secret in its environment is a secret one step from the site.
/// </summary> /// </summary>
+2 -2
View File
@@ -122,8 +122,8 @@ public sealed class ImportHub : IAsyncDisposable
Clock = _clock, Clock = _clock,
Thumbnails = library.Thumbnails, Thumbnails = library.Thumbnails,
HashIndex = library.HashIndex, HashIndex = library.HashIndex,
Frames = VideoFrameExtractor.TryCreate(), Frames = VideoFrameDecoder.Instance,
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(), VideoProbe = new ContainerVideoMetadataProbe(_clock),
SetFileTimeToPublication = settings.SetFileTimeToPublication, SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder, Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder,
DataFolder = library.Data.Root, 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 | | `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` | | `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) | | `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à - `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`. `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 }); var progress = new SyncProgress<RebuildProgress>(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked });
try 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); var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false);
State = State with { Running = false, Report = report, FinishedAt = clock.Now }; State = State with { Running = false, Report = report, FinishedAt = clock.Now };
changes.Publish(new LibraryChange(clock.Now, null, "rebuild")); changes.Publish(new LibraryChange(clock.Now, null, "rebuild"));
+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("marta.demo/travestita.png", ImportTestFiles.Photo(4, 320, 240));
bed.Write("Foto sparse/a.jpg", ImportTestFiles.Photo(5)); bed.Write("Foto sparse/a.jpg", ImportTestFiles.Photo(5));
bed.Write("marta.demo/Thumbs.db", [1, 2, 3]); bed.Write("marta.demo/Thumbs.db", [1, 2, 3]);
var realVideo = Path.Combine(bed.Source, "marta.demo", "storie", "ffmpeg.mp4"); bed.Write("marta.demo/storie/vero.mp4", ImportTestFiles.RealMp4(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero)));
var withFfmpeg = ImportTestFiles.TryMakeMp4WithFfmpeg(realVideo, 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 before = bed.Fingerprint();
var run = await bed.AnalyzeAsync(); var run = await bed.AnalyzeAsync();
@@ -32,16 +32,18 @@ public sealed class ImportAnalysisTests
Assert.AreEqual(ImportRunState.Reviewing, run.State); Assert.AreEqual(ImportRunState.Reviewing, run.State);
Assert.IsNotNull(run.AnalyzedAt); Assert.IsNotNull(run.AnalyzedAt);
CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "L'analisi è in sola lettura: nessun file della sorgente cambia."); 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(); var files = await bed.FilesAsync(run.Id);
Assert.HasCount(7, files, "Thumbs.db non è un contenuto e non si elenca."); Assert.HasCount(9, files, "Thumbs.db non è un contenuto e non si elenca.");
if (withFfmpeg) var real = await bed.FileAsync(run.Id, "marta.demo/storie/vero.mp4");
{ Assert.AreEqual("video/mp4", real.ContentType);
var real = await bed.FileAsync(run.Id, "marta.demo/storie/ffmpeg.mp4"); Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd.");
Assert.AreEqual("video/mp4", real.ContentType); Assert.AreEqual(ImportDateSource.Metadata, real.DateSource);
Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd."); Assert.AreEqual(ImportTestFiles.RealVideoSize, (real.Width!.Value, real.Height!.Value));
Assert.AreEqual(ImportDateSource.Metadata, real.DateSource); var webm = await bed.FileAsync(run.Id, "marta.demo/storie/vero.webm");
Assert.AreEqual((64, 48), (real.Width, real.Height)); 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)); 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."); Assert.IsNull(loose.ProbableAccount, "«Foto sparse» non può essere un nome utente.");
var summary = await bed.Review.GetSummaryAsync(run.Id); var summary = await bed.Review.GetSummaryAsync(run.Id);
Assert.AreEqual(withFfmpeg ? 8 : 7, summary.Files); Assert.AreEqual(9, summary.Files);
Assert.AreEqual(withFfmpeg ? 7 : 6, summary.ByOutcome[ImportOutcome.New]); Assert.AreEqual(8, summary.ByOutcome[ImportOutcome.New]);
Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Unrecognized]); Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Unrecognized]);
var marta = summary.Folders.Single(f => f.Folder == "marta.demo"); 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(FolderTargetKind.NewArchiveAccount, marta.Target.Kind, "Un nome valido senza account: nuovo account, solo archivio.");
Assert.AreEqual("marta.demo", marta.Target.Username); 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.AreEqual(FolderTargetKind.None, summary.Folders.Single(f => f.Folder == "Foto sparse").Target.Kind, "Nessun nome riconosciuto: nessuna scelta fatta.");
Assert.IsTrue(summary.CanMove); 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."); StringAssert.EndsWith(summary.Headline, "Nessun file è stato ancora copiato.");
} }
+19 -33
View File
@@ -121,55 +121,41 @@ public sealed class MediaReaderTests
} }
[TestMethod] [TestMethod]
public void AnMp4MadeByFfmpegCarriesItsCreationTime() public void ARealMp4CarriesItsCreationTime()
{ {
using var temp = new TempFolder("mp4"); using var temp = new TempFolder("mp4");
var path = temp.Combine("prova.mp4"); var path = temp.Combine("prova.mp4");
var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero);
if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created)) File.WriteAllBytes(path, ImportTestFiles.RealMp4(created));
{
Assert.Inconclusive("ffmpeg non è installato: la prova sulle intestazioni sintetiche copre il lettore.");
}
Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType); Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType);
var info = Mp4Reader.ReadFile(path, Now); var info = Mp4Reader.ReadFile(path, Now);
Assert.AreEqual(created, info?.CreatedAt); Assert.AreEqual(created, info?.CreatedAt);
Assert.AreEqual(64, info?.Width); Assert.AreEqual(ImportTestFiles.RealVideoSize, (info!.Width!.Value, info.Height!.Value));
Assert.AreEqual(48, info?.Height); Assert.IsTrue(info.Duration > TimeSpan.FromMilliseconds(500));
Assert.IsTrue(info?.Duration > TimeSpan.FromMilliseconds(500));
} }
[TestMethod] [TestMethod]
public async Task FfprobeIsAnOptionalExtra() public async Task TheContainerProbeReadsWhatTheMp4ReaderDoesNot()
{ {
var parsed = FfprobeVideoMetadataProbe.Parse(""" using var temp = new TempFolder("sonda");
{"streams":[{"codec_type":"audio"},{"codec_type":"video","width":1920,"height":1080,"tags":{"rotate":"90"}}], var webm = temp.Combine("prova.webm");
"format":{"duration":"12.500000","tags":{"creation_time":"2020-08-09T10:11:12.000000Z"}}} var mp4 = temp.Combine("prova.mp4");
""");
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");
var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero); 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.IsNull(await probe.ProbeAsync(temp.Combine("non-esiste.webm")));
Assert.AreEqual(created, metadata?.CreatedAt);
Assert.AreEqual(64, metadata?.Width);
} }
[TestMethod] [TestMethod]
@@ -1,6 +1,6 @@
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Diagnostics;
using System.Text; using System.Text;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Support; using Febe.Tests.Support;
using SkiaSharp; using SkiaSharp;
@@ -199,31 +199,16 @@ internal static class ImportTestFiles
return output.ToArray(); return output.ToArray();
} }
/// <summary>Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing.</summary> /// <summary>
public static bool TryMakeMp4WithFfmpeg(string path, DateTimeOffset createdAt) /// A real H.264 MP4 (a conformance stream, 176×144, muxed by the in-house writer) with the given creation time.
{ /// </summary>
var ffmpeg = new[] { "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg" }.FirstOrDefault(File.Exists); public static byte[] RealMp4(DateTimeOffset createdAt) => TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"), createdAt);
if (ffmpeg is null)
{
return false;
}
var start = new ProcessStartInfo(ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; /// <summary>A real H.264 WebM-style Matroska file (the same stream) with the given creation time.</summary>
foreach (var argument in new[] public static byte[] RealWebm(DateTimeOffset createdAt) => TestVideos.Matroska(ElementaryStream.Load("BA1_Sony_D"), createdAt, webm: true);
{
"-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);
}
using var process = Process.Start(start)!; /// <summary>Width and height of <see cref="RealMp4"/> and <see cref="RealWebm"/>.</summary>
process.StandardError.ReadToEnd(); public static (int Width, int Height) RealVideoSize => (176, 144);
process.WaitForExit(30_000);
return process.ExitCode == 0 && File.Exists(path);
}
/// <summary>The PNG encoding of a generated scene.</summary> /// <summary>The PNG encoding of a generated scene.</summary>
public static byte[] Png(int scene, int width = 400, int height = 300) public static byte[] Png(int scene, int width = 400, int height = 300)
@@ -1,4 +1,5 @@
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Support; using Febe.Tests.Support;
using SkiaSharp; using SkiaSharp;
@@ -105,39 +106,19 @@ public sealed class ThumbnailStoreTests
} }
[TestMethod] [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(); using var temp = new TempFolder();
var video = temp.Combine("prova.mp4"); var es = ElementaryStream.Load("CABA3_SVA_B");
var start = new System.Diagnostics.ProcessStartInfo(ffmpeg.Executable) var video = TestVideos.Write(temp, "prova.mp4", TestVideos.Mp4(es));
{
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);
}
using (var process = System.Diagnostics.Process.Start(start)!) var frame = await VideoFrameDecoder.Instance.ExtractImageAsync(video);
{
await process.WaitForExitAsync();
Assert.AreEqual(0, process.ExitCode, "ffmpeg non ha creato il video di prova.");
}
var frame = await ffmpeg.ExtractJpegAsync(video);
Assert.IsNotNull(frame); Assert.IsNotNull(frame);
var store = new ThumbnailStore(temp.Combine("miniature")); var store = new ThumbnailStore(temp.Combine("miniature"));
Assert.IsTrue(store.Create(Make.Sha(6), new MemoryStream(frame))); 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")));
} }
} }
@@ -0,0 +1,233 @@
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")]
[DataRow("FRExt1_Panasonic_D")]
public void AFragmentedMp4IsReadFromItsFragments(string name)
{
var es = ElementaryStream.Load(name);
var file = TestVideos.FragmentedMp4(es, perFragment: 7);
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!));
}
[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);
}
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,461 @@
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.ToI420())))
.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>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).</summary>
public static byte[] FragmentedMp4(ElementaryStream es, int perFragment = 10)
{
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)]);
var trex = FullBox("trex", 0, [.. U32(1), .. U32(1), .. U32(FrameTicks), .. U32(0), .. U32(0)]);
output.Write(Box("moov", mvhd, Box("trak", tkhd, mdia), Box("mvex", trex)));
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[] Moof(int dataOffset)
{
var run = new List<byte>();
run.AddRange(U32((uint)count));
run.AddRange(U32((uint)dataOffset));
for (var k = 0; k < count; k++)
{
var i = first + k;
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)));
}
return Box("moof",
FullBox("mfhd", 0, U32((uint)sequence)),
Box("traf",
FullBox("tfhd", 0x020000, U32(1)),
FullBox("tfdt", 0, U32((uint)(first * FrameTicks))),
FullBox("trun", 0x000F01, [.. run])));
}
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 (times in milliseconds).</summary>
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false)
{
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 durationMs = es.Count * 1000.0 / 30;
var info = new List<byte[]> { Element(0x2AD7B1, U32(1_000_000)), Element(0x4489, F64(durationMs)), 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);
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 and, when given, an IDIT date.</summary>
public static byte[] Avi(ElementaryStream es, string? idit = null, bool index = true)
{
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, 1, 30, 0, (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,145 @@
using Febe.Core.Codecs.H264;
using Febe.Core.Library;
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")]
public async Task TheFrameAtOneSecondIsTheOneTheStreamShowsThere(string kind)
{
var es = ElementaryStream.Load("CABA3_SVA_B");
using var temp = new TempFolder("fotogramma");
var data = kind switch
{
"mkv" => TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)),
"avi" => TestVideos.Avi(es),
"frammentato.mp4" => TestVideos.FragmentedMp4(es),
_ => 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 == "avi" ? 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 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 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);
}
}
@@ -0,0 +1,40 @@
# Flussi di conformità H.264
Questi flussi provano il decodificatore H.264 scritto in casa (`src/Febe.Core/Codecs/H264`) e, ricomposti in MP4,
Matroska e AVI dalle prove di `tests/Febe.Tests/Media/Containers`, anche i lettori dei contenitori e lo scrittore MP4.
## Provenienza
Sono flussi della serie di conformità ufficiale **ITU-T H.264.1** («Conformance specification for ITU-T H.264
advanced video coding»), pubblicata dall'ITU-T con i flussi di bit, i file `readme` dei loro autori e la ricostruzione
di riferimento di ogni flusso. Ogni cartella contiene il flusso così com'è (Annex B: `.264` o `.jsv`) e il suo `readme`.
## Che cosa contiene `riferimento.md5`
Una riga per fotogramma, nell'ordine di uscita: il numero del fotogramma e l'MD5 dei suoi campioni in I420 (Y, poi Cb,
poi Cr, ritagliati). I valori sono calcolati una volta dai file YUV ricostruiti ufficiali della serie ITU-T, che **non
sono nel repository** (pesano molto più dei flussi e non servono: basta il loro MD5). Una prova passa solo se ogni
fotogramma decodificato ha esattamente l'MD5 del riferimento.
## Che cosa copre ciascun flusso
Tutti i flussi sono a immagini intere (niente campi né MBAFF), in 4:2:0 a 8 bit, sulla sequenza «Foreman». Le
caratteristiche vengono dai `readme` degli autori.
| Flusso | Profilo, formato | Che cosa prova |
|---|---|---|
| `BA1_Sony_D` | Baseline, QCIF, 17 fotogrammi | CAVLC, un riferimento, IDR solo all'inizio, deblocking attivo |
| `SVA_BA1_B` | Baseline, QCIF, 17 | CAVLC, POC di tipo 2, fino a 5 riferimenti |
| `BA3_SVA_C` | Extended, QCIF, 33 | CAVLC con slice B, predizione diretta spaziale, 5 riferimenti |
| `BASQP1_Sony_C` | Baseline, QCIF, 4 | 20 slice per immagine con QP diverso per slice |
| `CI_MW_D` | Baseline, QCIF, 100 | CAVLC, IDR ogni 30 fotogrammi, 4 riferimenti |
| `CABA1_SVA_B` | Main, QCIF, 17 | CABAC, slice I |
| `CABA2_SVA_B` | Main, QCIF, 17 | CABAC, slice I e P, 5 riferimenti |
| `CABA3_SVA_B` | Main, QCIF, 33 | CABAC con slice B e predizione diretta temporale |
| `CANL1_SVA_B` | Main, QCIF, 17 | CABAC, POC di tipo 2, deblocking spento |
| `FRExt1_Panasonic_D` | High, CIF, 8 | CAVLC, solo trasformata 8×8, matrici di quantizzazione di sequenza e di immagine, slice B con diretta spaziale, SPS ripetuto |
| `FRExt3_Panasonic_E` | High, CIF, 11 | CABAC, trasformata 8×8 e 4×4 adattiva, matrici di quantizzazione, slice B con diretta temporale |
| `HCAFR1_HHI_C` | High, CIF, 10 | CABAC con inizializzazione adattiva (`cabac_init_idc` 0, 1, 2), trasformata 8×8, matrici predefinite, slice B |
Le immagini interlacciate (campi e MBAFF), il 4:2:2 e i campioni oltre gli 8 bit non sono gestiti dal decodificatore e
quindi non hanno flussi qui.
+4 -1
View File
@@ -69,11 +69,14 @@ public sealed partial class PipelineTests
StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\""); StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\"");
var environment = Script("ambiente-prove.sh"); var environment = Script("ambiente-prove.sh");
foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" }) foreach (var package in new[] { "chromium", "xvfb", "nsis", "locales" })
{ {
StringAssert.Contains(environment, package); StringAssert.Contains(environment, package);
} }
// Videos are read and decoded in house: no ffmpeg in the CI, nor in the image (Alberto, 18 November 2026).
Assert.IsFalse(environment.Contains("ffmpeg", StringComparison.Ordinal), "ffmpeg non serve più alle prove");
// tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project. // tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project.
foreach (var name in new[] { "verifica.yml", "rilascio.yml" }) foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
{ {
@@ -225,40 +225,6 @@ public sealed class SessionKeyOptionsTests
Assert.IsFalse(display.Environment.Keys.Any(ChildProcessEnvironment.IsSecret)); Assert.IsFalse(display.Environment.Keys.Any(ChildProcessEnvironment.IsSecret));
} }
[TestMethod]
[DoNotParallelize]
public void FfmpegAndFfprobeStartWithoutThePasswordOrTheKeyOfFebesEnvironment()
{
// Febe's own environment holds both (as in Docker): ffprobe and ffmpeg must not inherit them (spec §13.2).
using var folder = new TempFolder("figli");
var tool = folder.Combine("strumento-di-prova");
File.WriteAllText(tool, string.Empty);
var before = ChildProcessEnvironment.SecretVariables.Select(n => (Name: n, Value: Environment.GetEnvironmentVariable(n))).ToList();
try
{
foreach (var name in ChildProcessEnvironment.SecretVariables)
{
Environment.SetEnvironmentVariable(name, "valore-di-prova");
}
Assert.IsTrue(new System.Diagnostics.ProcessStartInfo("x").Environment.Keys.Any(ChildProcessEnvironment.IsSecret), "The parent holds them.");
var probe = Febe.Core.Import.FfprobeVideoMetadataProbe.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4");
var frame = VideoFrameExtractor.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4", "1");
foreach (var info in new[] { probe, frame })
{
Assert.IsFalse(info.Environment.Keys.Any(ChildProcessEnvironment.IsSecret), info.FileName);
CollectionAssert.Contains(info.ArgumentList.ToArray(), "video-di-prova.mp4");
}
}
finally
{
foreach (var (name, value) in before)
{
Environment.SetEnvironmentVariable(name, value);
}
}
}
private static Func<string, string?> Env(params (string Name, string Value)[] values) private static Func<string, string?> Env(params (string Name, string Value)[] values)
{ {
var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal); var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);